Merge from emacs--rel--22
[emacs.git] / lib-src / emacsclient.c
blobbfa4f9c01d7a23754574659fa5087ca077e778b1
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 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 #ifndef VERSION
90 #define VERSION "unspecified"
91 #endif
94 #ifndef EXIT_SUCCESS
95 #define EXIT_SUCCESS 0
96 #endif
98 #ifndef EXIT_FAILURE
99 #define EXIT_FAILURE 1
100 #endif
102 #ifndef FALSE
103 #define FALSE 0
104 #endif
106 #ifndef TRUE
107 #define TRUE 1
108 #endif
110 #ifndef NO_RETURN
111 #define NO_RETURN
112 #endif
114 /* Name used to invoke this program. */
115 char *progname;
117 /* The second argument to main. */
118 char **main_argv;
120 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
121 int nowait = 0;
123 /* Nonzero means args are expressions to be evaluated. --eval. */
124 int eval = 0;
126 /* Nonzero means don't open a new frame. Inverse of --create-frame. */
127 int current_frame = 1;
129 /* Nonzero means open a new graphical frame. */
130 int window_system = 0;
132 /* The display on which Emacs should work. --display. */
133 char *display = NULL;
135 /* Nonzero means open a new Emacs frame on the current terminal. */
136 int tty = 0;
138 /* If non-NULL, the name of an editor to fallback to if the server
139 is not running. --alternate-editor. */
140 const char *alternate_editor = NULL;
142 /* If non-NULL, the filename of the UNIX socket. */
143 char *socket_name = NULL;
145 /* If non-NULL, the filename of the authentication file. */
146 char *server_file = NULL;
148 /* PID of the Emacs server process. */
149 int emacs_pid = 0;
151 void print_help_and_exit () NO_RETURN;
153 struct option longopts[] =
155 { "no-wait", no_argument, NULL, 'n' },
156 { "eval", no_argument, NULL, 'e' },
157 { "help", no_argument, NULL, 'H' },
158 { "version", no_argument, NULL, 'V' },
159 { "tty", no_argument, NULL, 't' },
160 { "create-frame", no_argument, NULL, 'c' },
161 { "alternate-editor", required_argument, NULL, 'a' },
162 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
163 { "socket-name", required_argument, NULL, 's' },
164 #endif
165 { "server-file", required_argument, NULL, 'f' },
166 { "display", required_argument, NULL, 'd' },
167 { 0, 0, 0, 0 }
171 /* Like malloc but get fatal error if memory is exhausted. */
173 long *
174 xmalloc (size)
175 unsigned int size;
177 long *result = (long *) malloc (size);
178 if (result == NULL)
180 perror ("malloc");
181 exit (EXIT_FAILURE);
183 return result;
186 /* Like strdup but get a fatal error if memory is exhausted. */
188 char *
189 xstrdup (const char *s)
191 char *result = strdup (s);
192 if (result == NULL)
194 perror ("strdup");
195 exit (EXIT_FAILURE);
197 return result;
200 /* From sysdep.c */
201 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
203 /* From lisp.h */
204 #ifndef DIRECTORY_SEP
205 #define DIRECTORY_SEP '/'
206 #endif
207 #ifndef IS_DIRECTORY_SEP
208 #define IS_DIRECTORY_SEP(_c_) ((_c_) == DIRECTORY_SEP)
209 #endif
210 #ifndef IS_DEVICE_SEP
211 #ifndef DEVICE_SEP
212 #define IS_DEVICE_SEP(_c_) 0
213 #else
214 #define IS_DEVICE_SEP(_c_) ((_c_) == DEVICE_SEP)
215 #endif
216 #endif
217 #ifndef IS_ANY_SEP
218 #define IS_ANY_SEP(_c_) (IS_DIRECTORY_SEP (_c_))
219 #endif
222 /* Return the current working directory. Returns NULL on errors.
223 Any other returned value must be freed with free. This is used
224 only when get_current_dir_name is not defined on the system. */
225 char*
226 get_current_dir_name ()
228 char *buf;
229 char *pwd;
230 struct stat dotstat, pwdstat;
231 /* If PWD is accurate, use it instead of calling getwd. PWD is
232 sometimes a nicer name, and using it may avoid a fatal error if a
233 parent directory is searchable but not readable. */
234 if ((pwd = getenv ("PWD")) != 0
235 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
236 && stat (pwd, &pwdstat) == 0
237 && stat (".", &dotstat) == 0
238 && dotstat.st_ino == pwdstat.st_ino
239 && dotstat.st_dev == pwdstat.st_dev
240 #ifdef MAXPATHLEN
241 && strlen (pwd) < MAXPATHLEN
242 #endif
245 buf = (char *) xmalloc (strlen (pwd) + 1);
246 if (!buf)
247 return NULL;
248 strcpy (buf, pwd);
250 #ifdef HAVE_GETCWD
251 else
253 size_t buf_size = 1024;
254 buf = (char *) xmalloc (buf_size);
255 if (!buf)
256 return NULL;
257 for (;;)
259 if (getcwd (buf, buf_size) == buf)
260 break;
261 if (errno != ERANGE)
263 int tmp_errno = errno;
264 free (buf);
265 errno = tmp_errno;
266 return NULL;
268 buf_size *= 2;
269 buf = (char *) realloc (buf, buf_size);
270 if (!buf)
271 return NULL;
274 #else
275 else
277 /* We need MAXPATHLEN here. */
278 buf = (char *) xmalloc (MAXPATHLEN + 1);
279 if (!buf)
280 return NULL;
281 if (getwd (buf) == NULL)
283 int tmp_errno = errno;
284 free (buf);
285 errno = tmp_errno;
286 return NULL;
289 #endif
290 return buf;
292 #endif
294 /* Message functions. */
296 #ifdef WINDOWSNT
298 w32_window_app ()
300 static int window_app = -1;
301 char szTitle[MAX_PATH];
303 if (window_app < 0)
305 /* Checking for STDOUT does not work; it's a valid handle also in
306 nonconsole apps. Testing for the console title seems to work. */
307 window_app = (GetConsoleTitleA (szTitle, MAX_PATH) == 0);
308 if (window_app)
309 InitCommonControls();
312 return window_app;
316 execvp wrapper for Windows. Quotes arguments with embedded spaces.
318 This is necessary due to the broken implementation of exec* routines in
319 the Microsoft libraries: they concatenate the arguments together without
320 quoting special characters, and pass the result to CreateProcess, with
321 predictably bad results. By contrast, Posix execvp passes the arguments
322 directly into the argv array of the child process.
325 w32_execvp (path, argv)
326 char *path;
327 char **argv;
329 int i;
331 /* Required to allow a .BAT script as alternate editor. */
332 argv[0] = (char *) alternate_editor;
334 for (i = 0; argv[i]; i++)
335 if (strchr (argv[i], ' '))
337 char *quoted = alloca (strlen (argv[i]) + 3);
338 sprintf (quoted, "\"%s\"", argv[i]);
339 argv[i] = quoted;
342 return execvp (path, argv);
345 #undef execvp
346 #define execvp w32_execvp
348 #endif /* WINDOWSNT */
350 void
351 message (int is_error, char *message, ...)
353 char msg [2048];
354 va_list args;
356 va_start (args, message);
357 vsprintf (msg, message, args);
358 va_end (args);
360 #ifdef WINDOWSNT
361 if (w32_window_app ())
363 if (is_error)
364 MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
365 else
366 MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
368 else
369 #endif
371 FILE *f = is_error ? stderr : stdout;
373 fputs (msg, f);
374 fflush (f);
378 /* Decode the options from argv and argc.
379 The global variable `optind' will say how many arguments we used up. */
381 void
382 decode_options (argc, argv)
383 int argc;
384 char **argv;
386 alternate_editor = getenv ("ALTERNATE_EDITOR");
387 display = getenv ("DISPLAY");
388 if (display && strlen (display) == 0)
389 display = NULL;
391 while (1)
393 int opt = getopt_long (argc, argv,
394 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
395 "VHnea:s:f:d:tc",
396 #else
397 "VHnea:f:d:tc",
398 #endif
399 longopts, 0);
401 if (opt == EOF)
402 break;
404 switch (opt)
406 case 0:
407 /* If getopt returns 0, then it has already processed a
408 long-named option. We should do nothing. */
409 break;
411 case 'a':
412 alternate_editor = optarg;
413 break;
415 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
416 case 's':
417 socket_name = optarg;
418 break;
419 #endif
421 case 'f':
422 server_file = optarg;
423 break;
425 case 'd':
426 display = optarg;
427 break;
429 case 'n':
430 nowait = 1;
431 break;
433 case 'e':
434 eval = 1;
435 break;
437 case 'V':
438 message (FALSE, "emacsclient %s\n", VERSION);
439 exit (EXIT_SUCCESS);
440 break;
442 case 't':
443 tty = 1;
444 current_frame = 0;
445 break;
447 case 'c':
448 current_frame = 0;
449 break;
451 case 'H':
452 print_help_and_exit ();
453 break;
455 default:
456 message (TRUE, "Try `%s --help' for more information\n", progname);
457 exit (EXIT_FAILURE);
458 break;
462 if (!tty && display)
463 window_system = 1;
464 #if !defined (WINDOWSNT) && !defined (HAVE_CARBON)
465 else
466 tty = 1;
467 #endif
469 /* --no-wait implies --current-frame on ttys when there are file
470 arguments or expressions given. */
471 if (nowait && tty && argc - optind > 0)
472 current_frame = 1;
474 if (current_frame)
476 tty = 0;
477 window_system = 0;
480 if (tty)
481 window_system = 0;
485 void
486 print_help_and_exit ()
488 /* Spaces and tabs are significant in this message; they're chosen so the
489 message aligns properly both in a tty and in a Windows message box.
490 Please try to preserve them; otherwise the output is very hard to read
491 when using emacsclientw. */
492 message (FALSE,
493 "Usage: %s [OPTIONS] FILE...\n\
494 Tell the Emacs server to visit the specified files.\n\
495 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
497 The following OPTIONS are accepted:\n\
498 -V, --version Just print version info and return\n\
499 -H, --help Print this usage information message\n\
500 -t, --tty Open a new Emacs frame on the current terminal\n\
501 -c, --create-frame Create a new frame instead of trying to\n\
502 use the current Emacs frame\n\
503 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
504 -n, --no-wait Don't wait for the server to return\n\
505 -d, --display=DISPLAY Visit the file in the given display\n"
506 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
507 "-s, --socket-name=FILENAME\n\
508 Set filename of the UNIX socket for communication\n"
509 #endif
510 "-f, --server-file=FILENAME\n\
511 Set filename of the TCP authentication file\n\
512 -a, --alternate-editor=EDITOR\n\
513 Editor to fallback to if the server is not running\n\
515 Report bugs to bug-gnu-emacs@gnu.org.\n", progname);
516 exit (EXIT_SUCCESS);
520 Try to run a different command, or --if no alternate editor is
521 defined-- exit with an errorcode.
522 Uses argv, but gets it from the global variable main_argv.
524 void
525 fail (void)
527 if (alternate_editor)
529 int i = optind - 1;
531 execvp (alternate_editor, main_argv + i);
532 message (TRUE, "%s: error executing alternate editor \"%s\"\n",
533 progname, alternate_editor);
535 exit (EXIT_FAILURE);
539 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
542 main (argc, argv)
543 int argc;
544 char **argv;
546 main_argv = argv;
547 progname = argv[0];
548 message (TRUE, "%s: Sorry, the Emacs server is supported only\n"
549 "on systems with Berkeley sockets.\n",
550 argv[0]);
551 fail ();
554 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
556 #ifdef WINDOWSNT
557 # include <winsock2.h>
558 #else
559 # include <sys/types.h>
560 # include <sys/socket.h>
561 # include <sys/un.h>
562 #endif
564 #define AUTH_KEY_LENGTH 64
565 #define SEND_BUFFER_SIZE 4096
567 extern char *strerror ();
568 extern int errno;
570 /* Buffer to accumulate data to send in TCP connections. */
571 char send_buffer[SEND_BUFFER_SIZE + 1];
572 int sblen = 0; /* Fill pointer for the send buffer. */
573 /* Socket used to communicate with the Emacs server process. */
574 HSOCKET emacs_socket = 0;
576 /* Let's send the data to Emacs when either
577 - the data ends in "\n", or
578 - the buffer is full (but this shouldn't happen)
579 Otherwise, we just accumulate it. */
580 void
581 send_to_emacs (s, data)
582 HSOCKET s;
583 char *data;
585 while (data)
587 int dlen = strlen (data);
588 if (dlen + sblen >= SEND_BUFFER_SIZE)
590 int part = SEND_BUFFER_SIZE - sblen;
591 strncpy (&send_buffer[sblen], data, part);
592 data += part;
593 sblen = SEND_BUFFER_SIZE;
595 else if (dlen)
597 strcpy (&send_buffer[sblen], data);
598 data = NULL;
599 sblen += dlen;
601 else
602 break;
604 if (sblen == SEND_BUFFER_SIZE
605 || (sblen > 0 && send_buffer[sblen-1] == '\n'))
607 int sent = send (s, send_buffer, sblen, 0);
608 if (sent != sblen)
609 strcpy (send_buffer, &send_buffer[sent]);
610 sblen -= sent;
616 /* In STR, insert a & before each &, each space, each newline, and
617 any initial -. Change spaces to underscores, too, so that the
618 return value never contains a space.
620 Does not change the string. Outputs the result to STREAM. */
621 void
622 quote_argument (s, str)
623 HSOCKET s;
624 char *str;
626 char *copy = (char *) xmalloc (strlen (str) * 2 + 1);
627 char *p, *q;
629 p = str;
630 q = copy;
631 while (*p)
633 if (*p == ' ')
635 *q++ = '&';
636 *q++ = '_';
637 p++;
639 else if (*p == '\n')
641 *q++ = '&';
642 *q++ = 'n';
643 p++;
645 else
647 if (*p == '&' || (*p == '-' && p == str))
648 *q++ = '&';
649 *q++ = *p++;
652 *q++ = 0;
654 send_to_emacs (s, copy);
656 free (copy);
660 /* The inverse of quote_argument. Removes quoting in string STR by
661 modifying the string in place. Returns STR. */
663 char *
664 unquote_argument (str)
665 char *str;
667 char *p, *q;
669 if (! str)
670 return str;
672 p = str;
673 q = str;
674 while (*p)
676 if (*p == '&')
678 p++;
679 if (*p == '&')
680 *p = '&';
681 else if (*p == '_')
682 *p = ' ';
683 else if (*p == 'n')
684 *p = '\n';
685 else if (*p == '-')
686 *p = '-';
688 *q++ = *p++;
690 *q = 0;
691 return str;
696 file_name_absolute_p (filename)
697 const unsigned char *filename;
699 /* Sanity check, it shouldn't happen. */
700 if (! filename) return FALSE;
702 /* /xxx is always an absolute path. */
703 if (filename[0] == '/') return TRUE;
705 /* Empty filenames (which shouldn't happen) are relative. */
706 if (filename[0] == '\0') return FALSE;
708 #ifdef WINDOWSNT
709 /* X:\xxx is always absolute. */
710 if (isalpha (filename[0])
711 && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
712 return TRUE;
714 /* Both \xxx and \\xxx\yyy are absolute. */
715 if (filename[0] == '\\') return TRUE;
718 FIXME: There's a corner case not dealt with, "x:y", where:
720 1) x is a valid drive designation (usually a letter in the A-Z range)
721 and y is a path, relative to the current directory on drive x. This
722 is absolute, *after* fixing the y part to include the current
723 directory in x.
725 2) x is a relative file name, and y is an NTFS stream name. This is a
726 correct relative path, but it is very unusual.
728 The trouble is that first case items are also valid examples of the
729 second case, i.e., "c:test" can be understood as drive:path or as
730 file:stream.
732 The "right" fix would involve checking whether
733 - the current drive/partition is NTFS,
734 - x is a valid (and accesible) drive designator,
735 - x:y already exists as a file:stream in the current directory,
736 - y already exists on the current directory of drive x,
737 - the auspices are favorable,
738 and then taking an "informed decision" based on the above.
740 Whatever the result, Emacs currently does a very bad job of dealing
741 with NTFS file:streams: it cannot visit them, and the only way to
742 create one is by setting `buffer-file-name' to point to it (either
743 manually or with emacsclient). So perhaps resorting to 1) and ignoring
744 2) for now is the right thing to do.
746 Anyway, something to decide After the Release.
748 #endif
750 return FALSE;
753 #ifdef WINDOWSNT
754 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
755 void
756 __cdecl close_winsock ()
758 WSACleanup ();
761 /* Initialize the WinSock2 library. */
762 void
763 initialize_sockets ()
765 WSADATA wsaData;
767 if (WSAStartup (MAKEWORD (2, 0), &wsaData))
769 message (TRUE, "%s: error initializing WinSock2", progname);
770 exit (EXIT_FAILURE);
773 atexit (close_winsock);
775 #endif /* WINDOWSNT */
779 * Read the information needed to set up a TCP comm channel with
780 * the Emacs server: host, port, pid and authentication string.
783 get_server_config (server, authentication)
784 struct sockaddr_in *server;
785 char *authentication;
787 char dotted[32];
788 char *port;
789 char *pid;
790 FILE *config = NULL;
792 if (file_name_absolute_p (server_file))
793 config = fopen (server_file, "rb");
794 else
796 char *home = getenv ("HOME");
798 if (home)
800 char *path = alloca (32 + strlen (home) + strlen (server_file));
801 sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
802 config = fopen (path, "rb");
804 #ifdef WINDOWSNT
805 if (!config && (home = getenv ("APPDATA")))
807 char *path = alloca (32 + strlen (home) + strlen (server_file));
808 sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
809 config = fopen (path, "rb");
811 #endif
814 if (! config)
815 return FALSE;
817 if (fgets (dotted, sizeof dotted, config)
818 && (port = strchr (dotted, ':'))
819 && (pid = strchr (port, ' ')))
821 *port++ = '\0';
822 *pid++ = '\0';
824 else
826 message (TRUE, "%s: invalid configuration info", progname);
827 exit (EXIT_FAILURE);
830 server->sin_family = AF_INET;
831 server->sin_addr.s_addr = inet_addr (dotted);
832 server->sin_port = htons (atoi (port));
834 if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
836 message (TRUE, "%s: cannot read authentication info", progname);
837 exit (EXIT_FAILURE);
840 fclose (config);
842 emacs_pid = atoi (pid);
844 return TRUE;
847 HSOCKET
848 set_tcp_socket ()
850 HSOCKET s;
851 struct sockaddr_in server;
852 struct linger l_arg = {1, 1};
853 char auth_string[AUTH_KEY_LENGTH + 1];
855 if (! get_server_config (&server, auth_string))
856 return INVALID_SOCKET;
858 if (server.sin_addr.s_addr != inet_addr ("127.0.0.1"))
859 message (FALSE, "%s: connected to remote socket at %s\n",
860 progname, inet_ntoa (server.sin_addr));
863 * Open up an AF_INET socket
865 if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
867 message (TRUE, "%s: socket: %s\n", progname, strerror (errno));
868 return INVALID_SOCKET;
872 * Set up the socket
874 if (connect (s, (struct sockaddr *) &server, sizeof server) < 0)
876 message (TRUE, "%s: connect: %s\n", progname, strerror (errno));
877 return INVALID_SOCKET;
880 setsockopt (s, SOL_SOCKET, SO_LINGER, (char *) &l_arg, sizeof l_arg);
883 * Send the authentication
885 auth_string[AUTH_KEY_LENGTH] = '\0';
887 send_to_emacs (s, "-auth ");
888 send_to_emacs (s, auth_string);
889 send_to_emacs (s, "\n");
891 return s;
895 /* Returns 1 if PREFIX is a prefix of STRING. */
896 static int
897 strprefix (char *prefix, char *string)
899 return !strncmp (prefix, string, strlen (prefix));
903 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
905 /* Three possibilities:
906 2 - can't be `stat'ed (sets errno)
907 1 - isn't owned by us
908 0 - success: none of the above */
910 static int
911 socket_status (socket_name)
912 char *socket_name;
914 struct stat statbfr;
916 if (stat (socket_name, &statbfr) == -1)
917 return 2;
919 if (statbfr.st_uid != geteuid ())
920 return 1;
922 return 0;
926 /* A signal handler that passes the signal to the Emacs process.
927 Useful for SIGWINCH. */
929 SIGTYPE
930 pass_signal_to_emacs (int signalnum)
932 int old_errno = errno;
934 if (emacs_pid)
935 kill (emacs_pid, signalnum);
937 signal (signalnum, pass_signal_to_emacs);
938 errno = old_errno;
941 /* Signal handler for SIGCONT; notify the Emacs process that it can
942 now resume our tty frame. */
944 SIGTYPE
945 handle_sigcont (int signalnum)
947 int old_errno = errno;
949 if (tcgetpgrp (1) == getpgrp ())
951 /* We are in the foreground. */
952 send_to_emacs (emacs_socket, "-resume \n");
954 else
956 /* We are in the background; cancel the continue. */
957 kill (getpid (), SIGSTOP);
960 signal (signalnum, handle_sigcont);
961 errno = old_errno;
964 /* Signal handler for SIGTSTP; notify the Emacs process that we are
965 going to sleep. Normally the suspend is initiated by Emacs via
966 server-handle-suspend-tty, but if the server gets out of sync with
967 reality, we may get a SIGTSTP on C-z. Handling this signal and
968 notifying Emacs about it should get things under control again. */
970 SIGTYPE
971 handle_sigtstp (int signalnum)
973 int old_errno = errno;
974 sigset_t set;
976 if (emacs_socket)
977 send_to_emacs (emacs_socket, "-suspend \n");
979 /* Unblock this signal and call the default handler by temprarily
980 changing the handler and resignalling. */
981 sigprocmask (SIG_BLOCK, NULL, &set);
982 sigdelset (&set, signalnum);
983 signal (signalnum, SIG_DFL);
984 kill (getpid (), signalnum);
985 sigprocmask (SIG_SETMASK, &set, NULL); /* Let's the above signal through. */
986 signal (signalnum, handle_sigtstp);
988 errno = old_errno;
990 /* Set up signal handlers before opening a frame on the current tty. */
992 void
993 init_signals (void)
995 /* Set up signal handlers. */
996 signal (SIGWINCH, pass_signal_to_emacs);
998 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
999 deciding which terminal the signal came from. C-g is now a
1000 normal input event on secondary terminals. */
1001 #if 0
1002 signal (SIGINT, pass_signal_to_emacs);
1003 signal (SIGQUIT, pass_signal_to_emacs);
1004 #endif
1006 signal (SIGCONT, handle_sigcont);
1007 signal (SIGTSTP, handle_sigtstp);
1008 signal (SIGTTOU, handle_sigtstp);
1012 HSOCKET
1013 set_local_socket ()
1015 HSOCKET s;
1016 struct sockaddr_un server;
1019 * Open up an AF_UNIX socket in this person's home directory
1022 if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
1024 message (TRUE, "%s: socket: %s\n", progname, strerror (errno));
1025 return INVALID_SOCKET;
1028 server.sun_family = AF_UNIX;
1031 int sock_status = 0;
1032 int default_sock = !socket_name;
1033 int saved_errno = 0;
1034 char *server_name = "server";
1036 if (socket_name && !index (socket_name, '/') && !index (socket_name, '\\'))
1037 { /* socket_name is a file name component. */
1038 server_name = socket_name;
1039 socket_name = NULL;
1040 default_sock = 1; /* Try both UIDs. */
1043 if (default_sock)
1045 socket_name = alloca (100 + strlen (server_name));
1046 sprintf (socket_name, "/tmp/emacs%d/%s",
1047 (int) geteuid (), server_name);
1050 if (strlen (socket_name) < sizeof (server.sun_path))
1051 strcpy (server.sun_path, socket_name);
1052 else
1054 message (TRUE, "%s: socket-name %s too long",
1055 progname, socket_name);
1056 fail ();
1059 /* See if the socket exists, and if it's owned by us. */
1060 sock_status = socket_status (server.sun_path);
1061 saved_errno = errno;
1062 if (sock_status && default_sock)
1064 /* Failing that, see if LOGNAME or USER exist and differ from
1065 our euid. If so, look for a socket based on the UID
1066 associated with the name. This is reminiscent of the logic
1067 that init_editfns uses to set the global Vuser_full_name. */
1069 char *user_name = (char *) getenv ("LOGNAME");
1071 if (!user_name)
1072 user_name = (char *) getenv ("USER");
1074 if (user_name)
1076 struct passwd *pw = getpwnam (user_name);
1078 if (pw && (pw->pw_uid != geteuid ()))
1080 /* We're running under su, apparently. */
1081 socket_name = alloca (100 + strlen (server_name));
1082 sprintf (socket_name, "/tmp/emacs%d/%s",
1083 (int) pw->pw_uid, server_name);
1085 if (strlen (socket_name) < sizeof (server.sun_path))
1086 strcpy (server.sun_path, socket_name);
1087 else
1089 message (TRUE, "%s: socket-name %s too long",
1090 progname, socket_name);
1091 exit (EXIT_FAILURE);
1094 sock_status = socket_status (server.sun_path);
1095 saved_errno = errno;
1097 else
1098 errno = saved_errno;
1102 switch (sock_status)
1104 case 1:
1105 /* There's a socket, but it isn't owned by us. This is OK if
1106 we are root. */
1107 if (0 != geteuid ())
1109 message (TRUE, "%s: Invalid socket owner\n", progname);
1110 return INVALID_SOCKET;
1112 break;
1114 case 2:
1115 /* `stat' failed */
1116 if (saved_errno == ENOENT)
1117 message (TRUE,
1118 "%s: can't find socket; have you started the server?\n\
1119 To start the server in Emacs, type \"M-x server-start\".\n",
1120 progname);
1121 else
1122 message (TRUE, "%s: can't stat %s: %s\n",
1123 progname, server.sun_path, strerror (saved_errno));
1124 return INVALID_SOCKET;
1128 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
1129 < 0)
1131 message (TRUE, "%s: connect: %s\n", progname, strerror (errno));
1132 return INVALID_SOCKET;
1135 return s;
1137 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1139 HSOCKET
1140 set_socket ()
1142 HSOCKET s;
1144 INITIALIZE ();
1146 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1147 /* Explicit --socket-name argument. */
1148 if (socket_name)
1150 s = set_local_socket ();
1151 if ((s != INVALID_SOCKET) || alternate_editor)
1152 return s;
1153 message (TRUE, "%s: error accessing socket \"%s\"",
1154 progname, socket_name);
1155 exit (EXIT_FAILURE);
1157 #endif
1159 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1160 if (!server_file)
1161 server_file = getenv ("EMACS_SERVER_FILE");
1163 if (server_file)
1165 s = set_tcp_socket ();
1166 if ((s != INVALID_SOCKET) || alternate_editor)
1167 return s;
1169 message (TRUE, "%s: error accessing server file \"%s\"",
1170 progname, server_file);
1171 exit (EXIT_FAILURE);
1174 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1175 /* Implicit local socket. */
1176 s = set_local_socket ();
1177 if (s != INVALID_SOCKET)
1178 return s;
1179 #endif
1181 /* Implicit server file. */
1182 server_file = "server";
1183 s = set_tcp_socket ();
1184 if ((s != INVALID_SOCKET) || alternate_editor)
1185 return s;
1187 /* No implicit or explicit socket, and no alternate editor. */
1188 message (TRUE, "%s: No socket or alternate editor. Please use:\n\n"
1189 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1190 "\t--socket-name\n"
1191 #endif
1192 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1193 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1194 progname);
1195 exit (EXIT_FAILURE);
1198 #ifdef WINDOWSNT
1199 FARPROC set_fg; /* Pointer to AllowSetForegroundWindow. */
1200 FARPROC get_wc; /* Pointer to RealGetWindowClassA. */
1202 BOOL CALLBACK
1203 w32_find_emacs_process (hWnd, lParam)
1204 HWND hWnd;
1205 LPARAM lParam;
1207 DWORD pid;
1208 char class[6];
1210 /* Reject any window not of class "Emacs". */
1211 if (! get_wc (hWnd, class, sizeof (class))
1212 || strcmp (class, "Emacs"))
1213 return TRUE;
1215 /* We only need the process id, not the thread id. */
1216 (void) GetWindowThreadProcessId (hWnd, &pid);
1218 /* Not the one we're looking for. */
1219 if (pid != (DWORD) emacs_pid) return TRUE;
1221 /* OK, let's raise it. */
1222 set_fg (emacs_pid);
1224 /* Stop enumeration. */
1225 return FALSE;
1229 * Search for a window of class "Emacs" and owned by a process with
1230 * process id = emacs_pid. If found, allow it to grab the focus.
1232 void
1233 w32_give_focus ()
1235 HMODULE hUser32;
1237 /* It shouldn't happen when dealing with TCP sockets. */
1238 if (!emacs_pid) return;
1240 if (!(hUser32 = LoadLibrary ("user32.dll"))) return;
1242 /* Modern Windows restrict which processes can set the foreground window.
1243 emacsclient can allow Emacs to grab the focus by calling the function
1244 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1245 NT) lack this function, so we have to check its availability. */
1246 if ((set_fg = GetProcAddress (hUser32, "AllowSetForegroundWindow"))
1247 && (get_wc = GetProcAddress (hUser32, "RealGetWindowClassA")))
1248 EnumWindows (w32_find_emacs_process, (LPARAM) 0);
1250 FreeLibrary (hUser32);
1252 #endif
1255 main (argc, argv)
1256 int argc;
1257 char **argv;
1259 int i, rl, needlf = 0;
1260 char *cwd, *str;
1261 char string[BUFSIZ+1];
1263 main_argv = argv;
1264 progname = argv[0];
1266 /* Process options. */
1267 decode_options (argc, argv);
1269 if ((argc - optind < 1) && !eval && !tty && !window_system)
1271 message (TRUE, "%s: file name or argument required\n"
1272 "Try `%s --help' for more information\n",
1273 progname, progname);
1274 exit (EXIT_FAILURE);
1277 if ((emacs_socket = set_socket ()) == INVALID_SOCKET)
1278 fail ();
1281 cwd = get_current_dir_name ();
1282 if (cwd == 0)
1284 /* getwd puts message in STRING if it fails. */
1285 message (TRUE, "%s: %s\n", progname,
1286 "Cannot get current working directory");
1287 fail ();
1290 #ifdef WINDOWSNT
1291 w32_give_focus ();
1292 #endif
1294 /* Send over our environment. */
1295 if (!current_frame)
1297 extern char **environ;
1298 int i;
1299 for (i = 0; environ[i]; i++)
1301 char *name = xstrdup (environ[i]);
1302 char *value = strchr (name, '=');
1303 send_to_emacs (emacs_socket, "-env ");
1304 quote_argument (emacs_socket, environ[i]);
1305 send_to_emacs (emacs_socket, " ");
1309 /* Send over our current directory. */
1310 if (!current_frame)
1312 send_to_emacs (emacs_socket, "-dir ");
1313 quote_argument (emacs_socket, cwd);
1314 send_to_emacs (emacs_socket, "/");
1315 send_to_emacs (emacs_socket, " ");
1318 retry:
1319 if (nowait)
1320 send_to_emacs (emacs_socket, "-nowait ");
1322 if (current_frame)
1323 send_to_emacs (emacs_socket, "-current-frame ");
1325 if (display)
1327 send_to_emacs (emacs_socket, "-display ");
1328 quote_argument (emacs_socket, display);
1329 send_to_emacs (emacs_socket, " ");
1332 if (tty)
1334 char *type = getenv ("TERM");
1335 char *tty_name = NULL;
1336 #ifndef WINDOWSNT
1337 tty_name = ttyname (fileno (stdin));
1338 #endif
1340 if (! tty_name)
1342 message (TRUE, "%s: could not get terminal name\n", progname);
1343 fail ();
1346 if (! type)
1348 message (TRUE, "%s: please set the TERM variable to your terminal type\n",
1349 progname);
1350 fail ();
1353 if (! strcmp (type, "eterm"))
1355 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1356 message (TRUE, "%s: opening a frame in an Emacs term buffer"
1357 " is not supported\n", progname);
1358 fail ();
1360 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1361 init_signals ();
1362 #endif
1364 send_to_emacs (emacs_socket, "-tty ");
1365 quote_argument (emacs_socket, tty_name);
1366 send_to_emacs (emacs_socket, " ");
1367 quote_argument (emacs_socket, type);
1368 send_to_emacs (emacs_socket, " ");
1371 if (window_system)
1372 send_to_emacs (emacs_socket, "-window-system ");
1374 if ((argc - optind > 0))
1376 for (i = optind; i < argc; i++)
1378 int relative = 0;
1380 if (eval)
1382 /* Don't prepend cwd or anything like that. */
1383 send_to_emacs (emacs_socket, "-eval ");
1384 quote_argument (emacs_socket, argv[i]);
1385 send_to_emacs (emacs_socket, " ");
1386 continue;
1389 if (*argv[i] == '+')
1391 char *p = argv[i] + 1;
1392 while (isdigit ((unsigned char) *p) || *p == ':') p++;
1393 if (*p == 0)
1395 send_to_emacs (emacs_socket, "-position ");
1396 quote_argument (emacs_socket, argv[i]);
1397 send_to_emacs (emacs_socket, " ");
1398 continue;
1400 else
1401 relative = 1;
1403 else if (! file_name_absolute_p (argv[i]))
1404 relative = 1;
1406 send_to_emacs (emacs_socket, "-file ");
1407 if (relative)
1409 quote_argument (emacs_socket, cwd);
1410 send_to_emacs (emacs_socket, "/");
1412 quote_argument (emacs_socket, argv[i]);
1413 send_to_emacs (emacs_socket, " ");
1416 else
1418 if (!tty && !window_system)
1420 while ((str = fgets (string, BUFSIZ, stdin)))
1422 if (eval)
1423 send_to_emacs (emacs_socket, "-eval ");
1424 else
1425 send_to_emacs (emacs_socket, "-file ");
1426 quote_argument (emacs_socket, str);
1428 send_to_emacs (emacs_socket, " ");
1432 send_to_emacs (emacs_socket, "\n");
1434 /* Wait for an answer. */
1435 if (!eval && !tty && !nowait)
1437 printf ("Waiting for Emacs...");
1438 needlf = 2;
1440 fflush (stdout);
1441 fsync (1);
1443 /* Now, wait for an answer and print any messages. */
1444 while ((rl = recv (emacs_socket, string, BUFSIZ, 0)) > 0)
1446 char *p;
1447 string[rl] = '\0';
1449 p = string + strlen (string) - 1;
1450 while (p > string && *p == '\n')
1451 *p-- = 0;
1453 if (strprefix ("-emacs-pid ", string))
1455 /* -emacs-pid PID: The process id of the Emacs process. */
1456 emacs_pid = strtol (string + strlen ("-emacs-pid"), NULL, 10);
1458 else if (strprefix ("-window-system-unsupported ", string))
1460 /* -window-system-unsupported: Emacs was compiled without X
1461 support. Try again on the terminal. */
1462 window_system = 0;
1463 nowait = 0;
1464 tty = 1;
1465 goto retry;
1467 else if (strprefix ("-print ", string))
1469 /* -print STRING: Print STRING on the terminal. */
1470 str = unquote_argument (string + strlen ("-print "));
1471 if (needlf)
1472 printf ("\n");
1473 printf ("%s", str);
1474 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1476 else if (strprefix ("-error ", string))
1478 /* -error DESCRIPTION: Signal an error on the terminal. */
1479 str = unquote_argument (string + strlen ("-error "));
1480 if (needlf)
1481 printf ("\n");
1482 fprintf (stderr, "*ERROR*: %s", str);
1483 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1485 #ifdef SIGSTOP
1486 else if (strprefix ("-suspend ", string))
1488 /* -suspend: Suspend this terminal, i.e., stop the process. */
1489 if (needlf)
1490 printf ("\n");
1491 needlf = 0;
1492 kill (0, SIGSTOP);
1494 #endif
1495 else
1497 /* Unknown command. */
1498 if (needlf)
1499 printf ("\n");
1500 printf ("*ERROR*: Unknown message: %s", string);
1501 needlf = string[0] == '\0' ? needlf : string[strlen (string) - 1] != '\n';
1505 if (needlf)
1506 printf ("\n");
1507 fflush (stdout);
1508 fsync (1);
1510 CLOSE_SOCKET (emacs_socket);
1511 return EXIT_SUCCESS;
1514 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
1517 #ifndef HAVE_STRERROR
1518 char *
1519 strerror (errnum)
1520 int errnum;
1522 extern char *sys_errlist[];
1523 extern int sys_nerr;
1525 if (errnum >= 0 && errnum < sys_nerr)
1526 return sys_errlist[errnum];
1527 return (char *) "Unknown error";
1530 #endif /* ! HAVE_STRERROR */
1532 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
1533 (do not change this comment) */
1535 /* emacsclient.c ends here */