Undo last mistakenly commited change.
[emacs.git] / lib-src / emacsclient.c
bloba39376be3fbded8ba81657df56ac89d21c4188d3
1 /* Client process that communicates with GNU Emacs acting as server.
2 Copyright (C) 1986, 1987, 1994, 1999, 2000, 2001, 2002, 2003, 2004,
3 2005, 2006, 2007, 2008 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, or (at your option)
10 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; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA. */
23 #define NO_SHORTNAMES
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
29 #ifdef WINDOWSNT
31 /* config.h defines these, which disables sockets altogether! */
32 # undef _WINSOCKAPI_
33 # undef _WINSOCK_H
35 # include <malloc.h>
36 # include <stdlib.h>
37 # include <windows.h>
38 # include <commctrl.h>
40 # define NO_SOCKETS_IN_FILE_SYSTEM
42 # define HSOCKET SOCKET
43 # define CLOSE_SOCKET closesocket
44 # define INITIALIZE() (initialize_sockets ())
46 #else /* !WINDOWSNT */
48 # include <sys/types.h>
50 # ifdef HAVE_INET_SOCKETS
51 # include <netinet/in.h>
52 # endif
54 # define INVALID_SOCKET -1
55 # define HSOCKET int
56 # define CLOSE_SOCKET close
57 # define INITIALIZE()
59 #endif /* !WINDOWSNT */
61 #undef signal
63 #include <stdarg.h>
64 #include <ctype.h>
65 #include <stdio.h>
66 #include "getopt.h"
67 #ifdef HAVE_UNISTD_H
68 #include <unistd.h>
69 #endif
71 #ifdef VMS
72 # include "vms-pwd.h"
73 #else /* not VMS */
74 #ifdef WINDOWSNT
75 # include <io.h>
76 #else /* not WINDOWSNT */
77 # include <pwd.h>
78 #endif /* not WINDOWSNT */
79 #endif /* not VMS */
80 #include <sys/stat.h>
82 #include <signal.h>
83 #include <errno.h>
86 char *getenv (), *getwd ();
87 char *(getcwd) ();
89 #ifdef WINDOWSNT
90 char *w32_getenv ();
91 #define egetenv(VAR) w32_getenv(VAR)
92 #else
93 #define egetenv(VAR) getenv(VAR)
94 #endif
96 #ifndef VERSION
97 #define VERSION "unspecified"
98 #endif
101 #ifndef EXIT_SUCCESS
102 #define EXIT_SUCCESS 0
103 #endif
105 #ifndef EXIT_FAILURE
106 #define EXIT_FAILURE 1
107 #endif
109 #ifndef FALSE
110 #define FALSE 0
111 #endif
113 #ifndef TRUE
114 #define TRUE 1
115 #endif
117 #ifndef NO_RETURN
118 #define NO_RETURN
119 #endif
121 /* Name used to invoke this program. */
122 char *progname;
124 /* The second argument to main. */
125 char **main_argv;
127 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
128 int nowait = 0;
130 /* Nonzero means args are expressions to be evaluated. --eval. */
131 int eval = 0;
133 /* Nonzero means don't open a new frame. Inverse of --create-frame. */
134 int current_frame = 1;
136 /* Nonzero means open a new graphical frame. */
137 int window_system = 0;
139 /* The display on which Emacs should work. --display. */
140 char *display = NULL;
142 /* Nonzero means open a new Emacs frame on the current terminal. */
143 int tty = 0;
145 /* If non-NULL, the name of an editor to fallback to if the server
146 is not running. --alternate-editor. */
147 const char *alternate_editor = NULL;
149 /* If non-NULL, the filename of the UNIX socket. */
150 char *socket_name = NULL;
152 /* If non-NULL, the filename of the authentication file. */
153 char *server_file = NULL;
155 /* PID of the Emacs server process. */
156 int emacs_pid = 0;
158 void print_help_and_exit () NO_RETURN;
160 struct option longopts[] =
162 { "no-wait", no_argument, NULL, 'n' },
163 { "eval", no_argument, NULL, 'e' },
164 { "help", no_argument, NULL, 'H' },
165 { "version", no_argument, NULL, 'V' },
166 { "tty", no_argument, NULL, 't' },
167 { "create-frame", no_argument, NULL, 'c' },
168 { "alternate-editor", required_argument, NULL, 'a' },
169 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
170 { "socket-name", required_argument, NULL, 's' },
171 #endif
172 { "server-file", required_argument, NULL, 'f' },
173 #ifndef WINDOWSNT
174 { "display", required_argument, NULL, 'd' },
175 #endif
176 { 0, 0, 0, 0 }
180 /* Like malloc but get fatal error if memory is exhausted. */
182 long *
183 xmalloc (size)
184 unsigned int size;
186 long *result = (long *) malloc (size);
187 if (result == NULL)
189 perror ("malloc");
190 exit (EXIT_FAILURE);
192 return result;
195 /* Like strdup but get a fatal error if memory is exhausted. */
197 char *
198 xstrdup (const char *s)
200 char *result = strdup (s);
201 if (result == NULL)
203 perror ("strdup");
204 exit (EXIT_FAILURE);
206 return result;
209 /* From sysdep.c */
210 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
212 /* From lisp.h */
213 #ifndef DIRECTORY_SEP
214 #define DIRECTORY_SEP '/'
215 #endif
216 #ifndef IS_DIRECTORY_SEP
217 #define IS_DIRECTORY_SEP(_c_) ((_c_) == DIRECTORY_SEP)
218 #endif
219 #ifndef IS_DEVICE_SEP
220 #ifndef DEVICE_SEP
221 #define IS_DEVICE_SEP(_c_) 0
222 #else
223 #define IS_DEVICE_SEP(_c_) ((_c_) == DEVICE_SEP)
224 #endif
225 #endif
226 #ifndef IS_ANY_SEP
227 #define IS_ANY_SEP(_c_) (IS_DIRECTORY_SEP (_c_))
228 #endif
231 /* Return the current working directory. Returns NULL on errors.
232 Any other returned value must be freed with free. This is used
233 only when get_current_dir_name is not defined on the system. */
234 char*
235 get_current_dir_name ()
237 char *buf;
238 char *pwd;
239 struct stat dotstat, pwdstat;
240 /* If PWD is accurate, use it instead of calling getwd. PWD is
241 sometimes a nicer name, and using it may avoid a fatal error if a
242 parent directory is searchable but not readable. */
243 if ((pwd = egetenv ("PWD")) != 0
244 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
245 && stat (pwd, &pwdstat) == 0
246 && stat (".", &dotstat) == 0
247 && dotstat.st_ino == pwdstat.st_ino
248 && dotstat.st_dev == pwdstat.st_dev
249 #ifdef MAXPATHLEN
250 && strlen (pwd) < MAXPATHLEN
251 #endif
254 buf = (char *) xmalloc (strlen (pwd) + 1);
255 if (!buf)
256 return NULL;
257 strcpy (buf, pwd);
259 #ifdef HAVE_GETCWD
260 else
262 size_t buf_size = 1024;
263 buf = (char *) xmalloc (buf_size);
264 if (!buf)
265 return NULL;
266 for (;;)
268 if (getcwd (buf, buf_size) == buf)
269 break;
270 if (errno != ERANGE)
272 int tmp_errno = errno;
273 free (buf);
274 errno = tmp_errno;
275 return NULL;
277 buf_size *= 2;
278 buf = (char *) realloc (buf, buf_size);
279 if (!buf)
280 return NULL;
283 #else
284 else
286 /* We need MAXPATHLEN here. */
287 buf = (char *) xmalloc (MAXPATHLEN + 1);
288 if (!buf)
289 return NULL;
290 if (getwd (buf) == NULL)
292 int tmp_errno = errno;
293 free (buf);
294 errno = tmp_errno;
295 return NULL;
298 #endif
299 return buf;
301 #endif
303 #ifdef WINDOWSNT
305 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
307 /* Retrieve an environment variable from the Emacs subkeys of the registry.
308 Return NULL if the variable was not found, or it was empty.
309 This code is based on w32_get_resource (w32.c). */
310 char *
311 w32_get_resource (predefined, key, type)
312 HKEY predefined;
313 char *key;
314 LPDWORD type;
316 HKEY hrootkey = NULL;
317 char *result = NULL;
318 DWORD cbData;
320 if (RegOpenKeyEx (predefined, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
322 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS)
324 result = (char *) xmalloc (cbData);
326 if ((RegQueryValueEx (hrootkey, key, NULL, type, result, &cbData) != ERROR_SUCCESS) ||
327 (*result == 0))
329 free (result);
330 result = NULL;
334 RegCloseKey (hrootkey);
337 return result;
341 getenv wrapper for Windows
343 This is needed to duplicate Emacs's behavior, which is to look for enviroment
344 variables in the registry if they don't appear in the environment.
346 char *
347 w32_getenv (envvar)
348 char *envvar;
350 char *value;
351 DWORD dwType;
353 if (value = getenv (envvar))
354 /* Found in the environment. */
355 return value;
357 if (! (value = w32_get_resource (HKEY_CURRENT_USER, envvar, &dwType)) &&
358 ! (value = w32_get_resource (HKEY_LOCAL_MACHINE, envvar, &dwType)))
359 /* Not found in the registry. */
360 return NULL;
362 if (dwType == REG_SZ)
363 /* Registry; no need to expand. */
364 return value;
366 if (dwType == REG_EXPAND_SZ)
368 DWORD size;
370 if (size = ExpandEnvironmentStrings (value, NULL, 0))
372 char *buffer = (char *) xmalloc (size);
373 if (ExpandEnvironmentStrings (value, buffer, size))
375 /* Found and expanded. */
376 free (value);
377 return buffer;
380 /* Error expanding. */
381 free (buffer);
385 /* Not the right type, or not correctly expanded. */
386 free (value);
387 return NULL;
391 w32_window_app ()
393 static int window_app = -1;
394 char szTitle[MAX_PATH];
396 if (window_app < 0)
398 /* Checking for STDOUT does not work; it's a valid handle also in
399 nonconsole apps. Testing for the console title seems to work. */
400 window_app = (GetConsoleTitleA (szTitle, MAX_PATH) == 0);
401 if (window_app)
402 InitCommonControls();
405 return window_app;
409 execvp wrapper for Windows. Quotes arguments with embedded spaces.
411 This is necessary due to the broken implementation of exec* routines in
412 the Microsoft libraries: they concatenate the arguments together without
413 quoting special characters, and pass the result to CreateProcess, with
414 predictably bad results. By contrast, Posix execvp passes the arguments
415 directly into the argv array of the child process.
418 w32_execvp (path, argv)
419 char *path;
420 char **argv;
422 int i;
424 /* Required to allow a .BAT script as alternate editor. */
425 argv[0] = (char *) alternate_editor;
427 for (i = 0; argv[i]; i++)
428 if (strchr (argv[i], ' '))
430 char *quoted = alloca (strlen (argv[i]) + 3);
431 sprintf (quoted, "\"%s\"", argv[i]);
432 argv[i] = quoted;
435 return execvp (path, argv);
438 #undef execvp
439 #define execvp w32_execvp
441 #endif /* WINDOWSNT */
443 /* Display a normal or error message.
444 On Windows, use a message box if compiled as a Windows app. */
445 void
446 message (int is_error, char *message, ...)
448 char msg [2048];
449 va_list args;
451 va_start (args, message);
452 vsprintf (msg, message, args);
453 va_end (args);
455 #ifdef WINDOWSNT
456 if (w32_window_app ())
458 if (is_error)
459 MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
460 else
461 MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
463 else
464 #endif
466 FILE *f = is_error ? stderr : stdout;
468 fputs (msg, f);
469 fflush (f);
473 /* Decode the options from argv and argc.
474 The global variable `optind' will say how many arguments we used up. */
476 void
477 decode_options (argc, argv)
478 int argc;
479 char **argv;
481 alternate_editor = egetenv ("ALTERNATE_EDITOR");
483 while (1)
485 int opt = getopt_long (argc, argv,
486 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
487 "VHnea:s:f:d:tc",
488 #else
489 "VHnea:f:d:tc",
490 #endif
491 longopts, 0);
493 if (opt == EOF)
494 break;
496 switch (opt)
498 case 0:
499 /* If getopt returns 0, then it has already processed a
500 long-named option. We should do nothing. */
501 break;
503 case 'a':
504 alternate_editor = optarg;
505 break;
507 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
508 case 's':
509 socket_name = optarg;
510 break;
511 #endif
513 case 'f':
514 server_file = optarg;
515 break;
517 /* We used to disallow this argument in w32, but it seems better
518 to allow it, for the occasional case where the user is
519 connecting with a w32 client to a server compiled with X11
520 support. */
521 #if 1 /* !defined WINDOWS */
522 case 'd':
523 display = optarg;
524 break;
525 #endif
527 case 'n':
528 nowait = 1;
529 break;
531 case 'e':
532 eval = 1;
533 break;
535 case 'V':
536 message (FALSE, "emacsclient %s\n", VERSION);
537 exit (EXIT_SUCCESS);
538 break;
540 case 't':
541 tty = 1;
542 current_frame = 0;
543 break;
545 case 'c':
546 current_frame = 0;
547 break;
549 case 'H':
550 print_help_and_exit ();
551 break;
553 default:
554 message (TRUE, "Try `%s --help' for more information\n", progname);
555 exit (EXIT_FAILURE);
556 break;
560 /* We used to set `display' to $DISPLAY by default, but this changed the
561 default behavior and is sometimes inconvenient. So instead of forcing
562 users to say "--display ''" when they want to use Emacs's existing tty
563 or display connection, we force them to use "--display $DISPLAY" if
564 they want Emacs to connect to their current display.
565 -c still implicitly passes --display $DISPLAY unless -t was specified
566 so as to try and mimick the behavior of `emacs' which either uses
567 the current tty or the current $DISPLAY. */
568 if (!current_frame && !tty && !display)
569 display = egetenv ("DISPLAY");
571 if (display && strlen (display) == 0)
572 display = NULL;
574 if (!tty && display)
575 window_system = 1;
576 #if !defined (WINDOWSNT) && !defined (HAVE_CARBON)
577 else if (!current_frame)
578 tty = 1;
579 #endif
581 /* --no-wait implies --current-frame on ttys when there are file
582 arguments or expressions given. */
583 if (nowait && tty && argc - optind > 0)
584 current_frame = 1;
586 if (current_frame)
588 tty = 0;
589 window_system = 0;
592 if (tty)
593 window_system = 0;
597 void
598 print_help_and_exit ()
600 /* Spaces and tabs are significant in this message; they're chosen so the
601 message aligns properly both in a tty and in a Windows message box.
602 Please try to preserve them; otherwise the output is very hard to read
603 when using emacsclientw. */
604 message (FALSE,
605 "Usage: %s [OPTIONS] FILE...\n\
606 Tell the Emacs server to visit the specified files.\n\
607 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
609 The following OPTIONS are accepted:\n\
610 -V, --version Just print version info and return\n\
611 -H, --help Print this usage information message\n\
612 -t, --tty Open a new Emacs frame on the current terminal\n\
613 -c, --create-frame Create a new frame instead of trying to\n\
614 use the current Emacs frame\n\
615 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
616 -n, --no-wait Don't wait for the server to return\n"
617 #ifndef WINDOWSNT
618 "-d, --display=DISPLAY Visit the file in the given display\n"
619 #endif
620 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
621 "-s, --socket-name=FILENAME\n\
622 Set filename of the UNIX socket for communication\n"
623 #endif
624 "-f, --server-file=FILENAME\n\
625 Set filename of the TCP authentication file\n\
626 -a, --alternate-editor=EDITOR\n\
627 Editor to fallback to if the server is not running\n\
629 Report bugs to bug-gnu-emacs@gnu.org.\n", progname);
630 exit (EXIT_SUCCESS);
634 Try to run a different command, or --if no alternate editor is
635 defined-- exit with an errorcode.
636 Uses argv, but gets it from the global variable main_argv.
638 void
639 fail (void)
641 if (alternate_editor)
643 int i = optind - 1;
645 execvp (alternate_editor, main_argv + i);
646 message (TRUE, "%s: error executing alternate editor \"%s\"\n",
647 progname, alternate_editor);
649 exit (EXIT_FAILURE);
653 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
656 main (argc, argv)
657 int argc;
658 char **argv;
660 main_argv = argv;
661 progname = argv[0];
662 message (TRUE, "%s: Sorry, the Emacs server is supported only\n"
663 "on systems with Berkeley sockets.\n",
664 argv[0]);
665 fail ();
668 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
670 #ifdef WINDOWSNT
671 # include <winsock2.h>
672 #else
673 # include <sys/types.h>
674 # include <sys/socket.h>
675 # include <sys/un.h>
676 #endif
678 #define AUTH_KEY_LENGTH 64
679 #define SEND_BUFFER_SIZE 4096
681 extern char *strerror ();
682 extern int errno;
684 /* Buffer to accumulate data to send in TCP connections. */
685 char send_buffer[SEND_BUFFER_SIZE + 1];
686 int sblen = 0; /* Fill pointer for the send buffer. */
687 /* Socket used to communicate with the Emacs server process. */
688 HSOCKET emacs_socket = 0;
690 /* On Windows, the socket library was historically separate from the standard
691 C library, so errors are handled differently. */
692 void
693 sock_err_message (function_name)
694 char *function_name;
696 #ifdef WINDOWSNT
697 char* msg = NULL;
699 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
700 | FORMAT_MESSAGE_ALLOCATE_BUFFER
701 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
702 NULL, WSAGetLastError (), 0, (LPTSTR)&msg, 0, NULL);
704 message (TRUE, "%s: %s: %s\n", progname, function_name, msg);
706 LocalFree (msg);
707 #else
708 message (TRUE, "%s: %s: %s\n", progname, function_name, strerror (errno));
709 #endif
713 /* Let's send the data to Emacs when either
714 - the data ends in "\n", or
715 - the buffer is full (but this shouldn't happen)
716 Otherwise, we just accumulate it. */
717 void
718 send_to_emacs (s, data)
719 HSOCKET s;
720 char *data;
722 while (data)
724 int dlen = strlen (data);
725 if (dlen + sblen >= SEND_BUFFER_SIZE)
727 int part = SEND_BUFFER_SIZE - sblen;
728 strncpy (&send_buffer[sblen], data, part);
729 data += part;
730 sblen = SEND_BUFFER_SIZE;
732 else if (dlen)
734 strcpy (&send_buffer[sblen], data);
735 data = NULL;
736 sblen += dlen;
738 else
739 break;
741 if (sblen == SEND_BUFFER_SIZE
742 || (sblen > 0 && send_buffer[sblen-1] == '\n'))
744 int sent = send (s, send_buffer, sblen, 0);
745 if (sent != sblen)
746 strcpy (send_buffer, &send_buffer[sent]);
747 sblen -= sent;
753 /* In STR, insert a & before each &, each space, each newline, and
754 any initial -. Change spaces to underscores, too, so that the
755 return value never contains a space.
757 Does not change the string. Outputs the result to STREAM. */
758 void
759 quote_argument (s, str)
760 HSOCKET s;
761 char *str;
763 char *copy = (char *) xmalloc (strlen (str) * 2 + 1);
764 char *p, *q;
766 p = str;
767 q = copy;
768 while (*p)
770 if (*p == ' ')
772 *q++ = '&';
773 *q++ = '_';
774 p++;
776 else if (*p == '\n')
778 *q++ = '&';
779 *q++ = 'n';
780 p++;
782 else
784 if (*p == '&' || (*p == '-' && p == str))
785 *q++ = '&';
786 *q++ = *p++;
789 *q++ = 0;
791 send_to_emacs (s, copy);
793 free (copy);
797 /* The inverse of quote_argument. Removes quoting in string STR by
798 modifying the string in place. Returns STR. */
800 char *
801 unquote_argument (str)
802 char *str;
804 char *p, *q;
806 if (! str)
807 return str;
809 p = str;
810 q = str;
811 while (*p)
813 if (*p == '&')
815 p++;
816 if (*p == '&')
817 *p = '&';
818 else if (*p == '_')
819 *p = ' ';
820 else if (*p == 'n')
821 *p = '\n';
822 else if (*p == '-')
823 *p = '-';
825 *q++ = *p++;
827 *q = 0;
828 return str;
833 file_name_absolute_p (filename)
834 const unsigned char *filename;
836 /* Sanity check, it shouldn't happen. */
837 if (! filename) return FALSE;
839 /* /xxx is always an absolute path. */
840 if (filename[0] == '/') return TRUE;
842 /* Empty filenames (which shouldn't happen) are relative. */
843 if (filename[0] == '\0') return FALSE;
845 #ifdef WINDOWSNT
846 /* X:\xxx is always absolute. */
847 if (isalpha (filename[0])
848 && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
849 return TRUE;
851 /* Both \xxx and \\xxx\yyy are absolute. */
852 if (filename[0] == '\\') return TRUE;
855 FIXME: There's a corner case not dealt with, "x:y", where:
857 1) x is a valid drive designation (usually a letter in the A-Z range)
858 and y is a path, relative to the current directory on drive x. This
859 is absolute, *after* fixing the y part to include the current
860 directory in x.
862 2) x is a relative file name, and y is an NTFS stream name. This is a
863 correct relative path, but it is very unusual.
865 The trouble is that first case items are also valid examples of the
866 second case, i.e., "c:test" can be understood as drive:path or as
867 file:stream.
869 The "right" fix would involve checking whether
870 - the current drive/partition is NTFS,
871 - x is a valid (and accesible) drive designator,
872 - x:y already exists as a file:stream in the current directory,
873 - y already exists on the current directory of drive x,
874 - the auspices are favorable,
875 and then taking an "informed decision" based on the above.
877 Whatever the result, Emacs currently does a very bad job of dealing
878 with NTFS file:streams: it cannot visit them, and the only way to
879 create one is by setting `buffer-file-name' to point to it (either
880 manually or with emacsclient). So perhaps resorting to 1) and ignoring
881 2) for now is the right thing to do.
883 Anyway, something to decide After the Release.
885 #endif
887 return FALSE;
890 #ifdef WINDOWSNT
891 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
892 void
893 __cdecl close_winsock ()
895 WSACleanup ();
898 /* Initialize the WinSock2 library. */
899 void
900 initialize_sockets ()
902 WSADATA wsaData;
904 if (WSAStartup (MAKEWORD (2, 0), &wsaData))
906 message (TRUE, "%s: error initializing WinSock2\n", progname);
907 exit (EXIT_FAILURE);
910 atexit (close_winsock);
912 #endif /* WINDOWSNT */
916 * Read the information needed to set up a TCP comm channel with
917 * the Emacs server: host, port, pid and authentication string.
920 get_server_config (server, authentication)
921 struct sockaddr_in *server;
922 char *authentication;
924 char dotted[32];
925 char *port;
926 char *pid;
927 FILE *config = NULL;
929 if (file_name_absolute_p (server_file))
930 config = fopen (server_file, "rb");
931 else
933 char *home = egetenv ("HOME");
935 if (home)
937 char *path = alloca (32 + strlen (home) + strlen (server_file));
938 sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
939 config = fopen (path, "rb");
941 #ifdef WINDOWSNT
942 if (!config && (home = egetenv ("APPDATA")))
944 char *path = alloca (32 + strlen (home) + strlen (server_file));
945 sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
946 config = fopen (path, "rb");
948 #endif
951 if (! config)
952 return FALSE;
954 if (fgets (dotted, sizeof dotted, config)
955 && (port = strchr (dotted, ':'))
956 && (pid = strchr (port, ' ')))
958 *port++ = '\0';
959 *pid++ = '\0';
961 else
963 message (TRUE, "%s: invalid configuration info\n", progname);
964 exit (EXIT_FAILURE);
967 server->sin_family = AF_INET;
968 server->sin_addr.s_addr = inet_addr (dotted);
969 server->sin_port = htons (atoi (port));
971 if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
973 message (TRUE, "%s: cannot read authentication info\n", progname);
974 exit (EXIT_FAILURE);
977 fclose (config);
979 emacs_pid = atoi (pid);
981 return TRUE;
984 HSOCKET
985 set_tcp_socket ()
987 HSOCKET s;
988 struct sockaddr_in server;
989 struct linger l_arg = {1, 1};
990 char auth_string[AUTH_KEY_LENGTH + 1];
992 if (! get_server_config (&server, auth_string))
993 return INVALID_SOCKET;
995 if (server.sin_addr.s_addr != inet_addr ("127.0.0.1"))
996 message (FALSE, "%s: connected to remote socket at %s\n",
997 progname, inet_ntoa (server.sin_addr));
1000 * Open up an AF_INET socket
1002 if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
1004 sock_err_message ("socket");
1005 return INVALID_SOCKET;
1009 * Set up the socket
1011 if (connect (s, (struct sockaddr *) &server, sizeof server) < 0)
1013 sock_err_message ("connect");
1014 return INVALID_SOCKET;
1017 setsockopt (s, SOL_SOCKET, SO_LINGER, (char *) &l_arg, sizeof l_arg);
1020 * Send the authentication
1022 auth_string[AUTH_KEY_LENGTH] = '\0';
1024 send_to_emacs (s, "-auth ");
1025 send_to_emacs (s, auth_string);
1026 send_to_emacs (s, " ");
1028 return s;
1032 /* Returns 1 if PREFIX is a prefix of STRING. */
1033 static int
1034 strprefix (char *prefix, char *string)
1036 return !strncmp (prefix, string, strlen (prefix));
1040 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1042 /* Three possibilities:
1043 2 - can't be `stat'ed (sets errno)
1044 1 - isn't owned by us
1045 0 - success: none of the above */
1047 static int
1048 socket_status (socket_name)
1049 char *socket_name;
1051 struct stat statbfr;
1053 if (stat (socket_name, &statbfr) == -1)
1054 return 2;
1056 if (statbfr.st_uid != geteuid ())
1057 return 1;
1059 return 0;
1063 /* A signal handler that passes the signal to the Emacs process.
1064 Useful for SIGWINCH. */
1066 SIGTYPE
1067 pass_signal_to_emacs (int signalnum)
1069 int old_errno = errno;
1071 if (emacs_pid)
1072 kill (emacs_pid, signalnum);
1074 signal (signalnum, pass_signal_to_emacs);
1075 errno = old_errno;
1078 /* Signal handler for SIGCONT; notify the Emacs process that it can
1079 now resume our tty frame. */
1081 SIGTYPE
1082 handle_sigcont (int signalnum)
1084 int old_errno = errno;
1086 if (tcgetpgrp (1) == getpgrp ())
1088 /* We are in the foreground. */
1089 send_to_emacs (emacs_socket, "-resume \n");
1091 else
1093 /* We are in the background; cancel the continue. */
1094 kill (getpid (), SIGSTOP);
1097 signal (signalnum, handle_sigcont);
1098 errno = old_errno;
1101 /* Signal handler for SIGTSTP; notify the Emacs process that we are
1102 going to sleep. Normally the suspend is initiated by Emacs via
1103 server-handle-suspend-tty, but if the server gets out of sync with
1104 reality, we may get a SIGTSTP on C-z. Handling this signal and
1105 notifying Emacs about it should get things under control again. */
1107 SIGTYPE
1108 handle_sigtstp (int signalnum)
1110 int old_errno = errno;
1111 sigset_t set;
1113 if (emacs_socket)
1114 send_to_emacs (emacs_socket, "-suspend \n");
1116 /* Unblock this signal and call the default handler by temporarily
1117 changing the handler and resignalling. */
1118 sigprocmask (SIG_BLOCK, NULL, &set);
1119 sigdelset (&set, signalnum);
1120 signal (signalnum, SIG_DFL);
1121 kill (getpid (), signalnum);
1122 sigprocmask (SIG_SETMASK, &set, NULL); /* Let's the above signal through. */
1123 signal (signalnum, handle_sigtstp);
1125 errno = old_errno;
1127 /* Set up signal handlers before opening a frame on the current tty. */
1129 void
1130 init_signals (void)
1132 /* Set up signal handlers. */
1133 signal (SIGWINCH, pass_signal_to_emacs);
1135 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
1136 deciding which terminal the signal came from. C-g is now a
1137 normal input event on secondary terminals. */
1138 #if 0
1139 signal (SIGINT, pass_signal_to_emacs);
1140 signal (SIGQUIT, pass_signal_to_emacs);
1141 #endif
1143 signal (SIGCONT, handle_sigcont);
1144 signal (SIGTSTP, handle_sigtstp);
1145 signal (SIGTTOU, handle_sigtstp);
1149 HSOCKET
1150 set_local_socket ()
1152 HSOCKET s;
1153 struct sockaddr_un server;
1156 * Open up an AF_UNIX socket in this person's home directory
1159 if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
1161 message (TRUE, "%s: socket: %s\n", progname, strerror (errno));
1162 return INVALID_SOCKET;
1165 server.sun_family = AF_UNIX;
1168 int sock_status = 0;
1169 int default_sock = !socket_name;
1170 int saved_errno = 0;
1171 char *server_name = "server";
1173 if (socket_name && !index (socket_name, '/') && !index (socket_name, '\\'))
1174 { /* socket_name is a file name component. */
1175 server_name = socket_name;
1176 socket_name = NULL;
1177 default_sock = 1; /* Try both UIDs. */
1180 if (default_sock)
1182 socket_name = alloca (100 + strlen (server_name));
1183 sprintf (socket_name, "/tmp/emacs%d/%s",
1184 (int) geteuid (), server_name);
1187 if (strlen (socket_name) < sizeof (server.sun_path))
1188 strcpy (server.sun_path, socket_name);
1189 else
1191 message (TRUE, "%s: socket-name %s too long\n",
1192 progname, socket_name);
1193 fail ();
1196 /* See if the socket exists, and if it's owned by us. */
1197 sock_status = socket_status (server.sun_path);
1198 saved_errno = errno;
1199 if (sock_status && default_sock)
1201 /* Failing that, see if LOGNAME or USER exist and differ from
1202 our euid. If so, look for a socket based on the UID
1203 associated with the name. This is reminiscent of the logic
1204 that init_editfns uses to set the global Vuser_full_name. */
1206 char *user_name = (char *) egetenv ("LOGNAME");
1208 if (!user_name)
1209 user_name = (char *) egetenv ("USER");
1211 if (user_name)
1213 struct passwd *pw = getpwnam (user_name);
1215 if (pw && (pw->pw_uid != geteuid ()))
1217 /* We're running under su, apparently. */
1218 socket_name = alloca (100 + strlen (server_name));
1219 sprintf (socket_name, "/tmp/emacs%d/%s",
1220 (int) pw->pw_uid, server_name);
1222 if (strlen (socket_name) < sizeof (server.sun_path))
1223 strcpy (server.sun_path, socket_name);
1224 else
1226 message (TRUE, "%s: socket-name %s too long\n",
1227 progname, socket_name);
1228 exit (EXIT_FAILURE);
1231 sock_status = socket_status (server.sun_path);
1232 saved_errno = errno;
1234 else
1235 errno = saved_errno;
1239 switch (sock_status)
1241 case 1:
1242 /* There's a socket, but it isn't owned by us. This is OK if
1243 we are root. */
1244 if (0 != geteuid ())
1246 message (TRUE, "%s: Invalid socket owner\n", progname);
1247 return INVALID_SOCKET;
1249 break;
1251 case 2:
1252 /* `stat' failed */
1253 if (saved_errno == ENOENT)
1254 message (TRUE,
1255 "%s: can't find socket; have you started the server?\n\
1256 To start the server in Emacs, type \"M-x server-start\".\n",
1257 progname);
1258 else
1259 message (TRUE, "%s: can't stat %s: %s\n",
1260 progname, server.sun_path, strerror (saved_errno));
1261 return INVALID_SOCKET;
1265 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
1266 < 0)
1268 message (TRUE, "%s: connect: %s\n", progname, strerror (errno));
1269 return INVALID_SOCKET;
1272 return s;
1274 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1276 HSOCKET
1277 set_socket ()
1279 HSOCKET s;
1281 INITIALIZE ();
1283 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1284 /* Explicit --socket-name argument. */
1285 if (socket_name)
1287 s = set_local_socket ();
1288 if ((s != INVALID_SOCKET) || alternate_editor)
1289 return s;
1290 message (TRUE, "%s: error accessing socket \"%s\"\n",
1291 progname, socket_name);
1292 exit (EXIT_FAILURE);
1294 #endif
1296 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1297 if (!server_file)
1298 server_file = egetenv ("EMACS_SERVER_FILE");
1300 if (server_file)
1302 s = set_tcp_socket ();
1303 if ((s != INVALID_SOCKET) || alternate_editor)
1304 return s;
1306 message (TRUE, "%s: error accessing server file \"%s\"\n",
1307 progname, server_file);
1308 exit (EXIT_FAILURE);
1311 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1312 /* Implicit local socket. */
1313 s = set_local_socket ();
1314 if (s != INVALID_SOCKET)
1315 return s;
1316 #endif
1318 /* Implicit server file. */
1319 server_file = "server";
1320 s = set_tcp_socket ();
1321 if ((s != INVALID_SOCKET) || alternate_editor)
1322 return s;
1324 /* No implicit or explicit socket, and no alternate editor. */
1325 message (TRUE, "%s: No socket or alternate editor. Please use:\n\n"
1326 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1327 "\t--socket-name\n"
1328 #endif
1329 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1330 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1331 progname);
1332 exit (EXIT_FAILURE);
1335 #ifdef WINDOWSNT
1336 FARPROC set_fg; /* Pointer to AllowSetForegroundWindow. */
1337 FARPROC get_wc; /* Pointer to RealGetWindowClassA. */
1339 BOOL CALLBACK
1340 w32_find_emacs_process (hWnd, lParam)
1341 HWND hWnd;
1342 LPARAM lParam;
1344 DWORD pid;
1345 char class[6];
1347 /* Reject any window not of class "Emacs". */
1348 if (! get_wc (hWnd, class, sizeof (class))
1349 || strcmp (class, "Emacs"))
1350 return TRUE;
1352 /* We only need the process id, not the thread id. */
1353 (void) GetWindowThreadProcessId (hWnd, &pid);
1355 /* Not the one we're looking for. */
1356 if (pid != (DWORD) emacs_pid) return TRUE;
1358 /* OK, let's raise it. */
1359 set_fg (emacs_pid);
1361 /* Stop enumeration. */
1362 return FALSE;
1366 * Search for a window of class "Emacs" and owned by a process with
1367 * process id = emacs_pid. If found, allow it to grab the focus.
1369 void
1370 w32_give_focus ()
1372 HMODULE hUser32;
1374 /* It shouldn't happen when dealing with TCP sockets. */
1375 if (!emacs_pid) return;
1377 if (!(hUser32 = LoadLibrary ("user32.dll"))) return;
1379 /* Modern Windows restrict which processes can set the foreground window.
1380 emacsclient can allow Emacs to grab the focus by calling the function
1381 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1382 NT) lack this function, so we have to check its availability. */
1383 if ((set_fg = GetProcAddress (hUser32, "AllowSetForegroundWindow"))
1384 && (get_wc = GetProcAddress (hUser32, "RealGetWindowClassA")))
1385 EnumWindows (w32_find_emacs_process, (LPARAM) 0);
1387 FreeLibrary (hUser32);
1389 #endif
1392 main (argc, argv)
1393 int argc;
1394 char **argv;
1396 int i, rl, needlf = 0;
1397 char *cwd, *str;
1398 char string[BUFSIZ+1];
1400 main_argv = argv;
1401 progname = argv[0];
1403 /* Process options. */
1404 decode_options (argc, argv);
1406 if ((argc - optind < 1) && !eval && !tty && !window_system)
1408 message (TRUE, "%s: file name or argument required\n"
1409 "Try `%s --help' for more information\n",
1410 progname, progname);
1411 exit (EXIT_FAILURE);
1414 if ((emacs_socket = set_socket ()) == INVALID_SOCKET)
1415 fail ();
1418 cwd = get_current_dir_name ();
1419 if (cwd == 0)
1421 /* getwd puts message in STRING if it fails. */
1422 message (TRUE, "%s: %s\n", progname,
1423 "Cannot get current working directory");
1424 fail ();
1427 #ifdef WINDOWSNT
1428 w32_give_focus ();
1429 #endif
1431 /* Send over our environment. */
1432 if (!current_frame)
1434 extern char **environ;
1435 int i;
1436 for (i = 0; environ[i]; i++)
1438 char *name = xstrdup (environ[i]);
1439 char *value = strchr (name, '=');
1440 send_to_emacs (emacs_socket, "-env ");
1441 quote_argument (emacs_socket, environ[i]);
1442 send_to_emacs (emacs_socket, " ");
1446 /* Send over our current directory. */
1447 if (!current_frame)
1449 send_to_emacs (emacs_socket, "-dir ");
1450 quote_argument (emacs_socket, cwd);
1451 send_to_emacs (emacs_socket, "/");
1452 send_to_emacs (emacs_socket, " ");
1455 retry:
1456 if (nowait)
1457 send_to_emacs (emacs_socket, "-nowait ");
1459 if (current_frame)
1460 send_to_emacs (emacs_socket, "-current-frame ");
1462 if (display)
1464 send_to_emacs (emacs_socket, "-display ");
1465 quote_argument (emacs_socket, display);
1466 send_to_emacs (emacs_socket, " ");
1469 if (tty)
1471 char *type = egetenv ("TERM");
1472 char *tty_name = NULL;
1473 #ifndef WINDOWSNT
1474 tty_name = ttyname (fileno (stdin));
1475 #endif
1477 if (! tty_name)
1479 message (TRUE, "%s: could not get terminal name\n", progname);
1480 fail ();
1483 if (! type)
1485 message (TRUE, "%s: please set the TERM variable to your terminal type\n",
1486 progname);
1487 fail ();
1490 if (! strcmp (type, "eterm"))
1492 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1493 message (TRUE, "%s: opening a frame in an Emacs term buffer"
1494 " is not supported\n", progname);
1495 fail ();
1497 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1498 init_signals ();
1499 #endif
1501 send_to_emacs (emacs_socket, "-tty ");
1502 quote_argument (emacs_socket, tty_name);
1503 send_to_emacs (emacs_socket, " ");
1504 quote_argument (emacs_socket, type);
1505 send_to_emacs (emacs_socket, " ");
1508 if (window_system)
1509 send_to_emacs (emacs_socket, "-window-system ");
1511 if ((argc - optind > 0))
1513 for (i = optind; i < argc; i++)
1515 int relative = 0;
1517 if (eval)
1519 /* Don't prepend cwd or anything like that. */
1520 send_to_emacs (emacs_socket, "-eval ");
1521 quote_argument (emacs_socket, argv[i]);
1522 send_to_emacs (emacs_socket, " ");
1523 continue;
1526 if (*argv[i] == '+')
1528 char *p = argv[i] + 1;
1529 while (isdigit ((unsigned char) *p) || *p == ':') p++;
1530 if (*p == 0)
1532 send_to_emacs (emacs_socket, "-position ");
1533 quote_argument (emacs_socket, argv[i]);
1534 send_to_emacs (emacs_socket, " ");
1535 continue;
1537 else
1538 relative = 1;
1540 else if (! file_name_absolute_p (argv[i]))
1541 relative = 1;
1543 send_to_emacs (emacs_socket, "-file ");
1544 if (relative)
1546 quote_argument (emacs_socket, cwd);
1547 send_to_emacs (emacs_socket, "/");
1549 quote_argument (emacs_socket, argv[i]);
1550 send_to_emacs (emacs_socket, " ");
1553 else
1555 if (!tty && !window_system)
1557 while ((str = fgets (string, BUFSIZ, stdin)))
1559 if (eval)
1560 send_to_emacs (emacs_socket, "-eval ");
1561 else
1562 send_to_emacs (emacs_socket, "-file ");
1563 quote_argument (emacs_socket, str);
1565 send_to_emacs (emacs_socket, " ");
1569 send_to_emacs (emacs_socket, "\n");
1571 /* Wait for an answer. */
1572 if (!eval && !tty && !nowait)
1574 printf ("Waiting for Emacs...");
1575 needlf = 2;
1577 fflush (stdout);
1578 fsync (1);
1580 /* Now, wait for an answer and print any messages. */
1581 while ((rl = recv (emacs_socket, string, BUFSIZ, 0)) > 0)
1583 char *p;
1584 string[rl] = '\0';
1586 p = string + strlen (string) - 1;
1587 while (p > string && *p == '\n')
1588 *p-- = 0;
1590 if (strprefix ("-emacs-pid ", string))
1592 /* -emacs-pid PID: The process id of the Emacs process. */
1593 emacs_pid = strtol (string + strlen ("-emacs-pid"), NULL, 10);
1595 else if (strprefix ("-window-system-unsupported ", string))
1597 /* -window-system-unsupported: Emacs was compiled without X
1598 support. Try again on the terminal. */
1599 window_system = 0;
1600 nowait = 0;
1601 tty = 1;
1602 goto retry;
1604 else if (strprefix ("-print ", string))
1606 /* -print STRING: Print STRING on the terminal. */
1607 str = unquote_argument (string + strlen ("-print "));
1608 if (needlf)
1609 printf ("\n");
1610 printf ("%s", str);
1611 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1613 else if (strprefix ("-error ", string))
1615 /* -error DESCRIPTION: Signal an error on the terminal. */
1616 str = unquote_argument (string + strlen ("-error "));
1617 if (needlf)
1618 printf ("\n");
1619 fprintf (stderr, "*ERROR*: %s", str);
1620 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1622 #ifdef SIGSTOP
1623 else if (strprefix ("-suspend ", string))
1625 /* -suspend: Suspend this terminal, i.e., stop the process. */
1626 if (needlf)
1627 printf ("\n");
1628 needlf = 0;
1629 kill (0, SIGSTOP);
1631 #endif
1632 else
1634 /* Unknown command. */
1635 if (needlf)
1636 printf ("\n");
1637 printf ("*ERROR*: Unknown message: %s", string);
1638 needlf = string[0] == '\0' ? needlf : string[strlen (string) - 1] != '\n';
1642 if (needlf)
1643 printf ("\n");
1644 fflush (stdout);
1645 fsync (1);
1647 CLOSE_SOCKET (emacs_socket);
1648 return EXIT_SUCCESS;
1651 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
1654 #ifndef HAVE_STRERROR
1655 char *
1656 strerror (errnum)
1657 int errnum;
1659 extern char *sys_errlist[];
1660 extern int sys_nerr;
1662 if (errnum >= 0 && errnum < sys_nerr)
1663 return sys_errlist[errnum];
1664 return (char *) "Unknown error";
1667 #endif /* ! HAVE_STRERROR */
1669 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
1670 (do not change this comment) */
1672 /* emacsclient.c ends here */