; doc/emacs/misc.texi (Network Security): Fix typo.
[emacs.git] / lib-src / emacsclient.c
blob739e6d5949ef9b998da7b63257d21f84b2f61f6e
1 /* Client process that communicates with GNU Emacs acting as server.
3 Copyright (C) 1986-1987, 1994, 1999-2018 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
21 #include <config.h>
23 #ifdef WINDOWSNT
25 /* ms-w32.h defines these, which disables sockets altogether! */
26 # undef _WINSOCKAPI_
27 # undef _WINSOCK_H
29 # include <malloc.h>
30 # include <stdlib.h>
31 # include <windows.h>
32 # include <commctrl.h>
33 # include <io.h>
34 # include <winsock2.h>
36 # define NO_SOCKETS_IN_FILE_SYSTEM
38 # define HSOCKET SOCKET
39 # define CLOSE_SOCKET closesocket
40 # define INITIALIZE() (initialize_sockets ())
42 char *w32_getenv (const char *);
43 #define egetenv(VAR) w32_getenv(VAR)
45 #else /* !WINDOWSNT */
47 # ifdef HAVE_NTGUI
48 # include <windows.h>
49 # endif /* HAVE_NTGUI */
51 # include "syswait.h"
53 # ifdef HAVE_INET_SOCKETS
54 # include <netinet/in.h>
55 # ifdef HAVE_SOCKETS
56 # include <sys/types.h>
57 # include <sys/socket.h>
58 # include <sys/un.h>
59 # endif /* HAVE_SOCKETS */
60 # endif
61 # include <arpa/inet.h>
63 # define INVALID_SOCKET -1
64 # define HSOCKET int
65 # define CLOSE_SOCKET close
66 # define INITIALIZE()
68 #define egetenv(VAR) getenv(VAR)
70 #endif /* !WINDOWSNT */
72 #undef signal
74 #include <stdarg.h>
75 #include <ctype.h>
76 #include <stdlib.h>
77 #include <string.h>
78 #include <getopt.h>
79 #include <unistd.h>
81 #include <pwd.h>
82 #include <sys/stat.h>
83 #include <signal.h>
84 #include <errno.h>
86 #include <unlocked-io.h>
88 #ifndef VERSION
89 #define VERSION "unspecified"
90 #endif
93 #ifndef EXIT_SUCCESS
94 #define EXIT_SUCCESS 0
95 #endif
97 #ifndef EXIT_FAILURE
98 #define EXIT_FAILURE 1
99 #endif
101 /* Additional space when allocating buffers for filenames, etc. */
102 #define EXTRA_SPACE 100
104 #ifdef min
105 #undef min
106 #endif
107 #define min(x, y) (((x) < (y)) ? (x) : (y))
110 /* Name used to invoke this program. */
111 const char *progname;
113 /* The first argument to main. */
114 int main_argc;
116 /* The second argument to main. */
117 char **main_argv;
119 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
120 int nowait = 0;
122 /* Nonzero means don't print messages for successful operations. --quiet. */
123 int quiet = 0;
125 /* Nonzero means don't print values returned from emacs. --suppress-output. */
126 int suppress_output = 0;
128 /* Nonzero means args are expressions to be evaluated. --eval. */
129 int eval = 0;
131 /* Nonzero means don't open a new frame. Inverse of --create-frame. */
132 int current_frame = 1;
134 /* The display on which Emacs should work. --display. */
135 const char *display = NULL;
137 /* The alternate display we should try if Emacs does not support display. */
138 const char *alt_display = NULL;
140 /* The parent window ID, if we are opening a frame via XEmbed. */
141 char *parent_id = NULL;
143 /* Nonzero means open a new Emacs frame on the current terminal. */
144 int tty = 0;
146 /* If non-NULL, the name of an editor to fallback to if the server
147 is not running. --alternate-editor. */
148 const char *alternate_editor = NULL;
150 /* If non-NULL, the filename of the UNIX socket. */
151 const char *socket_name = NULL;
153 /* If non-NULL, the filename of the authentication file. */
154 const char *server_file = NULL;
156 /* If non-NULL, the tramp prefix emacs must use to find the files. */
157 const char *tramp_prefix = NULL;
159 /* PID of the Emacs server process. */
160 int emacs_pid = 0;
162 /* If non-NULL, a string that should form a frame parameter alist to
163 be used for the new frame. */
164 const char *frame_parameters = NULL;
166 static _Noreturn void print_help_and_exit (void);
169 struct option longopts[] =
171 { "no-wait", no_argument, NULL, 'n' },
172 { "quiet", no_argument, NULL, 'q' },
173 { "suppress-output", no_argument, NULL, 'u' },
174 { "eval", no_argument, NULL, 'e' },
175 { "help", no_argument, NULL, 'H' },
176 { "version", no_argument, NULL, 'V' },
177 { "tty", no_argument, NULL, 't' },
178 { "nw", no_argument, NULL, 't' },
179 { "create-frame", no_argument, NULL, 'c' },
180 { "alternate-editor", required_argument, NULL, 'a' },
181 { "frame-parameters", required_argument, NULL, 'F' },
182 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
183 { "socket-name", required_argument, NULL, 's' },
184 #endif
185 { "server-file", required_argument, NULL, 'f' },
186 { "display", required_argument, NULL, 'd' },
187 { "parent-id", required_argument, NULL, 'p' },
188 { "tramp", required_argument, NULL, 'T' },
189 { 0, 0, 0, 0 }
193 /* Like malloc but get fatal error if memory is exhausted. */
195 static void * ATTRIBUTE_MALLOC
196 xmalloc (size_t size)
198 void *result = malloc (size);
199 if (result == NULL)
201 perror ("malloc");
202 exit (EXIT_FAILURE);
204 return result;
207 /* Like realloc but get fatal error if memory is exhausted. */
209 static void *
210 xrealloc (void *ptr, size_t size)
212 void *result = realloc (ptr, size);
213 if (result == NULL)
215 perror ("realloc");
216 exit (EXIT_FAILURE);
218 return result;
221 /* Like strdup but get a fatal error if memory is exhausted. */
222 char *xstrdup (const char *) ATTRIBUTE_MALLOC;
224 char *
225 xstrdup (const char *s)
227 char *result = strdup (s);
228 if (result == NULL)
230 perror ("strdup");
231 exit (EXIT_FAILURE);
233 return result;
236 /* From sysdep.c */
237 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
239 char *get_current_dir_name (void);
241 /* Return the current working directory. Returns NULL on errors.
242 Any other returned value must be freed with free. This is used
243 only when get_current_dir_name is not defined on the system. */
244 char *
245 get_current_dir_name (void)
247 char *buf;
248 const char *pwd;
249 struct stat dotstat, pwdstat;
250 /* If PWD is accurate, use it instead of calling getcwd. PWD is
251 sometimes a nicer name, and using it may avoid a fatal error if a
252 parent directory is searchable but not readable. */
253 if ((pwd = egetenv ("PWD")) != 0
254 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
255 && stat (pwd, &pwdstat) == 0
256 && stat (".", &dotstat) == 0
257 && dotstat.st_ino == pwdstat.st_ino
258 && dotstat.st_dev == pwdstat.st_dev
259 #ifdef MAXPATHLEN
260 && strlen (pwd) < MAXPATHLEN
261 #endif
264 buf = xmalloc (strlen (pwd) + 1);
265 strcpy (buf, pwd);
267 else
269 size_t buf_size = 1024;
270 for (;;)
272 int tmp_errno;
273 buf = malloc (buf_size);
274 if (! buf)
275 break;
276 if (getcwd (buf, buf_size) == buf)
277 break;
278 tmp_errno = errno;
279 free (buf);
280 if (tmp_errno != ERANGE)
282 errno = tmp_errno;
283 return NULL;
285 buf_size *= 2;
286 if (! buf_size)
288 errno = ENOMEM;
289 return NULL;
293 return buf;
295 #endif
297 #ifdef WINDOWSNT
299 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
301 char *w32_get_resource (HKEY, const char *, LPDWORD);
303 /* Retrieve an environment variable from the Emacs subkeys of the registry.
304 Return NULL if the variable was not found, or it was empty.
305 This code is based on w32_get_resource (w32.c). */
306 char *
307 w32_get_resource (HKEY predefined, const char *key, LPDWORD type)
309 HKEY hrootkey = NULL;
310 char *result = NULL;
311 DWORD cbData;
313 if (RegOpenKeyEx (predefined, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
315 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData)
316 == ERROR_SUCCESS)
318 result = xmalloc (cbData);
320 if ((RegQueryValueEx (hrootkey, key, NULL, type, (LPBYTE) result,
321 &cbData)
322 != ERROR_SUCCESS)
323 || *result == 0)
325 free (result);
326 result = NULL;
330 RegCloseKey (hrootkey);
333 return result;
337 getenv wrapper for Windows
339 Value is allocated on the heap, and can be free'd.
341 This is needed to duplicate Emacs's behavior, which is to look for
342 environment variables in the registry if they don't appear in the
343 environment. */
344 char *
345 w32_getenv (const char *envvar)
347 char *value;
348 DWORD dwType;
350 if ((value = getenv (envvar)))
351 /* Found in the environment. strdup it, because values returned
352 by getenv cannot be free'd. */
353 return xstrdup (value);
355 if (! (value = w32_get_resource (HKEY_CURRENT_USER, envvar, &dwType)) &&
356 ! (value = w32_get_resource (HKEY_LOCAL_MACHINE, envvar, &dwType)))
358 /* "w32console" is what Emacs on Windows uses for tty-type under -nw. */
359 if (strcmp (envvar, "TERM") == 0)
360 return xstrdup ("w32console");
361 /* Found neither in the environment nor in the registry. */
362 return NULL;
365 if (dwType == REG_SZ)
366 /* Registry; no need to expand. */
367 return value;
369 if (dwType == REG_EXPAND_SZ)
371 DWORD size;
373 if ((size = ExpandEnvironmentStrings (value, NULL, 0)))
375 char *buffer = xmalloc (size);
376 if (ExpandEnvironmentStrings (value, buffer, size))
378 /* Found and expanded. */
379 free (value);
380 return buffer;
383 /* Error expanding. */
384 free (buffer);
388 /* Not the right type, or not correctly expanded. */
389 free (value);
390 return NULL;
393 int w32_window_app (void);
396 w32_window_app (void)
398 static int window_app = -1;
399 char szTitle[MAX_PATH];
401 if (window_app < 0)
403 /* Checking for STDOUT does not work; it's a valid handle also in
404 nonconsole apps. Testing for the console title seems to work. */
405 window_app = (GetConsoleTitleA (szTitle, MAX_PATH) == 0);
406 if (window_app)
407 InitCommonControls ();
410 return window_app;
413 /* execvp wrapper for Windows. Quotes arguments with embedded spaces.
415 This is necessary due to the broken implementation of exec* routines in
416 the Microsoft libraries: they concatenate the arguments together without
417 quoting special characters, and pass the result to CreateProcess, with
418 predictably bad results. By contrast, POSIX execvp passes the arguments
419 directly into the argv array of the child process. */
421 int w32_execvp (const char *, char **);
424 w32_execvp (const char *path, char **argv)
426 int i;
428 /* Required to allow a .BAT script as alternate editor. */
429 argv[0] = (char *) alternate_editor;
431 for (i = 0; argv[i]; i++)
432 if (strchr (argv[i], ' '))
434 char *quoted = alloca (strlen (argv[i]) + 3);
435 sprintf (quoted, "\"%s\"", argv[i]);
436 argv[i] = quoted;
439 return execvp (path, argv);
442 #undef execvp
443 #define execvp w32_execvp
445 /* Emulation of ttyname for Windows. */
446 const char *ttyname (int);
447 const char *
448 ttyname (int fd)
450 return "CONOUT$";
453 #endif /* WINDOWSNT */
455 /* Display a normal or error message.
456 On Windows, use a message box if compiled as a Windows app. */
457 static void message (bool, const char *, ...) ATTRIBUTE_FORMAT_PRINTF (2, 3);
458 static void
459 message (bool is_error, const char *format, ...)
461 va_list args;
463 va_start (args, format);
465 #ifdef WINDOWSNT
466 if (w32_window_app ())
468 char msg[2048];
469 vsnprintf (msg, sizeof msg, format, args);
470 msg[sizeof msg - 1] = '\0';
472 if (is_error)
473 MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
474 else
475 MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
477 else
478 #endif
480 FILE *f = is_error ? stderr : stdout;
482 vfprintf (f, format, args);
483 fflush (f);
486 va_end (args);
489 /* Decode the options from argv and argc.
490 The global variable `optind' will say how many arguments we used up. */
492 static void
493 decode_options (int argc, char **argv)
495 alternate_editor = egetenv ("ALTERNATE_EDITOR");
496 tramp_prefix = egetenv ("EMACSCLIENT_TRAMP");
498 while (1)
500 int opt = getopt_long_only (argc, argv,
501 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
502 "VHnequa:s:f:d:F:tcT:",
503 #else
504 "VHnequa:f:d:F:tcT:",
505 #endif
506 longopts, 0);
508 if (opt == EOF)
509 break;
511 switch (opt)
513 case 0:
514 /* If getopt returns 0, then it has already processed a
515 long-named option. We should do nothing. */
516 break;
518 case 'a':
519 alternate_editor = optarg;
520 break;
522 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
523 case 's':
524 socket_name = optarg;
525 break;
526 #endif
528 case 'f':
529 server_file = optarg;
530 break;
532 /* We used to disallow this argument in w32, but it seems better
533 to allow it, for the occasional case where the user is
534 connecting with a w32 client to a server compiled with X11
535 support. */
536 case 'd':
537 display = optarg;
538 break;
540 case 'n':
541 nowait = 1;
542 break;
544 case 'e':
545 eval = 1;
546 break;
548 case 'q':
549 quiet = 1;
550 break;
552 case 'u':
553 suppress_output = 1;
554 break;
556 case 'V':
557 message (false, "emacsclient %s\n", VERSION);
558 exit (EXIT_SUCCESS);
559 break;
561 case 't':
562 tty = 1;
563 current_frame = 0;
564 break;
566 case 'c':
567 current_frame = 0;
568 break;
570 case 'p':
571 parent_id = optarg;
572 current_frame = 0;
573 break;
575 case 'H':
576 print_help_and_exit ();
577 break;
579 case 'F':
580 frame_parameters = optarg;
581 break;
583 case 'T':
584 tramp_prefix = optarg;
585 break;
587 default:
588 message (true, "Try '%s --help' for more information\n", progname);
589 exit (EXIT_FAILURE);
590 break;
594 /* If the -c option is used (without -t) and no --display argument
595 is provided, try $DISPLAY.
596 Without the -c option, we used to set `display' to $DISPLAY by
597 default, but this changed the default behavior and is sometimes
598 inconvenient. So we force users to use "--display $DISPLAY" if
599 they want Emacs to connect to their current display.
601 Some window systems have a notion of default display not
602 reflected in the DISPLAY variable. If the user didn't give us an
603 explicit display, try this platform-specific after trying the
604 display in DISPLAY (if any). */
605 if (!current_frame && !tty && !display)
607 /* Set these here so we use a default_display only when the user
608 didn't give us an explicit display. */
609 #if defined (NS_IMPL_COCOA)
610 alt_display = "ns";
611 #elif defined (HAVE_NTGUI)
612 alt_display = "w32";
613 #endif
615 display = egetenv ("DISPLAY");
618 if (!display)
620 display = alt_display;
621 alt_display = NULL;
624 /* A null-string display is invalid. */
625 if (display && strlen (display) == 0)
626 display = NULL;
628 /* If no display is available, new frames are tty frames. */
629 if (!current_frame && !display)
630 tty = 1;
632 #ifdef WINDOWSNT
633 /* Emacs on Windows does not support graphical and text terminal
634 frames in the same instance. So, treat the -t and -c options as
635 equivalent, and open a new frame on the server's terminal.
636 Ideally, we would only set tty = 1 when the serve is running in a
637 console, but alas we don't know that. As a workaround, always
638 ask for a tty frame, and let server.el figure it out. */
639 if (!current_frame)
641 display = NULL;
642 tty = 1;
644 #endif /* WINDOWSNT */
648 static _Noreturn void
649 print_help_and_exit (void)
651 /* Spaces and tabs are significant in this message; they're chosen so the
652 message aligns properly both in a tty and in a Windows message box.
653 Please try to preserve them; otherwise the output is very hard to read
654 when using emacsclientw. */
655 message (false,
656 "Usage: %s [OPTIONS] FILE...\n%s%s%s", progname, "\
657 Tell the Emacs server to visit the specified files.\n\
658 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
660 The following OPTIONS are accepted:\n\
661 -V, --version Just print version info and return\n\
662 -H, --help Print this usage information message\n\
663 -nw, -t, --tty Open a new Emacs frame on the current terminal\n\
664 -c, --create-frame Create a new frame instead of trying to\n\
665 use the current Emacs frame\n\
666 ", "\
667 -F ALIST, --frame-parameters=ALIST\n\
668 Set the parameters of a new frame\n\
669 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
670 -n, --no-wait Don't wait for the server to return\n\
671 -q, --quiet Don't display messages on success\n\
672 -u, --suppress-output Don't display return values from the server\n\
673 -d DISPLAY, --display=DISPLAY\n\
674 Visit the file in the given display\n\
675 ", "\
676 --parent-id=ID Open in parent window ID, via XEmbed\n"
677 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
678 "-s SOCKET, --socket-name=SOCKET\n\
679 Set filename of the UNIX socket for communication\n"
680 #endif
681 "-f SERVER, --server-file=SERVER\n\
682 Set filename of the TCP authentication file\n\
683 -a EDITOR, --alternate-editor=EDITOR\n\
684 Editor to fallback to if the server is not running\n"
685 " If EDITOR is the empty string, start Emacs in daemon\n\
686 mode and try connecting again\n"
687 "-T PREFIX, --tramp=PREFIX\n\
688 PREFIX to prepend to filenames sent by emacsclient\n\
689 for locating files remotely via Tramp\n"
690 "\n\
691 Report bugs with M-x report-emacs-bug.\n");
692 exit (EXIT_SUCCESS);
695 /* Try to run a different command, or --if no alternate editor is
696 defined-- exit with an error code.
697 Uses argv, but gets it from the global variable main_argv. */
699 static _Noreturn void
700 fail (void)
702 if (alternate_editor)
704 size_t extra_args_size = (main_argc - optind + 1) * sizeof (char *);
705 size_t new_argv_size = extra_args_size;
706 char **new_argv = xmalloc (new_argv_size);
707 char *s = xstrdup (alternate_editor);
708 unsigned toks = 0;
710 /* Unpack alternate_editor's space-separated tokens into new_argv. */
711 for (char *tok = s; tok != NULL && *tok != '\0';)
713 /* Allocate new token. */
714 ++toks;
715 new_argv = xrealloc (new_argv, new_argv_size + toks * sizeof (char *));
717 /* Skip leading delimiters, and set separator, skipping any
718 opening quote. */
719 size_t skip = strspn (tok, " \"");
720 tok += skip;
721 char sep = (skip > 0 && tok[-1] == '"') ? '"' : ' ';
723 /* Record start of token. */
724 new_argv[toks - 1] = tok;
726 /* Find end of token and overwrite it with NUL. */
727 tok = strchr (tok, sep);
728 if (tok != NULL)
729 *tok++ = '\0';
732 /* Append main_argv arguments to new_argv. */
733 memcpy (&new_argv[toks], main_argv + optind, extra_args_size);
735 execvp (*new_argv, new_argv);
736 message (true, "%s: error executing alternate editor \"%s\"\n",
737 progname, alternate_editor);
739 exit (EXIT_FAILURE);
743 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
746 main (int argc, char **argv)
748 main_argc = argc;
749 main_argv = argv;
750 progname = argv[0];
751 message (true, "%s: Sorry, the Emacs server is supported only\n"
752 "on systems with Berkeley sockets.\n",
753 argv[0]);
754 fail ();
757 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
759 #define AUTH_KEY_LENGTH 64
760 #define SEND_BUFFER_SIZE 4096
762 /* Buffer to accumulate data to send in TCP connections. */
763 char send_buffer[SEND_BUFFER_SIZE + 1];
764 int sblen = 0; /* Fill pointer for the send buffer. */
765 /* Socket used to communicate with the Emacs server process. */
766 HSOCKET emacs_socket = 0;
768 /* On Windows, the socket library was historically separate from the
769 standard C library, so errors are handled differently. */
771 static void
772 sock_err_message (const char *function_name)
774 #ifdef WINDOWSNT
775 char* msg = NULL;
777 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
778 | FORMAT_MESSAGE_ALLOCATE_BUFFER
779 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
780 NULL, WSAGetLastError (), 0, (LPTSTR)&msg, 0, NULL);
782 message (true, "%s: %s: %s\n", progname, function_name, msg);
784 LocalFree (msg);
785 #else
786 message (true, "%s: %s: %s\n", progname, function_name, strerror (errno));
787 #endif
791 /* Let's send the data to Emacs when either
792 - the data ends in "\n", or
793 - the buffer is full (but this shouldn't happen)
794 Otherwise, we just accumulate it. */
795 static void
796 send_to_emacs (HSOCKET s, const char *data)
798 size_t dlen;
800 if (!data)
801 return;
803 dlen = strlen (data);
804 while (*data)
806 size_t part = min (dlen, SEND_BUFFER_SIZE - sblen);
807 memcpy (&send_buffer[sblen], data, part);
808 data += part;
809 sblen += part;
811 if (sblen == SEND_BUFFER_SIZE
812 || (sblen > 0 && send_buffer[sblen-1] == '\n'))
814 int sent = send (s, send_buffer, sblen, 0);
815 if (sent < 0)
817 message (true, "%s: failed to send %d bytes to socket: %s\n",
818 progname, sblen, strerror (errno));
819 fail ();
821 if (sent != sblen)
822 memmove (send_buffer, &send_buffer[sent], sblen - sent);
823 sblen -= sent;
826 dlen -= part;
831 /* In STR, insert a & before each &, each space, each newline, and
832 any initial -. Change spaces to underscores, too, so that the
833 return value never contains a space.
835 Does not change the string. Outputs the result to S. */
836 static void
837 quote_argument (HSOCKET s, const char *str)
839 char *copy = xmalloc (strlen (str) * 2 + 1);
840 const char *p;
841 char *q;
843 p = str;
844 q = copy;
845 while (*p)
847 if (*p == ' ')
849 *q++ = '&';
850 *q++ = '_';
851 p++;
853 else if (*p == '\n')
855 *q++ = '&';
856 *q++ = 'n';
857 p++;
859 else
861 if (*p == '&' || (*p == '-' && p == str))
862 *q++ = '&';
863 *q++ = *p++;
866 *q++ = 0;
868 send_to_emacs (s, copy);
870 free (copy);
874 /* The inverse of quote_argument. Removes quoting in string STR by
875 modifying the string in place. Returns STR. */
877 static char *
878 unquote_argument (char *str)
880 char *p, *q;
882 if (! str)
883 return str;
885 p = str;
886 q = str;
887 while (*p)
889 if (*p == '&')
891 p++;
892 if (*p == '&')
893 *p = '&';
894 else if (*p == '_')
895 *p = ' ';
896 else if (*p == 'n')
897 *p = '\n';
898 else if (*p == '-')
899 *p = '-';
901 *q++ = *p++;
903 *q = 0;
904 return str;
908 static int
909 file_name_absolute_p (const char *filename)
911 /* Sanity check, it shouldn't happen. */
912 if (! filename) return false;
914 /* /xxx is always an absolute path. */
915 if (filename[0] == '/') return true;
917 /* Empty filenames (which shouldn't happen) are relative. */
918 if (filename[0] == '\0') return false;
920 #ifdef WINDOWSNT
921 /* X:\xxx is always absolute. */
922 if (isalpha ((unsigned char) filename[0])
923 && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
924 return true;
926 /* Both \xxx and \\xxx\yyy are absolute. */
927 if (filename[0] == '\\') return true;
928 #endif
930 return false;
933 #ifdef WINDOWSNT
934 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
935 void __cdecl close_winsock (void);
936 void __cdecl
937 close_winsock (void)
939 WSACleanup ();
942 /* Initialize the WinSock2 library. */
943 void initialize_sockets (void);
944 void
945 initialize_sockets (void)
947 WSADATA wsaData;
949 if (WSAStartup (MAKEWORD (2, 0), &wsaData))
951 message (true, "%s: error initializing WinSock2\n", progname);
952 exit (EXIT_FAILURE);
955 atexit (close_winsock);
957 #endif /* WINDOWSNT */
960 /* Read the information needed to set up a TCP comm channel with
961 the Emacs server: host, port, and authentication string. */
963 static int
964 get_server_config (const char *config_file, struct sockaddr_in *server,
965 char *authentication)
967 char dotted[32];
968 char *port;
969 FILE *config = NULL;
971 if (file_name_absolute_p (config_file))
972 config = fopen (config_file, "rb");
973 else
975 const char *home = egetenv ("HOME");
977 if (home)
979 char *path = xmalloc (strlen (home) + strlen (config_file)
980 + EXTRA_SPACE);
981 char *z = stpcpy (path, home);
982 z = stpcpy (z, "/.emacs.d/server/");
983 strcpy (z, config_file);
984 config = fopen (path, "rb");
985 free (path);
987 #ifdef WINDOWSNT
988 if (!config && (home = egetenv ("APPDATA")))
990 char *path = xmalloc (strlen (home) + strlen (config_file)
991 + EXTRA_SPACE);
992 char *z = stpcpy (path, home);
993 z = stpcpy (z, "/.emacs.d/server/");
994 strcpy (z, config_file);
995 config = fopen (path, "rb");
996 free (path);
998 #endif
1001 if (! config)
1002 return false;
1004 if (fgets (dotted, sizeof dotted, config)
1005 && (port = strchr (dotted, ':')))
1006 *port++ = '\0';
1007 else
1009 message (true, "%s: invalid configuration info\n", progname);
1010 exit (EXIT_FAILURE);
1013 server->sin_family = AF_INET;
1014 server->sin_addr.s_addr = inet_addr (dotted);
1015 server->sin_port = htons (atoi (port));
1017 if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
1019 message (true, "%s: cannot read authentication info\n", progname);
1020 exit (EXIT_FAILURE);
1023 fclose (config);
1025 return true;
1028 static HSOCKET
1029 set_tcp_socket (const char *local_server_file)
1031 HSOCKET s;
1032 struct sockaddr_in server;
1033 struct linger l_arg = {1, 1};
1034 char auth_string[AUTH_KEY_LENGTH + 1];
1036 if (! get_server_config (local_server_file, &server, auth_string))
1037 return INVALID_SOCKET;
1039 if (server.sin_addr.s_addr != inet_addr ("127.0.0.1") && !quiet)
1040 message (false, "%s: connected to remote socket at %s\n",
1041 progname, inet_ntoa (server.sin_addr));
1043 /* Open up an AF_INET socket. */
1044 if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
1046 /* Since we have an alternate to try out, this is not an error
1047 yet; popping out a modal dialog at this stage would make -a
1048 option totally useless for emacsclientw -- the user will
1049 still get an error message if the alternate editor fails. */
1050 #ifdef WINDOWSNT
1051 if(!(w32_window_app () && alternate_editor))
1052 #endif
1053 sock_err_message ("socket");
1054 return INVALID_SOCKET;
1057 /* Set up the socket. */
1058 if (connect (s, (struct sockaddr *) &server, sizeof server) < 0)
1060 #ifdef WINDOWSNT
1061 if(!(w32_window_app () && alternate_editor))
1062 #endif
1063 sock_err_message ("connect");
1064 return INVALID_SOCKET;
1067 setsockopt (s, SOL_SOCKET, SO_LINGER, (char *) &l_arg, sizeof l_arg);
1069 /* Send the authentication. */
1070 auth_string[AUTH_KEY_LENGTH] = '\0';
1072 send_to_emacs (s, "-auth ");
1073 send_to_emacs (s, auth_string);
1074 send_to_emacs (s, " ");
1076 return s;
1080 /* Returns 1 if PREFIX is a prefix of STRING. */
1081 static int
1082 strprefix (const char *prefix, const char *string)
1084 return !strncmp (prefix, string, strlen (prefix));
1087 /* Get tty name and type. If successful, return the type in TTY_TYPE
1088 and the name in TTY_NAME, and return 1. Otherwise, fail if NOABORT
1089 is zero, or return 0 if NOABORT is non-zero. */
1091 static int
1092 find_tty (const char **tty_type, const char **tty_name, int noabort)
1094 const char *type = egetenv ("TERM");
1095 const char *name = ttyname (fileno (stdout));
1097 if (!name)
1099 if (noabort)
1100 return 0;
1101 else
1103 message (true, "%s: could not get terminal name\n", progname);
1104 fail ();
1108 if (!type)
1110 if (noabort)
1111 return 0;
1112 else
1114 message (true, "%s: please set the TERM variable to your terminal type\n",
1115 progname);
1116 fail ();
1120 if (strcmp (type, "eterm") == 0)
1122 if (noabort)
1123 return 0;
1124 else
1126 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1127 message (true, "%s: opening a frame in an Emacs term buffer"
1128 " is not supported\n", progname);
1129 fail ();
1133 *tty_name = name;
1134 *tty_type = type;
1135 return 1;
1139 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1141 /* Three possibilities:
1142 2 - can't be `stat'ed (sets errno)
1143 1 - isn't owned by us
1144 0 - success: none of the above */
1146 static int
1147 socket_status (const char *name)
1149 struct stat statbfr;
1151 if (stat (name, &statbfr) == -1)
1152 return 2;
1154 if (statbfr.st_uid != geteuid ())
1155 return 1;
1157 return 0;
1161 /* A signal handler that passes the signal to the Emacs process.
1162 Useful for SIGWINCH. */
1164 static void
1165 pass_signal_to_emacs (int signalnum)
1167 int old_errno = errno;
1169 if (emacs_pid)
1170 kill (emacs_pid, signalnum);
1172 signal (signalnum, pass_signal_to_emacs);
1173 errno = old_errno;
1176 /* Signal handler for SIGCONT; notify the Emacs process that it can
1177 now resume our tty frame. */
1179 static void
1180 handle_sigcont (int signalnum)
1182 int old_errno = errno;
1183 pid_t pgrp = getpgrp ();
1184 pid_t tcpgrp = tcgetpgrp (1);
1186 if (tcpgrp == pgrp)
1188 /* We are in the foreground. */
1189 send_to_emacs (emacs_socket, "-resume \n");
1191 else if (0 <= tcpgrp && tty)
1193 /* We are in the background; cancel the continue. */
1194 kill (-pgrp, SIGTTIN);
1197 signal (signalnum, handle_sigcont);
1198 errno = old_errno;
1201 /* Signal handler for SIGTSTP; notify the Emacs process that we are
1202 going to sleep. Normally the suspend is initiated by Emacs via
1203 server-handle-suspend-tty, but if the server gets out of sync with
1204 reality, we may get a SIGTSTP on C-z. Handling this signal and
1205 notifying Emacs about it should get things under control again. */
1207 static void
1208 handle_sigtstp (int signalnum)
1210 int old_errno = errno;
1211 sigset_t set;
1213 if (emacs_socket)
1214 send_to_emacs (emacs_socket, "-suspend \n");
1216 /* Unblock this signal and call the default handler by temporarily
1217 changing the handler and resignaling. */
1218 sigprocmask (SIG_BLOCK, NULL, &set);
1219 sigdelset (&set, signalnum);
1220 signal (signalnum, SIG_DFL);
1221 raise (signalnum);
1222 sigprocmask (SIG_SETMASK, &set, NULL); /* Let's the above signal through. */
1223 signal (signalnum, handle_sigtstp);
1225 errno = old_errno;
1229 /* Set up signal handlers before opening a frame on the current tty. */
1231 static void
1232 init_signals (void)
1234 /* Set up signal handlers. */
1235 signal (SIGWINCH, pass_signal_to_emacs);
1237 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
1238 deciding which terminal the signal came from. C-g is now a
1239 normal input event on secondary terminals. */
1240 #if 0
1241 signal (SIGINT, pass_signal_to_emacs);
1242 signal (SIGQUIT, pass_signal_to_emacs);
1243 #endif
1245 signal (SIGCONT, handle_sigcont);
1246 signal (SIGTSTP, handle_sigtstp);
1247 signal (SIGTTOU, handle_sigtstp);
1251 static HSOCKET
1252 set_local_socket (const char *local_socket_name)
1254 HSOCKET s;
1255 struct sockaddr_un server;
1257 /* Open up an AF_UNIX socket in this person's home directory. */
1258 if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
1260 message (true, "%s: socket: %s\n", progname, strerror (errno));
1261 return INVALID_SOCKET;
1264 server.sun_family = AF_UNIX;
1267 int sock_status;
1268 int saved_errno;
1269 const char *server_name = local_socket_name;
1270 const char *tmpdir = NULL;
1271 char *tmpdir_storage = NULL;
1272 char *socket_name_storage = NULL;
1274 if (!strchr (local_socket_name, '/') && !strchr (local_socket_name, '\\'))
1276 /* socket_name is a file name component. */
1277 long uid = geteuid ();
1278 tmpdir = egetenv ("TMPDIR");
1279 if (!tmpdir)
1281 #ifdef DARWIN_OS
1282 #ifndef _CS_DARWIN_USER_TEMP_DIR
1283 #define _CS_DARWIN_USER_TEMP_DIR 65537
1284 #endif
1285 size_t n = confstr (_CS_DARWIN_USER_TEMP_DIR, NULL, (size_t) 0);
1286 if (n > 0)
1288 tmpdir = tmpdir_storage = xmalloc (n);
1289 confstr (_CS_DARWIN_USER_TEMP_DIR, tmpdir_storage, n);
1291 else
1292 #endif
1293 tmpdir = "/tmp";
1295 socket_name_storage =
1296 xmalloc (strlen (tmpdir) + strlen (server_name) + EXTRA_SPACE);
1297 char *z = stpcpy (socket_name_storage, tmpdir);
1298 z += sprintf (z, "/emacs%ld/", uid);
1299 strcpy (z, server_name);
1300 local_socket_name = socket_name_storage;
1303 if (strlen (local_socket_name) < sizeof (server.sun_path))
1304 strcpy (server.sun_path, local_socket_name);
1305 else
1307 message (true, "%s: socket-name %s too long\n",
1308 progname, local_socket_name);
1309 fail ();
1312 /* See if the socket exists, and if it's owned by us. */
1313 sock_status = socket_status (server.sun_path);
1314 saved_errno = errno;
1315 if (sock_status && tmpdir)
1317 /* Failing that, see if LOGNAME or USER exist and differ from
1318 our euid. If so, look for a socket based on the UID
1319 associated with the name. This is reminiscent of the logic
1320 that init_editfns uses to set the global Vuser_full_name. */
1322 const char *user_name = egetenv ("LOGNAME");
1324 if (!user_name)
1325 user_name = egetenv ("USER");
1327 if (user_name)
1329 struct passwd *pw = getpwnam (user_name);
1331 if (pw && (pw->pw_uid != geteuid ()))
1333 /* We're running under su, apparently. */
1334 long uid = pw->pw_uid;
1335 char *user_socket_name
1336 = xmalloc (strlen (tmpdir) + strlen (server_name)
1337 + EXTRA_SPACE);
1338 char *z = stpcpy (user_socket_name, tmpdir);
1339 z += sprintf (z, "/emacs%ld/", uid);
1340 strcpy (z, server_name);
1342 if (strlen (user_socket_name) < sizeof (server.sun_path))
1343 strcpy (server.sun_path, user_socket_name);
1344 else
1346 message (true, "%s: socket-name %s too long\n",
1347 progname, user_socket_name);
1348 exit (EXIT_FAILURE);
1350 free (user_socket_name);
1352 sock_status = socket_status (server.sun_path);
1353 saved_errno = errno;
1355 else
1356 errno = saved_errno;
1360 free (socket_name_storage);
1361 free (tmpdir_storage);
1363 switch (sock_status)
1365 case 1:
1366 /* There's a socket, but it isn't owned by us. This is OK if
1367 we are root. */
1368 if (0 != geteuid ())
1370 message (true, "%s: Invalid socket owner\n", progname);
1371 return INVALID_SOCKET;
1373 break;
1375 case 2:
1376 /* `stat' failed */
1377 if (saved_errno == ENOENT)
1378 message (true,
1379 "%s: can't find socket; have you started the server?\n\
1380 To start the server in Emacs, type \"M-x server-start\".\n",
1381 progname);
1382 else
1383 message (true, "%s: can't stat %s: %s\n",
1384 progname, server.sun_path, strerror (saved_errno));
1385 return INVALID_SOCKET;
1389 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
1390 < 0)
1392 message (true, "%s: connect: %s\n", progname, strerror (errno));
1393 return INVALID_SOCKET;
1396 return s;
1398 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1400 static HSOCKET
1401 set_socket (int no_exit_if_error)
1403 HSOCKET s;
1404 const char *local_server_file = server_file;
1406 INITIALIZE ();
1408 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1409 /* Explicit --socket-name argument. */
1410 if (socket_name)
1412 s = set_local_socket (socket_name);
1413 if ((s != INVALID_SOCKET) || no_exit_if_error)
1414 return s;
1415 message (true, "%s: error accessing socket \"%s\"\n",
1416 progname, socket_name);
1417 exit (EXIT_FAILURE);
1419 #endif
1421 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1422 if (!local_server_file)
1423 local_server_file = egetenv ("EMACS_SERVER_FILE");
1425 if (local_server_file)
1427 s = set_tcp_socket (local_server_file);
1428 if ((s != INVALID_SOCKET) || no_exit_if_error)
1429 return s;
1431 message (true, "%s: error accessing server file \"%s\"\n",
1432 progname, local_server_file);
1433 exit (EXIT_FAILURE);
1436 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1437 /* Implicit local socket. */
1438 s = set_local_socket ("server");
1439 if (s != INVALID_SOCKET)
1440 return s;
1441 #endif
1443 /* Implicit server file. */
1444 s = set_tcp_socket ("server");
1445 if ((s != INVALID_SOCKET) || no_exit_if_error)
1446 return s;
1448 /* No implicit or explicit socket, and no alternate editor. */
1449 message (true, "%s: No socket or alternate editor. Please use:\n\n"
1450 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1451 "\t--socket-name\n"
1452 #endif
1453 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1454 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1455 progname);
1456 exit (EXIT_FAILURE);
1459 #ifdef HAVE_NTGUI
1460 FARPROC set_fg; /* Pointer to AllowSetForegroundWindow. */
1461 FARPROC get_wc; /* Pointer to RealGetWindowClassA. */
1463 void w32_set_user_model_id (void);
1465 void
1466 w32_set_user_model_id (void)
1468 HMODULE shell;
1469 HRESULT (WINAPI * set_user_model) (const wchar_t * id);
1471 /* On Windows 7 and later, we need to set the user model ID
1472 to associate emacsclient launched files with Emacs frames
1473 in the UI. */
1474 shell = LoadLibrary ("shell32.dll");
1475 if (shell)
1477 set_user_model
1478 = (void *) GetProcAddress (shell,
1479 "SetCurrentProcessExplicitAppUserModelID");
1480 /* If the function is defined, then we are running on Windows 7
1481 or newer, and the UI uses this to group related windows
1482 together. Since emacs, runemacs, emacsclient are related, we
1483 want them grouped even though the executables are different,
1484 so we need to set a consistent ID between them. */
1485 if (set_user_model)
1486 set_user_model (L"GNU.Emacs");
1488 FreeLibrary (shell);
1492 BOOL CALLBACK w32_find_emacs_process (HWND, LPARAM);
1494 BOOL CALLBACK
1495 w32_find_emacs_process (HWND hWnd, LPARAM lParam)
1497 DWORD pid;
1498 char class[6];
1500 /* Reject any window not of class "Emacs". */
1501 if (! get_wc (hWnd, class, sizeof (class))
1502 || strcmp (class, "Emacs"))
1503 return TRUE;
1505 /* We only need the process id, not the thread id. */
1506 (void) GetWindowThreadProcessId (hWnd, &pid);
1508 /* Not the one we're looking for. */
1509 if (pid != (DWORD) emacs_pid) return TRUE;
1511 /* OK, let's raise it. */
1512 set_fg (emacs_pid);
1514 /* Stop enumeration. */
1515 return FALSE;
1518 /* Search for a window of class "Emacs" and owned by a process with
1519 process id = emacs_pid. If found, allow it to grab the focus. */
1520 void w32_give_focus (void);
1522 void
1523 w32_give_focus (void)
1525 HANDLE user32;
1527 /* It shouldn't happen when dealing with TCP sockets. */
1528 if (!emacs_pid) return;
1530 user32 = GetModuleHandle ("user32.dll");
1532 if (!user32)
1533 return;
1535 /* Modern Windows restrict which processes can set the foreground window.
1536 emacsclient can allow Emacs to grab the focus by calling the function
1537 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1538 NT) lack this function, so we have to check its availability. */
1539 if ((set_fg = GetProcAddress (user32, "AllowSetForegroundWindow"))
1540 && (get_wc = GetProcAddress (user32, "RealGetWindowClassA")))
1541 EnumWindows (w32_find_emacs_process, (LPARAM) 0);
1543 #endif /* HAVE_NTGUI */
1545 /* Start the emacs daemon and try to connect to it. */
1547 static void
1548 start_daemon_and_retry_set_socket (void)
1550 #ifndef WINDOWSNT
1551 pid_t dpid;
1552 int status;
1554 dpid = fork ();
1556 if (dpid > 0)
1558 pid_t w;
1559 w = waitpid (dpid, &status, WUNTRACED | WCONTINUED);
1561 if ((w == -1) || !WIFEXITED (status) || WEXITSTATUS (status))
1563 message (true, "Error: Could not start the Emacs daemon\n");
1564 exit (EXIT_FAILURE);
1567 /* Try connecting, the daemon should have started by now. */
1568 message (true, "Emacs daemon should have started, trying to connect again\n");
1569 if ((emacs_socket = set_socket (1)) == INVALID_SOCKET)
1571 message (true, "Error: Cannot connect even after starting the Emacs daemon\n");
1572 exit (EXIT_FAILURE);
1575 else if (dpid < 0)
1577 fprintf (stderr, "Error: Cannot fork!\n");
1578 exit (EXIT_FAILURE);
1580 else
1582 char emacs[] = "emacs";
1583 char daemon_option[] = "--daemon";
1584 char *d_argv[3];
1585 d_argv[0] = emacs;
1586 d_argv[1] = daemon_option;
1587 d_argv[2] = 0;
1588 if (socket_name != NULL)
1590 /* Pass --daemon=socket_name as argument. */
1591 const char *deq = "--daemon=";
1592 char *daemon_arg = xmalloc (strlen (deq)
1593 + strlen (socket_name) + 1);
1594 strcpy (stpcpy (daemon_arg, deq), socket_name);
1595 d_argv[1] = daemon_arg;
1597 execvp ("emacs", d_argv);
1598 message (true, "%s: error starting emacs daemon\n", progname);
1600 #else /* WINDOWSNT */
1601 DWORD wait_result;
1602 HANDLE w32_daemon_event;
1603 STARTUPINFO si;
1604 PROCESS_INFORMATION pi;
1606 ZeroMemory (&si, sizeof si);
1607 si.cb = sizeof si;
1608 ZeroMemory (&pi, sizeof pi);
1610 /* We start Emacs in daemon mode, and then wait for it to signal us
1611 it is ready to accept client connections, by asserting an event
1612 whose name is known to the daemon (defined by nt/inc/ms-w32.h). */
1614 if (!CreateProcess (NULL, (LPSTR)"emacs --daemon", NULL, NULL, FALSE,
1615 CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
1617 char* msg = NULL;
1619 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
1620 | FORMAT_MESSAGE_ALLOCATE_BUFFER
1621 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1622 NULL, GetLastError (), 0, (LPTSTR)&msg, 0, NULL);
1623 message (true, "%s: error starting emacs daemon (%s)\n", progname, msg);
1624 exit (EXIT_FAILURE);
1627 w32_daemon_event = CreateEvent (NULL, TRUE, FALSE, W32_DAEMON_EVENT);
1628 if (w32_daemon_event == NULL)
1630 message (true, "Couldn't create Windows daemon event");
1631 exit (EXIT_FAILURE);
1633 if ((wait_result = WaitForSingleObject (w32_daemon_event, INFINITE))
1634 != WAIT_OBJECT_0)
1636 const char *msg = NULL;
1638 switch (wait_result)
1640 case WAIT_ABANDONED:
1641 msg = "The daemon exited unexpectedly";
1642 break;
1643 case WAIT_TIMEOUT:
1644 /* Can't happen due to INFINITE. */
1645 default:
1646 case WAIT_FAILED:
1647 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
1648 | FORMAT_MESSAGE_ALLOCATE_BUFFER
1649 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1650 NULL, GetLastError (), 0, (LPTSTR)&msg, 0, NULL);
1651 break;
1653 message (true, "Error: Could not start the Emacs daemon: %s\n", msg);
1654 exit (EXIT_FAILURE);
1656 CloseHandle (w32_daemon_event);
1658 /* Try connecting, the daemon should have started by now. */
1659 /* It's just a progress message, so don't pop a dialog if this is
1660 emacsclientw. */
1661 if (!w32_window_app ())
1662 message (true,
1663 "Emacs daemon should have started, trying to connect again\n");
1664 if ((emacs_socket = set_socket (1)) == INVALID_SOCKET)
1666 message (true,
1667 "Error: Cannot connect even after starting the Emacs daemon\n");
1668 exit (EXIT_FAILURE);
1670 #endif /* WINDOWSNT */
1674 main (int argc, char **argv)
1676 int rl = 0, needlf = 0;
1677 char *cwd, *str;
1678 char string[BUFSIZ+1];
1679 int start_daemon_if_needed;
1680 int exit_status = EXIT_SUCCESS;
1682 main_argc = argc;
1683 main_argv = argv;
1684 progname = argv[0];
1686 #ifdef HAVE_NTGUI
1687 /* On Windows 7 and later, we need to explicitly associate
1688 emacsclient with emacs so the UI behaves sensibly. This
1689 association does no harm if we're not actually connecting to an
1690 Emacs using a window display. */
1691 w32_set_user_model_id ();
1692 #endif /* HAVE_NTGUI */
1694 /* Process options. */
1695 decode_options (argc, argv);
1697 if ((argc - optind < 1) && !eval && current_frame)
1699 message (true, "%s: file name or argument required\n"
1700 "Try '%s --help' for more information\n",
1701 progname, progname);
1702 exit (EXIT_FAILURE);
1705 #ifndef WINDOWSNT
1706 if (tty)
1708 pid_t pgrp = getpgrp ();
1709 pid_t tcpgrp = tcgetpgrp (1);
1710 if (0 <= tcpgrp && tcpgrp != pgrp)
1711 kill (-pgrp, SIGTTIN);
1713 #endif /* !WINDOWSNT */
1715 /* If alternate_editor is the empty string, start the emacs daemon
1716 in case of failure to connect. */
1717 start_daemon_if_needed = (alternate_editor
1718 && (alternate_editor[0] == '\0'));
1720 emacs_socket = set_socket (alternate_editor || start_daemon_if_needed);
1721 if (emacs_socket == INVALID_SOCKET)
1723 if (! start_daemon_if_needed)
1724 fail ();
1726 start_daemon_and_retry_set_socket ();
1729 cwd = get_current_dir_name ();
1730 if (cwd == 0)
1732 message (true, "%s: %s\n", progname,
1733 "Cannot get current working directory");
1734 fail ();
1737 #ifdef HAVE_NTGUI
1738 if (display && !strcmp (display, "w32"))
1739 w32_give_focus ();
1740 #endif /* HAVE_NTGUI */
1742 /* Send over our environment and current directory. */
1743 if (!current_frame)
1745 int i;
1746 for (i = 0; environ[i]; i++)
1748 send_to_emacs (emacs_socket, "-env ");
1749 quote_argument (emacs_socket, environ[i]);
1750 send_to_emacs (emacs_socket, " ");
1753 send_to_emacs (emacs_socket, "-dir ");
1754 if (tramp_prefix)
1755 quote_argument (emacs_socket, tramp_prefix);
1756 quote_argument (emacs_socket, cwd);
1757 free (cwd);
1758 send_to_emacs (emacs_socket, "/");
1759 send_to_emacs (emacs_socket, " ");
1761 retry:
1762 if (nowait)
1763 send_to_emacs (emacs_socket, "-nowait ");
1765 if (current_frame)
1766 send_to_emacs (emacs_socket, "-current-frame ");
1768 if (display)
1770 send_to_emacs (emacs_socket, "-display ");
1771 quote_argument (emacs_socket, display);
1772 send_to_emacs (emacs_socket, " ");
1775 if (parent_id)
1777 send_to_emacs (emacs_socket, "-parent-id ");
1778 quote_argument (emacs_socket, parent_id);
1779 send_to_emacs (emacs_socket, " ");
1782 if (frame_parameters && !current_frame)
1784 send_to_emacs (emacs_socket, "-frame-parameters ");
1785 quote_argument (emacs_socket, frame_parameters);
1786 send_to_emacs (emacs_socket, " ");
1789 /* Unless we are certain we don't want to occupy the tty, send our
1790 tty information to Emacs. For example, in daemon mode Emacs may
1791 need to occupy this tty if no other frame is available. */
1792 if (!current_frame || !eval)
1794 const char *tty_type, *tty_name;
1796 if (find_tty (&tty_type, &tty_name, !tty))
1798 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1799 init_signals ();
1800 #endif
1801 send_to_emacs (emacs_socket, "-tty ");
1802 quote_argument (emacs_socket, tty_name);
1803 send_to_emacs (emacs_socket, " ");
1804 quote_argument (emacs_socket, tty_type);
1805 send_to_emacs (emacs_socket, " ");
1809 if (!current_frame && !tty)
1810 send_to_emacs (emacs_socket, "-window-system ");
1812 if ((argc - optind > 0))
1814 int i;
1815 for (i = optind; i < argc; i++)
1818 if (eval)
1820 /* Don't prepend cwd or anything like that. */
1821 send_to_emacs (emacs_socket, "-eval ");
1822 quote_argument (emacs_socket, argv[i]);
1823 send_to_emacs (emacs_socket, " ");
1824 continue;
1827 if (*argv[i] == '+')
1829 char *p = argv[i] + 1;
1830 while (isdigit ((unsigned char) *p) || *p == ':') p++;
1831 if (*p == 0)
1833 send_to_emacs (emacs_socket, "-position ");
1834 quote_argument (emacs_socket, argv[i]);
1835 send_to_emacs (emacs_socket, " ");
1836 continue;
1839 #ifdef WINDOWSNT
1840 else if (! file_name_absolute_p (argv[i])
1841 && (isalpha (argv[i][0]) && argv[i][1] == ':'))
1842 /* Windows can have a different default directory for each
1843 drive, so the cwd passed via "-dir" is not sufficient
1844 to account for that.
1845 If the user uses <drive>:<relpath>, we hence need to be
1846 careful to expand <relpath> with the default directory
1847 corresponding to <drive>. */
1849 char *filename = xmalloc (MAX_PATH);
1850 DWORD size;
1852 size = GetFullPathName (argv[i], MAX_PATH, filename, NULL);
1853 if (size > 0 && size < MAX_PATH)
1854 argv[i] = filename;
1855 else
1856 free (filename);
1858 #endif
1860 send_to_emacs (emacs_socket, "-file ");
1861 if (tramp_prefix && file_name_absolute_p (argv[i]))
1862 quote_argument (emacs_socket, tramp_prefix);
1863 quote_argument (emacs_socket, argv[i]);
1864 send_to_emacs (emacs_socket, " ");
1867 else if (eval)
1869 /* Read expressions interactively. */
1870 while ((str = fgets (string, BUFSIZ, stdin)))
1872 send_to_emacs (emacs_socket, "-eval ");
1873 quote_argument (emacs_socket, str);
1875 send_to_emacs (emacs_socket, " ");
1878 send_to_emacs (emacs_socket, "\n");
1880 /* Wait for an answer. */
1881 if (!eval && !tty && !nowait && !quiet)
1883 printf ("Waiting for Emacs...");
1884 needlf = 2;
1886 fflush (stdout);
1887 while (fdatasync (1) != 0 && errno == EINTR)
1888 continue;
1890 /* Now, wait for an answer and print any messages. */
1891 while (exit_status == EXIT_SUCCESS)
1893 char *p, *end_p;
1896 errno = 0;
1897 rl = recv (emacs_socket, string, BUFSIZ, 0);
1899 /* If we receive a signal (e.g. SIGWINCH, which we pass
1900 through to Emacs), on some OSes we get EINTR and must retry. */
1901 while (rl < 0 && errno == EINTR);
1903 if (rl <= 0)
1904 break;
1906 string[rl] = '\0';
1908 /* Loop over all NL-terminated messages. */
1909 for (end_p = p = string; end_p != NULL && *end_p != '\0'; p = end_p)
1911 end_p = strchr (p, '\n');
1912 if (end_p != NULL)
1913 *end_p++ = '\0';
1915 if (strprefix ("-emacs-pid ", p))
1917 /* -emacs-pid PID: The process id of the Emacs process. */
1918 emacs_pid = strtol (p + strlen ("-emacs-pid"), NULL, 10);
1920 else if (strprefix ("-window-system-unsupported ", p))
1922 /* -window-system-unsupported: Emacs was compiled without support
1923 for whatever window system we tried. Try the alternate
1924 display, or, failing that, try the terminal. */
1925 if (alt_display)
1927 display = alt_display;
1928 alt_display = NULL;
1930 else
1932 nowait = 0;
1933 tty = 1;
1936 goto retry;
1938 else if (strprefix ("-print ", p))
1940 /* -print STRING: Print STRING on the terminal. */
1941 if (!suppress_output)
1943 str = unquote_argument (p + strlen ("-print "));
1944 if (needlf)
1945 printf ("\n");
1946 printf ("%s", str);
1947 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1950 else if (strprefix ("-print-nonl ", p))
1952 /* -print-nonl STRING: Print STRING on the terminal.
1953 Used to continue a preceding -print command. */
1954 if (!suppress_output)
1956 str = unquote_argument (p + strlen ("-print-nonl "));
1957 printf ("%s", str);
1958 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1961 else if (strprefix ("-error ", p))
1963 /* -error DESCRIPTION: Signal an error on the terminal. */
1964 str = unquote_argument (p + strlen ("-error "));
1965 if (needlf)
1966 printf ("\n");
1967 fprintf (stderr, "*ERROR*: %s", str);
1968 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1969 exit_status = EXIT_FAILURE;
1971 #ifdef SIGSTOP
1972 else if (strprefix ("-suspend ", p))
1974 /* -suspend: Suspend this terminal, i.e., stop the process. */
1975 if (needlf)
1976 printf ("\n");
1977 needlf = 0;
1978 kill (0, SIGSTOP);
1980 #endif
1981 else
1983 /* Unknown command. */
1984 if (needlf)
1985 printf ("\n");
1986 needlf = 0;
1987 printf ("*ERROR*: Unknown message: %s\n", p);
1992 if (needlf)
1993 printf ("\n");
1994 fflush (stdout);
1995 while (fdatasync (1) != 0 && errno == EINTR)
1996 continue;
1998 if (rl < 0)
1999 exit_status = EXIT_FAILURE;
2001 CLOSE_SOCKET (emacs_socket);
2002 return exit_status;
2005 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */