* image.c (cache_image): Check for size arithmetic overflow.
[emacs.git] / lib-src / emacsclient.c
blobc334fb6a196c66fab4f9cf6850094be2823ba441
1 /* Client process that communicates with GNU Emacs acting as server.
2 Copyright (C) 1986-1987, 1994, 1999-2011 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
22 #ifdef WINDOWSNT
24 /* config.h defines these, which disables sockets altogether! */
25 # undef _WINSOCKAPI_
26 # undef _WINSOCK_H
28 # include <malloc.h>
29 # include <stdlib.h>
30 # include <windows.h>
31 # include <commctrl.h>
32 # include <io.h>
33 # include <winsock2.h>
35 # define NO_SOCKETS_IN_FILE_SYSTEM
37 # define HSOCKET SOCKET
38 # define CLOSE_SOCKET closesocket
39 # define INITIALIZE() (initialize_sockets ())
41 char *w32_getenv (char *);
42 #define egetenv(VAR) w32_getenv(VAR)
44 #else /* !WINDOWSNT */
46 # include "syswait.h"
48 # ifdef HAVE_INET_SOCKETS
49 # include <netinet/in.h>
50 # ifdef HAVE_SOCKETS
51 # include <sys/types.h>
52 # include <sys/socket.h>
53 # include <sys/un.h>
54 # endif /* HAVE_SOCKETS */
55 # endif
56 # include <arpa/inet.h>
58 # define INVALID_SOCKET -1
59 # define HSOCKET int
60 # define CLOSE_SOCKET close
61 # define INITIALIZE()
63 # ifndef WCONTINUED
64 # define WCONTINUED 8
65 # endif
67 #define egetenv(VAR) getenv(VAR)
69 #endif /* !WINDOWSNT */
71 #undef signal
73 #include <stdarg.h>
74 #include <ctype.h>
75 #include <stdio.h>
76 #include <getopt.h>
77 #include <unistd.h>
79 #include <pwd.h>
80 #include <sys/stat.h>
81 #include <signal.h>
82 #include <errno.h>
86 char *getenv (const char *), *getwd (char *);
87 #ifdef HAVE_GETCWD
88 char *(getcwd) (char *, size_t);
89 #endif
91 #ifndef VERSION
92 #define VERSION "unspecified"
93 #endif
96 #ifndef EXIT_SUCCESS
97 #define EXIT_SUCCESS 0
98 #endif
100 #ifndef EXIT_FAILURE
101 #define EXIT_FAILURE 1
102 #endif
104 #ifndef FALSE
105 #define FALSE 0
106 #endif
108 #ifndef TRUE
109 #define TRUE 1
110 #endif
112 /* Additional space when allocating buffers for filenames, etc. */
113 #define EXTRA_SPACE 100
115 /* Use this to suppress gcc's `...may be used before initialized' warnings. */
116 #ifdef lint
117 # define IF_LINT(Code) Code
118 #else
119 # define IF_LINT(Code) /* empty */
120 #endif
123 /* Name used to invoke this program. */
124 const char *progname;
126 /* The second argument to main. */
127 char **main_argv;
129 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
130 int nowait = 0;
132 /* Nonzero means don't print messages for successful operations. --quiet. */
133 int quiet = 0;
135 /* Nonzero means args are expressions to be evaluated. --eval. */
136 int eval = 0;
138 /* Nonzero means don't open a new frame. Inverse of --create-frame. */
139 int current_frame = 1;
141 /* The display on which Emacs should work. --display. */
142 const char *display = NULL;
144 /* The parent window ID, if we are opening a frame via XEmbed. */
145 char *parent_id = NULL;
147 /* Nonzero means open a new Emacs frame on the current terminal. */
148 int tty = 0;
150 /* If non-NULL, the name of an editor to fallback to if the server
151 is not running. --alternate-editor. */
152 const char *alternate_editor = NULL;
154 /* If non-NULL, the filename of the UNIX socket. */
155 char *socket_name = NULL;
157 /* If non-NULL, the filename of the authentication file. */
158 const char *server_file = NULL;
160 /* PID of the Emacs server process. */
161 int emacs_pid = 0;
163 static void print_help_and_exit (void) NO_RETURN;
164 static void fail (void) NO_RETURN;
167 struct option longopts[] =
169 { "no-wait", no_argument, NULL, 'n' },
170 { "quiet", no_argument, NULL, 'q' },
171 { "eval", no_argument, NULL, 'e' },
172 { "help", no_argument, NULL, 'H' },
173 { "version", no_argument, NULL, 'V' },
174 { "tty", no_argument, NULL, 't' },
175 { "nw", no_argument, NULL, 't' },
176 { "create-frame", no_argument, NULL, 'c' },
177 { "alternate-editor", required_argument, NULL, 'a' },
178 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
179 { "socket-name", required_argument, NULL, 's' },
180 #endif
181 { "server-file", required_argument, NULL, 'f' },
182 #ifndef WINDOWSNT
183 { "display", required_argument, NULL, 'd' },
184 #endif
185 { "parent-id", required_argument, NULL, 'p' },
186 { 0, 0, 0, 0 }
190 /* Like malloc but get fatal error if memory is exhausted. */
192 static long *
193 xmalloc (unsigned int size)
195 long *result = (long *) malloc (size);
196 if (result == NULL)
198 perror ("malloc");
199 exit (EXIT_FAILURE);
201 return result;
204 /* From sysdep.c */
205 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
207 /* From lisp.h */
208 #ifndef DIRECTORY_SEP
209 #define DIRECTORY_SEP '/'
210 #endif
211 #ifndef IS_DIRECTORY_SEP
212 #define IS_DIRECTORY_SEP(_c_) ((_c_) == DIRECTORY_SEP)
213 #endif
214 #ifndef IS_DEVICE_SEP
215 #ifndef DEVICE_SEP
216 #define IS_DEVICE_SEP(_c_) 0
217 #else
218 #define IS_DEVICE_SEP(_c_) ((_c_) == DEVICE_SEP)
219 #endif
220 #endif
222 char *get_current_dir_name (void);
224 /* Return the current working directory. Returns NULL on errors.
225 Any other returned value must be freed with free. This is used
226 only when get_current_dir_name is not defined on the system. */
227 char*
228 get_current_dir_name (void)
230 char *buf;
231 const char *pwd;
232 struct stat dotstat, pwdstat;
233 /* If PWD is accurate, use it instead of calling getwd. PWD is
234 sometimes a nicer name, and using it may avoid a fatal error if a
235 parent directory is searchable but not readable. */
236 if ((pwd = egetenv ("PWD")) != 0
237 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
238 && stat (pwd, &pwdstat) == 0
239 && stat (".", &dotstat) == 0
240 && dotstat.st_ino == pwdstat.st_ino
241 && dotstat.st_dev == pwdstat.st_dev
242 #ifdef MAXPATHLEN
243 && strlen (pwd) < MAXPATHLEN
244 #endif
247 buf = (char *) xmalloc (strlen (pwd) + 1);
248 if (!buf)
249 return NULL;
250 strcpy (buf, pwd);
252 #ifdef HAVE_GETCWD
253 else
255 size_t buf_size = 1024;
256 buf = (char *) xmalloc (buf_size);
257 if (!buf)
258 return NULL;
259 for (;;)
261 if (getcwd (buf, buf_size) == buf)
262 break;
263 if (errno != ERANGE)
265 int tmp_errno = errno;
266 free (buf);
267 errno = tmp_errno;
268 return NULL;
270 buf_size *= 2;
271 buf = (char *) realloc (buf, buf_size);
272 if (!buf)
273 return NULL;
276 #else
277 else
279 /* We need MAXPATHLEN here. */
280 buf = (char *) xmalloc (MAXPATHLEN + 1);
281 if (!buf)
282 return NULL;
283 if (getwd (buf) == NULL)
285 int tmp_errno = errno;
286 free (buf);
287 errno = tmp_errno;
288 return NULL;
291 #endif
292 return buf;
294 #endif
296 #ifdef WINDOWSNT
298 /* Like strdup but get a fatal error if memory is exhausted. */
300 char *
301 xstrdup (const char *s)
303 char *result = strdup (s);
304 if (result == NULL)
306 perror ("strdup");
307 exit (EXIT_FAILURE);
309 return result;
312 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
314 /* Retrieve an environment variable from the Emacs subkeys of the registry.
315 Return NULL if the variable was not found, or it was empty.
316 This code is based on w32_get_resource (w32.c). */
317 char *
318 w32_get_resource (HKEY predefined, char *key, LPDWORD type)
320 HKEY hrootkey = NULL;
321 char *result = NULL;
322 DWORD cbData;
324 if (RegOpenKeyEx (predefined, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
326 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS)
328 result = (char *) xmalloc (cbData);
330 if ((RegQueryValueEx (hrootkey, key, NULL, type, result, &cbData) != ERROR_SUCCESS)
331 || (*result == 0))
333 free (result);
334 result = NULL;
338 RegCloseKey (hrootkey);
341 return result;
345 getenv wrapper for Windows
347 Value is allocated on the heap, and can be free'd.
349 This is needed to duplicate Emacs's behavior, which is to look for
350 environment variables in the registry if they don't appear in the
351 environment. */
352 char *
353 w32_getenv (char *envvar)
355 char *value;
356 DWORD dwType;
358 if (value = getenv (envvar))
359 /* Found in the environment. strdup it, because values returned
360 by getenv cannot be free'd. */
361 return xstrdup (value);
363 if (! (value = w32_get_resource (HKEY_CURRENT_USER, envvar, &dwType)) &&
364 ! (value = w32_get_resource (HKEY_LOCAL_MACHINE, envvar, &dwType)))
366 /* "w32console" is what Emacs on Windows uses for tty-type under -nw. */
367 if (strcmp (envvar, "TERM") == 0)
368 return xstrdup ("w32console");
369 /* Found neither in the environment nor in the registry. */
370 return NULL;
373 if (dwType == REG_SZ)
374 /* Registry; no need to expand. */
375 return value;
377 if (dwType == REG_EXPAND_SZ)
379 DWORD size;
381 if (size = ExpandEnvironmentStrings (value, NULL, 0))
383 char *buffer = (char *) xmalloc (size);
384 if (ExpandEnvironmentStrings (value, buffer, size))
386 /* Found and expanded. */
387 free (value);
388 return buffer;
391 /* Error expanding. */
392 free (buffer);
396 /* Not the right type, or not correctly expanded. */
397 free (value);
398 return NULL;
401 void
402 w32_set_user_model_id (void)
404 HMODULE shell;
405 HRESULT (WINAPI * set_user_model) (wchar_t * id);
407 /* On Windows 7 and later, we need to set the user model ID
408 to associate emacsclient launched files with Emacs frames
409 in the UI. */
410 shell = LoadLibrary ("shell32.dll");
411 if (shell)
413 set_user_model
414 = (void *) GetProcAddress (shell,
415 "SetCurrentProcessExplicitAppUserModelID");
416 /* If the function is defined, then we are running on Windows 7
417 or newer, and the UI uses this to group related windows
418 together. Since emacs, runemacs, emacsclient are related, we
419 want them grouped even though the executables are different,
420 so we need to set a consistent ID between them. */
421 if (set_user_model)
422 set_user_model (L"GNU.Emacs");
424 FreeLibrary (shell);
429 w32_window_app (void)
431 static int window_app = -1;
432 char szTitle[MAX_PATH];
434 if (window_app < 0)
436 /* Checking for STDOUT does not work; it's a valid handle also in
437 nonconsole apps. Testing for the console title seems to work. */
438 window_app = (GetConsoleTitleA (szTitle, MAX_PATH) == 0);
439 if (window_app)
440 InitCommonControls ();
443 return window_app;
447 execvp wrapper for Windows. Quotes arguments with embedded spaces.
449 This is necessary due to the broken implementation of exec* routines in
450 the Microsoft libraries: they concatenate the arguments together without
451 quoting special characters, and pass the result to CreateProcess, with
452 predictably bad results. By contrast, POSIX execvp passes the arguments
453 directly into the argv array of the child process.
456 w32_execvp (const char *path, char **argv)
458 int i;
460 /* Required to allow a .BAT script as alternate editor. */
461 argv[0] = (char *) alternate_editor;
463 for (i = 0; argv[i]; i++)
464 if (strchr (argv[i], ' '))
466 char *quoted = alloca (strlen (argv[i]) + 3);
467 sprintf (quoted, "\"%s\"", argv[i]);
468 argv[i] = quoted;
471 return execvp (path, argv);
474 #undef execvp
475 #define execvp w32_execvp
477 /* Emulation of ttyname for Windows. */
478 char *
479 ttyname (int fd)
481 return "CONOUT$";
484 #endif /* WINDOWSNT */
486 /* Display a normal or error message.
487 On Windows, use a message box if compiled as a Windows app. */
488 static void message (int, const char *, ...) ATTRIBUTE_FORMAT_PRINTF (2, 3);
489 static void
490 message (int is_error, const char *format, ...)
492 char msg[2048];
493 va_list args;
495 va_start (args, format);
496 vsprintf (msg, format, args);
497 va_end (args);
499 #ifdef WINDOWSNT
500 if (w32_window_app ())
502 if (is_error)
503 MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
504 else
505 MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
507 else
508 #endif
510 FILE *f = is_error ? stderr : stdout;
512 fputs (msg, f);
513 fflush (f);
517 /* Decode the options from argv and argc.
518 The global variable `optind' will say how many arguments we used up. */
520 static void
521 decode_options (int argc, char **argv)
523 alternate_editor = egetenv ("ALTERNATE_EDITOR");
525 while (1)
527 int opt = getopt_long_only (argc, argv,
528 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
529 "VHneqa:s:f:d:tc",
530 #else
531 "VHneqa:f:d:tc",
532 #endif
533 longopts, 0);
535 if (opt == EOF)
536 break;
538 switch (opt)
540 case 0:
541 /* If getopt returns 0, then it has already processed a
542 long-named option. We should do nothing. */
543 break;
545 case 'a':
546 alternate_editor = optarg;
547 break;
549 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
550 case 's':
551 socket_name = optarg;
552 break;
553 #endif
555 case 'f':
556 server_file = optarg;
557 break;
559 /* We used to disallow this argument in w32, but it seems better
560 to allow it, for the occasional case where the user is
561 connecting with a w32 client to a server compiled with X11
562 support. */
563 case 'd':
564 display = optarg;
565 break;
567 case 'n':
568 nowait = 1;
569 break;
571 case 'e':
572 eval = 1;
573 break;
575 case 'q':
576 quiet = 1;
577 break;
579 case 'V':
580 message (FALSE, "emacsclient %s\n", VERSION);
581 exit (EXIT_SUCCESS);
582 break;
584 case 't':
585 tty = 1;
586 current_frame = 0;
587 break;
589 case 'c':
590 current_frame = 0;
591 break;
593 case 'p':
594 parent_id = optarg;
595 current_frame = 0;
596 break;
598 case 'H':
599 print_help_and_exit ();
600 break;
602 default:
603 message (TRUE, "Try `%s --help' for more information\n", progname);
604 exit (EXIT_FAILURE);
605 break;
609 /* If the -c option is used (without -t) and no --display argument
610 is provided, try $DISPLAY.
611 Without the -c option, we used to set `display' to $DISPLAY by
612 default, but this changed the default behavior and is sometimes
613 inconvenient. So we force users to use "--display $DISPLAY" if
614 they want Emacs to connect to their current display. */
615 if (!current_frame && !tty && !display)
617 display = egetenv ("DISPLAY");
618 #ifdef NS_IMPL_COCOA
619 /* Under Cocoa, we don't really use displays the same way as in X,
620 so provide a dummy. */
621 if (!display || strlen (display) == 0)
622 display = "ns";
623 #endif
626 /* A null-string display is invalid. */
627 if (display && strlen (display) == 0)
628 display = NULL;
630 /* If no display is available, new frames are tty frames. */
631 if (!current_frame && !display)
632 tty = 1;
634 /* --no-wait implies --current-frame on ttys when there are file
635 arguments or expressions given. */
636 if (nowait && tty && argc - optind > 0)
637 current_frame = 1;
639 #ifdef WINDOWSNT
640 if (alternate_editor && alternate_editor[0] == '\0')
642 message (TRUE, "--alternate-editor argument or ALTERNATE_EDITOR variable cannot be\n\
643 an empty string");
644 exit (EXIT_FAILURE);
646 #endif /* WINDOWSNT */
650 static void
651 print_help_and_exit (void)
653 /* Spaces and tabs are significant in this message; they're chosen so the
654 message aligns properly both in a tty and in a Windows message box.
655 Please try to preserve them; otherwise the output is very hard to read
656 when using emacsclientw. */
657 message (FALSE,
658 "Usage: %s [OPTIONS] FILE...\n\
659 Tell the Emacs server to visit the specified files.\n\
660 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
662 The following OPTIONS are accepted:\n\
663 -V, --version Just print version info and return\n\
664 -H, --help Print this usage information message\n\
665 -nw, -t, --tty Open a new Emacs frame on the current terminal\n\
666 -c, --create-frame Create a new frame instead of trying to\n\
667 use the current Emacs frame\n\
668 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
669 -n, --no-wait Don't wait for the server to return\n\
670 -q, --quiet Don't display messages on success\n\
671 -d DISPLAY, --display=DISPLAY\n\
672 Visit the file in the given display\n\
673 --parent-id=ID Open in parent window ID, via XEmbed\n"
674 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
675 "-s SOCKET, --socket-name=SOCKET\n\
676 Set filename of the UNIX socket for communication\n"
677 #endif
678 "-f SERVER, --server-file=SERVER\n\
679 Set filename of the TCP authentication file\n\
680 -a EDITOR, --alternate-editor=EDITOR\n\
681 Editor to fallback to if the server is not running\n"
682 #ifndef WINDOWSNT
683 " If EDITOR is the empty string, start Emacs in daemon\n\
684 mode and try connecting again\n"
685 #endif /* not WINDOWSNT */
686 "\n\
687 Report bugs with M-x report-emacs-bug.\n", progname);
688 exit (EXIT_SUCCESS);
692 Try to run a different command, or --if no alternate editor is
693 defined-- exit with an errorcode.
694 Uses argv, but gets it from the global variable main_argv.
696 static void
697 fail (void)
699 if (alternate_editor)
701 int i = optind - 1;
703 execvp (alternate_editor, main_argv + i);
704 message (TRUE, "%s: error executing alternate editor \"%s\"\n",
705 progname, alternate_editor);
707 exit (EXIT_FAILURE);
711 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
714 main (int argc, char **argv)
716 main_argv = argv;
717 progname = argv[0];
718 message (TRUE, "%s: Sorry, the Emacs server is supported only\n"
719 "on systems with Berkeley sockets.\n",
720 argv[0]);
721 fail ();
724 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
726 #define AUTH_KEY_LENGTH 64
727 #define SEND_BUFFER_SIZE 4096
729 extern char *strerror (int);
731 /* Buffer to accumulate data to send in TCP connections. */
732 char send_buffer[SEND_BUFFER_SIZE + 1];
733 int sblen = 0; /* Fill pointer for the send buffer. */
734 /* Socket used to communicate with the Emacs server process. */
735 HSOCKET emacs_socket = 0;
737 /* On Windows, the socket library was historically separate from the standard
738 C library, so errors are handled differently. */
739 static void
740 sock_err_message (const char *function_name)
742 #ifdef WINDOWSNT
743 char* msg = NULL;
745 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
746 | FORMAT_MESSAGE_ALLOCATE_BUFFER
747 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
748 NULL, WSAGetLastError (), 0, (LPTSTR)&msg, 0, NULL);
750 message (TRUE, "%s: %s: %s\n", progname, function_name, msg);
752 LocalFree (msg);
753 #else
754 message (TRUE, "%s: %s: %s\n", progname, function_name, strerror (errno));
755 #endif
759 /* Let's send the data to Emacs when either
760 - the data ends in "\n", or
761 - the buffer is full (but this shouldn't happen)
762 Otherwise, we just accumulate it. */
763 static void
764 send_to_emacs (HSOCKET s, const char *data)
766 while (data)
768 size_t dlen = strlen (data);
769 if (dlen + sblen >= SEND_BUFFER_SIZE)
771 int part = SEND_BUFFER_SIZE - sblen;
772 strncpy (&send_buffer[sblen], data, part);
773 data += part;
774 sblen = SEND_BUFFER_SIZE;
776 else if (dlen)
778 strcpy (&send_buffer[sblen], data);
779 data = NULL;
780 sblen += dlen;
782 else
783 break;
785 if (sblen == SEND_BUFFER_SIZE
786 || (sblen > 0 && send_buffer[sblen-1] == '\n'))
788 int sent = send (s, send_buffer, sblen, 0);
789 if (sent != sblen)
790 strcpy (send_buffer, &send_buffer[sent]);
791 sblen -= sent;
797 /* In STR, insert a & before each &, each space, each newline, and
798 any initial -. Change spaces to underscores, too, so that the
799 return value never contains a space.
801 Does not change the string. Outputs the result to S. */
802 static void
803 quote_argument (HSOCKET s, const char *str)
805 char *copy = (char *) xmalloc (strlen (str) * 2 + 1);
806 const char *p;
807 char *q;
809 p = str;
810 q = copy;
811 while (*p)
813 if (*p == ' ')
815 *q++ = '&';
816 *q++ = '_';
817 p++;
819 else if (*p == '\n')
821 *q++ = '&';
822 *q++ = 'n';
823 p++;
825 else
827 if (*p == '&' || (*p == '-' && p == str))
828 *q++ = '&';
829 *q++ = *p++;
832 *q++ = 0;
834 send_to_emacs (s, copy);
836 free (copy);
840 /* The inverse of quote_argument. Removes quoting in string STR by
841 modifying the string in place. Returns STR. */
843 static char *
844 unquote_argument (char *str)
846 char *p, *q;
848 if (! str)
849 return str;
851 p = str;
852 q = str;
853 while (*p)
855 if (*p == '&')
857 p++;
858 if (*p == '&')
859 *p = '&';
860 else if (*p == '_')
861 *p = ' ';
862 else if (*p == 'n')
863 *p = '\n';
864 else if (*p == '-')
865 *p = '-';
867 *q++ = *p++;
869 *q = 0;
870 return str;
874 static int
875 file_name_absolute_p (const char *filename)
877 /* Sanity check, it shouldn't happen. */
878 if (! filename) return FALSE;
880 /* /xxx is always an absolute path. */
881 if (filename[0] == '/') return TRUE;
883 /* Empty filenames (which shouldn't happen) are relative. */
884 if (filename[0] == '\0') return FALSE;
886 #ifdef WINDOWSNT
887 /* X:\xxx is always absolute. */
888 if (isalpha ((unsigned char) filename[0])
889 && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
890 return TRUE;
892 /* Both \xxx and \\xxx\yyy are absolute. */
893 if (filename[0] == '\\') return TRUE;
894 #endif
896 return FALSE;
899 #ifdef WINDOWSNT
900 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
901 void __cdecl
902 close_winsock (void)
904 WSACleanup ();
907 /* Initialize the WinSock2 library. */
908 void
909 initialize_sockets (void)
911 WSADATA wsaData;
913 if (WSAStartup (MAKEWORD (2, 0), &wsaData))
915 message (TRUE, "%s: error initializing WinSock2\n", progname);
916 exit (EXIT_FAILURE);
919 atexit (close_winsock);
921 #endif /* WINDOWSNT */
925 * Read the information needed to set up a TCP comm channel with
926 * the Emacs server: host, port, and authentication string.
928 static int
929 get_server_config (struct sockaddr_in *server, char *authentication)
931 char dotted[32];
932 char *port;
933 FILE *config = NULL;
935 if (file_name_absolute_p (server_file))
936 config = fopen (server_file, "rb");
937 else
939 const char *home = egetenv ("HOME");
941 if (home)
943 char *path = alloca (strlen (home) + strlen (server_file)
944 + EXTRA_SPACE);
945 sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
946 config = fopen (path, "rb");
948 #ifdef WINDOWSNT
949 if (!config && (home = egetenv ("APPDATA")))
951 char *path = alloca (strlen (home) + strlen (server_file)
952 + EXTRA_SPACE);
953 sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
954 config = fopen (path, "rb");
956 #endif
959 if (! config)
960 return FALSE;
962 if (fgets (dotted, sizeof dotted, config)
963 && (port = strchr (dotted, ':')))
964 *port++ = '\0';
965 else
967 message (TRUE, "%s: invalid configuration info\n", progname);
968 exit (EXIT_FAILURE);
971 server->sin_family = AF_INET;
972 server->sin_addr.s_addr = inet_addr (dotted);
973 server->sin_port = htons (atoi (port));
975 if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
977 message (TRUE, "%s: cannot read authentication info\n", progname);
978 exit (EXIT_FAILURE);
981 fclose (config);
983 return TRUE;
986 static HSOCKET
987 set_tcp_socket (void)
989 HSOCKET s;
990 struct sockaddr_in server;
991 struct linger l_arg = {1, 1};
992 char auth_string[AUTH_KEY_LENGTH + 1];
994 if (! get_server_config (&server, auth_string))
995 return INVALID_SOCKET;
997 if (server.sin_addr.s_addr != inet_addr ("127.0.0.1") && !quiet)
998 message (FALSE, "%s: connected to remote socket at %s\n",
999 progname, inet_ntoa (server.sin_addr));
1002 * Open up an AF_INET socket
1004 if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
1006 sock_err_message ("socket");
1007 return INVALID_SOCKET;
1011 * Set up the socket
1013 if (connect (s, (struct sockaddr *) &server, sizeof server) < 0)
1015 sock_err_message ("connect");
1016 return INVALID_SOCKET;
1019 setsockopt (s, SOL_SOCKET, SO_LINGER, (char *) &l_arg, sizeof l_arg);
1022 * Send the authentication
1024 auth_string[AUTH_KEY_LENGTH] = '\0';
1026 send_to_emacs (s, "-auth ");
1027 send_to_emacs (s, auth_string);
1028 send_to_emacs (s, " ");
1030 return s;
1034 /* Returns 1 if PREFIX is a prefix of STRING. */
1035 static int
1036 strprefix (const char *prefix, const char *string)
1038 return !strncmp (prefix, string, strlen (prefix));
1041 /* Get tty name and type. If successful, return the type in TTY_TYPE
1042 and the name in TTY_NAME, and return 1. Otherwise, fail if NOABORT
1043 is zero, or return 0 if NOABORT is non-zero. */
1045 static int
1046 find_tty (const char **tty_type, const char **tty_name, int noabort)
1048 const char *type = egetenv ("TERM");
1049 const char *name = ttyname (fileno (stdout));
1051 if (!name)
1053 if (noabort)
1054 return 0;
1055 else
1057 message (TRUE, "%s: could not get terminal name\n", progname);
1058 fail ();
1062 if (!type)
1064 if (noabort)
1065 return 0;
1066 else
1068 message (TRUE, "%s: please set the TERM variable to your terminal type\n",
1069 progname);
1070 fail ();
1074 if (strcmp (type, "eterm") == 0)
1076 if (noabort)
1077 return 0;
1078 else
1080 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1081 message (TRUE, "%s: opening a frame in an Emacs term buffer"
1082 " is not supported\n", progname);
1083 fail ();
1087 *tty_name = name;
1088 *tty_type = type;
1089 return 1;
1093 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1095 /* Three possibilities:
1096 2 - can't be `stat'ed (sets errno)
1097 1 - isn't owned by us
1098 0 - success: none of the above */
1100 static int
1101 socket_status (const char *name)
1103 struct stat statbfr;
1105 if (stat (name, &statbfr) == -1)
1106 return 2;
1108 if (statbfr.st_uid != geteuid ())
1109 return 1;
1111 return 0;
1115 /* A signal handler that passes the signal to the Emacs process.
1116 Useful for SIGWINCH. */
1118 static void
1119 pass_signal_to_emacs (int signalnum)
1121 int old_errno = errno;
1123 if (emacs_pid)
1124 kill (emacs_pid, signalnum);
1126 signal (signalnum, pass_signal_to_emacs);
1127 errno = old_errno;
1130 /* Signal handler for SIGCONT; notify the Emacs process that it can
1131 now resume our tty frame. */
1133 static void
1134 handle_sigcont (int signalnum)
1136 int old_errno = errno;
1138 if (tcgetpgrp (1) == getpgrp ())
1140 /* We are in the foreground. */
1141 send_to_emacs (emacs_socket, "-resume \n");
1143 else
1145 /* We are in the background; cancel the continue. */
1146 kill (getpid (), SIGSTOP);
1149 signal (signalnum, handle_sigcont);
1150 errno = old_errno;
1153 /* Signal handler for SIGTSTP; notify the Emacs process that we are
1154 going to sleep. Normally the suspend is initiated by Emacs via
1155 server-handle-suspend-tty, but if the server gets out of sync with
1156 reality, we may get a SIGTSTP on C-z. Handling this signal and
1157 notifying Emacs about it should get things under control again. */
1159 static void
1160 handle_sigtstp (int signalnum)
1162 int old_errno = errno;
1163 sigset_t set;
1165 if (emacs_socket)
1166 send_to_emacs (emacs_socket, "-suspend \n");
1168 /* Unblock this signal and call the default handler by temporarily
1169 changing the handler and resignalling. */
1170 sigprocmask (SIG_BLOCK, NULL, &set);
1171 sigdelset (&set, signalnum);
1172 signal (signalnum, SIG_DFL);
1173 kill (getpid (), signalnum);
1174 sigprocmask (SIG_SETMASK, &set, NULL); /* Let's the above signal through. */
1175 signal (signalnum, handle_sigtstp);
1177 errno = old_errno;
1181 /* Set up signal handlers before opening a frame on the current tty. */
1183 static void
1184 init_signals (void)
1186 /* Set up signal handlers. */
1187 signal (SIGWINCH, pass_signal_to_emacs);
1189 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
1190 deciding which terminal the signal came from. C-g is now a
1191 normal input event on secondary terminals. */
1192 #if 0
1193 signal (SIGINT, pass_signal_to_emacs);
1194 signal (SIGQUIT, pass_signal_to_emacs);
1195 #endif
1197 signal (SIGCONT, handle_sigcont);
1198 signal (SIGTSTP, handle_sigtstp);
1199 signal (SIGTTOU, handle_sigtstp);
1203 static HSOCKET
1204 set_local_socket (void)
1206 HSOCKET s;
1207 struct sockaddr_un server;
1210 * Open up an AF_UNIX socket in this person's home directory
1213 if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
1215 message (TRUE, "%s: socket: %s\n", progname, strerror (errno));
1216 return INVALID_SOCKET;
1219 server.sun_family = AF_UNIX;
1222 int sock_status = 0;
1223 int default_sock = !socket_name;
1224 int saved_errno = 0;
1225 const char *server_name = "server";
1226 const char *tmpdir IF_LINT ( = NULL);
1228 if (socket_name && !strchr (socket_name, '/')
1229 && !strchr (socket_name, '\\'))
1231 /* socket_name is a file name component. */
1232 server_name = socket_name;
1233 socket_name = NULL;
1234 default_sock = 1; /* Try both UIDs. */
1237 if (default_sock)
1239 tmpdir = egetenv ("TMPDIR");
1240 if (!tmpdir)
1242 #ifdef DARWIN_OS
1243 #ifndef _CS_DARWIN_USER_TEMP_DIR
1244 #define _CS_DARWIN_USER_TEMP_DIR 65537
1245 #endif
1246 size_t n = confstr (_CS_DARWIN_USER_TEMP_DIR, NULL, (size_t) 0);
1247 if (n > 0)
1249 tmpdir = alloca (n);
1250 confstr (_CS_DARWIN_USER_TEMP_DIR, tmpdir, n);
1252 else
1253 #endif
1254 tmpdir = "/tmp";
1256 socket_name = alloca (strlen (tmpdir) + strlen (server_name)
1257 + EXTRA_SPACE);
1258 sprintf (socket_name, "%s/emacs%d/%s",
1259 tmpdir, (int) geteuid (), server_name);
1262 if (strlen (socket_name) < sizeof (server.sun_path))
1263 strcpy (server.sun_path, socket_name);
1264 else
1266 message (TRUE, "%s: socket-name %s too long\n",
1267 progname, socket_name);
1268 fail ();
1271 /* See if the socket exists, and if it's owned by us. */
1272 sock_status = socket_status (server.sun_path);
1273 saved_errno = errno;
1274 if (sock_status && default_sock)
1276 /* Failing that, see if LOGNAME or USER exist and differ from
1277 our euid. If so, look for a socket based on the UID
1278 associated with the name. This is reminiscent of the logic
1279 that init_editfns uses to set the global Vuser_full_name. */
1281 const char *user_name = egetenv ("LOGNAME");
1283 if (!user_name)
1284 user_name = egetenv ("USER");
1286 if (user_name)
1288 struct passwd *pw = getpwnam (user_name);
1290 if (pw && (pw->pw_uid != geteuid ()))
1292 /* We're running under su, apparently. */
1293 socket_name = alloca (strlen (tmpdir) + strlen (server_name)
1294 + EXTRA_SPACE);
1295 sprintf (socket_name, "%s/emacs%d/%s",
1296 tmpdir, (int) pw->pw_uid, server_name);
1298 if (strlen (socket_name) < sizeof (server.sun_path))
1299 strcpy (server.sun_path, socket_name);
1300 else
1302 message (TRUE, "%s: socket-name %s too long\n",
1303 progname, socket_name);
1304 exit (EXIT_FAILURE);
1307 sock_status = socket_status (server.sun_path);
1308 saved_errno = errno;
1310 else
1311 errno = saved_errno;
1315 switch (sock_status)
1317 case 1:
1318 /* There's a socket, but it isn't owned by us. This is OK if
1319 we are root. */
1320 if (0 != geteuid ())
1322 message (TRUE, "%s: Invalid socket owner\n", progname);
1323 return INVALID_SOCKET;
1325 break;
1327 case 2:
1328 /* `stat' failed */
1329 if (saved_errno == ENOENT)
1330 message (TRUE,
1331 "%s: can't find socket; have you started the server?\n\
1332 To start the server in Emacs, type \"M-x server-start\".\n",
1333 progname);
1334 else
1335 message (TRUE, "%s: can't stat %s: %s\n",
1336 progname, server.sun_path, strerror (saved_errno));
1337 return INVALID_SOCKET;
1341 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
1342 < 0)
1344 message (TRUE, "%s: connect: %s\n", progname, strerror (errno));
1345 return INVALID_SOCKET;
1348 return s;
1350 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1352 static HSOCKET
1353 set_socket (int no_exit_if_error)
1355 HSOCKET s;
1357 INITIALIZE ();
1359 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1360 /* Explicit --socket-name argument. */
1361 if (socket_name)
1363 s = set_local_socket ();
1364 if ((s != INVALID_SOCKET) || no_exit_if_error)
1365 return s;
1366 message (TRUE, "%s: error accessing socket \"%s\"\n",
1367 progname, socket_name);
1368 exit (EXIT_FAILURE);
1370 #endif
1372 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1373 if (!server_file)
1374 server_file = egetenv ("EMACS_SERVER_FILE");
1376 if (server_file)
1378 s = set_tcp_socket ();
1379 if ((s != INVALID_SOCKET) || no_exit_if_error)
1380 return s;
1382 message (TRUE, "%s: error accessing server file \"%s\"\n",
1383 progname, server_file);
1384 exit (EXIT_FAILURE);
1387 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1388 /* Implicit local socket. */
1389 s = set_local_socket ();
1390 if (s != INVALID_SOCKET)
1391 return s;
1392 #endif
1394 /* Implicit server file. */
1395 server_file = "server";
1396 s = set_tcp_socket ();
1397 if ((s != INVALID_SOCKET) || no_exit_if_error)
1398 return s;
1400 /* No implicit or explicit socket, and no alternate editor. */
1401 message (TRUE, "%s: No socket or alternate editor. Please use:\n\n"
1402 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1403 "\t--socket-name\n"
1404 #endif
1405 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1406 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1407 progname);
1408 exit (EXIT_FAILURE);
1411 #ifdef WINDOWSNT
1412 FARPROC set_fg; /* Pointer to AllowSetForegroundWindow. */
1413 FARPROC get_wc; /* Pointer to RealGetWindowClassA. */
1415 BOOL CALLBACK
1416 w32_find_emacs_process (HWND hWnd, LPARAM lParam)
1418 DWORD pid;
1419 char class[6];
1421 /* Reject any window not of class "Emacs". */
1422 if (! get_wc (hWnd, class, sizeof (class))
1423 || strcmp (class, "Emacs"))
1424 return TRUE;
1426 /* We only need the process id, not the thread id. */
1427 (void) GetWindowThreadProcessId (hWnd, &pid);
1429 /* Not the one we're looking for. */
1430 if (pid != (DWORD) emacs_pid) return TRUE;
1432 /* OK, let's raise it. */
1433 set_fg (emacs_pid);
1435 /* Stop enumeration. */
1436 return FALSE;
1440 * Search for a window of class "Emacs" and owned by a process with
1441 * process id = emacs_pid. If found, allow it to grab the focus.
1443 void
1444 w32_give_focus (void)
1446 HANDLE user32;
1448 /* It shouldn't happen when dealing with TCP sockets. */
1449 if (!emacs_pid) return;
1451 user32 = GetModuleHandle ("user32.dll");
1453 if (!user32)
1454 return;
1456 /* Modern Windows restrict which processes can set the foreground window.
1457 emacsclient can allow Emacs to grab the focus by calling the function
1458 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1459 NT) lack this function, so we have to check its availability. */
1460 if ((set_fg = GetProcAddress (user32, "AllowSetForegroundWindow"))
1461 && (get_wc = GetProcAddress (user32, "RealGetWindowClassA")))
1462 EnumWindows (w32_find_emacs_process, (LPARAM) 0);
1464 #endif
1466 /* Start the emacs daemon and try to connect to it. */
1468 static void
1469 start_daemon_and_retry_set_socket (void)
1471 #ifndef WINDOWSNT
1472 pid_t dpid;
1473 int status;
1475 dpid = fork ();
1477 if (dpid > 0)
1479 pid_t w;
1480 w = waitpid (dpid, &status, WUNTRACED | WCONTINUED);
1482 if ((w == -1) || !WIFEXITED (status) || WEXITSTATUS (status))
1484 message (TRUE, "Error: Could not start the Emacs daemon\n");
1485 exit (EXIT_FAILURE);
1488 /* Try connecting, the daemon should have started by now. */
1489 message (TRUE, "Emacs daemon should have started, trying to connect again\n");
1490 if ((emacs_socket = set_socket (1)) == INVALID_SOCKET)
1492 message (TRUE, "Error: Cannot connect even after starting the Emacs daemon\n");
1493 exit (EXIT_FAILURE);
1496 else if (dpid < 0)
1498 fprintf (stderr, "Error: Cannot fork!\n");
1499 exit (EXIT_FAILURE);
1501 else
1503 char emacs[] = "emacs";
1504 char daemon_option[] = "--daemon";
1505 char *d_argv[] = {emacs, daemon_option, 0 };
1506 if (socket_name != NULL)
1508 /* Pass --daemon=socket_name as argument. */
1509 const char *deq = "--daemon=";
1510 char *daemon_arg = alloca (strlen (deq)
1511 + strlen (socket_name) + 1);
1512 strcpy (daemon_arg, deq);
1513 strcat (daemon_arg, socket_name);
1514 d_argv[1] = daemon_arg;
1516 execvp ("emacs", d_argv);
1517 message (TRUE, "%s: error starting emacs daemon\n", progname);
1519 #endif /* WINDOWSNT */
1523 main (int argc, char **argv)
1525 int rl = 0, needlf = 0;
1526 char *cwd, *str;
1527 char string[BUFSIZ+1];
1528 int null_socket_name IF_LINT ( = 0);
1529 int null_server_file IF_LINT ( = 0);
1530 int start_daemon_if_needed;
1531 int exit_status = EXIT_SUCCESS;
1533 main_argv = argv;
1534 progname = argv[0];
1536 #ifdef WINDOWSNT
1537 /* On Windows 7 and later, we need to explicitly associate emacsclient
1538 with emacs so the UI behaves sensibly. */
1539 w32_set_user_model_id ();
1540 #endif
1542 /* Process options. */
1543 decode_options (argc, argv);
1545 if ((argc - optind < 1) && !eval && current_frame)
1547 message (TRUE, "%s: file name or argument required\n"
1548 "Try `%s --help' for more information\n",
1549 progname, progname);
1550 exit (EXIT_FAILURE);
1553 /* If alternate_editor is the empty string, start the emacs daemon
1554 in case of failure to connect. */
1555 start_daemon_if_needed = (alternate_editor
1556 && (alternate_editor[0] == '\0'));
1557 if (start_daemon_if_needed)
1559 /* set_socket changes the values for socket_name and
1560 server_file, we need to reset them, if they were NULL before
1561 for the second call to set_socket. */
1562 null_socket_name = (socket_name == NULL);
1563 null_server_file = (server_file == NULL);
1566 emacs_socket = set_socket (alternate_editor || start_daemon_if_needed);
1567 if (emacs_socket == INVALID_SOCKET)
1569 if (! start_daemon_if_needed)
1570 fail ();
1572 /* Reset socket_name and server_file if they were NULL
1573 before the set_socket call. */
1574 if (null_socket_name)
1575 socket_name = NULL;
1576 if (null_server_file)
1577 server_file = NULL;
1579 start_daemon_and_retry_set_socket ();
1582 cwd = get_current_dir_name ();
1583 if (cwd == 0)
1585 /* getwd puts message in STRING if it fails. */
1586 message (TRUE, "%s: %s\n", progname,
1587 "Cannot get current working directory");
1588 fail ();
1591 #ifdef WINDOWSNT
1592 w32_give_focus ();
1593 #endif
1595 /* Send over our environment and current directory. */
1596 if (!current_frame)
1598 extern char **environ;
1599 int i;
1600 for (i = 0; environ[i]; i++)
1602 send_to_emacs (emacs_socket, "-env ");
1603 quote_argument (emacs_socket, environ[i]);
1604 send_to_emacs (emacs_socket, " ");
1607 send_to_emacs (emacs_socket, "-dir ");
1608 quote_argument (emacs_socket, cwd);
1609 send_to_emacs (emacs_socket, "/");
1610 send_to_emacs (emacs_socket, " ");
1612 retry:
1613 if (nowait)
1614 send_to_emacs (emacs_socket, "-nowait ");
1616 if (current_frame)
1617 send_to_emacs (emacs_socket, "-current-frame ");
1619 if (display)
1621 send_to_emacs (emacs_socket, "-display ");
1622 quote_argument (emacs_socket, display);
1623 send_to_emacs (emacs_socket, " ");
1626 if (parent_id)
1628 send_to_emacs (emacs_socket, "-parent-id ");
1629 quote_argument (emacs_socket, parent_id);
1630 send_to_emacs (emacs_socket, " ");
1633 /* If using the current frame, send tty information to Emacs anyway.
1634 In daemon mode, Emacs may need to occupy this tty if no other
1635 frame is available. */
1636 if (tty || (current_frame && !eval))
1638 const char *tty_type, *tty_name;
1640 if (find_tty (&tty_type, &tty_name, !tty))
1642 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1643 init_signals ();
1644 #endif
1645 send_to_emacs (emacs_socket, "-tty ");
1646 quote_argument (emacs_socket, tty_name);
1647 send_to_emacs (emacs_socket, " ");
1648 quote_argument (emacs_socket, tty_type);
1649 send_to_emacs (emacs_socket, " ");
1653 if (!current_frame && !tty)
1654 send_to_emacs (emacs_socket, "-window-system ");
1656 if ((argc - optind > 0))
1658 int i;
1659 for (i = optind; i < argc; i++)
1662 if (eval)
1664 /* Don't prepend cwd or anything like that. */
1665 send_to_emacs (emacs_socket, "-eval ");
1666 quote_argument (emacs_socket, argv[i]);
1667 send_to_emacs (emacs_socket, " ");
1668 continue;
1671 if (*argv[i] == '+')
1673 char *p = argv[i] + 1;
1674 while (isdigit ((unsigned char) *p) || *p == ':') p++;
1675 if (*p == 0)
1677 send_to_emacs (emacs_socket, "-position ");
1678 quote_argument (emacs_socket, argv[i]);
1679 send_to_emacs (emacs_socket, " ");
1680 continue;
1683 #ifdef WINDOWSNT
1684 else if (! file_name_absolute_p (argv[i])
1685 && (isalpha (argv[i][0]) && argv[i][1] == ':'))
1686 /* Windows can have a different default directory for each
1687 drive, so the cwd passed via "-dir" is not sufficient
1688 to account for that.
1689 If the user uses <drive>:<relpath>, we hence need to be
1690 careful to expand <relpath> with the default directory
1691 corresponding to <drive>. */
1693 char *filename = (char *) xmalloc (MAX_PATH);
1694 DWORD size;
1696 size = GetFullPathName (argv[i], MAX_PATH, filename, NULL);
1697 if (size > 0 && size < MAX_PATH)
1698 argv[i] = filename;
1699 else
1700 free (filename);
1702 #endif
1704 send_to_emacs (emacs_socket, "-file ");
1705 quote_argument (emacs_socket, argv[i]);
1706 send_to_emacs (emacs_socket, " ");
1709 else if (eval)
1711 /* Read expressions interactively. */
1712 while ((str = fgets (string, BUFSIZ, stdin)))
1714 send_to_emacs (emacs_socket, "-eval ");
1715 quote_argument (emacs_socket, str);
1717 send_to_emacs (emacs_socket, " ");
1720 send_to_emacs (emacs_socket, "\n");
1722 /* Wait for an answer. */
1723 if (!eval && !tty && !nowait && !quiet)
1725 printf ("Waiting for Emacs...");
1726 needlf = 2;
1728 fflush (stdout);
1729 fsync (1);
1731 /* Now, wait for an answer and print any messages. */
1732 while (exit_status == EXIT_SUCCESS)
1734 char *p;
1737 errno = 0;
1738 rl = recv (emacs_socket, string, BUFSIZ, 0);
1740 /* If we receive a signal (e.g. SIGWINCH, which we pass
1741 through to Emacs), on some OSes we get EINTR and must retry. */
1742 while (rl < 0 && errno == EINTR);
1744 if (rl <= 0)
1745 break;
1747 string[rl] = '\0';
1749 p = string + strlen (string) - 1;
1750 while (p > string && *p == '\n')
1751 *p-- = 0;
1753 if (strprefix ("-emacs-pid ", string))
1755 /* -emacs-pid PID: The process id of the Emacs process. */
1756 emacs_pid = strtol (string + strlen ("-emacs-pid"), NULL, 10);
1758 else if (strprefix ("-window-system-unsupported ", string))
1760 /* -window-system-unsupported: Emacs was compiled without X
1761 support. Try again on the terminal. */
1762 nowait = 0;
1763 tty = 1;
1764 goto retry;
1766 else if (strprefix ("-print ", string))
1768 /* -print STRING: Print STRING on the terminal. */
1769 str = unquote_argument (string + strlen ("-print "));
1770 if (needlf)
1771 printf ("\n");
1772 printf ("%s", str);
1773 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1775 else if (strprefix ("-error ", string))
1777 /* -error DESCRIPTION: Signal an error on the terminal. */
1778 str = unquote_argument (string + strlen ("-error "));
1779 if (needlf)
1780 printf ("\n");
1781 fprintf (stderr, "*ERROR*: %s", str);
1782 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1783 exit_status = EXIT_FAILURE;
1785 #ifdef SIGSTOP
1786 else if (strprefix ("-suspend ", string))
1788 /* -suspend: Suspend this terminal, i.e., stop the process. */
1789 if (needlf)
1790 printf ("\n");
1791 needlf = 0;
1792 kill (0, SIGSTOP);
1794 #endif
1795 else
1797 /* Unknown command. */
1798 if (needlf)
1799 printf ("\n");
1800 printf ("*ERROR*: Unknown message: %s", string);
1801 needlf = string[0]
1802 == '\0' ? needlf : string[strlen (string) - 1] != '\n';
1806 if (needlf)
1807 printf ("\n");
1808 fflush (stdout);
1809 fsync (1);
1811 if (rl < 0)
1812 exit_status = EXIT_FAILURE;
1814 CLOSE_SOCKET (emacs_socket);
1815 return exit_status;
1818 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
1821 #ifndef HAVE_STRERROR
1822 char *
1823 strerror (errnum)
1824 int errnum;
1826 extern char *sys_errlist[];
1827 extern int sys_nerr;
1829 if (errnum >= 0 && errnum < sys_nerr)
1830 return sys_errlist[errnum];
1831 return (char *) "Unknown error";
1834 #endif /* ! HAVE_STRERROR */
1837 /* emacsclient.c ends here */