Make list-processes support display-line-numbers
[emacs.git] / lib-src / emacsclient.c
blobf1d4e8976da3edb3feaecbd1a6d8c5f9501d9002
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 <stdlib.h>
77 #include <string.h>
78 #include <getopt.h>
79 #include <unistd.h>
81 #include <pwd.h>
82 #include <sys/stat.h>
83 #include <signal.h>
84 #include <errno.h>
86 #include <unlocked-io.h>
88 #ifndef VERSION
89 #define VERSION "unspecified"
90 #endif
93 #ifndef EXIT_SUCCESS
94 #define EXIT_SUCCESS 0
95 #endif
97 #ifndef EXIT_FAILURE
98 #define EXIT_FAILURE 1
99 #endif
101 /* Additional space when allocating buffers for filenames, etc. */
102 #define EXTRA_SPACE 100
104 #ifdef min
105 #undef min
106 #endif
107 #define min(x, y) (((x) < (y)) ? (x) : (y))
110 /* Name used to invoke this program. */
111 const char *progname;
113 /* The second argument to main. */
114 char **main_argv;
116 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
117 int nowait = 0;
119 /* Nonzero means don't print messages for successful operations. --quiet. */
120 int quiet = 0;
122 /* Nonzero means don't print values returned from emacs. --suppress-output. */
123 int suppress_output = 0;
125 /* Nonzero means args are expressions to be evaluated. --eval. */
126 int eval = 0;
128 /* Nonzero means don't open a new frame. Inverse of --create-frame. */
129 int current_frame = 1;
131 /* The display on which Emacs should work. --display. */
132 const char *display = NULL;
134 /* The alternate display we should try if Emacs does not support display. */
135 const char *alt_display = NULL;
137 /* The parent window ID, if we are opening a frame via XEmbed. */
138 char *parent_id = NULL;
140 /* Nonzero means open a new Emacs frame on the current terminal. */
141 int tty = 0;
143 /* If non-NULL, the name of an editor to fallback to if the server
144 is not running. --alternate-editor. */
145 const char *alternate_editor = NULL;
147 /* If non-NULL, the filename of the UNIX socket. */
148 const char *socket_name = NULL;
150 /* If non-NULL, the filename of the authentication file. */
151 const char *server_file = NULL;
153 /* If non-NULL, the tramp prefix emacs must use to find the files. */
154 const char *tramp_prefix = NULL;
156 /* PID of the Emacs server process. */
157 int emacs_pid = 0;
159 /* If non-NULL, a string that should form a frame parameter alist to
160 be used for the new frame. */
161 const char *frame_parameters = NULL;
163 static _Noreturn void print_help_and_exit (void);
166 struct option longopts[] =
168 { "no-wait", no_argument, NULL, 'n' },
169 { "quiet", no_argument, NULL, 'q' },
170 { "suppress-output", no_argument, NULL, 'u' },
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 { "frame-parameters", required_argument, NULL, 'F' },
179 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
180 { "socket-name", required_argument, NULL, 's' },
181 #endif
182 { "server-file", required_argument, NULL, 'f' },
183 { "display", required_argument, NULL, 'd' },
184 { "parent-id", required_argument, NULL, 'p' },
185 { "tramp", required_argument, NULL, 'T' },
186 { 0, 0, 0, 0 }
190 /* Like malloc but get fatal error if memory is exhausted. */
192 static void *
193 xmalloc (size_t size)
195 void *result = 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 char *get_current_dir_name (void);
209 /* Return the current working directory. Returns NULL on errors.
210 Any other returned value must be freed with free. This is used
211 only when get_current_dir_name is not defined on the system. */
212 char *
213 get_current_dir_name (void)
215 char *buf;
216 const char *pwd;
217 struct stat dotstat, pwdstat;
218 /* If PWD is accurate, use it instead of calling getcwd. PWD is
219 sometimes a nicer name, and using it may avoid a fatal error if a
220 parent directory is searchable but not readable. */
221 if ((pwd = egetenv ("PWD")) != 0
222 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
223 && stat (pwd, &pwdstat) == 0
224 && stat (".", &dotstat) == 0
225 && dotstat.st_ino == pwdstat.st_ino
226 && dotstat.st_dev == pwdstat.st_dev
227 #ifdef MAXPATHLEN
228 && strlen (pwd) < MAXPATHLEN
229 #endif
232 buf = (char *) xmalloc (strlen (pwd) + 1);
233 strcpy (buf, pwd);
235 else
237 size_t buf_size = 1024;
238 for (;;)
240 int tmp_errno;
241 buf = malloc (buf_size);
242 if (! buf)
243 break;
244 if (getcwd (buf, buf_size) == buf)
245 break;
246 tmp_errno = errno;
247 free (buf);
248 if (tmp_errno != ERANGE)
250 errno = tmp_errno;
251 return NULL;
253 buf_size *= 2;
254 if (! buf_size)
256 errno = ENOMEM;
257 return NULL;
261 return buf;
263 #endif
265 #ifdef WINDOWSNT
267 /* Like strdup but get a fatal error if memory is exhausted. */
268 char *xstrdup (const char *);
270 char *
271 xstrdup (const char *s)
273 char *result = strdup (s);
274 if (result == NULL)
276 perror ("strdup");
277 exit (EXIT_FAILURE);
279 return result;
282 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
284 char *w32_get_resource (HKEY, const char *, LPDWORD);
286 /* Retrieve an environment variable from the Emacs subkeys of the registry.
287 Return NULL if the variable was not found, or it was empty.
288 This code is based on w32_get_resource (w32.c). */
289 char *
290 w32_get_resource (HKEY predefined, const char *key, LPDWORD type)
292 HKEY hrootkey = NULL;
293 char *result = NULL;
294 DWORD cbData;
296 if (RegOpenKeyEx (predefined, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
298 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS)
300 result = (char *) xmalloc (cbData);
302 if ((RegQueryValueEx (hrootkey, key, NULL, type, (LPBYTE)result, &cbData) != ERROR_SUCCESS)
303 || (*result == 0))
305 free (result);
306 result = NULL;
310 RegCloseKey (hrootkey);
313 return result;
317 getenv wrapper for Windows
319 Value is allocated on the heap, and can be free'd.
321 This is needed to duplicate Emacs's behavior, which is to look for
322 environment variables in the registry if they don't appear in the
323 environment. */
324 char *
325 w32_getenv (const char *envvar)
327 char *value;
328 DWORD dwType;
330 if ((value = getenv (envvar)))
331 /* Found in the environment. strdup it, because values returned
332 by getenv cannot be free'd. */
333 return xstrdup (value);
335 if (! (value = w32_get_resource (HKEY_CURRENT_USER, envvar, &dwType)) &&
336 ! (value = w32_get_resource (HKEY_LOCAL_MACHINE, envvar, &dwType)))
338 /* "w32console" is what Emacs on Windows uses for tty-type under -nw. */
339 if (strcmp (envvar, "TERM") == 0)
340 return xstrdup ("w32console");
341 /* Found neither in the environment nor in the registry. */
342 return NULL;
345 if (dwType == REG_SZ)
346 /* Registry; no need to expand. */
347 return value;
349 if (dwType == REG_EXPAND_SZ)
351 DWORD size;
353 if ((size = ExpandEnvironmentStrings (value, NULL, 0)))
355 char *buffer = (char *) xmalloc (size);
356 if (ExpandEnvironmentStrings (value, buffer, size))
358 /* Found and expanded. */
359 free (value);
360 return buffer;
363 /* Error expanding. */
364 free (buffer);
368 /* Not the right type, or not correctly expanded. */
369 free (value);
370 return NULL;
373 int w32_window_app (void);
376 w32_window_app (void)
378 static int window_app = -1;
379 char szTitle[MAX_PATH];
381 if (window_app < 0)
383 /* Checking for STDOUT does not work; it's a valid handle also in
384 nonconsole apps. Testing for the console title seems to work. */
385 window_app = (GetConsoleTitleA (szTitle, MAX_PATH) == 0);
386 if (window_app)
387 InitCommonControls ();
390 return window_app;
393 /* execvp wrapper for Windows. Quotes arguments with embedded spaces.
395 This is necessary due to the broken implementation of exec* routines in
396 the Microsoft libraries: they concatenate the arguments together without
397 quoting special characters, and pass the result to CreateProcess, with
398 predictably bad results. By contrast, POSIX execvp passes the arguments
399 directly into the argv array of the child process. */
401 int w32_execvp (const char *, char **);
404 w32_execvp (const char *path, char **argv)
406 int i;
408 /* Required to allow a .BAT script as alternate editor. */
409 argv[0] = (char *) alternate_editor;
411 for (i = 0; argv[i]; i++)
412 if (strchr (argv[i], ' '))
414 char *quoted = alloca (strlen (argv[i]) + 3);
415 sprintf (quoted, "\"%s\"", argv[i]);
416 argv[i] = quoted;
419 return execvp (path, argv);
422 #undef execvp
423 #define execvp w32_execvp
425 /* Emulation of ttyname for Windows. */
426 const char *ttyname (int);
427 const char *
428 ttyname (int fd)
430 return "CONOUT$";
433 #endif /* WINDOWSNT */
435 /* Display a normal or error message.
436 On Windows, use a message box if compiled as a Windows app. */
437 static void message (bool, const char *, ...) ATTRIBUTE_FORMAT_PRINTF (2, 3);
438 static void
439 message (bool is_error, const char *format, ...)
441 va_list args;
443 va_start (args, format);
445 #ifdef WINDOWSNT
446 if (w32_window_app ())
448 char msg[2048];
449 vsnprintf (msg, sizeof msg, format, args);
450 msg[sizeof msg - 1] = '\0';
452 if (is_error)
453 MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
454 else
455 MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
457 else
458 #endif
460 FILE *f = is_error ? stderr : stdout;
462 vfprintf (f, format, args);
463 fflush (f);
466 va_end (args);
469 /* Decode the options from argv and argc.
470 The global variable `optind' will say how many arguments we used up. */
472 static void
473 decode_options (int argc, char **argv)
475 alternate_editor = egetenv ("ALTERNATE_EDITOR");
476 tramp_prefix = egetenv ("EMACSCLIENT_TRAMP");
478 while (1)
480 int opt = getopt_long_only (argc, argv,
481 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
482 "VHnequa:s:f:d:F:tcT:",
483 #else
484 "VHnequa:f:d:F:tcT:",
485 #endif
486 longopts, 0);
488 if (opt == EOF)
489 break;
491 switch (opt)
493 case 0:
494 /* If getopt returns 0, then it has already processed a
495 long-named option. We should do nothing. */
496 break;
498 case 'a':
499 alternate_editor = optarg;
500 break;
502 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
503 case 's':
504 socket_name = optarg;
505 break;
506 #endif
508 case 'f':
509 server_file = optarg;
510 break;
512 /* We used to disallow this argument in w32, but it seems better
513 to allow it, for the occasional case where the user is
514 connecting with a w32 client to a server compiled with X11
515 support. */
516 case 'd':
517 display = optarg;
518 break;
520 case 'n':
521 nowait = 1;
522 break;
524 case 'e':
525 eval = 1;
526 break;
528 case 'q':
529 quiet = 1;
530 break;
532 case 'u':
533 suppress_output = 1;
534 break;
536 case 'V':
537 message (false, "emacsclient %s\n", VERSION);
538 exit (EXIT_SUCCESS);
539 break;
541 case 't':
542 tty = 1;
543 current_frame = 0;
544 break;
546 case 'c':
547 current_frame = 0;
548 break;
550 case 'p':
551 parent_id = optarg;
552 current_frame = 0;
553 break;
555 case 'H':
556 print_help_and_exit ();
557 break;
559 case 'F':
560 frame_parameters = optarg;
561 break;
563 case 'T':
564 tramp_prefix = optarg;
565 break;
567 default:
568 message (true, "Try '%s --help' for more information\n", progname);
569 exit (EXIT_FAILURE);
570 break;
574 /* If the -c option is used (without -t) and no --display argument
575 is provided, try $DISPLAY.
576 Without the -c option, we used to set `display' to $DISPLAY by
577 default, but this changed the default behavior and is sometimes
578 inconvenient. So we force users to use "--display $DISPLAY" if
579 they want Emacs to connect to their current display.
581 Some window systems have a notion of default display not
582 reflected in the DISPLAY variable. If the user didn't give us an
583 explicit display, try this platform-specific after trying the
584 display in DISPLAY (if any). */
585 if (!current_frame && !tty && !display)
587 /* Set these here so we use a default_display only when the user
588 didn't give us an explicit display. */
589 #if defined (NS_IMPL_COCOA)
590 alt_display = "ns";
591 #elif defined (HAVE_NTGUI)
592 alt_display = "w32";
593 #endif
595 display = egetenv ("DISPLAY");
598 if (!display)
600 display = alt_display;
601 alt_display = NULL;
604 /* A null-string display is invalid. */
605 if (display && strlen (display) == 0)
606 display = NULL;
608 /* If no display is available, new frames are tty frames. */
609 if (!current_frame && !display)
610 tty = 1;
612 #ifdef WINDOWSNT
613 /* Emacs on Windows does not support graphical and text terminal
614 frames in the same instance. So, treat the -t and -c options as
615 equivalent, and open a new frame on the server's terminal.
616 Ideally, we would only set tty = 1 when the serve is running in a
617 console, but alas we don't know that. As a workaround, always
618 ask for a tty frame, and let server.el figure it out. */
619 if (!current_frame)
621 display = NULL;
622 tty = 1;
624 #endif /* WINDOWSNT */
628 static _Noreturn void
629 print_help_and_exit (void)
631 /* Spaces and tabs are significant in this message; they're chosen so the
632 message aligns properly both in a tty and in a Windows message box.
633 Please try to preserve them; otherwise the output is very hard to read
634 when using emacsclientw. */
635 message (false,
636 "Usage: %s [OPTIONS] FILE...\n%s%s%s", progname, "\
637 Tell the Emacs server to visit the specified files.\n\
638 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
640 The following OPTIONS are accepted:\n\
641 -V, --version Just print version info and return\n\
642 -H, --help Print this usage information message\n\
643 -nw, -t, --tty Open a new Emacs frame on the current terminal\n\
644 -c, --create-frame Create a new frame instead of trying to\n\
645 use the current Emacs frame\n\
646 ", "\
647 -F ALIST, --frame-parameters=ALIST\n\
648 Set the parameters of a new frame\n\
649 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
650 -n, --no-wait Don't wait for the server to return\n\
651 -q, --quiet Don't display messages on success\n\
652 -u, --suppress-output Don't display return values from the server\n\
653 -d DISPLAY, --display=DISPLAY\n\
654 Visit the file in the given display\n\
655 ", "\
656 --parent-id=ID Open in parent window ID, via XEmbed\n"
657 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
658 "-s SOCKET, --socket-name=SOCKET\n\
659 Set filename of the UNIX socket for communication\n"
660 #endif
661 "-f SERVER, --server-file=SERVER\n\
662 Set filename of the TCP authentication file\n\
663 -a EDITOR, --alternate-editor=EDITOR\n\
664 Editor to fallback to if the server is not running\n"
665 " If EDITOR is the empty string, start Emacs in daemon\n\
666 mode and try connecting again\n"
667 "-T PREFIX, --tramp=PREFIX\n\
668 PREFIX to prepend to filenames sent by emacsclient\n\
669 for locating files remotely via Tramp\n"
670 "\n\
671 Report bugs with M-x report-emacs-bug.\n");
672 exit (EXIT_SUCCESS);
675 /* Try to run a different command, or --if no alternate editor is
676 defined-- exit with an errorcode.
677 Uses argv, but gets it from the global variable main_argv. */
679 static _Noreturn void
680 fail (void)
682 if (alternate_editor)
684 int i = optind - 1;
686 execvp (alternate_editor, main_argv + i);
687 message (true, "%s: error executing alternate editor \"%s\"\n",
688 progname, alternate_editor);
690 exit (EXIT_FAILURE);
694 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
697 main (int argc, char **argv)
699 main_argv = argv;
700 progname = argv[0];
701 message (true, "%s: Sorry, the Emacs server is supported only\n"
702 "on systems with Berkeley sockets.\n",
703 argv[0]);
704 fail ();
707 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
709 #define AUTH_KEY_LENGTH 64
710 #define SEND_BUFFER_SIZE 4096
712 /* Buffer to accumulate data to send in TCP connections. */
713 char send_buffer[SEND_BUFFER_SIZE + 1];
714 int sblen = 0; /* Fill pointer for the send buffer. */
715 /* Socket used to communicate with the Emacs server process. */
716 HSOCKET emacs_socket = 0;
718 /* On Windows, the socket library was historically separate from the
719 standard C library, so errors are handled differently. */
721 static void
722 sock_err_message (const char *function_name)
724 #ifdef WINDOWSNT
725 char* msg = NULL;
727 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
728 | FORMAT_MESSAGE_ALLOCATE_BUFFER
729 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
730 NULL, WSAGetLastError (), 0, (LPTSTR)&msg, 0, NULL);
732 message (true, "%s: %s: %s\n", progname, function_name, msg);
734 LocalFree (msg);
735 #else
736 message (true, "%s: %s: %s\n", progname, function_name, strerror (errno));
737 #endif
741 /* Let's send the data to Emacs when either
742 - the data ends in "\n", or
743 - the buffer is full (but this shouldn't happen)
744 Otherwise, we just accumulate it. */
745 static void
746 send_to_emacs (HSOCKET s, const char *data)
748 size_t dlen;
750 if (!data)
751 return;
753 dlen = strlen (data);
754 while (*data)
756 size_t part = min (dlen, SEND_BUFFER_SIZE - sblen);
757 memcpy (&send_buffer[sblen], data, part);
758 data += part;
759 sblen += part;
761 if (sblen == SEND_BUFFER_SIZE
762 || (sblen > 0 && send_buffer[sblen-1] == '\n'))
764 int sent = send (s, send_buffer, sblen, 0);
765 if (sent < 0)
767 message (true, "%s: failed to send %d bytes to socket: %s\n",
768 progname, sblen, strerror (errno));
769 fail ();
771 if (sent != sblen)
772 memmove (send_buffer, &send_buffer[sent], sblen - sent);
773 sblen -= sent;
776 dlen -= part;
781 /* In STR, insert a & before each &, each space, each newline, and
782 any initial -. Change spaces to underscores, too, so that the
783 return value never contains a space.
785 Does not change the string. Outputs the result to S. */
786 static void
787 quote_argument (HSOCKET s, const char *str)
789 char *copy = (char *) xmalloc (strlen (str) * 2 + 1);
790 const char *p;
791 char *q;
793 p = str;
794 q = copy;
795 while (*p)
797 if (*p == ' ')
799 *q++ = '&';
800 *q++ = '_';
801 p++;
803 else if (*p == '\n')
805 *q++ = '&';
806 *q++ = 'n';
807 p++;
809 else
811 if (*p == '&' || (*p == '-' && p == str))
812 *q++ = '&';
813 *q++ = *p++;
816 *q++ = 0;
818 send_to_emacs (s, copy);
820 free (copy);
824 /* The inverse of quote_argument. Removes quoting in string STR by
825 modifying the string in place. Returns STR. */
827 static char *
828 unquote_argument (char *str)
830 char *p, *q;
832 if (! str)
833 return str;
835 p = str;
836 q = str;
837 while (*p)
839 if (*p == '&')
841 p++;
842 if (*p == '&')
843 *p = '&';
844 else if (*p == '_')
845 *p = ' ';
846 else if (*p == 'n')
847 *p = '\n';
848 else if (*p == '-')
849 *p = '-';
851 *q++ = *p++;
853 *q = 0;
854 return str;
858 static int
859 file_name_absolute_p (const char *filename)
861 /* Sanity check, it shouldn't happen. */
862 if (! filename) return false;
864 /* /xxx is always an absolute path. */
865 if (filename[0] == '/') return true;
867 /* Empty filenames (which shouldn't happen) are relative. */
868 if (filename[0] == '\0') return false;
870 #ifdef WINDOWSNT
871 /* X:\xxx is always absolute. */
872 if (isalpha ((unsigned char) filename[0])
873 && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
874 return true;
876 /* Both \xxx and \\xxx\yyy are absolute. */
877 if (filename[0] == '\\') return true;
878 #endif
880 return false;
883 #ifdef WINDOWSNT
884 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
885 void __cdecl close_winsock (void);
886 void __cdecl
887 close_winsock (void)
889 WSACleanup ();
892 /* Initialize the WinSock2 library. */
893 void initialize_sockets (void);
894 void
895 initialize_sockets (void)
897 WSADATA wsaData;
899 if (WSAStartup (MAKEWORD (2, 0), &wsaData))
901 message (true, "%s: error initializing WinSock2\n", progname);
902 exit (EXIT_FAILURE);
905 atexit (close_winsock);
907 #endif /* WINDOWSNT */
910 /* Read the information needed to set up a TCP comm channel with
911 the Emacs server: host, port, and authentication string. */
913 static int
914 get_server_config (const char *config_file, struct sockaddr_in *server,
915 char *authentication)
917 char dotted[32];
918 char *port;
919 FILE *config = NULL;
921 if (file_name_absolute_p (config_file))
922 config = fopen (config_file, "rb");
923 else
925 const char *home = egetenv ("HOME");
927 if (home)
929 char *path = xmalloc (strlen (home) + strlen (config_file)
930 + EXTRA_SPACE);
931 char *z = stpcpy (path, home);
932 z = stpcpy (z, "/.emacs.d/server/");
933 strcpy (z, config_file);
934 config = fopen (path, "rb");
935 free (path);
937 #ifdef WINDOWSNT
938 if (!config && (home = egetenv ("APPDATA")))
940 char *path = xmalloc (strlen (home) + strlen (config_file)
941 + EXTRA_SPACE);
942 char *z = stpcpy (path, home);
943 z = stpcpy (z, "/.emacs.d/server/");
944 strcpy (z, config_file);
945 config = fopen (path, "rb");
946 free (path);
948 #endif
951 if (! config)
952 return false;
954 if (fgets (dotted, sizeof dotted, config)
955 && (port = strchr (dotted, ':')))
956 *port++ = '\0';
957 else
959 message (true, "%s: invalid configuration info\n", progname);
960 exit (EXIT_FAILURE);
963 server->sin_family = AF_INET;
964 server->sin_addr.s_addr = inet_addr (dotted);
965 server->sin_port = htons (atoi (port));
967 if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
969 message (true, "%s: cannot read authentication info\n", progname);
970 exit (EXIT_FAILURE);
973 fclose (config);
975 return true;
978 static HSOCKET
979 set_tcp_socket (const char *local_server_file)
981 HSOCKET s;
982 struct sockaddr_in server;
983 struct linger l_arg = {1, 1};
984 char auth_string[AUTH_KEY_LENGTH + 1];
986 if (! get_server_config (local_server_file, &server, auth_string))
987 return INVALID_SOCKET;
989 if (server.sin_addr.s_addr != inet_addr ("127.0.0.1") && !quiet)
990 message (false, "%s: connected to remote socket at %s\n",
991 progname, inet_ntoa (server.sin_addr));
993 /* Open up an AF_INET socket. */
994 if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
996 /* Since we have an alternate to try out, this is not an error
997 yet; popping out a modal dialog at this stage would make -a
998 option totally useless for emacsclientw -- the user will
999 still get an error message if the alternate editor fails. */
1000 #ifdef WINDOWSNT
1001 if(!(w32_window_app () && alternate_editor))
1002 #endif
1003 sock_err_message ("socket");
1004 return INVALID_SOCKET;
1007 /* Set up the socket. */
1008 if (connect (s, (struct sockaddr *) &server, sizeof server) < 0)
1010 #ifdef WINDOWSNT
1011 if(!(w32_window_app () && alternate_editor))
1012 #endif
1013 sock_err_message ("connect");
1014 return INVALID_SOCKET;
1017 setsockopt (s, SOL_SOCKET, SO_LINGER, (char *) &l_arg, sizeof l_arg);
1019 /* Send the authentication. */
1020 auth_string[AUTH_KEY_LENGTH] = '\0';
1022 send_to_emacs (s, "-auth ");
1023 send_to_emacs (s, auth_string);
1024 send_to_emacs (s, " ");
1026 return s;
1030 /* Returns 1 if PREFIX is a prefix of STRING. */
1031 static int
1032 strprefix (const char *prefix, const char *string)
1034 return !strncmp (prefix, string, strlen (prefix));
1037 /* Get tty name and type. If successful, return the type in TTY_TYPE
1038 and the name in TTY_NAME, and return 1. Otherwise, fail if NOABORT
1039 is zero, or return 0 if NOABORT is non-zero. */
1041 static int
1042 find_tty (const char **tty_type, const char **tty_name, int noabort)
1044 const char *type = egetenv ("TERM");
1045 const char *name = ttyname (fileno (stdout));
1047 if (!name)
1049 if (noabort)
1050 return 0;
1051 else
1053 message (true, "%s: could not get terminal name\n", progname);
1054 fail ();
1058 if (!type)
1060 if (noabort)
1061 return 0;
1062 else
1064 message (true, "%s: please set the TERM variable to your terminal type\n",
1065 progname);
1066 fail ();
1070 if (strcmp (type, "eterm") == 0)
1072 if (noabort)
1073 return 0;
1074 else
1076 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1077 message (true, "%s: opening a frame in an Emacs term buffer"
1078 " is not supported\n", progname);
1079 fail ();
1083 *tty_name = name;
1084 *tty_type = type;
1085 return 1;
1089 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1091 /* Three possibilities:
1092 2 - can't be `stat'ed (sets errno)
1093 1 - isn't owned by us
1094 0 - success: none of the above */
1096 static int
1097 socket_status (const char *name)
1099 struct stat statbfr;
1101 if (stat (name, &statbfr) == -1)
1102 return 2;
1104 if (statbfr.st_uid != geteuid ())
1105 return 1;
1107 return 0;
1111 /* A signal handler that passes the signal to the Emacs process.
1112 Useful for SIGWINCH. */
1114 static void
1115 pass_signal_to_emacs (int signalnum)
1117 int old_errno = errno;
1119 if (emacs_pid)
1120 kill (emacs_pid, signalnum);
1122 signal (signalnum, pass_signal_to_emacs);
1123 errno = old_errno;
1126 /* Signal handler for SIGCONT; notify the Emacs process that it can
1127 now resume our tty frame. */
1129 static void
1130 handle_sigcont (int signalnum)
1132 int old_errno = errno;
1133 pid_t pgrp = getpgrp ();
1134 pid_t tcpgrp = tcgetpgrp (1);
1136 if (tcpgrp == pgrp)
1138 /* We are in the foreground. */
1139 send_to_emacs (emacs_socket, "-resume \n");
1141 else if (0 <= tcpgrp && tty)
1143 /* We are in the background; cancel the continue. */
1144 kill (-pgrp, SIGTTIN);
1147 signal (signalnum, handle_sigcont);
1148 errno = old_errno;
1151 /* Signal handler for SIGTSTP; notify the Emacs process that we are
1152 going to sleep. Normally the suspend is initiated by Emacs via
1153 server-handle-suspend-tty, but if the server gets out of sync with
1154 reality, we may get a SIGTSTP on C-z. Handling this signal and
1155 notifying Emacs about it should get things under control again. */
1157 static void
1158 handle_sigtstp (int signalnum)
1160 int old_errno = errno;
1161 sigset_t set;
1163 if (emacs_socket)
1164 send_to_emacs (emacs_socket, "-suspend \n");
1166 /* Unblock this signal and call the default handler by temporarily
1167 changing the handler and resignaling. */
1168 sigprocmask (SIG_BLOCK, NULL, &set);
1169 sigdelset (&set, signalnum);
1170 signal (signalnum, SIG_DFL);
1171 raise (signalnum);
1172 sigprocmask (SIG_SETMASK, &set, NULL); /* Let's the above signal through. */
1173 signal (signalnum, handle_sigtstp);
1175 errno = old_errno;
1179 /* Set up signal handlers before opening a frame on the current tty. */
1181 static void
1182 init_signals (void)
1184 /* Set up signal handlers. */
1185 signal (SIGWINCH, pass_signal_to_emacs);
1187 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
1188 deciding which terminal the signal came from. C-g is now a
1189 normal input event on secondary terminals. */
1190 #if 0
1191 signal (SIGINT, pass_signal_to_emacs);
1192 signal (SIGQUIT, pass_signal_to_emacs);
1193 #endif
1195 signal (SIGCONT, handle_sigcont);
1196 signal (SIGTSTP, handle_sigtstp);
1197 signal (SIGTTOU, handle_sigtstp);
1201 static HSOCKET
1202 set_local_socket (const char *local_socket_name)
1204 HSOCKET s;
1205 struct sockaddr_un server;
1207 /* Open up an AF_UNIX socket in this person's home directory. */
1208 if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
1210 message (true, "%s: socket: %s\n", progname, strerror (errno));
1211 return INVALID_SOCKET;
1214 server.sun_family = AF_UNIX;
1217 int sock_status;
1218 int saved_errno;
1219 const char *server_name = local_socket_name;
1220 const char *tmpdir = NULL;
1221 char *tmpdir_storage = NULL;
1222 char *socket_name_storage = NULL;
1224 if (!strchr (local_socket_name, '/') && !strchr (local_socket_name, '\\'))
1226 /* socket_name is a file name component. */
1227 long uid = geteuid ();
1228 tmpdir = egetenv ("TMPDIR");
1229 if (!tmpdir)
1231 #ifdef DARWIN_OS
1232 #ifndef _CS_DARWIN_USER_TEMP_DIR
1233 #define _CS_DARWIN_USER_TEMP_DIR 65537
1234 #endif
1235 size_t n = confstr (_CS_DARWIN_USER_TEMP_DIR, NULL, (size_t) 0);
1236 if (n > 0)
1238 tmpdir = tmpdir_storage = xmalloc (n);
1239 confstr (_CS_DARWIN_USER_TEMP_DIR, tmpdir_storage, n);
1241 else
1242 #endif
1243 tmpdir = "/tmp";
1245 socket_name_storage =
1246 xmalloc (strlen (tmpdir) + strlen (server_name) + EXTRA_SPACE);
1247 char *z = stpcpy (socket_name_storage, tmpdir);
1248 z += sprintf (z, "/emacs%ld/", uid);
1249 strcpy (z, server_name);
1250 local_socket_name = socket_name_storage;
1253 if (strlen (local_socket_name) < sizeof (server.sun_path))
1254 strcpy (server.sun_path, local_socket_name);
1255 else
1257 message (true, "%s: socket-name %s too long\n",
1258 progname, local_socket_name);
1259 fail ();
1262 /* See if the socket exists, and if it's owned by us. */
1263 sock_status = socket_status (server.sun_path);
1264 saved_errno = errno;
1265 if (sock_status && tmpdir)
1267 /* Failing that, see if LOGNAME or USER exist and differ from
1268 our euid. If so, look for a socket based on the UID
1269 associated with the name. This is reminiscent of the logic
1270 that init_editfns uses to set the global Vuser_full_name. */
1272 const char *user_name = egetenv ("LOGNAME");
1274 if (!user_name)
1275 user_name = egetenv ("USER");
1277 if (user_name)
1279 struct passwd *pw = getpwnam (user_name);
1281 if (pw && (pw->pw_uid != geteuid ()))
1283 /* We're running under su, apparently. */
1284 long uid = pw->pw_uid;
1285 char *user_socket_name
1286 = xmalloc (strlen (tmpdir) + strlen (server_name)
1287 + EXTRA_SPACE);
1288 char *z = stpcpy (user_socket_name, tmpdir);
1289 z += sprintf (z, "/emacs%ld/", uid);
1290 strcpy (z, server_name);
1292 if (strlen (user_socket_name) < sizeof (server.sun_path))
1293 strcpy (server.sun_path, user_socket_name);
1294 else
1296 message (true, "%s: socket-name %s too long\n",
1297 progname, user_socket_name);
1298 exit (EXIT_FAILURE);
1300 free (user_socket_name);
1302 sock_status = socket_status (server.sun_path);
1303 saved_errno = errno;
1305 else
1306 errno = saved_errno;
1310 free (socket_name_storage);
1311 free (tmpdir_storage);
1313 switch (sock_status)
1315 case 1:
1316 /* There's a socket, but it isn't owned by us. This is OK if
1317 we are root. */
1318 if (0 != geteuid ())
1320 message (true, "%s: Invalid socket owner\n", progname);
1321 return INVALID_SOCKET;
1323 break;
1325 case 2:
1326 /* `stat' failed */
1327 if (saved_errno == ENOENT)
1328 message (true,
1329 "%s: can't find socket; have you started the server?\n\
1330 To start the server in Emacs, type \"M-x server-start\".\n",
1331 progname);
1332 else
1333 message (true, "%s: can't stat %s: %s\n",
1334 progname, server.sun_path, strerror (saved_errno));
1335 return INVALID_SOCKET;
1339 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
1340 < 0)
1342 message (true, "%s: connect: %s\n", progname, strerror (errno));
1343 return INVALID_SOCKET;
1346 return s;
1348 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1350 static HSOCKET
1351 set_socket (int no_exit_if_error)
1353 HSOCKET s;
1354 const char *local_server_file = server_file;
1356 INITIALIZE ();
1358 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1359 /* Explicit --socket-name argument. */
1360 if (socket_name)
1362 s = set_local_socket (socket_name);
1363 if ((s != INVALID_SOCKET) || no_exit_if_error)
1364 return s;
1365 message (true, "%s: error accessing socket \"%s\"\n",
1366 progname, socket_name);
1367 exit (EXIT_FAILURE);
1369 #endif
1371 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1372 if (!local_server_file)
1373 local_server_file = egetenv ("EMACS_SERVER_FILE");
1375 if (local_server_file)
1377 s = set_tcp_socket (local_server_file);
1378 if ((s != INVALID_SOCKET) || no_exit_if_error)
1379 return s;
1381 message (true, "%s: error accessing server file \"%s\"\n",
1382 progname, local_server_file);
1383 exit (EXIT_FAILURE);
1386 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1387 /* Implicit local socket. */
1388 s = set_local_socket ("server");
1389 if (s != INVALID_SOCKET)
1390 return s;
1391 #endif
1393 /* Implicit server file. */
1394 s = set_tcp_socket ("server");
1395 if ((s != INVALID_SOCKET) || no_exit_if_error)
1396 return s;
1398 /* No implicit or explicit socket, and no alternate editor. */
1399 message (true, "%s: No socket or alternate editor. Please use:\n\n"
1400 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1401 "\t--socket-name\n"
1402 #endif
1403 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1404 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1405 progname);
1406 exit (EXIT_FAILURE);
1409 #ifdef HAVE_NTGUI
1410 FARPROC set_fg; /* Pointer to AllowSetForegroundWindow. */
1411 FARPROC get_wc; /* Pointer to RealGetWindowClassA. */
1413 void w32_set_user_model_id (void);
1415 void
1416 w32_set_user_model_id (void)
1418 HMODULE shell;
1419 HRESULT (WINAPI * set_user_model) (const wchar_t * id);
1421 /* On Windows 7 and later, we need to set the user model ID
1422 to associate emacsclient launched files with Emacs frames
1423 in the UI. */
1424 shell = LoadLibrary ("shell32.dll");
1425 if (shell)
1427 set_user_model
1428 = (void *) GetProcAddress (shell,
1429 "SetCurrentProcessExplicitAppUserModelID");
1430 /* If the function is defined, then we are running on Windows 7
1431 or newer, and the UI uses this to group related windows
1432 together. Since emacs, runemacs, emacsclient are related, we
1433 want them grouped even though the executables are different,
1434 so we need to set a consistent ID between them. */
1435 if (set_user_model)
1436 set_user_model (L"GNU.Emacs");
1438 FreeLibrary (shell);
1442 BOOL CALLBACK w32_find_emacs_process (HWND, LPARAM);
1444 BOOL CALLBACK
1445 w32_find_emacs_process (HWND hWnd, LPARAM lParam)
1447 DWORD pid;
1448 char class[6];
1450 /* Reject any window not of class "Emacs". */
1451 if (! get_wc (hWnd, class, sizeof (class))
1452 || strcmp (class, "Emacs"))
1453 return TRUE;
1455 /* We only need the process id, not the thread id. */
1456 (void) GetWindowThreadProcessId (hWnd, &pid);
1458 /* Not the one we're looking for. */
1459 if (pid != (DWORD) emacs_pid) return TRUE;
1461 /* OK, let's raise it. */
1462 set_fg (emacs_pid);
1464 /* Stop enumeration. */
1465 return FALSE;
1468 /* Search for a window of class "Emacs" and owned by a process with
1469 process id = emacs_pid. If found, allow it to grab the focus. */
1470 void w32_give_focus (void);
1472 void
1473 w32_give_focus (void)
1475 HANDLE user32;
1477 /* It shouldn't happen when dealing with TCP sockets. */
1478 if (!emacs_pid) return;
1480 user32 = GetModuleHandle ("user32.dll");
1482 if (!user32)
1483 return;
1485 /* Modern Windows restrict which processes can set the foreground window.
1486 emacsclient can allow Emacs to grab the focus by calling the function
1487 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1488 NT) lack this function, so we have to check its availability. */
1489 if ((set_fg = GetProcAddress (user32, "AllowSetForegroundWindow"))
1490 && (get_wc = GetProcAddress (user32, "RealGetWindowClassA")))
1491 EnumWindows (w32_find_emacs_process, (LPARAM) 0);
1493 #endif /* HAVE_NTGUI */
1495 /* Start the emacs daemon and try to connect to it. */
1497 static void
1498 start_daemon_and_retry_set_socket (void)
1500 #ifndef WINDOWSNT
1501 pid_t dpid;
1502 int status;
1504 dpid = fork ();
1506 if (dpid > 0)
1508 pid_t w;
1509 w = waitpid (dpid, &status, WUNTRACED | WCONTINUED);
1511 if ((w == -1) || !WIFEXITED (status) || WEXITSTATUS (status))
1513 message (true, "Error: Could not start the Emacs daemon\n");
1514 exit (EXIT_FAILURE);
1517 /* Try connecting, the daemon should have started by now. */
1518 message (true, "Emacs daemon should have started, trying to connect again\n");
1519 if ((emacs_socket = set_socket (1)) == INVALID_SOCKET)
1521 message (true, "Error: Cannot connect even after starting the Emacs daemon\n");
1522 exit (EXIT_FAILURE);
1525 else if (dpid < 0)
1527 fprintf (stderr, "Error: Cannot fork!\n");
1528 exit (EXIT_FAILURE);
1530 else
1532 char emacs[] = "emacs";
1533 char daemon_option[] = "--daemon";
1534 char *d_argv[3];
1535 d_argv[0] = emacs;
1536 d_argv[1] = daemon_option;
1537 d_argv[2] = 0;
1538 if (socket_name != NULL)
1540 /* Pass --daemon=socket_name as argument. */
1541 const char *deq = "--daemon=";
1542 char *daemon_arg = xmalloc (strlen (deq)
1543 + strlen (socket_name) + 1);
1544 strcpy (stpcpy (daemon_arg, deq), socket_name);
1545 d_argv[1] = daemon_arg;
1547 execvp ("emacs", d_argv);
1548 message (true, "%s: error starting emacs daemon\n", progname);
1550 #else /* WINDOWSNT */
1551 DWORD wait_result;
1552 HANDLE w32_daemon_event;
1553 STARTUPINFO si;
1554 PROCESS_INFORMATION pi;
1556 ZeroMemory (&si, sizeof si);
1557 si.cb = sizeof si;
1558 ZeroMemory (&pi, sizeof pi);
1560 /* We start Emacs in daemon mode, and then wait for it to signal us
1561 it is ready to accept client connections, by asserting an event
1562 whose name is known to the daemon (defined by nt/inc/ms-w32.h). */
1564 if (!CreateProcess (NULL, (LPSTR)"emacs --daemon", NULL, NULL, FALSE,
1565 CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
1567 char* msg = NULL;
1569 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
1570 | FORMAT_MESSAGE_ALLOCATE_BUFFER
1571 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1572 NULL, GetLastError (), 0, (LPTSTR)&msg, 0, NULL);
1573 message (true, "%s: error starting emacs daemon (%s)\n", progname, msg);
1574 exit (EXIT_FAILURE);
1577 w32_daemon_event = CreateEvent (NULL, TRUE, FALSE, W32_DAEMON_EVENT);
1578 if (w32_daemon_event == NULL)
1580 message (true, "Couldn't create Windows daemon event");
1581 exit (EXIT_FAILURE);
1583 if ((wait_result = WaitForSingleObject (w32_daemon_event, INFINITE))
1584 != WAIT_OBJECT_0)
1586 const char *msg = NULL;
1588 switch (wait_result)
1590 case WAIT_ABANDONED:
1591 msg = "The daemon exited unexpectedly";
1592 break;
1593 case WAIT_TIMEOUT:
1594 /* Can't happen due to INFINITE. */
1595 default:
1596 case WAIT_FAILED:
1597 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
1598 | FORMAT_MESSAGE_ALLOCATE_BUFFER
1599 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1600 NULL, GetLastError (), 0, (LPTSTR)&msg, 0, NULL);
1601 break;
1603 message (true, "Error: Could not start the Emacs daemon: %s\n", msg);
1604 exit (EXIT_FAILURE);
1606 CloseHandle (w32_daemon_event);
1608 /* Try connecting, the daemon should have started by now. */
1609 /* It's just a progress message, so don't pop a dialog if this is
1610 emacsclientw. */
1611 if (!w32_window_app ())
1612 message (true,
1613 "Emacs daemon should have started, trying to connect again\n");
1614 if ((emacs_socket = set_socket (1)) == INVALID_SOCKET)
1616 message (true,
1617 "Error: Cannot connect even after starting the Emacs daemon\n");
1618 exit (EXIT_FAILURE);
1620 #endif /* WINDOWSNT */
1624 main (int argc, char **argv)
1626 int rl = 0, needlf = 0;
1627 char *cwd, *str;
1628 char string[BUFSIZ+1];
1629 int start_daemon_if_needed;
1630 int exit_status = EXIT_SUCCESS;
1632 main_argv = argv;
1633 progname = argv[0];
1635 #ifdef HAVE_NTGUI
1636 /* On Windows 7 and later, we need to explicitly associate
1637 emacsclient with emacs so the UI behaves sensibly. This
1638 association does no harm if we're not actually connecting to an
1639 Emacs using a window display. */
1640 w32_set_user_model_id ();
1641 #endif /* HAVE_NTGUI */
1643 /* Process options. */
1644 decode_options (argc, argv);
1646 if ((argc - optind < 1) && !eval && current_frame)
1648 message (true, "%s: file name or argument required\n"
1649 "Try '%s --help' for more information\n",
1650 progname, progname);
1651 exit (EXIT_FAILURE);
1654 #ifndef WINDOWSNT
1655 if (tty)
1657 pid_t pgrp = getpgrp ();
1658 pid_t tcpgrp = tcgetpgrp (1);
1659 if (0 <= tcpgrp && tcpgrp != pgrp)
1660 kill (-pgrp, SIGTTIN);
1662 #endif /* !WINDOWSNT */
1664 /* If alternate_editor is the empty string, start the emacs daemon
1665 in case of failure to connect. */
1666 start_daemon_if_needed = (alternate_editor
1667 && (alternate_editor[0] == '\0'));
1669 emacs_socket = set_socket (alternate_editor || start_daemon_if_needed);
1670 if (emacs_socket == INVALID_SOCKET)
1672 if (! start_daemon_if_needed)
1673 fail ();
1675 start_daemon_and_retry_set_socket ();
1678 cwd = get_current_dir_name ();
1679 if (cwd == 0)
1681 message (true, "%s: %s\n", progname,
1682 "Cannot get current working directory");
1683 fail ();
1686 #ifdef HAVE_NTGUI
1687 if (display && !strcmp (display, "w32"))
1688 w32_give_focus ();
1689 #endif /* HAVE_NTGUI */
1691 /* Send over our environment and current directory. */
1692 if (!current_frame)
1694 int i;
1695 for (i = 0; environ[i]; i++)
1697 send_to_emacs (emacs_socket, "-env ");
1698 quote_argument (emacs_socket, environ[i]);
1699 send_to_emacs (emacs_socket, " ");
1702 send_to_emacs (emacs_socket, "-dir ");
1703 if (tramp_prefix)
1704 quote_argument (emacs_socket, tramp_prefix);
1705 quote_argument (emacs_socket, cwd);
1706 free (cwd);
1707 send_to_emacs (emacs_socket, "/");
1708 send_to_emacs (emacs_socket, " ");
1710 retry:
1711 if (nowait)
1712 send_to_emacs (emacs_socket, "-nowait ");
1714 if (current_frame)
1715 send_to_emacs (emacs_socket, "-current-frame ");
1717 if (display)
1719 send_to_emacs (emacs_socket, "-display ");
1720 quote_argument (emacs_socket, display);
1721 send_to_emacs (emacs_socket, " ");
1724 if (parent_id)
1726 send_to_emacs (emacs_socket, "-parent-id ");
1727 quote_argument (emacs_socket, parent_id);
1728 send_to_emacs (emacs_socket, " ");
1731 if (frame_parameters && !current_frame)
1733 send_to_emacs (emacs_socket, "-frame-parameters ");
1734 quote_argument (emacs_socket, frame_parameters);
1735 send_to_emacs (emacs_socket, " ");
1738 /* Unless we are certain we don't want to occupy the tty, send our
1739 tty information to Emacs. For example, in daemon mode Emacs may
1740 need to occupy this tty if no other frame is available. */
1741 if (!current_frame || !eval)
1743 const char *tty_type, *tty_name;
1745 if (find_tty (&tty_type, &tty_name, !tty))
1747 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1748 init_signals ();
1749 #endif
1750 send_to_emacs (emacs_socket, "-tty ");
1751 quote_argument (emacs_socket, tty_name);
1752 send_to_emacs (emacs_socket, " ");
1753 quote_argument (emacs_socket, tty_type);
1754 send_to_emacs (emacs_socket, " ");
1758 if (!current_frame && !tty)
1759 send_to_emacs (emacs_socket, "-window-system ");
1761 if ((argc - optind > 0))
1763 int i;
1764 for (i = optind; i < argc; i++)
1767 if (eval)
1769 /* Don't prepend cwd or anything like that. */
1770 send_to_emacs (emacs_socket, "-eval ");
1771 quote_argument (emacs_socket, argv[i]);
1772 send_to_emacs (emacs_socket, " ");
1773 continue;
1776 if (*argv[i] == '+')
1778 char *p = argv[i] + 1;
1779 while (isdigit ((unsigned char) *p) || *p == ':') p++;
1780 if (*p == 0)
1782 send_to_emacs (emacs_socket, "-position ");
1783 quote_argument (emacs_socket, argv[i]);
1784 send_to_emacs (emacs_socket, " ");
1785 continue;
1788 #ifdef WINDOWSNT
1789 else if (! file_name_absolute_p (argv[i])
1790 && (isalpha (argv[i][0]) && argv[i][1] == ':'))
1791 /* Windows can have a different default directory for each
1792 drive, so the cwd passed via "-dir" is not sufficient
1793 to account for that.
1794 If the user uses <drive>:<relpath>, we hence need to be
1795 careful to expand <relpath> with the default directory
1796 corresponding to <drive>. */
1798 char *filename = (char *) xmalloc (MAX_PATH);
1799 DWORD size;
1801 size = GetFullPathName (argv[i], MAX_PATH, filename, NULL);
1802 if (size > 0 && size < MAX_PATH)
1803 argv[i] = filename;
1804 else
1805 free (filename);
1807 #endif
1809 send_to_emacs (emacs_socket, "-file ");
1810 if (tramp_prefix && file_name_absolute_p (argv[i]))
1811 quote_argument (emacs_socket, tramp_prefix);
1812 quote_argument (emacs_socket, argv[i]);
1813 send_to_emacs (emacs_socket, " ");
1816 else if (eval)
1818 /* Read expressions interactively. */
1819 while ((str = fgets (string, BUFSIZ, stdin)))
1821 send_to_emacs (emacs_socket, "-eval ");
1822 quote_argument (emacs_socket, str);
1824 send_to_emacs (emacs_socket, " ");
1827 send_to_emacs (emacs_socket, "\n");
1829 /* Wait for an answer. */
1830 if (!eval && !tty && !nowait && !quiet)
1832 printf ("Waiting for Emacs...");
1833 needlf = 2;
1835 fflush (stdout);
1836 while (fdatasync (1) != 0 && errno == EINTR)
1837 continue;
1839 /* Now, wait for an answer and print any messages. */
1840 while (exit_status == EXIT_SUCCESS)
1842 char *p, *end_p;
1845 errno = 0;
1846 rl = recv (emacs_socket, string, BUFSIZ, 0);
1848 /* If we receive a signal (e.g. SIGWINCH, which we pass
1849 through to Emacs), on some OSes we get EINTR and must retry. */
1850 while (rl < 0 && errno == EINTR);
1852 if (rl <= 0)
1853 break;
1855 string[rl] = '\0';
1857 /* Loop over all NL-terminated messages. */
1858 for (end_p = p = string; end_p != NULL && *end_p != '\0'; p = end_p)
1860 end_p = strchr (p, '\n');
1861 if (end_p != NULL)
1862 *end_p++ = '\0';
1864 if (strprefix ("-emacs-pid ", p))
1866 /* -emacs-pid PID: The process id of the Emacs process. */
1867 emacs_pid = strtol (p + strlen ("-emacs-pid"), NULL, 10);
1869 else if (strprefix ("-window-system-unsupported ", p))
1871 /* -window-system-unsupported: Emacs was compiled without support
1872 for whatever window system we tried. Try the alternate
1873 display, or, failing that, try the terminal. */
1874 if (alt_display)
1876 display = alt_display;
1877 alt_display = NULL;
1879 else
1881 nowait = 0;
1882 tty = 1;
1885 goto retry;
1887 else if (strprefix ("-print ", p))
1889 /* -print STRING: Print STRING on the terminal. */
1890 if (!suppress_output)
1892 str = unquote_argument (p + strlen ("-print "));
1893 if (needlf)
1894 printf ("\n");
1895 printf ("%s", str);
1896 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1899 else if (strprefix ("-print-nonl ", p))
1901 /* -print-nonl STRING: Print STRING on the terminal.
1902 Used to continue a preceding -print command. */
1903 if (!suppress_output)
1905 str = unquote_argument (p + strlen ("-print-nonl "));
1906 printf ("%s", str);
1907 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1910 else if (strprefix ("-error ", p))
1912 /* -error DESCRIPTION: Signal an error on the terminal. */
1913 str = unquote_argument (p + strlen ("-error "));
1914 if (needlf)
1915 printf ("\n");
1916 fprintf (stderr, "*ERROR*: %s", str);
1917 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1918 exit_status = EXIT_FAILURE;
1920 #ifdef SIGSTOP
1921 else if (strprefix ("-suspend ", p))
1923 /* -suspend: Suspend this terminal, i.e., stop the process. */
1924 if (needlf)
1925 printf ("\n");
1926 needlf = 0;
1927 kill (0, SIGSTOP);
1929 #endif
1930 else
1932 /* Unknown command. */
1933 if (needlf)
1934 printf ("\n");
1935 needlf = 0;
1936 printf ("*ERROR*: Unknown message: %s\n", p);
1941 if (needlf)
1942 printf ("\n");
1943 fflush (stdout);
1944 while (fdatasync (1) != 0 && errno == EINTR)
1945 continue;
1947 if (rl < 0)
1948 exit_status = EXIT_FAILURE;
1950 CLOSE_SOCKET (emacs_socket);
1951 return exit_status;
1954 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */