Minor casefiddle.c cleanups
[emacs.git] / lib-src / emacsclient.c
blob7b735dfb05dca303bf299b5d21f3e73ea571e022
1 /* Client process that communicates with GNU Emacs acting as server.
3 Copyright (C) 1986-1987, 1994, 1999-2017 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 <http://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 <stdio.h>
77 #include <stdlib.h>
78 #include <string.h>
79 #include <getopt.h>
80 #include <unistd.h>
82 #include <pwd.h>
83 #include <sys/stat.h>
84 #include <signal.h>
85 #include <errno.h>
87 #ifndef VERSION
88 #define VERSION "unspecified"
89 #endif
92 #ifndef EXIT_SUCCESS
93 #define EXIT_SUCCESS 0
94 #endif
96 #ifndef EXIT_FAILURE
97 #define EXIT_FAILURE 1
98 #endif
100 /* Additional space when allocating buffers for filenames, etc. */
101 #define EXTRA_SPACE 100
103 #ifdef min
104 #undef min
105 #endif
106 #define min(x, y) (((x) < (y)) ? (x) : (y))
109 /* Name used to invoke this program. */
110 const char *progname;
112 /* The second argument to main. */
113 char **main_argv;
115 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
116 int nowait = 0;
118 /* Nonzero means don't print messages for successful operations. --quiet. */
119 int quiet = 0;
121 /* Nonzero means don't print values returned from emacs. --suppress-output. */
122 int suppress_output = 0;
124 /* Nonzero means args are expressions to be evaluated. --eval. */
125 int eval = 0;
127 /* Nonzero means don't open a new frame. Inverse of --create-frame. */
128 int current_frame = 1;
130 /* The display on which Emacs should work. --display. */
131 const char *display = NULL;
133 /* The alternate display we should try if Emacs does not support display. */
134 const char *alt_display = NULL;
136 /* The parent window ID, if we are opening a frame via XEmbed. */
137 char *parent_id = NULL;
139 /* Nonzero means open a new Emacs frame on the current terminal. */
140 int tty = 0;
142 /* If non-NULL, the name of an editor to fallback to if the server
143 is not running. --alternate-editor. */
144 const char *alternate_editor = NULL;
146 /* If non-NULL, the filename of the UNIX socket. */
147 const char *socket_name = NULL;
149 /* If non-NULL, the filename of the authentication file. */
150 const char *server_file = NULL;
152 /* PID of the Emacs server process. */
153 int emacs_pid = 0;
155 /* If non-NULL, a string that should form a frame parameter alist to
156 be used for the new frame. */
157 const char *frame_parameters = NULL;
159 static _Noreturn void print_help_and_exit (void);
162 struct option longopts[] =
164 { "no-wait", no_argument, NULL, 'n' },
165 { "quiet", no_argument, NULL, 'q' },
166 { "suppress-output", no_argument, NULL, 'u' },
167 { "eval", no_argument, NULL, 'e' },
168 { "help", no_argument, NULL, 'H' },
169 { "version", no_argument, NULL, 'V' },
170 { "tty", no_argument, NULL, 't' },
171 { "nw", no_argument, NULL, 't' },
172 { "create-frame", no_argument, NULL, 'c' },
173 { "alternate-editor", required_argument, NULL, 'a' },
174 { "frame-parameters", required_argument, NULL, 'F' },
175 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
176 { "socket-name", required_argument, NULL, 's' },
177 #endif
178 { "server-file", required_argument, NULL, 'f' },
179 { "display", required_argument, NULL, 'd' },
180 { "parent-id", required_argument, NULL, 'p' },
181 { 0, 0, 0, 0 }
185 /* Like malloc but get fatal error if memory is exhausted. */
187 static void *
188 xmalloc (size_t size)
190 void *result = malloc (size);
191 if (result == NULL)
193 perror ("malloc");
194 exit (EXIT_FAILURE);
196 return result;
199 /* From sysdep.c */
200 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
202 char *get_current_dir_name (void);
204 /* Return the current working directory. Returns NULL on errors.
205 Any other returned value must be freed with free. This is used
206 only when get_current_dir_name is not defined on the system. */
207 char*
208 get_current_dir_name (void)
210 char *buf;
211 const char *pwd;
212 struct stat dotstat, pwdstat;
213 /* If PWD is accurate, use it instead of calling getcwd. PWD is
214 sometimes a nicer name, and using it may avoid a fatal error if a
215 parent directory is searchable but not readable. */
216 if ((pwd = egetenv ("PWD")) != 0
217 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
218 && stat (pwd, &pwdstat) == 0
219 && stat (".", &dotstat) == 0
220 && dotstat.st_ino == pwdstat.st_ino
221 && dotstat.st_dev == pwdstat.st_dev
222 #ifdef MAXPATHLEN
223 && strlen (pwd) < MAXPATHLEN
224 #endif
227 buf = (char *) xmalloc (strlen (pwd) + 1);
228 strcpy (buf, pwd);
230 else
232 size_t buf_size = 1024;
233 for (;;)
235 int tmp_errno;
236 buf = malloc (buf_size);
237 if (! buf)
238 break;
239 if (getcwd (buf, buf_size) == buf)
240 break;
241 tmp_errno = errno;
242 free (buf);
243 if (tmp_errno != ERANGE)
245 errno = tmp_errno;
246 return NULL;
248 buf_size *= 2;
249 if (! buf_size)
251 errno = ENOMEM;
252 return NULL;
256 return buf;
258 #endif
260 #ifdef WINDOWSNT
262 /* Like strdup but get a fatal error if memory is exhausted. */
263 char *xstrdup (const char *);
265 char *
266 xstrdup (const char *s)
268 char *result = strdup (s);
269 if (result == NULL)
271 perror ("strdup");
272 exit (EXIT_FAILURE);
274 return result;
277 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
279 char *w32_get_resource (HKEY, const char *, LPDWORD);
281 /* Retrieve an environment variable from the Emacs subkeys of the registry.
282 Return NULL if the variable was not found, or it was empty.
283 This code is based on w32_get_resource (w32.c). */
284 char *
285 w32_get_resource (HKEY predefined, const char *key, LPDWORD type)
287 HKEY hrootkey = NULL;
288 char *result = NULL;
289 DWORD cbData;
291 if (RegOpenKeyEx (predefined, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
293 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS)
295 result = (char *) xmalloc (cbData);
297 if ((RegQueryValueEx (hrootkey, key, NULL, type, (LPBYTE)result, &cbData) != ERROR_SUCCESS)
298 || (*result == 0))
300 free (result);
301 result = NULL;
305 RegCloseKey (hrootkey);
308 return result;
312 getenv wrapper for Windows
314 Value is allocated on the heap, and can be free'd.
316 This is needed to duplicate Emacs's behavior, which is to look for
317 environment variables in the registry if they don't appear in the
318 environment. */
319 char *
320 w32_getenv (const char *envvar)
322 char *value;
323 DWORD dwType;
325 if ((value = getenv (envvar)))
326 /* Found in the environment. strdup it, because values returned
327 by getenv cannot be free'd. */
328 return xstrdup (value);
330 if (! (value = w32_get_resource (HKEY_CURRENT_USER, envvar, &dwType)) &&
331 ! (value = w32_get_resource (HKEY_LOCAL_MACHINE, envvar, &dwType)))
333 /* "w32console" is what Emacs on Windows uses for tty-type under -nw. */
334 if (strcmp (envvar, "TERM") == 0)
335 return xstrdup ("w32console");
336 /* Found neither in the environment nor in the registry. */
337 return NULL;
340 if (dwType == REG_SZ)
341 /* Registry; no need to expand. */
342 return value;
344 if (dwType == REG_EXPAND_SZ)
346 DWORD size;
348 if ((size = ExpandEnvironmentStrings (value, NULL, 0)))
350 char *buffer = (char *) xmalloc (size);
351 if (ExpandEnvironmentStrings (value, buffer, size))
353 /* Found and expanded. */
354 free (value);
355 return buffer;
358 /* Error expanding. */
359 free (buffer);
363 /* Not the right type, or not correctly expanded. */
364 free (value);
365 return NULL;
368 int w32_window_app (void);
371 w32_window_app (void)
373 static int window_app = -1;
374 char szTitle[MAX_PATH];
376 if (window_app < 0)
378 /* Checking for STDOUT does not work; it's a valid handle also in
379 nonconsole apps. Testing for the console title seems to work. */
380 window_app = (GetConsoleTitleA (szTitle, MAX_PATH) == 0);
381 if (window_app)
382 InitCommonControls ();
385 return window_app;
388 /* execvp wrapper for Windows. Quotes arguments with embedded spaces.
390 This is necessary due to the broken implementation of exec* routines in
391 the Microsoft libraries: they concatenate the arguments together without
392 quoting special characters, and pass the result to CreateProcess, with
393 predictably bad results. By contrast, POSIX execvp passes the arguments
394 directly into the argv array of the child process. */
396 int w32_execvp (const char *, char **);
399 w32_execvp (const char *path, char **argv)
401 int i;
403 /* Required to allow a .BAT script as alternate editor. */
404 argv[0] = (char *) alternate_editor;
406 for (i = 0; argv[i]; i++)
407 if (strchr (argv[i], ' '))
409 char *quoted = alloca (strlen (argv[i]) + 3);
410 sprintf (quoted, "\"%s\"", argv[i]);
411 argv[i] = quoted;
414 return execvp (path, argv);
417 #undef execvp
418 #define execvp w32_execvp
420 /* Emulation of ttyname for Windows. */
421 const char *ttyname (int);
422 const char *
423 ttyname (int fd)
425 return "CONOUT$";
428 #endif /* WINDOWSNT */
430 /* Display a normal or error message.
431 On Windows, use a message box if compiled as a Windows app. */
432 static void message (bool, const char *, ...) ATTRIBUTE_FORMAT_PRINTF (2, 3);
433 static void
434 message (bool is_error, const char *format, ...)
436 va_list args;
438 va_start (args, format);
440 #ifdef WINDOWSNT
441 if (w32_window_app ())
443 char msg[2048];
444 vsnprintf (msg, sizeof msg, format, args);
445 msg[sizeof msg - 1] = '\0';
447 if (is_error)
448 MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
449 else
450 MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
452 else
453 #endif
455 FILE *f = is_error ? stderr : stdout;
457 vfprintf (f, format, args);
458 fflush (f);
461 va_end (args);
464 /* Decode the options from argv and argc.
465 The global variable `optind' will say how many arguments we used up. */
467 static void
468 decode_options (int argc, char **argv)
470 alternate_editor = egetenv ("ALTERNATE_EDITOR");
472 while (1)
474 int opt = getopt_long_only (argc, argv,
475 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
476 "VHnequa:s:f:d:F:tc",
477 #else
478 "VHnequa:f:d:F:tc",
479 #endif
480 longopts, 0);
482 if (opt == EOF)
483 break;
485 switch (opt)
487 case 0:
488 /* If getopt returns 0, then it has already processed a
489 long-named option. We should do nothing. */
490 break;
492 case 'a':
493 alternate_editor = optarg;
494 break;
496 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
497 case 's':
498 socket_name = optarg;
499 break;
500 #endif
502 case 'f':
503 server_file = optarg;
504 break;
506 /* We used to disallow this argument in w32, but it seems better
507 to allow it, for the occasional case where the user is
508 connecting with a w32 client to a server compiled with X11
509 support. */
510 case 'd':
511 display = optarg;
512 break;
514 case 'n':
515 nowait = 1;
516 break;
518 case 'e':
519 eval = 1;
520 break;
522 case 'q':
523 quiet = 1;
524 break;
526 case 'u':
527 suppress_output = 1;
528 break;
530 case 'V':
531 message (false, "emacsclient %s\n", VERSION);
532 exit (EXIT_SUCCESS);
533 break;
535 case 't':
536 tty = 1;
537 current_frame = 0;
538 break;
540 case 'c':
541 current_frame = 0;
542 break;
544 case 'p':
545 parent_id = optarg;
546 current_frame = 0;
547 break;
549 case 'H':
550 print_help_and_exit ();
551 break;
553 case 'F':
554 frame_parameters = optarg;
555 break;
557 default:
558 message (true, "Try '%s --help' for more information\n", progname);
559 exit (EXIT_FAILURE);
560 break;
564 /* If the -c option is used (without -t) and no --display argument
565 is provided, try $DISPLAY.
566 Without the -c option, we used to set `display' to $DISPLAY by
567 default, but this changed the default behavior and is sometimes
568 inconvenient. So we force users to use "--display $DISPLAY" if
569 they want Emacs to connect to their current display.
571 Some window systems have a notion of default display not
572 reflected in the DISPLAY variable. If the user didn't give us an
573 explicit display, try this platform-specific after trying the
574 display in DISPLAY (if any). */
575 if (!current_frame && !tty && !display)
577 /* Set these here so we use a default_display only when the user
578 didn't give us an explicit display. */
579 #if defined (NS_IMPL_COCOA)
580 alt_display = "ns";
581 #elif defined (HAVE_NTGUI)
582 alt_display = "w32";
583 #endif
585 display = egetenv ("DISPLAY");
588 if (!display)
590 display = alt_display;
591 alt_display = NULL;
594 /* A null-string display is invalid. */
595 if (display && strlen (display) == 0)
596 display = NULL;
598 /* If no display is available, new frames are tty frames. */
599 if (!current_frame && !display)
600 tty = 1;
602 #ifdef WINDOWSNT
603 /* Emacs on Windows does not support graphical and text terminal
604 frames in the same instance. So, treat the -t and -c options as
605 equivalent, and open a new frame on the server's terminal.
606 Ideally, we would only set tty = 1 when the serve is running in a
607 console, but alas we don't know that. As a workaround, always
608 ask for a tty frame, and let server.el figure it out. */
609 if (!current_frame)
611 display = NULL;
612 tty = 1;
614 #endif /* WINDOWSNT */
618 static _Noreturn void
619 print_help_and_exit (void)
621 /* Spaces and tabs are significant in this message; they're chosen so the
622 message aligns properly both in a tty and in a Windows message box.
623 Please try to preserve them; otherwise the output is very hard to read
624 when using emacsclientw. */
625 message (false,
626 "Usage: %s [OPTIONS] FILE...\n%s%s%s", progname, "\
627 Tell the Emacs server to visit the specified files.\n\
628 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
630 The following OPTIONS are accepted:\n\
631 -V, --version Just print version info and return\n\
632 -H, --help Print this usage information message\n\
633 -nw, -t, --tty Open a new Emacs frame on the current terminal\n\
634 -c, --create-frame Create a new frame instead of trying to\n\
635 use the current Emacs frame\n\
636 ", "\
637 -F ALIST, --frame-parameters=ALIST\n\
638 Set the parameters of a new frame\n\
639 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
640 -n, --no-wait Don't wait for the server to return\n\
641 -q, --quiet Don't display messages on success\n\
642 -u, --suppress-output Don't display return values from the server\n\
643 -d DISPLAY, --display=DISPLAY\n\
644 Visit the file in the given display\n\
645 ", "\
646 --parent-id=ID Open in parent window ID, via XEmbed\n"
647 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
648 "-s SOCKET, --socket-name=SOCKET\n\
649 Set filename of the UNIX socket for communication\n"
650 #endif
651 "-f SERVER, --server-file=SERVER\n\
652 Set filename of the TCP authentication file\n\
653 -a EDITOR, --alternate-editor=EDITOR\n\
654 Editor to fallback to if the server is not running\n"
655 " If EDITOR is the empty string, start Emacs in daemon\n\
656 mode and try connecting again\n"
657 "\n\
658 Report bugs with M-x report-emacs-bug.\n");
659 exit (EXIT_SUCCESS);
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. */
666 static _Noreturn void
667 fail (void)
669 if (alternate_editor)
671 int i = optind - 1;
673 execvp (alternate_editor, main_argv + i);
674 message (true, "%s: error executing alternate editor \"%s\"\n",
675 progname, alternate_editor);
677 exit (EXIT_FAILURE);
681 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
684 main (int argc, char **argv)
686 main_argv = argv;
687 progname = argv[0];
688 message (true, "%s: Sorry, the Emacs server is supported only\n"
689 "on systems with Berkeley sockets.\n",
690 argv[0]);
691 fail ();
694 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
696 #define AUTH_KEY_LENGTH 64
697 #define SEND_BUFFER_SIZE 4096
699 /* Buffer to accumulate data to send in TCP connections. */
700 char send_buffer[SEND_BUFFER_SIZE + 1];
701 int sblen = 0; /* Fill pointer for the send buffer. */
702 /* Socket used to communicate with the Emacs server process. */
703 HSOCKET emacs_socket = 0;
705 /* On Windows, the socket library was historically separate from the
706 standard C library, so errors are handled differently. */
708 static void
709 sock_err_message (const char *function_name)
711 #ifdef WINDOWSNT
712 char* msg = NULL;
714 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
715 | FORMAT_MESSAGE_ALLOCATE_BUFFER
716 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
717 NULL, WSAGetLastError (), 0, (LPTSTR)&msg, 0, NULL);
719 message (true, "%s: %s: %s\n", progname, function_name, msg);
721 LocalFree (msg);
722 #else
723 message (true, "%s: %s: %s\n", progname, function_name, strerror (errno));
724 #endif
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. */
732 static void
733 send_to_emacs (HSOCKET s, const char *data)
735 size_t dlen;
737 if (!data)
738 return;
740 dlen = strlen (data);
741 while (*data)
743 size_t part = min (dlen, SEND_BUFFER_SIZE - sblen);
744 memcpy (&send_buffer[sblen], data, part);
745 data += part;
746 sblen += part;
748 if (sblen == SEND_BUFFER_SIZE
749 || (sblen > 0 && send_buffer[sblen-1] == '\n'))
751 int sent = send (s, send_buffer, sblen, 0);
752 if (sent < 0)
754 message (true, "%s: failed to send %d bytes to socket: %s\n",
755 progname, sblen, strerror (errno));
756 fail ();
758 if (sent != sblen)
759 memmove (send_buffer, &send_buffer[sent], sblen - sent);
760 sblen -= sent;
763 dlen -= part;
768 /* In STR, insert a & before each &, each space, each newline, and
769 any initial -. Change spaces to underscores, too, so that the
770 return value never contains a space.
772 Does not change the string. Outputs the result to S. */
773 static void
774 quote_argument (HSOCKET s, const char *str)
776 char *copy = (char *) xmalloc (strlen (str) * 2 + 1);
777 const char *p;
778 char *q;
780 p = str;
781 q = copy;
782 while (*p)
784 if (*p == ' ')
786 *q++ = '&';
787 *q++ = '_';
788 p++;
790 else if (*p == '\n')
792 *q++ = '&';
793 *q++ = 'n';
794 p++;
796 else
798 if (*p == '&' || (*p == '-' && p == str))
799 *q++ = '&';
800 *q++ = *p++;
803 *q++ = 0;
805 send_to_emacs (s, copy);
807 free (copy);
811 /* The inverse of quote_argument. Removes quoting in string STR by
812 modifying the string in place. Returns STR. */
814 static char *
815 unquote_argument (char *str)
817 char *p, *q;
819 if (! str)
820 return str;
822 p = str;
823 q = str;
824 while (*p)
826 if (*p == '&')
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 = '-';
838 *q++ = *p++;
840 *q = 0;
841 return str;
845 static int
846 file_name_absolute_p (const char *filename)
848 /* Sanity check, it shouldn't happen. */
849 if (! filename) return false;
851 /* /xxx is always an absolute path. */
852 if (filename[0] == '/') return true;
854 /* Empty filenames (which shouldn't happen) are relative. */
855 if (filename[0] == '\0') return false;
857 #ifdef WINDOWSNT
858 /* X:\xxx is always absolute. */
859 if (isalpha ((unsigned char) filename[0])
860 && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
861 return true;
863 /* Both \xxx and \\xxx\yyy are absolute. */
864 if (filename[0] == '\\') return true;
865 #endif
867 return false;
870 #ifdef WINDOWSNT
871 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
872 void __cdecl close_winsock (void);
873 void __cdecl
874 close_winsock (void)
876 WSACleanup ();
879 /* Initialize the WinSock2 library. */
880 void initialize_sockets (void);
881 void
882 initialize_sockets (void)
884 WSADATA wsaData;
886 if (WSAStartup (MAKEWORD (2, 0), &wsaData))
888 message (true, "%s: error initializing WinSock2\n", progname);
889 exit (EXIT_FAILURE);
892 atexit (close_winsock);
894 #endif /* WINDOWSNT */
897 /* Read the information needed to set up a TCP comm channel with
898 the Emacs server: host, port, and authentication string. */
900 static int
901 get_server_config (const char *config_file, struct sockaddr_in *server,
902 char *authentication)
904 char dotted[32];
905 char *port;
906 FILE *config = NULL;
908 if (file_name_absolute_p (config_file))
909 config = fopen (config_file, "rb");
910 else
912 const char *home = egetenv ("HOME");
914 if (home)
916 char *path = xmalloc (strlen (home) + strlen (config_file)
917 + EXTRA_SPACE);
918 char *z = stpcpy (path, home);
919 z = stpcpy (z, "/.emacs.d/server/");
920 strcpy (z, config_file);
921 config = fopen (path, "rb");
922 free (path);
924 #ifdef WINDOWSNT
925 if (!config && (home = egetenv ("APPDATA")))
927 char *path = xmalloc (strlen (home) + strlen (config_file)
928 + EXTRA_SPACE);
929 char *z = stpcpy (path, home);
930 z = stpcpy (z, "/.emacs.d/server/");
931 strcpy (z, config_file);
932 config = fopen (path, "rb");
933 free (path);
935 #endif
938 if (! config)
939 return false;
941 if (fgets (dotted, sizeof dotted, config)
942 && (port = strchr (dotted, ':')))
943 *port++ = '\0';
944 else
946 message (true, "%s: invalid configuration info\n", progname);
947 exit (EXIT_FAILURE);
950 server->sin_family = AF_INET;
951 server->sin_addr.s_addr = inet_addr (dotted);
952 server->sin_port = htons (atoi (port));
954 if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
956 message (true, "%s: cannot read authentication info\n", progname);
957 exit (EXIT_FAILURE);
960 fclose (config);
962 return true;
965 static HSOCKET
966 set_tcp_socket (const char *local_server_file)
968 HSOCKET s;
969 struct sockaddr_in server;
970 struct linger l_arg = {1, 1};
971 char auth_string[AUTH_KEY_LENGTH + 1];
973 if (! get_server_config (local_server_file, &server, auth_string))
974 return INVALID_SOCKET;
976 if (server.sin_addr.s_addr != inet_addr ("127.0.0.1") && !quiet)
977 message (false, "%s: connected to remote socket at %s\n",
978 progname, inet_ntoa (server.sin_addr));
980 /* Open up an AF_INET socket. */
981 if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
983 /* Since we have an alternate to try out, this is not an error
984 yet; popping out a modal dialog at this stage would make -a
985 option totally useless for emacsclientw -- the user will
986 still get an error message if the alternate editor fails. */
987 #ifdef WINDOWSNT
988 if(!(w32_window_app () && alternate_editor))
989 #endif
990 sock_err_message ("socket");
991 return INVALID_SOCKET;
994 /* Set up the socket. */
995 if (connect (s, (struct sockaddr *) &server, sizeof server) < 0)
997 #ifdef WINDOWSNT
998 if(!(w32_window_app () && alternate_editor))
999 #endif
1000 sock_err_message ("connect");
1001 return INVALID_SOCKET;
1004 setsockopt (s, SOL_SOCKET, SO_LINGER, (char *) &l_arg, sizeof l_arg);
1006 /* Send the authentication. */
1007 auth_string[AUTH_KEY_LENGTH] = '\0';
1009 send_to_emacs (s, "-auth ");
1010 send_to_emacs (s, auth_string);
1011 send_to_emacs (s, " ");
1013 return s;
1017 /* Returns 1 if PREFIX is a prefix of STRING. */
1018 static int
1019 strprefix (const char *prefix, const char *string)
1021 return !strncmp (prefix, string, strlen (prefix));
1024 /* Get tty name and type. If successful, return the type in TTY_TYPE
1025 and the name in TTY_NAME, and return 1. Otherwise, fail if NOABORT
1026 is zero, or return 0 if NOABORT is non-zero. */
1028 static int
1029 find_tty (const char **tty_type, const char **tty_name, int noabort)
1031 const char *type = egetenv ("TERM");
1032 const char *name = ttyname (fileno (stdout));
1034 if (!name)
1036 if (noabort)
1037 return 0;
1038 else
1040 message (true, "%s: could not get terminal name\n", progname);
1041 fail ();
1045 if (!type)
1047 if (noabort)
1048 return 0;
1049 else
1051 message (true, "%s: please set the TERM variable to your terminal type\n",
1052 progname);
1053 fail ();
1057 if (strcmp (type, "eterm") == 0)
1059 if (noabort)
1060 return 0;
1061 else
1063 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1064 message (true, "%s: opening a frame in an Emacs term buffer"
1065 " is not supported\n", progname);
1066 fail ();
1070 *tty_name = name;
1071 *tty_type = type;
1072 return 1;
1076 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1078 /* Three possibilities:
1079 2 - can't be `stat'ed (sets errno)
1080 1 - isn't owned by us
1081 0 - success: none of the above */
1083 static int
1084 socket_status (const char *name)
1086 struct stat statbfr;
1088 if (stat (name, &statbfr) == -1)
1089 return 2;
1091 if (statbfr.st_uid != geteuid ())
1092 return 1;
1094 return 0;
1098 /* A signal handler that passes the signal to the Emacs process.
1099 Useful for SIGWINCH. */
1101 static void
1102 pass_signal_to_emacs (int signalnum)
1104 int old_errno = errno;
1106 if (emacs_pid)
1107 kill (emacs_pid, signalnum);
1109 signal (signalnum, pass_signal_to_emacs);
1110 errno = old_errno;
1113 /* Signal handler for SIGCONT; notify the Emacs process that it can
1114 now resume our tty frame. */
1116 static void
1117 handle_sigcont (int signalnum)
1119 int old_errno = errno;
1120 pid_t pgrp = getpgrp ();
1121 pid_t tcpgrp = tcgetpgrp (1);
1123 if (tcpgrp == pgrp)
1125 /* We are in the foreground. */
1126 send_to_emacs (emacs_socket, "-resume \n");
1128 else if (0 <= tcpgrp && tty)
1130 /* We are in the background; cancel the continue. */
1131 kill (-pgrp, SIGTTIN);
1134 signal (signalnum, handle_sigcont);
1135 errno = old_errno;
1138 /* Signal handler for SIGTSTP; notify the Emacs process that we are
1139 going to sleep. Normally the suspend is initiated by Emacs via
1140 server-handle-suspend-tty, but if the server gets out of sync with
1141 reality, we may get a SIGTSTP on C-z. Handling this signal and
1142 notifying Emacs about it should get things under control again. */
1144 static void
1145 handle_sigtstp (int signalnum)
1147 int old_errno = errno;
1148 sigset_t set;
1150 if (emacs_socket)
1151 send_to_emacs (emacs_socket, "-suspend \n");
1153 /* Unblock this signal and call the default handler by temporarily
1154 changing the handler and resignaling. */
1155 sigprocmask (SIG_BLOCK, NULL, &set);
1156 sigdelset (&set, signalnum);
1157 signal (signalnum, SIG_DFL);
1158 raise (signalnum);
1159 sigprocmask (SIG_SETMASK, &set, NULL); /* Let's the above signal through. */
1160 signal (signalnum, handle_sigtstp);
1162 errno = old_errno;
1166 /* Set up signal handlers before opening a frame on the current tty. */
1168 static void
1169 init_signals (void)
1171 /* Set up signal handlers. */
1172 signal (SIGWINCH, pass_signal_to_emacs);
1174 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
1175 deciding which terminal the signal came from. C-g is now a
1176 normal input event on secondary terminals. */
1177 #if 0
1178 signal (SIGINT, pass_signal_to_emacs);
1179 signal (SIGQUIT, pass_signal_to_emacs);
1180 #endif
1182 signal (SIGCONT, handle_sigcont);
1183 signal (SIGTSTP, handle_sigtstp);
1184 signal (SIGTTOU, handle_sigtstp);
1188 static HSOCKET
1189 set_local_socket (const char *local_socket_name)
1191 HSOCKET s;
1192 struct sockaddr_un server;
1194 /* Open up an AF_UNIX socket in this person's home directory. */
1195 if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
1197 message (true, "%s: socket: %s\n", progname, strerror (errno));
1198 return INVALID_SOCKET;
1201 server.sun_family = AF_UNIX;
1204 int sock_status;
1205 int saved_errno;
1206 const char *server_name = local_socket_name;
1207 const char *tmpdir = NULL;
1208 char *tmpdir_storage = NULL;
1209 char *socket_name_storage = NULL;
1211 if (!strchr (local_socket_name, '/') && !strchr (local_socket_name, '\\'))
1213 /* socket_name is a file name component. */
1214 long uid = geteuid ();
1215 tmpdir = egetenv ("TMPDIR");
1216 if (!tmpdir)
1218 #ifdef DARWIN_OS
1219 #ifndef _CS_DARWIN_USER_TEMP_DIR
1220 #define _CS_DARWIN_USER_TEMP_DIR 65537
1221 #endif
1222 size_t n = confstr (_CS_DARWIN_USER_TEMP_DIR, NULL, (size_t) 0);
1223 if (n > 0)
1225 tmpdir = tmpdir_storage = xmalloc (n);
1226 confstr (_CS_DARWIN_USER_TEMP_DIR, tmpdir_storage, n);
1228 else
1229 #endif
1230 tmpdir = "/tmp";
1232 socket_name_storage =
1233 xmalloc (strlen (tmpdir) + strlen (server_name) + EXTRA_SPACE);
1234 char *z = stpcpy (socket_name_storage, tmpdir);
1235 z += sprintf (z, "/emacs%ld/", uid);
1236 strcpy (z, server_name);
1237 local_socket_name = socket_name_storage;
1240 if (strlen (local_socket_name) < sizeof (server.sun_path))
1241 strcpy (server.sun_path, local_socket_name);
1242 else
1244 message (true, "%s: socket-name %s too long\n",
1245 progname, local_socket_name);
1246 fail ();
1249 /* See if the socket exists, and if it's owned by us. */
1250 sock_status = socket_status (server.sun_path);
1251 saved_errno = errno;
1252 if (sock_status && tmpdir)
1254 /* Failing that, see if LOGNAME or USER exist and differ from
1255 our euid. If so, look for a socket based on the UID
1256 associated with the name. This is reminiscent of the logic
1257 that init_editfns uses to set the global Vuser_full_name. */
1259 const char *user_name = egetenv ("LOGNAME");
1261 if (!user_name)
1262 user_name = egetenv ("USER");
1264 if (user_name)
1266 struct passwd *pw = getpwnam (user_name);
1268 if (pw && (pw->pw_uid != geteuid ()))
1270 /* We're running under su, apparently. */
1271 long uid = pw->pw_uid;
1272 char *user_socket_name
1273 = xmalloc (strlen (tmpdir) + strlen (server_name)
1274 + EXTRA_SPACE);
1275 char *z = stpcpy (user_socket_name, tmpdir);
1276 z += sprintf (z, "/emacs%ld/", uid);
1277 strcpy (z, server_name);
1279 if (strlen (user_socket_name) < sizeof (server.sun_path))
1280 strcpy (server.sun_path, user_socket_name);
1281 else
1283 message (true, "%s: socket-name %s too long\n",
1284 progname, user_socket_name);
1285 exit (EXIT_FAILURE);
1287 free (user_socket_name);
1289 sock_status = socket_status (server.sun_path);
1290 saved_errno = errno;
1292 else
1293 errno = saved_errno;
1297 free (socket_name_storage);
1298 free (tmpdir_storage);
1300 switch (sock_status)
1302 case 1:
1303 /* There's a socket, but it isn't owned by us. This is OK if
1304 we are root. */
1305 if (0 != geteuid ())
1307 message (true, "%s: Invalid socket owner\n", progname);
1308 return INVALID_SOCKET;
1310 break;
1312 case 2:
1313 /* `stat' failed */
1314 if (saved_errno == ENOENT)
1315 message (true,
1316 "%s: can't find socket; have you started the server?\n\
1317 To start the server in Emacs, type \"M-x server-start\".\n",
1318 progname);
1319 else
1320 message (true, "%s: can't stat %s: %s\n",
1321 progname, server.sun_path, strerror (saved_errno));
1322 return INVALID_SOCKET;
1326 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
1327 < 0)
1329 message (true, "%s: connect: %s\n", progname, strerror (errno));
1330 return INVALID_SOCKET;
1333 return s;
1335 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1337 static HSOCKET
1338 set_socket (int no_exit_if_error)
1340 HSOCKET s;
1341 const char *local_server_file = server_file;
1343 INITIALIZE ();
1345 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1346 /* Explicit --socket-name argument. */
1347 if (socket_name)
1349 s = set_local_socket (socket_name);
1350 if ((s != INVALID_SOCKET) || no_exit_if_error)
1351 return s;
1352 message (true, "%s: error accessing socket \"%s\"\n",
1353 progname, socket_name);
1354 exit (EXIT_FAILURE);
1356 #endif
1358 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1359 if (!local_server_file)
1360 local_server_file = egetenv ("EMACS_SERVER_FILE");
1362 if (local_server_file)
1364 s = set_tcp_socket (local_server_file);
1365 if ((s != INVALID_SOCKET) || no_exit_if_error)
1366 return s;
1368 message (true, "%s: error accessing server file \"%s\"\n",
1369 progname, local_server_file);
1370 exit (EXIT_FAILURE);
1373 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1374 /* Implicit local socket. */
1375 s = set_local_socket ("server");
1376 if (s != INVALID_SOCKET)
1377 return s;
1378 #endif
1380 /* Implicit server file. */
1381 s = set_tcp_socket ("server");
1382 if ((s != INVALID_SOCKET) || no_exit_if_error)
1383 return s;
1385 /* No implicit or explicit socket, and no alternate editor. */
1386 message (true, "%s: No socket or alternate editor. Please use:\n\n"
1387 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1388 "\t--socket-name\n"
1389 #endif
1390 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1391 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1392 progname);
1393 exit (EXIT_FAILURE);
1396 #ifdef HAVE_NTGUI
1397 FARPROC set_fg; /* Pointer to AllowSetForegroundWindow. */
1398 FARPROC get_wc; /* Pointer to RealGetWindowClassA. */
1400 void w32_set_user_model_id (void);
1402 void
1403 w32_set_user_model_id (void)
1405 HMODULE shell;
1406 HRESULT (WINAPI * set_user_model) (const wchar_t * id);
1408 /* On Windows 7 and later, we need to set the user model ID
1409 to associate emacsclient launched files with Emacs frames
1410 in the UI. */
1411 shell = LoadLibrary ("shell32.dll");
1412 if (shell)
1414 set_user_model
1415 = (void *) GetProcAddress (shell,
1416 "SetCurrentProcessExplicitAppUserModelID");
1417 /* If the function is defined, then we are running on Windows 7
1418 or newer, and the UI uses this to group related windows
1419 together. Since emacs, runemacs, emacsclient are related, we
1420 want them grouped even though the executables are different,
1421 so we need to set a consistent ID between them. */
1422 if (set_user_model)
1423 set_user_model (L"GNU.Emacs");
1425 FreeLibrary (shell);
1429 BOOL CALLBACK w32_find_emacs_process (HWND, LPARAM);
1431 BOOL CALLBACK
1432 w32_find_emacs_process (HWND hWnd, LPARAM lParam)
1434 DWORD pid;
1435 char class[6];
1437 /* Reject any window not of class "Emacs". */
1438 if (! get_wc (hWnd, class, sizeof (class))
1439 || strcmp (class, "Emacs"))
1440 return TRUE;
1442 /* We only need the process id, not the thread id. */
1443 (void) GetWindowThreadProcessId (hWnd, &pid);
1445 /* Not the one we're looking for. */
1446 if (pid != (DWORD) emacs_pid) return TRUE;
1448 /* OK, let's raise it. */
1449 set_fg (emacs_pid);
1451 /* Stop enumeration. */
1452 return FALSE;
1455 /* Search for a window of class "Emacs" and owned by a process with
1456 process id = emacs_pid. If found, allow it to grab the focus. */
1457 void w32_give_focus (void);
1459 void
1460 w32_give_focus (void)
1462 HANDLE user32;
1464 /* It shouldn't happen when dealing with TCP sockets. */
1465 if (!emacs_pid) return;
1467 user32 = GetModuleHandle ("user32.dll");
1469 if (!user32)
1470 return;
1472 /* Modern Windows restrict which processes can set the foreground window.
1473 emacsclient can allow Emacs to grab the focus by calling the function
1474 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1475 NT) lack this function, so we have to check its availability. */
1476 if ((set_fg = GetProcAddress (user32, "AllowSetForegroundWindow"))
1477 && (get_wc = GetProcAddress (user32, "RealGetWindowClassA")))
1478 EnumWindows (w32_find_emacs_process, (LPARAM) 0);
1480 #endif /* HAVE_NTGUI */
1482 /* Start the emacs daemon and try to connect to it. */
1484 static void
1485 start_daemon_and_retry_set_socket (void)
1487 #ifndef WINDOWSNT
1488 pid_t dpid;
1489 int status;
1491 dpid = fork ();
1493 if (dpid > 0)
1495 pid_t w;
1496 w = waitpid (dpid, &status, WUNTRACED | WCONTINUED);
1498 if ((w == -1) || !WIFEXITED (status) || WEXITSTATUS (status))
1500 message (true, "Error: Could not start the Emacs daemon\n");
1501 exit (EXIT_FAILURE);
1504 /* Try connecting, the daemon should have started by now. */
1505 message (true, "Emacs daemon should have started, trying to connect again\n");
1506 if ((emacs_socket = set_socket (1)) == INVALID_SOCKET)
1508 message (true, "Error: Cannot connect even after starting the Emacs daemon\n");
1509 exit (EXIT_FAILURE);
1512 else if (dpid < 0)
1514 fprintf (stderr, "Error: Cannot fork!\n");
1515 exit (EXIT_FAILURE);
1517 else
1519 char emacs[] = "emacs";
1520 char daemon_option[] = "--daemon";
1521 char *d_argv[3];
1522 d_argv[0] = emacs;
1523 d_argv[1] = daemon_option;
1524 d_argv[2] = 0;
1525 if (socket_name != NULL)
1527 /* Pass --daemon=socket_name as argument. */
1528 const char *deq = "--daemon=";
1529 char *daemon_arg = xmalloc (strlen (deq)
1530 + strlen (socket_name) + 1);
1531 strcpy (stpcpy (daemon_arg, deq), socket_name);
1532 d_argv[1] = daemon_arg;
1534 execvp ("emacs", d_argv);
1535 message (true, "%s: error starting emacs daemon\n", progname);
1537 #else /* WINDOWSNT */
1538 DWORD wait_result;
1539 HANDLE w32_daemon_event;
1540 STARTUPINFO si;
1541 PROCESS_INFORMATION pi;
1543 ZeroMemory (&si, sizeof si);
1544 si.cb = sizeof si;
1545 ZeroMemory (&pi, sizeof pi);
1547 /* We start Emacs in daemon mode, and then wait for it to signal us
1548 it is ready to accept client connections, by asserting an event
1549 whose name is known to the daemon (defined by nt/inc/ms-w32.h). */
1551 if (!CreateProcess (NULL, (LPSTR)"emacs --daemon", NULL, NULL, FALSE,
1552 CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
1554 char* msg = NULL;
1556 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
1557 | FORMAT_MESSAGE_ALLOCATE_BUFFER
1558 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1559 NULL, GetLastError (), 0, (LPTSTR)&msg, 0, NULL);
1560 message (true, "%s: error starting emacs daemon (%s)\n", progname, msg);
1561 exit (EXIT_FAILURE);
1564 w32_daemon_event = CreateEvent (NULL, TRUE, FALSE, W32_DAEMON_EVENT);
1565 if (w32_daemon_event == NULL)
1567 message (true, "Couldn't create Windows daemon event");
1568 exit (EXIT_FAILURE);
1570 if ((wait_result = WaitForSingleObject (w32_daemon_event, INFINITE))
1571 != WAIT_OBJECT_0)
1573 const char *msg = NULL;
1575 switch (wait_result)
1577 case WAIT_ABANDONED:
1578 msg = "The daemon exited unexpectedly";
1579 break;
1580 case WAIT_TIMEOUT:
1581 /* Can't happen due to INFINITE. */
1582 default:
1583 case WAIT_FAILED:
1584 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
1585 | FORMAT_MESSAGE_ALLOCATE_BUFFER
1586 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1587 NULL, GetLastError (), 0, (LPTSTR)&msg, 0, NULL);
1588 break;
1590 message (true, "Error: Could not start the Emacs daemon: %s\n", msg);
1591 exit (EXIT_FAILURE);
1593 CloseHandle (w32_daemon_event);
1595 /* Try connecting, the daemon should have started by now. */
1596 /* It's just a progress message, so don't pop a dialog if this is
1597 emacsclientw. */
1598 if (!w32_window_app ())
1599 message (true,
1600 "Emacs daemon should have started, trying to connect again\n");
1601 if ((emacs_socket = set_socket (1)) == INVALID_SOCKET)
1603 message (true,
1604 "Error: Cannot connect even after starting the Emacs daemon\n");
1605 exit (EXIT_FAILURE);
1607 #endif /* WINDOWSNT */
1611 main (int argc, char **argv)
1613 int rl = 0, needlf = 0;
1614 char *cwd, *str;
1615 char string[BUFSIZ+1];
1616 int start_daemon_if_needed;
1617 int exit_status = EXIT_SUCCESS;
1619 main_argv = argv;
1620 progname = argv[0];
1622 #ifdef HAVE_NTGUI
1623 /* On Windows 7 and later, we need to explicitly associate
1624 emacsclient with emacs so the UI behaves sensibly. This
1625 association does no harm if we're not actually connecting to an
1626 Emacs using a window display. */
1627 w32_set_user_model_id ();
1628 #endif /* HAVE_NTGUI */
1630 /* Process options. */
1631 decode_options (argc, argv);
1633 if ((argc - optind < 1) && !eval && current_frame)
1635 message (true, "%s: file name or argument required\n"
1636 "Try '%s --help' for more information\n",
1637 progname, progname);
1638 exit (EXIT_FAILURE);
1641 #ifndef WINDOWSNT
1642 if (tty)
1644 pid_t pgrp = getpgrp ();
1645 pid_t tcpgrp = tcgetpgrp (1);
1646 if (0 <= tcpgrp && tcpgrp != pgrp)
1647 kill (-pgrp, SIGTTIN);
1649 #endif /* !WINDOWSNT */
1651 /* If alternate_editor is the empty string, start the emacs daemon
1652 in case of failure to connect. */
1653 start_daemon_if_needed = (alternate_editor
1654 && (alternate_editor[0] == '\0'));
1656 emacs_socket = set_socket (alternate_editor || start_daemon_if_needed);
1657 if (emacs_socket == INVALID_SOCKET)
1659 if (! start_daemon_if_needed)
1660 fail ();
1662 start_daemon_and_retry_set_socket ();
1665 cwd = get_current_dir_name ();
1666 if (cwd == 0)
1668 message (true, "%s: %s\n", progname,
1669 "Cannot get current working directory");
1670 fail ();
1673 #ifdef HAVE_NTGUI
1674 if (display && !strcmp (display, "w32"))
1675 w32_give_focus ();
1676 #endif /* HAVE_NTGUI */
1678 /* Send over our environment and current directory. */
1679 if (!current_frame)
1681 int i;
1682 for (i = 0; environ[i]; i++)
1684 send_to_emacs (emacs_socket, "-env ");
1685 quote_argument (emacs_socket, environ[i]);
1686 send_to_emacs (emacs_socket, " ");
1689 send_to_emacs (emacs_socket, "-dir ");
1690 quote_argument (emacs_socket, cwd);
1691 send_to_emacs (emacs_socket, "/");
1692 send_to_emacs (emacs_socket, " ");
1694 retry:
1695 if (nowait)
1696 send_to_emacs (emacs_socket, "-nowait ");
1698 if (current_frame)
1699 send_to_emacs (emacs_socket, "-current-frame ");
1701 if (display)
1703 send_to_emacs (emacs_socket, "-display ");
1704 quote_argument (emacs_socket, display);
1705 send_to_emacs (emacs_socket, " ");
1708 if (parent_id)
1710 send_to_emacs (emacs_socket, "-parent-id ");
1711 quote_argument (emacs_socket, parent_id);
1712 send_to_emacs (emacs_socket, " ");
1715 if (frame_parameters && !current_frame)
1717 send_to_emacs (emacs_socket, "-frame-parameters ");
1718 quote_argument (emacs_socket, frame_parameters);
1719 send_to_emacs (emacs_socket, " ");
1722 /* Unless we are certain we don't want to occupy the tty, send our
1723 tty information to Emacs. For example, in daemon mode Emacs may
1724 need to occupy this tty if no other frame is available. */
1725 if (!current_frame || !eval)
1727 const char *tty_type, *tty_name;
1729 if (find_tty (&tty_type, &tty_name, !tty))
1731 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1732 init_signals ();
1733 #endif
1734 send_to_emacs (emacs_socket, "-tty ");
1735 quote_argument (emacs_socket, tty_name);
1736 send_to_emacs (emacs_socket, " ");
1737 quote_argument (emacs_socket, tty_type);
1738 send_to_emacs (emacs_socket, " ");
1742 if (!current_frame && !tty)
1743 send_to_emacs (emacs_socket, "-window-system ");
1745 if ((argc - optind > 0))
1747 int i;
1748 for (i = optind; i < argc; i++)
1751 if (eval)
1753 /* Don't prepend cwd or anything like that. */
1754 send_to_emacs (emacs_socket, "-eval ");
1755 quote_argument (emacs_socket, argv[i]);
1756 send_to_emacs (emacs_socket, " ");
1757 continue;
1760 if (*argv[i] == '+')
1762 char *p = argv[i] + 1;
1763 while (isdigit ((unsigned char) *p) || *p == ':') p++;
1764 if (*p == 0)
1766 send_to_emacs (emacs_socket, "-position ");
1767 quote_argument (emacs_socket, argv[i]);
1768 send_to_emacs (emacs_socket, " ");
1769 continue;
1772 #ifdef WINDOWSNT
1773 else if (! file_name_absolute_p (argv[i])
1774 && (isalpha (argv[i][0]) && argv[i][1] == ':'))
1775 /* Windows can have a different default directory for each
1776 drive, so the cwd passed via "-dir" is not sufficient
1777 to account for that.
1778 If the user uses <drive>:<relpath>, we hence need to be
1779 careful to expand <relpath> with the default directory
1780 corresponding to <drive>. */
1782 char *filename = (char *) xmalloc (MAX_PATH);
1783 DWORD size;
1785 size = GetFullPathName (argv[i], MAX_PATH, filename, NULL);
1786 if (size > 0 && size < MAX_PATH)
1787 argv[i] = filename;
1788 else
1789 free (filename);
1791 #endif
1793 send_to_emacs (emacs_socket, "-file ");
1794 quote_argument (emacs_socket, argv[i]);
1795 send_to_emacs (emacs_socket, " ");
1798 else if (eval)
1800 /* Read expressions interactively. */
1801 while ((str = fgets (string, BUFSIZ, stdin)))
1803 send_to_emacs (emacs_socket, "-eval ");
1804 quote_argument (emacs_socket, str);
1806 send_to_emacs (emacs_socket, " ");
1809 send_to_emacs (emacs_socket, "\n");
1811 /* Wait for an answer. */
1812 if (!eval && !tty && !nowait && !quiet)
1814 printf ("Waiting for Emacs...");
1815 needlf = 2;
1817 fflush (stdout);
1818 while (fdatasync (1) != 0 && errno == EINTR)
1819 continue;
1821 /* Now, wait for an answer and print any messages. */
1822 while (exit_status == EXIT_SUCCESS)
1824 char *p, *end_p;
1827 errno = 0;
1828 rl = recv (emacs_socket, string, BUFSIZ, 0);
1830 /* If we receive a signal (e.g. SIGWINCH, which we pass
1831 through to Emacs), on some OSes we get EINTR and must retry. */
1832 while (rl < 0 && errno == EINTR);
1834 if (rl <= 0)
1835 break;
1837 string[rl] = '\0';
1839 /* Loop over all NL-terminated messages. */
1840 for (end_p = p = string; end_p != NULL && *end_p != '\0'; p = end_p)
1842 end_p = strchr (p, '\n');
1843 if (end_p != NULL)
1844 *end_p++ = '\0';
1846 if (strprefix ("-emacs-pid ", p))
1848 /* -emacs-pid PID: The process id of the Emacs process. */
1849 emacs_pid = strtol (p + strlen ("-emacs-pid"), NULL, 10);
1851 else if (strprefix ("-window-system-unsupported ", p))
1853 /* -window-system-unsupported: Emacs was compiled without support
1854 for whatever window system we tried. Try the alternate
1855 display, or, failing that, try the terminal. */
1856 if (alt_display)
1858 display = alt_display;
1859 alt_display = NULL;
1861 else
1863 nowait = 0;
1864 tty = 1;
1867 goto retry;
1869 else if (strprefix ("-print ", p))
1871 /* -print STRING: Print STRING on the terminal. */
1872 if (!suppress_output)
1874 str = unquote_argument (p + strlen ("-print "));
1875 if (needlf)
1876 printf ("\n");
1877 printf ("%s", str);
1878 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1881 else if (strprefix ("-print-nonl ", p))
1883 /* -print-nonl STRING: Print STRING on the terminal.
1884 Used to continue a preceding -print command. */
1885 if (!suppress_output)
1887 str = unquote_argument (p + strlen ("-print-nonl "));
1888 printf ("%s", str);
1889 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1892 else if (strprefix ("-error ", p))
1894 /* -error DESCRIPTION: Signal an error on the terminal. */
1895 str = unquote_argument (p + strlen ("-error "));
1896 if (needlf)
1897 printf ("\n");
1898 fprintf (stderr, "*ERROR*: %s", str);
1899 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1900 exit_status = EXIT_FAILURE;
1902 #ifdef SIGSTOP
1903 else if (strprefix ("-suspend ", p))
1905 /* -suspend: Suspend this terminal, i.e., stop the process. */
1906 if (needlf)
1907 printf ("\n");
1908 needlf = 0;
1909 kill (0, SIGSTOP);
1911 #endif
1912 else
1914 /* Unknown command. */
1915 if (needlf)
1916 printf ("\n");
1917 needlf = 0;
1918 printf ("*ERROR*: Unknown message: %s\n", p);
1923 if (needlf)
1924 printf ("\n");
1925 fflush (stdout);
1926 while (fdatasync (1) != 0 && errno == EINTR)
1927 continue;
1929 if (rl < 0)
1930 exit_status = EXIT_FAILURE;
1932 CLOSE_SOCKET (emacs_socket);
1933 return exit_status;
1936 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */