Merge from mh-e; up to 2012-01-03T19:41:14Z!larsi@gnus.org.
[bpt/emacs.git] / lib-src / emacsclient.c
CommitLineData
efb859b4 1/* Client process that communicates with GNU Emacs acting as server.
9374581a 2
ba318903 3Copyright (C) 1986-1987, 1994, 1999-2014 Free Software Foundation, Inc.
46cec291
RS
4
5This file is part of GNU Emacs.
6
294981c7 7GNU Emacs is free software: you can redistribute it and/or modify
46cec291 8it under the terms of the GNU General Public License as published by
294981c7
GM
9the Free Software Foundation, either version 3 of the License, or
10(at your option) any later version.
46cec291
RS
11
12GNU Emacs is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15GNU General Public License for more details.
16
17You should have received a copy of the GNU General Public License
294981c7 18along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
46cec291
RS
19
20
2f8fe2f4 21#include <config.h>
e69233c2 22
aa0b6932 23#ifdef WINDOWSNT
aa0b6932 24
79432772 25/* ms-w32.h defines these, which disables sockets altogether! */
bc28de71
JB
26# undef _WINSOCKAPI_
27# undef _WINSOCK_H
28
411b80a5
JB
29# include <malloc.h>
30# include <stdlib.h>
42073bfb 31# include <windows.h>
dbf60b07 32# include <commctrl.h>
0613f5d5
DN
33# include <io.h>
34# include <winsock2.h>
411b80a5 35
411b80a5
JB
36# define NO_SOCKETS_IN_FILE_SYSTEM
37
aa0b6932
JB
38# define HSOCKET SOCKET
39# define CLOSE_SOCKET closesocket
aa0b6932 40# define INITIALIZE() (initialize_sockets ())
411b80a5 41
728a982d
DN
42char *w32_getenv (char *);
43#define egetenv(VAR) w32_getenv(VAR)
44
411b80a5
JB
45#else /* !WINDOWSNT */
46
5e0944c6
DC
47# ifdef HAVE_NTGUI
48# include <windows.h>
49# endif /* HAVE_NTGUI */
50
67c1df01 51# include "syswait.h"
ed4a3730 52
1e7823d0
JB
53# ifdef HAVE_INET_SOCKETS
54# include <netinet/in.h>
0613f5d5
DN
55# ifdef HAVE_SOCKETS
56# include <sys/types.h>
57# include <sys/socket.h>
58# include <sys/un.h>
59# endif /* HAVE_SOCKETS */
1e7823d0 60# endif
18d2ad29 61# include <arpa/inet.h>
448d4085 62
e35fc962 63# define INVALID_SOCKET -1
aa0b6932
JB
64# define HSOCKET int
65# define CLOSE_SOCKET close
aa0b6932 66# define INITIALIZE()
411b80a5 67
5445ab06
DN
68# ifndef WCONTINUED
69# define WCONTINUED 8
70# endif
71
728a982d
DN
72#define egetenv(VAR) getenv(VAR)
73
411b80a5 74#endif /* !WINDOWSNT */
aa0b6932 75
4e23f2ba 76#undef signal
46cec291 77
42073bfb 78#include <stdarg.h>
e69233c2 79#include <ctype.h>
8f9aaa0a 80#include <stdio.h>
613f7bda 81#include <getopt.h>
4004364e 82#include <unistd.h>
8f9aaa0a 83
0613f5d5 84#include <pwd.h>
dc4a4a14 85#include <sys/stat.h>
9628b887 86#include <signal.h>
4d553a13 87#include <errno.h>
9628b887 88
0613f5d5 89
9628b887 90\f
9239d970 91char *getenv (const char *);
8f9aaa0a 92
8f9aaa0a
RS
93#ifndef VERSION
94#define VERSION "unspecified"
95#endif
96\f
aa0b6932
JB
97
98#ifndef EXIT_SUCCESS
99#define EXIT_SUCCESS 0
100#endif
101
102#ifndef EXIT_FAILURE
103#define EXIT_FAILURE 1
104#endif
105
bc558f3e
JB
106/* Additional space when allocating buffers for filenames, etc. */
107#define EXTRA_SPACE 100
108
069a7756
JB
109#ifdef min
110#undef min
111#endif
1e6f32f8
JM
112#define min(x, y) (((x) < (y)) ? (x) : (y))
113
aa0b6932 114\f
8f9aaa0a 115/* Name used to invoke this program. */
728a982d 116const char *progname;
8f9aaa0a 117
0a125897
KL
118/* The second argument to main. */
119char **main_argv;
120
749ae770 121/* Nonzero means don't wait for a response from Emacs. --no-wait. */
8f9aaa0a
RS
122int nowait = 0;
123
0b973fc5
DW
124/* Nonzero means don't print messages for successful operations. --quiet. */
125int quiet = 0;
126
30be2360
SM
127/* Nonzero means args are expressions to be evaluated. --eval. */
128int eval = 0;
129
31fa6595
SM
130/* Nonzero means don't open a new frame. Inverse of --create-frame. */
131int current_frame = 1;
92071250 132
30be2360 133/* The display on which Emacs should work. --display. */
988e88ab 134const char *display = NULL;
30be2360 135
6b59694e
DC
136/* The alternate display we should try if Emacs does not support display. */
137const char *alt_display = NULL;
138
0191e222
CY
139/* The parent window ID, if we are opening a frame via XEmbed. */
140char *parent_id = NULL;
141
9628b887 142/* Nonzero means open a new Emacs frame on the current terminal. */
77134727 143int tty = 0;
9628b887 144
30be2360
SM
145/* If non-NULL, the name of an editor to fallback to if the server
146 is not running. --alternate-editor. */
b03d27bd 147const char *alternate_editor = NULL;
30be2360 148
3db926be 149/* If non-NULL, the filename of the UNIX socket. */
6b0c8984 150const char *socket_name = NULL;
254107e4 151
aa0b6932 152/* If non-NULL, the filename of the authentication file. */
988e88ab 153const char *server_file = NULL;
aa0b6932 154
c66648e0
JB
155/* PID of the Emacs server process. */
156int emacs_pid = 0;
157
18a4ce5e
AR
158/* If non-NULL, a string that should form a frame parameter alist to
159 be used for the new frame */
160const char *frame_parameters = NULL;
161
845ca893 162static _Noreturn void print_help_and_exit (void);
68441b90 163
7f3bff3e 164
8f9aaa0a
RS
165struct option longopts[] =
166{
749ae770 167 { "no-wait", no_argument, NULL, 'n' },
0b973fc5 168 { "quiet", no_argument, NULL, 'q' },
30be2360 169 { "eval", no_argument, NULL, 'e' },
8f9aaa0a
RS
170 { "help", no_argument, NULL, 'H' },
171 { "version", no_argument, NULL, 'V' },
b28c910d 172 { "tty", no_argument, NULL, 't' },
dc1cd5f7 173 { "nw", no_argument, NULL, 't' },
31fa6595 174 { "create-frame", no_argument, NULL, 'c' },
3cf8c6aa 175 { "alternate-editor", required_argument, NULL, 'a' },
18a4ce5e 176 { "frame-parameters", required_argument, NULL, 'F' },
b03d27bd 177#ifndef NO_SOCKETS_IN_FILE_SYSTEM
254107e4 178 { "socket-name", required_argument, NULL, 's' },
b03d27bd 179#endif
aa0b6932 180 { "server-file", required_argument, NULL, 'f' },
30be2360 181 { "display", required_argument, NULL, 'd' },
0191e222 182 { "parent-id", required_argument, NULL, 'p' },
30be2360 183 { 0, 0, 0, 0 }
8f9aaa0a
RS
184};
185
974b73e8
KL
186\f
187/* Like malloc but get fatal error if memory is exhausted. */
188
17107bb6
PE
189static void *
190xmalloc (size_t size)
974b73e8 191{
17107bb6 192 void *result = malloc (size);
974b73e8
KL
193 if (result == NULL)
194 {
195 perror ("malloc");
196 exit (EXIT_FAILURE);
197 }
198 return result;
199}
200
974b73e8
KL
201/* From sysdep.c */
202#if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
203
c5443aa5 204char *get_current_dir_name (void);
cb06b8dc 205
974b73e8 206/* Return the current working directory. Returns NULL on errors.
5ab73228 207 Any other returned value must be freed with free. This is used
974b73e8
KL
208 only when get_current_dir_name is not defined on the system. */
209char*
7c3320d8 210get_current_dir_name (void)
974b73e8
KL
211{
212 char *buf;
b9170155 213 const char *pwd;
974b73e8 214 struct stat dotstat, pwdstat;
9239d970 215 /* If PWD is accurate, use it instead of calling getcwd. PWD is
974b73e8
KL
216 sometimes a nicer name, and using it may avoid a fatal error if a
217 parent directory is searchable but not readable. */
7ce8671d 218 if ((pwd = egetenv ("PWD")) != 0
974b73e8
KL
219 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
220 && stat (pwd, &pwdstat) == 0
221 && stat (".", &dotstat) == 0
222 && dotstat.st_ino == pwdstat.st_ino
223 && dotstat.st_dev == pwdstat.st_dev
224#ifdef MAXPATHLEN
225 && strlen (pwd) < MAXPATHLEN
226#endif
227 )
228 {
229 buf = (char *) xmalloc (strlen (pwd) + 1);
974b73e8
KL
230 strcpy (buf, pwd);
231 }
974b73e8
KL
232 else
233 {
234 size_t buf_size = 1024;
974b73e8
KL
235 for (;;)
236 {
17107bb6
PE
237 int tmp_errno;
238 buf = malloc (buf_size);
239 if (! buf)
240 break;
974b73e8
KL
241 if (getcwd (buf, buf_size) == buf)
242 break;
17107bb6
PE
243 tmp_errno = errno;
244 free (buf);
245 if (tmp_errno != ERANGE)
974b73e8 246 {
974b73e8
KL
247 errno = tmp_errno;
248 return NULL;
249 }
250 buf_size *= 2;
17107bb6
PE
251 if (! buf_size)
252 {
253 errno = ENOMEM;
254 return NULL;
255 }
974b73e8
KL
256 }
257 }
974b73e8
KL
258 return buf;
259}
260#endif
261
42073bfb 262#ifdef WINDOWSNT
7ce8671d 263
a54af40e
EZ
264/* Like strdup but get a fatal error if memory is exhausted. */
265
266char *
267xstrdup (const char *s)
268{
269 char *result = strdup (s);
270 if (result == NULL)
271 {
272 perror ("strdup");
273 exit (EXIT_FAILURE);
274 }
275 return result;
276}
277
7ce8671d
JB
278#define REG_ROOT "SOFTWARE\\GNU\\Emacs"
279
280/* Retrieve an environment variable from the Emacs subkeys of the registry.
281 Return NULL if the variable was not found, or it was empty.
282 This code is based on w32_get_resource (w32.c). */
283char *
7c3320d8 284w32_get_resource (HKEY predefined, char *key, LPDWORD type)
7ce8671d
JB
285{
286 HKEY hrootkey = NULL;
287 char *result = NULL;
288 DWORD cbData;
289
290 if (RegOpenKeyEx (predefined, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
291 {
292 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS)
293 {
294 result = (char *) xmalloc (cbData);
295
bc558f3e
JB
296 if ((RegQueryValueEx (hrootkey, key, NULL, type, result, &cbData) != ERROR_SUCCESS)
297 || (*result == 0))
7ce8671d
JB
298 {
299 free (result);
300 result = NULL;
301 }
302 }
303
304 RegCloseKey (hrootkey);
305 }
306
307 return result;
308}
309
310/*
311 getenv wrapper for Windows
312
a54af40e
EZ
313 Value is allocated on the heap, and can be free'd.
314
315 This is needed to duplicate Emacs's behavior, which is to look for
316 environment variables in the registry if they don't appear in the
317 environment. */
7ce8671d 318char *
7c3320d8 319w32_getenv (char *envvar)
7ce8671d
JB
320{
321 char *value;
322 DWORD dwType;
323
657d08d3 324 if ((value = getenv (envvar)))
a54af40e
EZ
325 /* Found in the environment. strdup it, because values returned
326 by getenv cannot be free'd. */
327 return xstrdup (value);
7ce8671d
JB
328
329 if (! (value = w32_get_resource (HKEY_CURRENT_USER, envvar, &dwType)) &&
330 ! (value = w32_get_resource (HKEY_LOCAL_MACHINE, envvar, &dwType)))
d41784ee
EZ
331 {
332 /* "w32console" is what Emacs on Windows uses for tty-type under -nw. */
333 if (strcmp (envvar, "TERM") == 0)
a54af40e 334 return xstrdup ("w32console");
d41784ee
EZ
335 /* Found neither in the environment nor in the registry. */
336 return NULL;
337 }
7ce8671d
JB
338
339 if (dwType == REG_SZ)
340 /* Registry; no need to expand. */
341 return value;
342
343 if (dwType == REG_EXPAND_SZ)
344 {
345 DWORD size;
346
657d08d3 347 if ((size = ExpandEnvironmentStrings (value, NULL, 0)))
7ce8671d
JB
348 {
349 char *buffer = (char *) xmalloc (size);
350 if (ExpandEnvironmentStrings (value, buffer, size))
351 {
352 /* Found and expanded. */
353 free (value);
354 return buffer;
355 }
356
357 /* Error expanding. */
358 free (buffer);
359 }
360 }
361
362 /* Not the right type, or not correctly expanded. */
363 free (value);
364 return NULL;
365}
366
ff90fbde 367
42073bfb 368int
7c3320d8 369w32_window_app (void)
42073bfb
JB
370{
371 static int window_app = -1;
372 char szTitle[MAX_PATH];
373
374 if (window_app < 0)
dbf60b07
JR
375 {
376 /* Checking for STDOUT does not work; it's a valid handle also in
377 nonconsole apps. Testing for the console title seems to work. */
378 window_app = (GetConsoleTitleA (szTitle, MAX_PATH) == 0);
379 if (window_app)
361358ea 380 InitCommonControls ();
dbf60b07 381 }
42073bfb
JB
382
383 return window_app;
384}
105faa84 385
79432772 386/* execvp wrapper for Windows. Quotes arguments with embedded spaces.
105faa84
DN
387
388 This is necessary due to the broken implementation of exec* routines in
389 the Microsoft libraries: they concatenate the arguments together without
390 quoting special characters, and pass the result to CreateProcess, with
7c3320d8 391 predictably bad results. By contrast, POSIX execvp passes the arguments
79432772
JB
392 directly into the argv array of the child process. */
393
105faa84 394int
7c3320d8 395w32_execvp (const char *path, char **argv)
105faa84
DN
396{
397 int i;
ad0a19b7 398 extern int execvp (const char*, char **);
105faa84
DN
399
400 /* Required to allow a .BAT script as alternate editor. */
401 argv[0] = (char *) alternate_editor;
402
403 for (i = 0; argv[i]; i++)
404 if (strchr (argv[i], ' '))
405 {
406 char *quoted = alloca (strlen (argv[i]) + 3);
407 sprintf (quoted, "\"%s\"", argv[i]);
408 argv[i] = quoted;
409 }
410
411 return execvp (path, argv);
412}
413
414#undef execvp
415#define execvp w32_execvp
416
d41784ee
EZ
417/* Emulation of ttyname for Windows. */
418char *
419ttyname (int fd)
420{
421 return "CONOUT$";
422}
423
105faa84 424#endif /* WINDOWSNT */
42073bfb 425
f387c1ee
JB
426/* Display a normal or error message.
427 On Windows, use a message box if compiled as a Windows app. */
96c06863 428static void message (bool, const char *, ...) ATTRIBUTE_FORMAT_PRINTF (2, 3);
b23b5a5b 429static void
96c06863 430message (bool is_error, const char *format, ...)
42073bfb 431{
42073bfb
JB
432 va_list args;
433
b0bbc07d 434 va_start (args, format);
42073bfb
JB
435
436#ifdef WINDOWSNT
437 if (w32_window_app ())
438 {
17107bb6
PE
439 char msg[2048];
440 vsnprintf (msg, sizeof msg, format, args);
441 msg[sizeof msg - 1] = '\0';
442
42073bfb
JB
443 if (is_error)
444 MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
445 else
446 MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
447 }
448 else
449#endif
9219db75
JB
450 {
451 FILE *f = is_error ? stderr : stdout;
452
17107bb6 453 vfprintf (f, format, args);
9219db75
JB
454 fflush (f);
455 }
17107bb6
PE
456
457 va_end (args);
42073bfb
JB
458}
459
8f9aaa0a 460/* Decode the options from argv and argc.
5212210c 461 The global variable `optind' will say how many arguments we used up. */
8f9aaa0a 462
b23b5a5b 463static void
873fbd0b 464decode_options (int argc, char **argv)
8f9aaa0a 465{
7ce8671d 466 alternate_editor = egetenv ("ALTERNATE_EDITOR");
0ea5797a 467
8f9aaa0a
RS
468 while (1)
469 {
dc1cd5f7 470 int opt = getopt_long_only (argc, argv,
b03d27bd 471#ifndef NO_SOCKETS_IN_FILE_SYSTEM
3794a2d3 472 "VHneqa:s:f:d:F:tc",
b03d27bd 473#else
3794a2d3 474 "VHneqa:f:d:F:tc",
b03d27bd 475#endif
974b73e8 476 longopts, 0);
8f9aaa0a
RS
477
478 if (opt == EOF)
479 break;
480
481 switch (opt)
482 {
483 case 0:
484 /* If getopt returns 0, then it has already processed a
485 long-named option. We should do nothing. */
486 break;
e69233c2 487
97e3214d
GM
488 case 'a':
489 alternate_editor = optarg;
490 break;
e69233c2 491
b03d27bd 492#ifndef NO_SOCKETS_IN_FILE_SYSTEM
254107e4
RS
493 case 's':
494 socket_name = optarg;
495 break;
b03d27bd 496#endif
254107e4 497
aa0b6932
JB
498 case 'f':
499 server_file = optarg;
500 break;
254107e4 501
0ea5797a
SM
502 /* We used to disallow this argument in w32, but it seems better
503 to allow it, for the occasional case where the user is
504 connecting with a w32 client to a server compiled with X11
505 support. */
30be2360
SM
506 case 'd':
507 display = optarg;
508 break;
509
8f9aaa0a
RS
510 case 'n':
511 nowait = 1;
512 break;
513
30be2360
SM
514 case 'e':
515 eval = 1;
516 break;
517
0b973fc5
DW
518 case 'q':
519 quiet = 1;
520 break;
521
8f9aaa0a 522 case 'V':
96c06863 523 message (false, "emacsclient %s\n", VERSION);
65396510 524 exit (EXIT_SUCCESS);
8f9aaa0a 525 break;
46cec291 526
819b8f00 527 case 't':
77134727 528 tty = 1;
c1b8e896 529 current_frame = 0;
77134727
KL
530 break;
531
e5299d8d 532 case 'c':
31fa6595 533 current_frame = 0;
9628b887 534 break;
0b0d3e0b 535
0191e222
CY
536 case 'p':
537 parent_id = optarg;
538 current_frame = 0;
539 break;
540
8f9aaa0a 541 case 'H':
8f9aaa0a 542 print_help_and_exit ();
20c396e8
JB
543 break;
544
18a4ce5e
AR
545 case 'F':
546 frame_parameters = optarg;
547 break;
548
20c396e8 549 default:
96c06863 550 message (true, "Try `%s --help' for more information\n", progname);
65396510 551 exit (EXIT_FAILURE);
20c396e8 552 break;
8f9aaa0a
RS
553 }
554 }
9628b887 555
273b9028
CY
556 /* If the -c option is used (without -t) and no --display argument
557 is provided, try $DISPLAY.
558 Without the -c option, we used to set `display' to $DISPLAY by
559 default, but this changed the default behavior and is sometimes
560 inconvenient. So we force users to use "--display $DISPLAY" if
6b59694e
DC
561 they want Emacs to connect to their current display.
562
563 Some window systems have a notion of default display not
564 reflected in the DISPLAY variable. If the user didn't give us an
565 explicit display, try this platform-specific after trying the
566 display in DISPLAY (if any). */
09317bf4 567 if (!current_frame && !tty && !display)
e7534fc4 568 {
6b59694e
DC
569 /* Set these here so we use a default_display only when the user
570 didn't give us an explicit display. */
571#if defined (NS_IMPL_COCOA)
572 alt_display = "ns";
573#elif defined (HAVE_NTGUI)
efc3dd3c 574 alt_display = "w32";
e7534fc4 575#endif
6b59694e
DC
576
577 display = egetenv ("DISPLAY");
578 }
579
580 if (!display)
581 {
582 display = alt_display;
583 alt_display = NULL;
e7534fc4 584 }
9997dc15 585
273b9028 586 /* A null-string display is invalid. */
0ea5797a
SM
587 if (display && strlen (display) == 0)
588 display = NULL;
589
273b9028
CY
590 /* If no display is available, new frames are tty frames. */
591 if (!current_frame && !display)
92071250 592 tty = 1;
c0f342ab 593
802bdb3c 594#ifdef WINDOWSNT
9a864fa2
CY
595 /* Emacs on Windows does not support graphical and text terminal
596 frames in the same instance. So, treat the -t and -c options as
597 equivalent, and open a new frame on the server's terminal.
598 Ideally, we would only set tty = 1 when the serve is running in a
599 console, but alas we don't know that. As a workaround, always
600 ask for a tty frame, and let server.el figure it out. */
601 if (!current_frame)
602 {
603 display = NULL;
604 tty = 1;
605 }
606
69157c99 607 if (alternate_editor && alternate_editor[0] == '\0')
802bdb3c 608 {
96c06863 609 message (true, "--alternate-editor argument or ALTERNATE_EDITOR variable cannot be\n\
802bdb3c
DN
610an empty string");
611 exit (EXIT_FAILURE);
612 }
613#endif /* WINDOWSNT */
8f9aaa0a
RS
614}
615
974b73e8 616\f
845ca893 617static _Noreturn void
873fbd0b 618print_help_and_exit (void)
8f9aaa0a 619{
c0f342ab
JB
620 /* Spaces and tabs are significant in this message; they're chosen so the
621 message aligns properly both in a tty and in a Windows message box.
622 Please try to preserve them; otherwise the output is very hard to read
623 when using emacsclientw. */
96c06863 624 message (false,
29abe551 625 "Usage: %s [OPTIONS] FILE...\n%s%s%s", progname, "\
30be2360
SM
626Tell the Emacs server to visit the specified files.\n\
627Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
20c396e8 628\n\
30be2360 629The following OPTIONS are accepted:\n\
c0f342ab
JB
630-V, --version Just print version info and return\n\
631-H, --help Print this usage information message\n\
dc1cd5f7 632-nw, -t, --tty Open a new Emacs frame on the current terminal\n\
c4b858e3 633-c, --create-frame Create a new frame instead of trying to\n\
9dfda22f 634 use the current Emacs frame\n\
29abe551 635", "\
a150502a 636-F ALIST, --frame-parameters=ALIST\n\
5f9388d0 637 Set the parameters of a new frame\n\
c0f342ab 638-e, --eval Evaluate the FILE arguments as ELisp expressions\n\
d07529f3 639-n, --no-wait Don't wait for the server to return\n\
0b973fc5 640-q, --quiet Don't display messages on success\n\
24d5010d 641-d DISPLAY, --display=DISPLAY\n\
0191e222 642 Visit the file in the given display\n\
29abe551 643", "\
0191e222 644--parent-id=ID Open in parent window ID, via XEmbed\n"
aa0b6932 645#ifndef NO_SOCKETS_IN_FILE_SYSTEM
24d5010d 646"-s SOCKET, --socket-name=SOCKET\n\
9dfda22f 647 Set filename of the UNIX socket for communication\n"
aa0b6932 648#endif
24d5010d 649"-f SERVER, --server-file=SERVER\n\
9dfda22f 650 Set filename of the TCP authentication file\n\
24d5010d 651-a EDITOR, --alternate-editor=EDITOR\n\
9dfda22f 652 Editor to fallback to if the server is not running\n"
6133a1a9 653#ifndef WINDOWSNT
c3f995a2
JB
654" If EDITOR is the empty string, start Emacs in daemon\n\
655 mode and try connecting again\n"
6133a1a9 656#endif /* not WINDOWSNT */
c3f995a2 657"\n\
29abe551 658Report bugs with M-x report-emacs-bug.\n");
65396510 659 exit (EXIT_SUCCESS);
8f9aaa0a 660}
5212210c 661
79432772
JB
662/* Try to run a different command, or --if no alternate editor is
663 defined-- exit with an errorcode.
664 Uses argv, but gets it from the global variable main_argv. */
665
845ca893 666static _Noreturn void
974b73e8 667fail (void)
9002956f 668{
aa0b6932 669 if (alternate_editor)
9002956f 670 {
aa0b6932 671 int i = optind - 1;
4472aef4 672
974b73e8 673 execvp (alternate_editor, main_argv + i);
96c06863 674 message (true, "%s: error executing alternate editor \"%s\"\n",
974b73e8 675 progname, alternate_editor);
9002956f 676 }
aa0b6932 677 exit (EXIT_FAILURE);
9002956f
KL
678}
679
aa0b6932 680\f
1e7823d0 681#if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
9002956f 682
aa0b6932 683int
0613f5d5 684main (int argc, char **argv)
9002956f 685{
974b73e8
KL
686 main_argv = argv;
687 progname = argv[0];
96c06863 688 message (true, "%s: Sorry, the Emacs server is supported only\n"
c0f342ab 689 "on systems with Berkeley sockets.\n",
aa0b6932 690 argv[0]);
974b73e8 691 fail ();
9002956f
KL
692}
693
1e7823d0 694#else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
2828d5f9 695
aa0b6932
JB
696#define AUTH_KEY_LENGTH 64
697#define SEND_BUFFER_SIZE 4096
698
aa0b6932
JB
699/* Buffer to accumulate data to send in TCP connections. */
700char send_buffer[SEND_BUFFER_SIZE + 1];
701int sblen = 0; /* Fill pointer for the send buffer. */
4b7b77f6
JR
702/* Socket used to communicate with the Emacs server process. */
703HSOCKET emacs_socket = 0;
aa0b6932 704
79432772
JB
705/* On Windows, the socket library was historically separate from the
706 standard C library, so errors are handled differently. */
707
b23b5a5b 708static void
988e88ab 709sock_err_message (const char *function_name)
d22b00e5
JR
710{
711#ifdef WINDOWSNT
712 char* msg = NULL;
713
714 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
715 | FORMAT_MESSAGE_ALLOCATE_BUFFER
716 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
717 NULL, WSAGetLastError (), 0, (LPTSTR)&msg, 0, NULL);
718
96c06863 719 message (true, "%s: %s: %s\n", progname, function_name, msg);
d22b00e5
JR
720
721 LocalFree (msg);
722#else
96c06863 723 message (true, "%s: %s: %s\n", progname, function_name, strerror (errno));
d22b00e5
JR
724#endif
725}
726
727
aa0b6932
JB
728/* Let's send the data to Emacs when either
729 - the data ends in "\n", or
730 - the buffer is full (but this shouldn't happen)
731 Otherwise, we just accumulate it. */
b23b5a5b 732static void
988e88ab 733send_to_emacs (HSOCKET s, const char *data)
aa0b6932 734{
1e6f32f8
JM
735 size_t dlen;
736
737 if (!data)
738 return;
739
740 dlen = strlen (data);
741 while (*data)
2828d5f9 742 {
1e6f32f8
JM
743 size_t part = min (dlen, SEND_BUFFER_SIZE - sblen);
744 memcpy (&send_buffer[sblen], data, part);
745 data += part;
746 sblen += part;
aa0b6932
JB
747
748 if (sblen == SEND_BUFFER_SIZE
749 || (sblen > 0 && send_buffer[sblen-1] == '\n'))
750 {
751 int sent = send (s, send_buffer, sblen, 0);
1e6f32f8
JM
752 if (sent < 0)
753 {
96c06863 754 message (true, "%s: failed to send %d bytes to socket: %s\n",
1e6f32f8
JM
755 progname, sblen, strerror (errno));
756 fail ();
757 }
aa0b6932 758 if (sent != sblen)
1e6f32f8 759 memmove (send_buffer, &send_buffer[sent], sblen - sent);
aa0b6932
JB
760 sblen -= sent;
761 }
1e6f32f8
JM
762
763 dlen -= part;
2828d5f9 764 }
2828d5f9 765}
2828d5f9
KL
766
767\f
0b0d3e0b 768/* In STR, insert a & before each &, each space, each newline, and
a4cf2096 769 any initial -. Change spaces to underscores, too, so that the
0b0d3e0b
KL
770 return value never contains a space.
771
3a35a84c 772 Does not change the string. Outputs the result to S. */
b23b5a5b 773static void
988e88ab 774quote_argument (HSOCKET s, const char *str)
5212210c 775{
9002956f 776 char *copy = (char *) xmalloc (strlen (str) * 2 + 1);
988e88ab
J
777 const char *p;
778 char *q;
5212210c 779
0b0d3e0b 780 p = str;
5212210c
RS
781 q = copy;
782 while (*p)
783 {
784 if (*p == ' ')
785 {
f1db6a73 786 *q++ = '&';
5212210c
RS
787 *q++ = '_';
788 p++;
789 }
3cf8c6aa
SM
790 else if (*p == '\n')
791 {
792 *q++ = '&';
793 *q++ = 'n';
794 p++;
795 }
5212210c
RS
796 else
797 {
0b0d3e0b 798 if (*p == '&' || (*p == '-' && p == str))
f1db6a73 799 *q++ = '&';
5212210c
RS
800 *q++ = *p++;
801 }
802 }
f1db6a73 803 *q++ = 0;
5212210c 804
486ba65f 805 send_to_emacs (s, copy);
87209357
EZ
806
807 free (copy);
5212210c 808}
0c76956f 809
0b0d3e0b
KL
810
811/* The inverse of quote_argument. Removes quoting in string STR by
79432772 812 modifying the string in place. Returns STR. */
0b0d3e0b 813
b23b5a5b 814static char *
873fbd0b 815unquote_argument (char *str)
0b0d3e0b
KL
816{
817 char *p, *q;
818
819 if (! str)
820 return str;
821
822 p = str;
823 q = str;
824 while (*p)
825 {
826 if (*p == '&')
827 {
828 p++;
829 if (*p == '&')
830 *p = '&';
831 else if (*p == '_')
832 *p = ' ';
833 else if (*p == 'n')
834 *p = '\n';
835 else if (*p == '-')
836 *p = '-';
837 }
838 *q++ = *p++;
839 }
840 *q = 0;
841 return str;
842}
843
8f9aaa0a 844\f
b23b5a5b 845static int
03fc768b 846file_name_absolute_p (const char *filename)
b03d27bd
JB
847{
848 /* Sanity check, it shouldn't happen. */
96c06863 849 if (! filename) return false;
b03d27bd
JB
850
851 /* /xxx is always an absolute path. */
96c06863 852 if (filename[0] == '/') return true;
b03d27bd
JB
853
854 /* Empty filenames (which shouldn't happen) are relative. */
96c06863 855 if (filename[0] == '\0') return false;
b03d27bd
JB
856
857#ifdef WINDOWSNT
71b8f735 858 /* X:\xxx is always absolute. */
03fc768b 859 if (isalpha ((unsigned char) filename[0])
cb0297bb 860 && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
96c06863 861 return true;
b03d27bd
JB
862
863 /* Both \xxx and \\xxx\yyy are absolute. */
96c06863 864 if (filename[0] == '\\') return true;
b03d27bd
JB
865#endif
866
96c06863 867 return false;
b03d27bd
JB
868}
869
aa0b6932 870#ifdef WINDOWSNT
f0384499 871/* Wrapper to make WSACleanup a cdecl, as required by atexit. */
7c3320d8
JB
872void __cdecl
873close_winsock (void)
aa0b6932
JB
874{
875 WSACleanup ();
876}
0c76956f 877
b03d27bd
JB
878/* Initialize the WinSock2 library. */
879void
7c3320d8 880initialize_sockets (void)
0c76956f 881{
aa0b6932
JB
882 WSADATA wsaData;
883
aa0b6932
JB
884 if (WSAStartup (MAKEWORD (2, 0), &wsaData))
885 {
96c06863 886 message (true, "%s: error initializing WinSock2\n", progname);
aa0b6932
JB
887 exit (EXIT_FAILURE);
888 }
889
890 atexit (close_winsock);
0c76956f 891}
e35fc962 892#endif /* WINDOWSNT */
974b73e8 893
8f9aaa0a 894\f
79432772
JB
895/* Read the information needed to set up a TCP comm channel with
896 the Emacs server: host, port, and authentication string. */
897
b23b5a5b 898static int
6b0c8984
AS
899get_server_config (const char *config_file, struct sockaddr_in *server,
900 char *authentication)
97e3214d 901{
aa0b6932
JB
902 char dotted[32];
903 char *port;
b03d27bd 904 FILE *config = NULL;
aa0b6932 905
6b0c8984
AS
906 if (file_name_absolute_p (config_file))
907 config = fopen (config_file, "rb");
b03d27bd 908 else
97e3214d 909 {
b9170155 910 const char *home = egetenv ("HOME");
88b46d84 911
aa0b6932
JB
912 if (home)
913 {
6b0c8984 914 char *path = xmalloc (strlen (home) + strlen (config_file)
17107bb6
PE
915 + EXTRA_SPACE);
916 strcpy (path, home);
917 strcat (path, "/.emacs.d/server/");
6b0c8984 918 strcat (path, config_file);
aa0b6932 919 config = fopen (path, "rb");
17107bb6 920 free (path);
aa0b6932 921 }
88b46d84 922#ifdef WINDOWSNT
7ce8671d 923 if (!config && (home = egetenv ("APPDATA")))
88b46d84 924 {
6b0c8984 925 char *path = xmalloc (strlen (home) + strlen (config_file)
17107bb6
PE
926 + EXTRA_SPACE);
927 strcpy (path, home);
928 strcat (path, "/.emacs.d/server/");
6b0c8984 929 strcat (path, config_file);
88b46d84 930 config = fopen (path, "rb");
17107bb6 931 free (path);
88b46d84
JB
932 }
933#endif
aa0b6932
JB
934 }
935
936 if (! config)
96c06863 937 return false;
aa0b6932
JB
938
939 if (fgets (dotted, sizeof dotted, config)
968ef9b4
JB
940 && (port = strchr (dotted, ':')))
941 *port++ = '\0';
97e3214d
GM
942 else
943 {
96c06863 944 message (true, "%s: invalid configuration info\n", progname);
65396510 945 exit (EXIT_FAILURE);
97e3214d 946 }
97e3214d 947
aa0b6932
JB
948 server->sin_family = AF_INET;
949 server->sin_addr.s_addr = inet_addr (dotted);
950 server->sin_port = htons (atoi (port));
97e3214d 951
aa0b6932
JB
952 if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
953 {
96c06863 954 message (true, "%s: cannot read authentication info\n", progname);
aa0b6932
JB
955 exit (EXIT_FAILURE);
956 }
46cec291 957
aa0b6932 958 fclose (config);
97e3214d 959
96c06863 960 return true;
97e3214d
GM
961}
962
b23b5a5b 963static HSOCKET
6b0c8984 964set_tcp_socket (const char *local_server_file)
aa0b6932
JB
965{
966 HSOCKET s;
967 struct sockaddr_in server;
aa0b6932
JB
968 struct linger l_arg = {1, 1};
969 char auth_string[AUTH_KEY_LENGTH + 1];
9628b887 970
6b0c8984 971 if (! get_server_config (local_server_file, &server, auth_string))
aa0b6932
JB
972 return INVALID_SOCKET;
973
0b973fc5 974 if (server.sin_addr.s_addr != inet_addr ("127.0.0.1") && !quiet)
96c06863 975 message (false, "%s: connected to remote socket at %s\n",
b03d27bd
JB
976 progname, inet_ntoa (server.sin_addr));
977
79432772 978 /* Open up an AF_INET socket. */
aa0b6932
JB
979 if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
980 {
d22b00e5 981 sock_err_message ("socket");
aa0b6932
JB
982 return INVALID_SOCKET;
983 }
984
79432772 985 /* Set up the socket. */
aa0b6932
JB
986 if (connect (s, (struct sockaddr *) &server, sizeof server) < 0)
987 {
d22b00e5 988 sock_err_message ("connect");
aa0b6932
JB
989 return INVALID_SOCKET;
990 }
991
aa0b6932
JB
992 setsockopt (s, SOL_SOCKET, SO_LINGER, (char *) &l_arg, sizeof l_arg);
993
79432772 994 /* Send the authentication. */
aa0b6932
JB
995 auth_string[AUTH_KEY_LENGTH] = '\0';
996
486ba65f
JR
997 send_to_emacs (s, "-auth ");
998 send_to_emacs (s, auth_string);
5ab73228 999 send_to_emacs (s, " ");
aa0b6932
JB
1000
1001 return s;
1002}
1003
b2ff54a0
JR
1004
1005/* Returns 1 if PREFIX is a prefix of STRING. */
1006static int
988e88ab 1007strprefix (const char *prefix, const char *string)
b2ff54a0 1008{
cb06b8dc 1009 return !strncmp (prefix, string, strlen (prefix));
b2ff54a0
JR
1010}
1011
a336ee5b
CY
1012/* Get tty name and type. If successful, return the type in TTY_TYPE
1013 and the name in TTY_NAME, and return 1. Otherwise, fail if NOABORT
1014 is zero, or return 0 if NOABORT is non-zero. */
1015
b23b5a5b 1016static int
b9170155 1017find_tty (const char **tty_type, const char **tty_name, int noabort)
a336ee5b 1018{
b9170155
PE
1019 const char *type = egetenv ("TERM");
1020 const char *name = ttyname (fileno (stdout));
a336ee5b
CY
1021
1022 if (!name)
1023 {
1024 if (noabort)
1025 return 0;
1026 else
1027 {
96c06863 1028 message (true, "%s: could not get terminal name\n", progname);
a336ee5b
CY
1029 fail ();
1030 }
1031 }
1032
1033 if (!type)
1034 {
1035 if (noabort)
1036 return 0;
1037 else
1038 {
96c06863 1039 message (true, "%s: please set the TERM variable to your terminal type\n",
a336ee5b
CY
1040 progname);
1041 fail ();
1042 }
1043 }
1044
1045 if (strcmp (type, "eterm") == 0)
1046 {
1047 if (noabort)
1048 return 0;
1049 else
1050 {
1051 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
96c06863 1052 message (true, "%s: opening a frame in an Emacs term buffer"
a336ee5b
CY
1053 " is not supported\n", progname);
1054 fail ();
1055 }
1056 }
1057
1058 *tty_name = name;
1059 *tty_type = type;
1060 return 1;
1061}
1062
b2ff54a0 1063
aa0b6932 1064#if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
46cec291 1065
9f637eea
GM
1066/* Three possibilities:
1067 2 - can't be `stat'ed (sets errno)
1068 1 - isn't owned by us
1069 0 - success: none of the above */
1070
1071static int
fe91f5a0 1072socket_status (const char *name)
9f637eea
GM
1073{
1074 struct stat statbfr;
1075
b0bbc07d 1076 if (stat (name, &statbfr) == -1)
9f637eea
GM
1077 return 2;
1078
1079 if (statbfr.st_uid != geteuid ())
1080 return 1;
0b0d3e0b 1081
9f637eea
GM
1082 return 0;
1083}
1084
974b73e8 1085\f
da8e1115
KL
1086/* A signal handler that passes the signal to the Emacs process.
1087 Useful for SIGWINCH. */
1088
9af30bdf 1089static void
428a555e 1090pass_signal_to_emacs (int signalnum)
9628b887
KL
1091{
1092 int old_errno = errno;
1093
9f729af5 1094 if (emacs_pid)
428a555e 1095 kill (emacs_pid, signalnum);
9f729af5 1096
428a555e 1097 signal (signalnum, pass_signal_to_emacs);
9f729af5
KL
1098 errno = old_errno;
1099}
1100
0b0d3e0b
KL
1101/* Signal handler for SIGCONT; notify the Emacs process that it can
1102 now resume our tty frame. */
1103
9af30bdf 1104static void
0b0d3e0b
KL
1105handle_sigcont (int signalnum)
1106{
1107 int old_errno = errno;
d050de75
PE
1108 pid_t pgrp = getpgrp ();
1109 pid_t tcpgrp = tcgetpgrp (1);
0b0d3e0b 1110
d050de75 1111 if (tcpgrp == pgrp)
0b0d3e0b 1112 {
591debed 1113 /* We are in the foreground. */
486ba65f 1114 send_to_emacs (emacs_socket, "-resume \n");
0b0d3e0b 1115 }
d050de75 1116 else if (0 <= tcpgrp && tty)
0b0d3e0b 1117 {
591debed 1118 /* We are in the background; cancel the continue. */
d050de75 1119 kill (-pgrp, SIGTTIN);
0b0d3e0b 1120 }
c6c53c3e
KL
1121
1122 signal (signalnum, handle_sigcont);
0b0d3e0b
KL
1123 errno = old_errno;
1124}
1125
1126/* Signal handler for SIGTSTP; notify the Emacs process that we are
1127 going to sleep. Normally the suspend is initiated by Emacs via
1128 server-handle-suspend-tty, but if the server gets out of sync with
1129 reality, we may get a SIGTSTP on C-z. Handling this signal and
79432772 1130 notifying Emacs about it should get things under control again. */
0b0d3e0b 1131
9af30bdf 1132static void
0b0d3e0b
KL
1133handle_sigtstp (int signalnum)
1134{
1135 int old_errno = errno;
1136 sigset_t set;
c0f342ab 1137
90843190 1138 if (emacs_socket)
486ba65f 1139 send_to_emacs (emacs_socket, "-suspend \n");
0b0d3e0b 1140
5ab73228 1141 /* Unblock this signal and call the default handler by temporarily
8350f087 1142 changing the handler and resignaling. */
0b0d3e0b
KL
1143 sigprocmask (SIG_BLOCK, NULL, &set);
1144 sigdelset (&set, signalnum);
1145 signal (signalnum, SIG_DFL);
a7db35b3 1146 raise (signalnum);
0b0d3e0b
KL
1147 sigprocmask (SIG_SETMASK, &set, NULL); /* Let's the above signal through. */
1148 signal (signalnum, handle_sigtstp);
1149
1150 errno = old_errno;
1151}
273b9028
CY
1152
1153
da8e1115 1154/* Set up signal handlers before opening a frame on the current tty. */
0b0d3e0b 1155
b23b5a5b 1156static void
4d553a13 1157init_signals (void)
9628b887
KL
1158{
1159 /* Set up signal handlers. */
428a555e 1160 signal (SIGWINCH, pass_signal_to_emacs);
4ca927b4
KL
1161
1162 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
1163 deciding which terminal the signal came from. C-g is now a
1164 normal input event on secondary terminals. */
1165#if 0
428a555e
KL
1166 signal (SIGINT, pass_signal_to_emacs);
1167 signal (SIGQUIT, pass_signal_to_emacs);
4ca927b4 1168#endif
0b0d3e0b
KL
1169
1170 signal (SIGCONT, handle_sigcont);
1171 signal (SIGTSTP, handle_sigtstp);
1172 signal (SIGTTOU, handle_sigtstp);
9628b887
KL
1173}
1174
46cec291 1175
b23b5a5b 1176static HSOCKET
6b0c8984 1177set_local_socket (const char *local_socket_name)
46cec291 1178{
aa0b6932 1179 HSOCKET s;
46cec291 1180 struct sockaddr_un server;
46cec291 1181
79432772 1182 /* Open up an AF_UNIX socket in this person's home directory. */
46cec291
RS
1183 if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
1184 {
96c06863 1185 message (true, "%s: socket: %s\n", progname, strerror (errno));
aa0b6932 1186 return INVALID_SOCKET;
46cec291 1187 }
e69233c2 1188
46cec291 1189 server.sun_family = AF_UNIX;
c5fee545 1190
c5fee545 1191 {
6b0c8984
AS
1192 int sock_status;
1193 int use_tmpdir = 0;
1194 int saved_errno;
1195 const char *server_name = local_socket_name;
4be3dfc5 1196 const char *tmpdir IF_LINT ( = NULL);
17107bb6
PE
1197 char *tmpdir_storage = NULL;
1198 char *socket_name_storage = NULL;
0b0d3e0b 1199
6b0c8984 1200 if (!strchr (local_socket_name, '/') && !strchr (local_socket_name, '\\'))
8966b757
AS
1201 {
1202 /* socket_name is a file name component. */
17107bb6
PE
1203 long uid = geteuid ();
1204 ptrdiff_t tmpdirlen;
6b0c8984 1205 use_tmpdir = 1;
f77b11a0
JB
1206 tmpdir = egetenv ("TMPDIR");
1207 if (!tmpdir)
b336bfcd
GM
1208 {
1209#ifdef DARWIN_OS
e6068ab3
YM
1210#ifndef _CS_DARWIN_USER_TEMP_DIR
1211#define _CS_DARWIN_USER_TEMP_DIR 65537
1212#endif
b336bfcd
GM
1213 size_t n = confstr (_CS_DARWIN_USER_TEMP_DIR, NULL, (size_t) 0);
1214 if (n > 0)
1215 {
17107bb6 1216 tmpdir = tmpdir_storage = xmalloc (n);
dd1ff7c0 1217 confstr (_CS_DARWIN_USER_TEMP_DIR, tmpdir_storage, n);
b336bfcd
GM
1218 }
1219 else
1220#endif
1221 tmpdir = "/tmp";
1222 }
17107bb6 1223 tmpdirlen = strlen (tmpdir);
6b0c8984 1224 socket_name_storage =
17107bb6 1225 xmalloc (tmpdirlen + strlen (server_name) + EXTRA_SPACE);
6b0c8984
AS
1226 strcpy (socket_name_storage, tmpdir);
1227 sprintf (socket_name_storage + tmpdirlen, "/emacs%ld/", uid);
1228 strcat (socket_name_storage + tmpdirlen, server_name);
1229 local_socket_name = socket_name_storage;
254107e4
RS
1230 }
1231
6b0c8984
AS
1232 if (strlen (local_socket_name) < sizeof (server.sun_path))
1233 strcpy (server.sun_path, local_socket_name);
254107e4 1234 else
819b8f00 1235 {
96c06863 1236 message (true, "%s: socket-name %s too long\n",
6b0c8984 1237 progname, local_socket_name);
819b8f00
KL
1238 fail ();
1239 }
efb859b4 1240
9f637eea
GM
1241 /* See if the socket exists, and if it's owned by us. */
1242 sock_status = socket_status (server.sun_path);
152b6e83 1243 saved_errno = errno;
6b0c8984 1244 if (sock_status && use_tmpdir)
efb859b4 1245 {
9f637eea
GM
1246 /* Failing that, see if LOGNAME or USER exist and differ from
1247 our euid. If so, look for a socket based on the UID
1248 associated with the name. This is reminiscent of the logic
1249 that init_editfns uses to set the global Vuser_full_name. */
e69233c2 1250
b9170155 1251 const char *user_name = egetenv ("LOGNAME");
293f9f2a 1252
9f637eea 1253 if (!user_name)
b9170155 1254 user_name = egetenv ("USER");
e69233c2 1255
9f637eea
GM
1256 if (user_name)
1257 {
1258 struct passwd *pw = getpwnam (user_name);
293f9f2a 1259
9f637eea
GM
1260 if (pw && (pw->pw_uid != geteuid ()))
1261 {
1262 /* We're running under su, apparently. */
17107bb6
PE
1263 long uid = pw->pw_uid;
1264 ptrdiff_t tmpdirlen = strlen (tmpdir);
6b0c8984
AS
1265 char *user_socket_name
1266 = xmalloc (tmpdirlen + strlen (server_name) + EXTRA_SPACE);
1267 strcpy (user_socket_name, tmpdir);
1268 sprintf (user_socket_name + tmpdirlen, "/emacs%ld/", uid);
1269 strcat (user_socket_name + tmpdirlen, server_name);
1270
1271 if (strlen (user_socket_name) < sizeof (server.sun_path))
1272 strcpy (server.sun_path, user_socket_name);
5c9659d3
SM
1273 else
1274 {
96c06863 1275 message (true, "%s: socket-name %s too long\n",
6b0c8984 1276 progname, user_socket_name);
65396510 1277 exit (EXIT_FAILURE);
5c9659d3 1278 }
6b0c8984 1279 free (user_socket_name);
5c9659d3 1280
9f637eea 1281 sock_status = socket_status (server.sun_path);
b80bf66e 1282 saved_errno = errno;
9f637eea 1283 }
293f9f2a
RS
1284 else
1285 errno = saved_errno;
9f637eea 1286 }
efb859b4 1287 }
e69233c2 1288
17107bb6
PE
1289 free (socket_name_storage);
1290 free (tmpdir_storage);
1291
aa0b6932
JB
1292 switch (sock_status)
1293 {
1294 case 1:
974b73e8
KL
1295 /* There's a socket, but it isn't owned by us. This is OK if
1296 we are root. */
1297 if (0 != geteuid ())
1298 {
96c06863 1299 message (true, "%s: Invalid socket owner\n", progname);
aa0b6932 1300 return INVALID_SOCKET;
974b73e8
KL
1301 }
1302 break;
aa0b6932
JB
1303
1304 case 2:
974b73e8
KL
1305 /* `stat' failed */
1306 if (saved_errno == ENOENT)
96c06863 1307 message (true,
974b73e8 1308 "%s: can't find socket; have you started the server?\n\
45adde32 1309To start the server in Emacs, type \"M-x server-start\".\n",
aa0b6932 1310 progname);
974b73e8 1311 else
96c06863 1312 message (true, "%s: can't stat %s: %s\n",
aa0b6932 1313 progname, server.sun_path, strerror (saved_errno));
974b73e8 1314 return INVALID_SOCKET;
aa0b6932 1315 }
efb859b4 1316 }
46cec291 1317
4e23f2ba
JB
1318 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
1319 < 0)
46cec291 1320 {
96c06863 1321 message (true, "%s: connect: %s\n", progname, strerror (errno));
aa0b6932 1322 return INVALID_SOCKET;
46cec291 1323 }
23a7488d 1324
aa0b6932
JB
1325 return s;
1326}
1327#endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1328
b23b5a5b 1329static HSOCKET
636b507b 1330set_socket (int no_exit_if_error)
aa0b6932 1331{
b03d27bd 1332 HSOCKET s;
6b0c8984 1333 const char *local_server_file = server_file;
c0f342ab 1334
b03d27bd 1335 INITIALIZE ();
c0f342ab 1336
aa0b6932 1337#ifndef NO_SOCKETS_IN_FILE_SYSTEM
b03d27bd
JB
1338 /* Explicit --socket-name argument. */
1339 if (socket_name)
46cec291 1340 {
6b0c8984 1341 s = set_local_socket (socket_name);
636b507b 1342 if ((s != INVALID_SOCKET) || no_exit_if_error)
974b73e8 1343 return s;
96c06863 1344 message (true, "%s: error accessing socket \"%s\"\n",
974b73e8 1345 progname, socket_name);
b03d27bd 1346 exit (EXIT_FAILURE);
46cec291 1347 }
b03d27bd
JB
1348#endif
1349
1350 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
6b0c8984
AS
1351 if (!local_server_file)
1352 local_server_file = egetenv ("EMACS_SERVER_FILE");
46cec291 1353
6b0c8984 1354 if (local_server_file)
23a7488d 1355 {
6b0c8984 1356 s = set_tcp_socket (local_server_file);
636b507b 1357 if ((s != INVALID_SOCKET) || no_exit_if_error)
974b73e8 1358 return s;
c0f342ab 1359
96c06863 1360 message (true, "%s: error accessing server file \"%s\"\n",
6b0c8984 1361 progname, local_server_file);
b03d27bd 1362 exit (EXIT_FAILURE);
23a7488d 1363 }
c0f342ab 1364
b03d27bd
JB
1365#ifndef NO_SOCKETS_IN_FILE_SYSTEM
1366 /* Implicit local socket. */
6b0c8984 1367 s = set_local_socket ("server");
b03d27bd
JB
1368 if (s != INVALID_SOCKET)
1369 return s;
1370#endif
23a7488d 1371
b03d27bd 1372 /* Implicit server file. */
6b0c8984 1373 s = set_tcp_socket ("server");
636b507b 1374 if ((s != INVALID_SOCKET) || no_exit_if_error)
b03d27bd
JB
1375 return s;
1376
1377 /* No implicit or explicit socket, and no alternate editor. */
96c06863 1378 message (true, "%s: No socket or alternate editor. Please use:\n\n"
b03d27bd
JB
1379#ifndef NO_SOCKETS_IN_FILE_SYSTEM
1380"\t--socket-name\n"
ee6a193c 1381#endif
b03d27bd
JB
1382"\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1383\t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1384 progname);
1385 exit (EXIT_FAILURE);
aa0b6932 1386}
46cec291 1387
5e0944c6 1388#ifdef HAVE_NTGUI
0e0dced5
JB
1389FARPROC set_fg; /* Pointer to AllowSetForegroundWindow. */
1390FARPROC get_wc; /* Pointer to RealGetWindowClassA. */
1391
5e0944c6
DC
1392void
1393w32_set_user_model_id (void)
1394{
1395 HMODULE shell;
1396 HRESULT (WINAPI * set_user_model) (wchar_t * id);
1397
1398 /* On Windows 7 and later, we need to set the user model ID
1399 to associate emacsclient launched files with Emacs frames
1400 in the UI. */
1401 shell = LoadLibrary ("shell32.dll");
1402 if (shell)
1403 {
1404 set_user_model
1405 = (void *) GetProcAddress (shell,
1406 "SetCurrentProcessExplicitAppUserModelID");
1407 /* If the function is defined, then we are running on Windows 7
1408 or newer, and the UI uses this to group related windows
1409 together. Since emacs, runemacs, emacsclient are related, we
1410 want them grouped even though the executables are different,
1411 so we need to set a consistent ID between them. */
1412 if (set_user_model)
1413 set_user_model (L"GNU.Emacs");
1414
1415 FreeLibrary (shell);
1416 }
1417}
1418
0e0dced5 1419BOOL CALLBACK
7c3320d8 1420w32_find_emacs_process (HWND hWnd, LPARAM lParam)
0e0dced5
JB
1421{
1422 DWORD pid;
1423 char class[6];
1424
1425 /* Reject any window not of class "Emacs". */
1426 if (! get_wc (hWnd, class, sizeof (class))
1427 || strcmp (class, "Emacs"))
1428 return TRUE;
1429
1430 /* We only need the process id, not the thread id. */
1431 (void) GetWindowThreadProcessId (hWnd, &pid);
1432
1433 /* Not the one we're looking for. */
1434 if (pid != (DWORD) emacs_pid) return TRUE;
1435
1436 /* OK, let's raise it. */
1437 set_fg (emacs_pid);
1438
1439 /* Stop enumeration. */
1440 return FALSE;
1441}
1442
79432772
JB
1443/* Search for a window of class "Emacs" and owned by a process with
1444 process id = emacs_pid. If found, allow it to grab the focus. */
1445
0e0dced5 1446void
7c3320d8 1447w32_give_focus (void)
0e0dced5 1448{
ff90fbde 1449 HANDLE user32;
0e0dced5 1450
71b8f735 1451 /* It shouldn't happen when dealing with TCP sockets. */
0e0dced5
JB
1452 if (!emacs_pid) return;
1453
ff90fbde
JR
1454 user32 = GetModuleHandle ("user32.dll");
1455
1456 if (!user32)
1457 return;
0e0dced5
JB
1458
1459 /* Modern Windows restrict which processes can set the foreground window.
1460 emacsclient can allow Emacs to grab the focus by calling the function
1461 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1462 NT) lack this function, so we have to check its availability. */
ff90fbde
JR
1463 if ((set_fg = GetProcAddress (user32, "AllowSetForegroundWindow"))
1464 && (get_wc = GetProcAddress (user32, "RealGetWindowClassA")))
0e0dced5 1465 EnumWindows (w32_find_emacs_process, (LPARAM) 0);
0e0dced5 1466}
5e0944c6 1467#endif /* HAVE_NTGUI */
0e0dced5 1468
636b507b
DN
1469/* Start the emacs daemon and try to connect to it. */
1470
b23b5a5b 1471static void
636b507b
DN
1472start_daemon_and_retry_set_socket (void)
1473{
802bdb3c 1474#ifndef WINDOWSNT
636b507b
DN
1475 pid_t dpid;
1476 int status;
636b507b
DN
1477
1478 dpid = fork ();
1479
1480 if (dpid > 0)
1481 {
fd95644b
DN
1482 pid_t w;
1483 w = waitpid (dpid, &status, WUNTRACED | WCONTINUED);
636b507b 1484
361358ea 1485 if ((w == -1) || !WIFEXITED (status) || WEXITSTATUS (status))
fd95644b 1486 {
96c06863 1487 message (true, "Error: Could not start the Emacs daemon\n");
fd95644b
DN
1488 exit (EXIT_FAILURE);
1489 }
1490
1491 /* Try connecting, the daemon should have started by now. */
96c06863 1492 message (true, "Emacs daemon should have started, trying to connect again\n");
636b507b 1493 if ((emacs_socket = set_socket (1)) == INVALID_SOCKET)
fd95644b 1494 {
96c06863 1495 message (true, "Error: Cannot connect even after starting the Emacs daemon\n");
fd95644b
DN
1496 exit (EXIT_FAILURE);
1497 }
636b507b
DN
1498 }
1499 else if (dpid < 0)
1500 {
fd95644b 1501 fprintf (stderr, "Error: Cannot fork!\n");
6ab88e02 1502 exit (EXIT_FAILURE);
636b507b
DN
1503 }
1504 else
1505 {
988e88ab 1506 char emacs[] = "emacs";
b0bbc07d 1507 char daemon_option[] = "--daemon";
29abe551
PE
1508 char *d_argv[3];
1509 d_argv[0] = emacs;
1510 d_argv[1] = daemon_option;
1511 d_argv[2] = 0;
636b507b
DN
1512 if (socket_name != NULL)
1513 {
1514 /* Pass --daemon=socket_name as argument. */
988e88ab 1515 const char *deq = "--daemon=";
17107bb6
PE
1516 char *daemon_arg = xmalloc (strlen (deq)
1517 + strlen (socket_name) + 1);
636b507b
DN
1518 strcpy (daemon_arg, deq);
1519 strcat (daemon_arg, socket_name);
1520 d_argv[1] = daemon_arg;
1521 }
1522 execvp ("emacs", d_argv);
96c06863 1523 message (true, "%s: error starting emacs daemon\n", progname);
636b507b 1524 }
802bdb3c 1525#endif /* WINDOWSNT */
636b507b
DN
1526}
1527
aa0b6932 1528int
873fbd0b 1529main (int argc, char **argv)
aa0b6932 1530{
c5443aa5 1531 int rl = 0, needlf = 0;
974b73e8 1532 char *cwd, *str;
aa0b6932 1533 char string[BUFSIZ+1];
4be3dfc5 1534 int start_daemon_if_needed;
3ecb8d93 1535 int exit_status = EXIT_SUCCESS;
aa0b6932 1536
974b73e8 1537 main_argv = argv;
aa0b6932
JB
1538 progname = argv[0];
1539
5e0944c6 1540#ifdef HAVE_NTGUI
6b59694e
DC
1541 /* On Windows 7 and later, we need to explicitly associate
1542 emacsclient with emacs so the UI behaves sensibly. This
1543 association does no harm if we're not actually connecting to an
1544 Emacs using a window display. */
ff90fbde 1545 w32_set_user_model_id ();
5e0944c6 1546#endif /* HAVE_NTGUI */
ff90fbde 1547
aa0b6932
JB
1548 /* Process options. */
1549 decode_options (argc, argv);
1550
273b9028 1551 if ((argc - optind < 1) && !eval && current_frame)
23a7488d 1552 {
96c06863 1553 message (true, "%s: file name or argument required\n"
974b73e8
KL
1554 "Try `%s --help' for more information\n",
1555 progname, progname);
aa0b6932 1556 exit (EXIT_FAILURE);
23a7488d
RS
1557 }
1558
f11352e6 1559#ifndef WINDOWSNT
d050de75
PE
1560 if (tty)
1561 {
1562 pid_t pgrp = getpgrp ();
1563 pid_t tcpgrp = tcgetpgrp (1);
1564 if (0 <= tcpgrp && tcpgrp != pgrp)
1565 kill (-pgrp, SIGTTIN);
1566 }
f11352e6 1567#endif /* !WINDOWSNT */
d050de75 1568
636b507b
DN
1569 /* If alternate_editor is the empty string, start the emacs daemon
1570 in case of failure to connect. */
1571 start_daemon_if_needed = (alternate_editor
1572 && (alternate_editor[0] == '\0'));
aa0b6932 1573
7e6bb4c9
PE
1574 emacs_socket = set_socket (alternate_editor || start_daemon_if_needed);
1575 if (emacs_socket == INVALID_SOCKET)
1576 {
1577 if (! start_daemon_if_needed)
1578 fail ();
1579
7e6bb4c9
PE
1580 start_daemon_and_retry_set_socket ();
1581 }
974b73e8
KL
1582
1583 cwd = get_current_dir_name ();
46cec291
RS
1584 if (cwd == 0)
1585 {
96c06863 1586 message (true, "%s: %s\n", progname,
974b73e8 1587 "Cannot get current working directory");
819b8f00 1588 fail ();
46cec291
RS
1589 }
1590
5e0944c6 1591#ifdef HAVE_NTGUI
efc3dd3c 1592 if (display && !strcmp (display, "w32"))
0e0dced5 1593 w32_give_focus ();
5e0944c6 1594#endif /* HAVE_NTGUI */
c66648e0 1595
273b9028 1596 /* Send over our environment and current directory. */
59e085e0
KL
1597 if (!current_frame)
1598 {
59e085e0
KL
1599 int i;
1600 for (i = 0; environ[i]; i++)
1601 {
486ba65f
JR
1602 send_to_emacs (emacs_socket, "-env ");
1603 quote_argument (emacs_socket, environ[i]);
1604 send_to_emacs (emacs_socket, " ");
59e085e0 1605 }
2828d5f9 1606 }
ba528748
SM
1607 send_to_emacs (emacs_socket, "-dir ");
1608 quote_argument (emacs_socket, cwd);
1609 send_to_emacs (emacs_socket, "/");
1610 send_to_emacs (emacs_socket, " ");
2828d5f9 1611
6afdd335 1612 retry:
5212210c 1613 if (nowait)
486ba65f 1614 send_to_emacs (emacs_socket, "-nowait ");
292d74a3 1615
92071250 1616 if (current_frame)
486ba65f 1617 send_to_emacs (emacs_socket, "-current-frame ");
c0f342ab 1618
30be2360 1619 if (display)
87209357 1620 {
486ba65f
JR
1621 send_to_emacs (emacs_socket, "-display ");
1622 quote_argument (emacs_socket, display);
1623 send_to_emacs (emacs_socket, " ");
87209357 1624 }
30be2360 1625
0191e222
CY
1626 if (parent_id)
1627 {
1628 send_to_emacs (emacs_socket, "-parent-id ");
1629 quote_argument (emacs_socket, parent_id);
1630 send_to_emacs (emacs_socket, " ");
1631 }
1632
18a4ce5e
AR
1633 if (frame_parameters && !current_frame)
1634 {
1635 send_to_emacs (emacs_socket, "-frame-parameters ");
1636 quote_argument (emacs_socket, frame_parameters);
1637 send_to_emacs (emacs_socket, " ");
1638 }
1639
2d0e8e61
CY
1640 /* Unless we are certain we don't want to occupy the tty, send our
1641 tty information to Emacs. For example, in daemon mode Emacs may
1642 need to occupy this tty if no other frame is available. */
1643 if (!current_frame || !eval)
9628b887 1644 {
b9170155 1645 const char *tty_type, *tty_name;
0b0d3e0b 1646
273b9028
CY
1647 if (find_tty (&tty_type, &tty_name, !tty))
1648 {
b2ff54a0 1649#if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
273b9028 1650 init_signals ();
b2ff54a0 1651#endif
273b9028
CY
1652 send_to_emacs (emacs_socket, "-tty ");
1653 quote_argument (emacs_socket, tty_name);
1654 send_to_emacs (emacs_socket, " ");
1655 quote_argument (emacs_socket, tty_type);
1656 send_to_emacs (emacs_socket, " ");
1657 }
9628b887 1658 }
77134727 1659
273b9028 1660 if (!current_frame && !tty)
486ba65f 1661 send_to_emacs (emacs_socket, "-window-system ");
0b0d3e0b 1662
87209357 1663 if ((argc - optind > 0))
5212210c 1664 {
b0bbc07d 1665 int i;
87209357 1666 for (i = optind; i < argc; i++)
46cec291 1667 {
0b0d3e0b 1668
87209357 1669 if (eval)
0b0d3e0b 1670 {
974b73e8 1671 /* Don't prepend cwd or anything like that. */
486ba65f
JR
1672 send_to_emacs (emacs_socket, "-eval ");
1673 quote_argument (emacs_socket, argv[i]);
1674 send_to_emacs (emacs_socket, " ");
0b0d3e0b
KL
1675 continue;
1676 }
1677
1678 if (*argv[i] == '+')
1679 {
87209357
EZ
1680 char *p = argv[i] + 1;
1681 while (isdigit ((unsigned char) *p) || *p == ':') p++;
0b0d3e0b
KL
1682 if (*p == 0)
1683 {
486ba65f
JR
1684 send_to_emacs (emacs_socket, "-position ");
1685 quote_argument (emacs_socket, argv[i]);
1686 send_to_emacs (emacs_socket, " ");
0b0d3e0b
KL
1687 continue;
1688 }
0b0d3e0b 1689 }
6cde1b21
JB
1690#ifdef WINDOWSNT
1691 else if (! file_name_absolute_p (argv[i])
1692 && (isalpha (argv[i][0]) && argv[i][1] == ':'))
1693 /* Windows can have a different default directory for each
1694 drive, so the cwd passed via "-dir" is not sufficient
1695 to account for that.
1696 If the user uses <drive>:<relpath>, we hence need to be
1697 careful to expand <relpath> with the default directory
1698 corresponding to <drive>. */
1699 {
1700 char *filename = (char *) xmalloc (MAX_PATH);
1701 DWORD size;
1702
1703 size = GetFullPathName (argv[i], MAX_PATH, filename, NULL);
1704 if (size > 0 && size < MAX_PATH)
1705 argv[i] = filename;
1706 else
1707 free (filename);
1708 }
1709#endif
0b0d3e0b 1710
486ba65f 1711 send_to_emacs (emacs_socket, "-file ");
486ba65f
JR
1712 quote_argument (emacs_socket, argv[i]);
1713 send_to_emacs (emacs_socket, " ");
0b0d3e0b 1714 }
46cec291 1715 }
273b9028 1716 else if (eval)
87209357 1717 {
273b9028
CY
1718 /* Read expressions interactively. */
1719 while ((str = fgets (string, BUFSIZ, stdin)))
1720 {
1721 send_to_emacs (emacs_socket, "-eval ");
1722 quote_argument (emacs_socket, str);
1723 }
1724 send_to_emacs (emacs_socket, " ");
87209357 1725 }
0b0d3e0b 1726
486ba65f 1727 send_to_emacs (emacs_socket, "\n");
46cec291 1728
fc2040c0 1729 /* Wait for an answer. */
0b973fc5 1730 if (!eval && !tty && !nowait && !quiet)
30be2360
SM
1731 {
1732 printf ("Waiting for Emacs...");
1733 needlf = 2;
1734 }
46cec291 1735 fflush (stdout);
47d7532e
PE
1736 while (fdatasync (1) != 0 && errno == EINTR)
1737 continue;
46cec291 1738
3cf8c6aa 1739 /* Now, wait for an answer and print any messages. */
b166dcd8 1740 while (exit_status == EXIT_SUCCESS)
3cf8c6aa 1741 {
2b84f674 1742 char *p, *end_p;
b166dcd8
KC
1743 do
1744 {
1745 errno = 0;
1746 rl = recv (emacs_socket, string, BUFSIZ, 0);
1747 }
1748 /* If we receive a signal (e.g. SIGWINCH, which we pass
1749 through to Emacs), on some OSes we get EINTR and must retry. */
1750 while (rl < 0 && errno == EINTR);
1751
1752 if (rl <= 0)
1753 break;
b23b5a5b 1754
974b73e8
KL
1755 string[rl] = '\0';
1756
2b84f674
AS
1757 /* Loop over all NL-terminated messages. */
1758 for (end_p = p = string; end_p != NULL && *end_p != '\0'; p = end_p)
1759 {
1760 end_p = strchr (p, '\n');
1761 if (end_p != NULL)
1762 *end_p++ = '\0';
0b0d3e0b 1763
6b59694e
DC
1764 if (strprefix ("-emacs-pid ", p))
1765 {
1766 /* -emacs-pid PID: The process id of the Emacs process. */
1767 emacs_pid = strtol (p + strlen ("-emacs-pid"), NULL, 10);
1768 }
1769 else if (strprefix ("-window-system-unsupported ", p))
1770 {
1771 /* -window-system-unsupported: Emacs was compiled without support
1772 for whatever window system we tried. Try the alternate
1773 display, or, failing that, try the terminal. */
1774 if (alt_display)
1775 {
1776 display = alt_display;
1777 alt_display = NULL;
1778 }
1779 else
1780 {
1781 nowait = 0;
1782 tty = 1;
1783 }
1784
1785 goto retry;
1786 }
1787 else if (strprefix ("-print ", p))
1788 {
1789 /* -print STRING: Print STRING on the terminal. */
1790 str = unquote_argument (p + strlen ("-print "));
1791 if (needlf)
1792 printf ("\n");
1793 printf ("%s", str);
1794 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1795 }
1796 else if (strprefix ("-print-nonl ", p))
1797 {
1798 /* -print-nonl STRING: Print STRING on the terminal.
1799 Used to continue a preceding -print command. */
1800 str = unquote_argument (p + strlen ("-print-nonl "));
1801 printf ("%s", str);
1802 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1803 }
1804 else if (strprefix ("-error ", p))
1805 {
1806 /* -error DESCRIPTION: Signal an error on the terminal. */
1807 str = unquote_argument (p + strlen ("-error "));
1808 if (needlf)
1809 printf ("\n");
1810 fprintf (stderr, "*ERROR*: %s", str);
1811 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1812 exit_status = EXIT_FAILURE;
1813 }
c801ad51 1814#ifdef SIGSTOP
2b84f674
AS
1815 else if (strprefix ("-suspend ", p))
1816 {
1817 /* -suspend: Suspend this terminal, i.e., stop the process. */
1818 if (needlf)
1819 printf ("\n");
1820 needlf = 0;
1821 kill (0, SIGSTOP);
1822 }
b2ff54a0 1823#endif
2b84f674
AS
1824 else
1825 {
1826 /* Unknown command. */
1827 if (needlf)
1828 printf ("\n");
1829 needlf = 0;
1830 printf ("*ERROR*: Unknown message: %s\n", p);
1831 }
1832 }
3cf8c6aa
SM
1833 }
1834
1835 if (needlf)
1836 printf ("\n");
1837 fflush (stdout);
47d7532e
PE
1838 while (fdatasync (1) != 0 && errno == EINTR)
1839 continue;
23a7488d 1840
3ecb8d93
WS
1841 if (rl < 0)
1842 exit_status = EXIT_FAILURE;
1843
4b7b77f6 1844 CLOSE_SOCKET (emacs_socket);
3ecb8d93 1845 return exit_status;
46cec291
RS
1846}
1847
1e7823d0 1848#endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */