Merged from emacs--devo--0
[emacs.git] / lib-src / emacsclient.c
blob8e8cb9b379ad433432511227864933740f42533b
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 2, 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>
39 # define NO_SOCKETS_IN_FILE_SYSTEM
41 # define HSOCKET SOCKET
42 # define CLOSE_SOCKET closesocket
43 # define INITIALIZE() (initialize_sockets ())
45 #else /* !WINDOWSNT */
47 # include <sys/types.h>
49 # ifdef HAVE_INET_SOCKETS
50 # include <netinet/in.h>
51 # endif
53 # define INVALID_SOCKET -1
54 # define HSOCKET int
55 # define CLOSE_SOCKET close
56 # define INITIALIZE()
58 #endif /* !WINDOWSNT */
60 #undef signal
62 #include <stdarg.h>
63 #include <ctype.h>
64 #include <stdio.h>
65 #include "getopt.h"
66 #ifdef HAVE_UNISTD_H
67 #include <unistd.h>
68 #endif
70 #ifdef VMS
71 # include "vms-pwd.h"
72 #else /* not VMS */
73 #ifdef WINDOWSNT
74 # include <io.h>
75 #else /* not WINDOWSNT */
76 # include <pwd.h>
77 #endif /* not WINDOWSNT */
78 #endif /* not VMS */
79 #include <sys/stat.h>
81 #include <signal.h>
82 #include <errno.h>
84 /* From lisp.h */
85 #ifndef DIRECTORY_SEP
86 #define DIRECTORY_SEP '/'
87 #endif
88 #ifndef IS_DIRECTORY_SEP
89 #define IS_DIRECTORY_SEP(_c_) ((_c_) == DIRECTORY_SEP)
90 #endif
91 #ifndef IS_DEVICE_SEP
92 #ifndef DEVICE_SEP
93 #define IS_DEVICE_SEP(_c_) 0
94 #else
95 #define IS_DEVICE_SEP(_c_) ((_c_) == DEVICE_SEP)
96 #endif
97 #endif
98 #ifndef IS_ANY_SEP
99 #define IS_ANY_SEP(_c_) (IS_DIRECTORY_SEP (_c_))
100 #endif
104 char *getenv (), *getwd ();
105 char *(getcwd) ();
107 #ifndef VERSION
108 #define VERSION "unspecified"
109 #endif
112 #ifndef EXIT_SUCCESS
113 #define EXIT_SUCCESS 0
114 #endif
116 #ifndef EXIT_FAILURE
117 #define EXIT_FAILURE 1
118 #endif
120 #ifndef FALSE
121 #define FALSE 0
122 #endif
124 #ifndef TRUE
125 #define TRUE 1
126 #endif
128 #ifndef NO_RETURN
129 #define NO_RETURN
130 #endif
132 /* Name used to invoke this program. */
133 char *progname;
135 /* The first argument to main. */
136 int main_argc;
138 /* The second argument to main. */
139 char **main_argv;
141 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
142 int nowait = 0;
144 /* Nonzero means args are expressions to be evaluated. --eval. */
145 int eval = 0;
147 /* Nonzero means don't open a new frame. --current-frame. */
148 int current_frame = 0;
150 /* Nonzero means open a new graphical frame. */
151 int window_system = 0;
153 /* The display on which Emacs should work. --display. */
154 char *display = NULL;
156 /* Nonzero means open a new Emacs frame on the current terminal. */
157 int tty = 0;
159 /* If non-NULL, the name of an editor to fallback to if the server
160 is not running. --alternate-editor. */
161 const char *alternate_editor = NULL;
163 /* If non-NULL, the filename of the UNIX socket. */
164 char *socket_name = NULL;
166 /* If non-NULL, the filename of the authentication file. */
167 char *server_file = NULL;
169 /* PID of the Emacs server process. */
170 int emacs_pid = 0;
172 void print_help_and_exit () NO_RETURN;
174 struct option longopts[] =
176 { "no-wait", no_argument, NULL, 'n' },
177 { "eval", no_argument, NULL, 'e' },
178 { "help", no_argument, NULL, 'H' },
179 { "version", no_argument, NULL, 'V' },
180 { "tty", no_argument, NULL, 't' },
181 { "current-frame", no_argument, NULL, 'c' },
182 { "alternate-editor", required_argument, NULL, 'a' },
183 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
184 { "socket-name", required_argument, NULL, 's' },
185 #endif
186 { "server-file", required_argument, NULL, 'f' },
187 { "display", required_argument, NULL, 'd' },
188 { 0, 0, 0, 0 }
192 /* Like malloc but get fatal error if memory is exhausted. */
194 long *
195 xmalloc (size)
196 unsigned int size;
198 long *result = (long *) malloc (size);
199 if (result == NULL)
201 perror ("malloc");
202 exit (EXIT_FAILURE);
204 return result;
207 /* Like strdup but get a fatal error if memory is exhausted. */
209 char *
210 xstrdup (const char *s)
212 char *result = strdup (s);
213 if (result == NULL)
215 perror ("strdup");
216 exit (EXIT_FAILURE);
218 return result;
221 /* From sysdep.c */
222 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
224 /* Return the current working directory. Returns NULL on errors.
225 Any other returned value must be freed with free. This is used
226 only when get_current_dir_name is not defined on the system. */
227 char*
228 get_current_dir_name ()
230 char *buf;
231 char *pwd;
232 struct stat dotstat, pwdstat;
233 /* If PWD is accurate, use it instead of calling getwd. PWD is
234 sometimes a nicer name, and using it may avoid a fatal error if a
235 parent directory is searchable but not readable. */
236 if ((pwd = getenv ("PWD")) != 0
237 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
238 && stat (pwd, &pwdstat) == 0
239 && stat (".", &dotstat) == 0
240 && dotstat.st_ino == pwdstat.st_ino
241 && dotstat.st_dev == pwdstat.st_dev
242 #ifdef MAXPATHLEN
243 && strlen (pwd) < MAXPATHLEN
244 #endif
247 buf = (char *) xmalloc (strlen (pwd) + 1);
248 if (!buf)
249 return NULL;
250 strcpy (buf, pwd);
252 #ifdef HAVE_GETCWD
253 else
255 size_t buf_size = 1024;
256 buf = (char *) xmalloc (buf_size);
257 if (!buf)
258 return NULL;
259 for (;;)
261 if (getcwd (buf, buf_size) == buf)
262 break;
263 if (errno != ERANGE)
265 int tmp_errno = errno;
266 free (buf);
267 errno = tmp_errno;
268 return NULL;
270 buf_size *= 2;
271 buf = (char *) realloc (buf, buf_size);
272 if (!buf)
273 return NULL;
276 #else
277 else
279 /* We need MAXPATHLEN here. */
280 buf = (char *) xmalloc (MAXPATHLEN + 1);
281 if (!buf)
282 return NULL;
283 if (getwd (buf) == NULL)
285 int tmp_errno = errno;
286 free (buf);
287 errno = tmp_errno;
288 return NULL;
291 #endif
292 return buf;
294 #endif
296 /* Message functions. */
298 #ifdef WINDOWSNT
300 w32_window_app ()
302 static int window_app = -1;
303 char szTitle[MAX_PATH];
305 if (window_app < 0)
306 /* Checking for STDOUT does not work; it's a valid handle also in
307 nonconsole apps. Testing for the console title seems to work. */
308 window_app = (GetConsoleTitleA (szTitle, MAX_PATH) == 0);
310 return window_app;
314 execvp wrapper for Windows. Quotes arguments with embedded spaces.
316 This is necessary due to the broken implementation of exec* routines in
317 the Microsoft libraries: they concatenate the arguments together without
318 quoting special characters, and pass the result to CreateProcess, with
319 predictably bad results. By contrast, Posix execvp passes the arguments
320 directly into the argv array of the child process.
323 w32_execvp (path, argv)
324 char *path;
325 char **argv;
327 int i;
329 /* Required to allow a .BAT script as alternate editor. */
330 argv[0] = (char *) alternate_editor;
332 for (i = 0; argv[i]; i++)
333 if (strchr (argv[i], ' '))
335 char *quoted = alloca (strlen (argv[i]) + 3);
336 sprintf (quoted, "\"%s\"", argv[i]);
337 argv[i] = quoted;
340 return execvp (path, argv);
343 #undef execvp
344 #define execvp w32_execvp
346 #endif /* WINDOWSNT */
348 void
349 message (int is_error, char *message, ...)
351 char msg [2048];
352 va_list args;
354 va_start (args, message);
355 vsprintf (msg, message, args);
356 va_end (args);
358 #ifdef WINDOWSNT
359 if (w32_window_app ())
361 if (is_error)
362 MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
363 else
364 MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
366 else
367 #endif
369 FILE *f = is_error ? stderr : stdout;
371 fputs (msg, f);
372 fflush (f);
376 /* Decode the options from argv and argc.
377 The global variable `optind' will say how many arguments we used up. */
379 void
380 decode_options (argc, argv)
381 int argc;
382 char **argv;
384 alternate_editor = getenv ("ALTERNATE_EDITOR");
385 display = getenv ("DISPLAY");
386 if (display && strlen (display) == 0)
387 display = NULL;
389 while (1)
391 int opt = getopt_long (argc, argv,
392 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
393 "VHnea:s:f:d:tc",
394 #else
395 "VHnea:f:d:tc",
396 #endif
397 longopts, 0);
399 if (opt == EOF)
400 break;
402 switch (opt)
404 case 0:
405 /* If getopt returns 0, then it has already processed a
406 long-named option. We should do nothing. */
407 break;
409 case 'a':
410 alternate_editor = optarg;
411 break;
413 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
414 case 's':
415 socket_name = optarg;
416 break;
417 #endif
419 case 'f':
420 server_file = optarg;
421 break;
423 case 'd':
424 display = optarg;
425 break;
427 case 'n':
428 nowait = 1;
429 break;
431 case 'e':
432 eval = 1;
433 break;
435 case 'V':
436 message (FALSE, "emacsclient %s\n", VERSION);
437 exit (EXIT_SUCCESS);
438 break;
440 case 't':
441 tty = 1;
442 break;
444 case 'c':
445 current_frame = 1;
446 break;
448 case 'H':
449 print_help_and_exit ();
450 break;
452 default:
453 message (TRUE, "Try `%s --help' for more information\n", progname);
454 exit (EXIT_FAILURE);
455 break;
459 if (!tty && display)
460 window_system = 1;
461 #if !defined (WINDOWSNT) && !defined (HAVE_CARBON)
462 else
463 tty = 1;
464 #endif
466 /* --no-wait implies --current-frame on ttys when there are file
467 arguments or expressions given. */
468 if (nowait && tty && argc - optind > 0)
469 current_frame = 1;
471 if (current_frame)
473 tty = 0;
474 window_system = 0;
477 if (tty)
478 window_system = 0;
482 void
483 print_help_and_exit ()
485 message (FALSE,
486 "Usage: %s [OPTIONS] FILE...\n\
487 Tell the Emacs server to visit the specified files.\n\
488 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
490 The following OPTIONS are accepted:\n\
491 -V, --version Just print version info and return\n\
492 -H, --help Print this usage information message\n\
493 -t, --tty Open a new Emacs frame on the current terminal\n\
494 -c, --current-frame Do not create a new frame; use the current Emacs frame\n\
495 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
496 -n, --no-wait Don't wait for the server to return\n\
497 -d, --display=DISPLAY Visit the file in the given display\n"
498 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
499 "-s, --socket-name=FILENAME\n\
500 Set filename of the UNIX socket for communication\n"
501 #endif
502 "-f, --server-file=FILENAME\n\
503 Set filename of the TCP authentication file\n\
504 -a, --alternate-editor=EDITOR\n\
505 Editor to fallback to if the server is not running\n\
507 Report bugs to bug-gnu-emacs@gnu.org.\n", progname);
508 exit (EXIT_SUCCESS);
512 Try to run a different command, or --if no alternate editor is
513 defined-- exit with an errorcode.
515 void
516 fail (void)
518 if (alternate_editor)
520 int i = optind - 1;
522 execvp (alternate_editor, main_argv + i);
523 message (TRUE, "%s: error executing alternate editor \"%s\"\n",
524 progname, alternate_editor);
526 exit (EXIT_FAILURE);
530 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
533 main (argc, argv)
534 int argc;
535 char **argv;
537 main_argc = argc;
538 main_argv = argv;
539 progname = argv[0];
540 message (TRUE, "%s: Sorry, the Emacs server is supported only\n"
541 "on systems with Berkeley sockets.\n",
542 argv[0]);
543 fail ();
546 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
548 #ifdef WINDOWSNT
549 # include <winsock2.h>
550 #else
551 # include <sys/types.h>
552 # include <sys/socket.h>
553 # include <sys/un.h>
554 # include <sys/stat.h>
555 # include <errno.h>
556 #endif
558 #define AUTH_KEY_LENGTH 64
559 #define SEND_BUFFER_SIZE 4096
561 extern char *strerror ();
562 extern int errno;
564 /* Buffer to accumulate data to send in TCP connections. */
565 char send_buffer[SEND_BUFFER_SIZE + 1];
566 int sblen = 0; /* Fill pointer for the send buffer. */
567 /* Socket used to communicate with the Emacs server process. */
568 HSOCKET emacs_socket = 0;
570 /* Let's send the data to Emacs when either
571 - the data ends in "\n", or
572 - the buffer is full (but this shouldn't happen)
573 Otherwise, we just accumulate it. */
574 void
575 send_to_emacs (s, data)
576 HSOCKET s;
577 char *data;
579 while (data)
581 int dlen = strlen (data);
582 if (dlen + sblen >= SEND_BUFFER_SIZE)
584 int part = SEND_BUFFER_SIZE - sblen;
585 strncpy (&send_buffer[sblen], data, part);
586 data += part;
587 sblen = SEND_BUFFER_SIZE;
589 else if (dlen)
591 strcpy (&send_buffer[sblen], data);
592 data = NULL;
593 sblen += dlen;
595 else
596 break;
598 if (sblen == SEND_BUFFER_SIZE
599 || (sblen > 0 && send_buffer[sblen-1] == '\n'))
601 int sent = send (s, send_buffer, sblen, 0);
602 if (sent != sblen)
603 strcpy (send_buffer, &send_buffer[sent]);
604 sblen -= sent;
610 /* In STR, insert a & before each &, each space, each newline, and
611 any initial -. Change spaces to underscores, too, so that the
612 return value never contains a space.
614 Does not change the string. Outputs the result to STREAM. */
615 void
616 quote_argument (s, str)
617 HSOCKET s;
618 char *str;
620 char *copy = (char *) xmalloc (strlen (str) * 2 + 1);
621 char *p, *q;
623 p = str;
624 q = copy;
625 while (*p)
627 if (*p == ' ')
629 *q++ = '&';
630 *q++ = '_';
631 p++;
633 else if (*p == '\n')
635 *q++ = '&';
636 *q++ = 'n';
637 p++;
639 else
641 if (*p == '&' || (*p == '-' && p == str))
642 *q++ = '&';
643 *q++ = *p++;
646 *q++ = 0;
648 send_to_emacs (s, copy);
650 free (copy);
654 /* The inverse of quote_argument. Removes quoting in string STR by
655 modifying the string in place. Returns STR. */
657 char *
658 unquote_argument (str)
659 char *str;
661 char *p, *q;
663 if (! str)
664 return str;
666 p = str;
667 q = str;
668 while (*p)
670 if (*p == '&')
672 p++;
673 if (*p == '&')
674 *p = '&';
675 else if (*p == '_')
676 *p = ' ';
677 else if (*p == 'n')
678 *p = '\n';
679 else if (*p == '-')
680 *p = '-';
682 *q++ = *p++;
684 *q = 0;
685 return str;
690 file_name_absolute_p (filename)
691 const unsigned char *filename;
693 /* Sanity check, it shouldn't happen. */
694 if (! filename) return FALSE;
696 /* /xxx is always an absolute path. */
697 if (filename[0] == '/') return TRUE;
699 /* Empty filenames (which shouldn't happen) are relative. */
700 if (filename[0] == '\0') return FALSE;
702 #ifdef WINDOWSNT
703 /* X:\xxx is always absolute. */
704 if (isalpha (filename[0])
705 && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
706 return TRUE;
708 /* Both \xxx and \\xxx\yyy are absolute. */
709 if (filename[0] == '\\') return TRUE;
712 FIXME: There's a corner case not dealt with, "x:y", where:
714 1) x is a valid drive designation (usually a letter in the A-Z range)
715 and y is a path, relative to the current directory on drive x. This
716 is absolute, *after* fixing the y part to include the current
717 directory in x.
719 2) x is a relative file name, and y is an NTFS stream name. This is a
720 correct relative path, but it is very unusual.
722 The trouble is that first case items are also valid examples of the
723 second case, i.e., "c:test" can be understood as drive:path or as
724 file:stream.
726 The "right" fix would involve checking whether
727 - the current drive/partition is NTFS,
728 - x is a valid (and accesible) drive designator,
729 - x:y already exists as a file:stream in the current directory,
730 - y already exists on the current directory of drive x,
731 - the auspices are favorable,
732 and then taking an "informed decision" based on the above.
734 Whatever the result, Emacs currently does a very bad job of dealing
735 with NTFS file:streams: it cannot visit them, and the only way to
736 create one is by setting `buffer-file-name' to point to it (either
737 manually or with emacsclient). So perhaps resorting to 1) and ignoring
738 2) for now is the right thing to do.
740 Anyway, something to decide After the Release.
742 #endif
744 return FALSE;
747 #ifdef WINDOWSNT
748 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
749 void
750 __cdecl close_winsock ()
752 WSACleanup ();
755 /* Initialize the WinSock2 library. */
756 void
757 initialize_sockets ()
759 WSADATA wsaData;
761 if (WSAStartup (MAKEWORD (2, 0), &wsaData))
763 message (TRUE, "%s: error initializing WinSock2", progname);
764 exit (EXIT_FAILURE);
767 atexit (close_winsock);
769 #endif /* WINDOWSNT */
773 * Read the information needed to set up a TCP comm channel with
774 * the Emacs server: host, port, pid and authentication string.
777 get_server_config (server, authentication)
778 struct sockaddr_in *server;
779 char *authentication;
781 char dotted[32];
782 char *port;
783 char *pid;
784 FILE *config = NULL;
786 if (file_name_absolute_p (server_file))
787 config = fopen (server_file, "rb");
788 else
790 char *home = getenv ("HOME");
792 if (home)
794 char *path = alloca (32 + strlen (home) + strlen (server_file));
795 sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
796 config = fopen (path, "rb");
798 #ifdef WINDOWSNT
799 if (!config && (home = getenv ("APPDATA")))
801 char *path = alloca (32 + strlen (home) + strlen (server_file));
802 sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
803 config = fopen (path, "rb");
805 #endif
808 if (! config)
809 return FALSE;
811 if (fgets (dotted, sizeof dotted, config)
812 && (port = strchr (dotted, ':'))
813 && (pid = strchr (port, ' ')))
815 *port++ = '\0';
816 *pid++ = '\0';
818 else
820 message (TRUE, "%s: invalid configuration info", progname);
821 exit (EXIT_FAILURE);
824 server->sin_family = AF_INET;
825 server->sin_addr.s_addr = inet_addr (dotted);
826 server->sin_port = htons (atoi (port));
828 if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
830 message (TRUE, "%s: cannot read authentication info", progname);
831 exit (EXIT_FAILURE);
834 fclose (config);
836 emacs_pid = atoi (pid);
838 return TRUE;
841 HSOCKET
842 set_tcp_socket ()
844 HSOCKET s;
845 struct sockaddr_in server;
846 struct linger l_arg = {1, 1};
847 char auth_string[AUTH_KEY_LENGTH + 1];
849 if (! get_server_config (&server, auth_string))
850 return INVALID_SOCKET;
852 if (server.sin_addr.s_addr != inet_addr ("127.0.0.1"))
853 message (FALSE, "%s: connected to remote socket at %s\n",
854 progname, inet_ntoa (server.sin_addr));
857 * Open up an AF_INET socket
859 if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
861 message (TRUE, "%s: socket: %s\n", progname, strerror (errno));
862 return INVALID_SOCKET;
866 * Set up the socket
868 if (connect (s, (struct sockaddr *) &server, sizeof server) < 0)
870 message (TRUE, "%s: connect: %s\n", progname, strerror (errno));
871 return INVALID_SOCKET;
874 setsockopt (s, SOL_SOCKET, SO_LINGER, (char *) &l_arg, sizeof l_arg);
877 * Send the authentication
879 auth_string[AUTH_KEY_LENGTH] = '\0';
881 send_to_emacs (s, "-auth ");
882 send_to_emacs (s, auth_string);
883 send_to_emacs (s, "\n");
885 return s;
889 /* Returns 1 if PREFIX is a prefix of STRING. */
890 static int
891 strprefix (char *prefix, char *string)
893 int i;
894 if (! prefix)
895 return 1;
897 if (!string)
898 return 0;
900 for (i = 0; prefix[i]; i++)
901 if (!string[i] || string[i] != prefix[i])
902 return 0;
903 return 1;
907 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
909 /* Three possibilities:
910 2 - can't be `stat'ed (sets errno)
911 1 - isn't owned by us
912 0 - success: none of the above */
914 static int
915 socket_status (socket_name)
916 char *socket_name;
918 struct stat statbfr;
920 if (stat (socket_name, &statbfr) == -1)
921 return 2;
923 if (statbfr.st_uid != geteuid ())
924 return 1;
926 return 0;
930 /* A signal handler that passes the signal to the Emacs process.
931 Useful for SIGWINCH. */
933 SIGTYPE
934 pass_signal_to_emacs (int signalnum)
936 int old_errno = errno;
938 if (emacs_pid)
939 kill (emacs_pid, signalnum);
941 signal (signalnum, pass_signal_to_emacs);
942 errno = old_errno;
945 /* Signal handler for SIGCONT; notify the Emacs process that it can
946 now resume our tty frame. */
948 SIGTYPE
949 handle_sigcont (int signalnum)
951 int old_errno = errno;
953 if (tcgetpgrp (1) == getpgrp ())
955 /* We are in the foreground. */
956 send_to_emacs (emacs_socket, "-resume \n");
958 else
960 /* We are in the background; cancel the continue. */
961 kill (getpid (), SIGSTOP);
964 signal (signalnum, handle_sigcont);
965 errno = old_errno;
968 /* Signal handler for SIGTSTP; notify the Emacs process that we are
969 going to sleep. Normally the suspend is initiated by Emacs via
970 server-handle-suspend-tty, but if the server gets out of sync with
971 reality, we may get a SIGTSTP on C-z. Handling this signal and
972 notifying Emacs about it should get things under control again. */
974 SIGTYPE
975 handle_sigtstp (int signalnum)
977 int old_errno = errno;
978 sigset_t set;
980 if (emacs_socket)
981 send_to_emacs (emacs_socket, "-suspend \n");
983 /* Unblock this signal and call the default handler by temprarily
984 changing the handler and resignalling. */
985 sigprocmask (SIG_BLOCK, NULL, &set);
986 sigdelset (&set, signalnum);
987 signal (signalnum, SIG_DFL);
988 kill (getpid (), signalnum);
989 sigprocmask (SIG_SETMASK, &set, NULL); /* Let's the above signal through. */
990 signal (signalnum, handle_sigtstp);
992 errno = old_errno;
994 /* Set up signal handlers before opening a frame on the current tty. */
996 void
997 init_signals (void)
999 /* Set up signal handlers. */
1000 signal (SIGWINCH, pass_signal_to_emacs);
1002 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
1003 deciding which terminal the signal came from. C-g is now a
1004 normal input event on secondary terminals. */
1005 #if 0
1006 signal (SIGINT, pass_signal_to_emacs);
1007 signal (SIGQUIT, pass_signal_to_emacs);
1008 #endif
1010 signal (SIGCONT, handle_sigcont);
1011 signal (SIGTSTP, handle_sigtstp);
1012 signal (SIGTTOU, handle_sigtstp);
1016 HSOCKET
1017 set_local_socket ()
1019 HSOCKET s;
1020 struct sockaddr_un server;
1023 * Open up an AF_UNIX socket in this person's home directory
1026 if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
1028 message (TRUE, "%s: socket: %s\n", progname, strerror (errno));
1029 return INVALID_SOCKET;
1032 server.sun_family = AF_UNIX;
1035 int sock_status = 0;
1036 int default_sock = !socket_name;
1037 int saved_errno = 0;
1039 char *server_name = "server";
1041 if (socket_name && !index (socket_name, '/') && !index (socket_name, '\\'))
1042 { /* socket_name is a file name component. */
1043 server_name = socket_name;
1044 socket_name = NULL;
1045 default_sock = 1; /* Try both UIDs. */
1048 if (default_sock)
1050 socket_name = alloca (100 + strlen (server_name));
1051 sprintf (socket_name, "/tmp/emacs%d/%s",
1052 (int) geteuid (), server_name);
1055 if (strlen (socket_name) < sizeof (server.sun_path))
1056 strcpy (server.sun_path, socket_name);
1057 else
1059 message (TRUE, "%s: socket-name %s too long",
1060 progname, socket_name);
1061 fail ();
1064 /* See if the socket exists, and if it's owned by us. */
1065 sock_status = socket_status (server.sun_path);
1066 saved_errno = errno;
1067 if (sock_status && default_sock)
1069 /* Failing that, see if LOGNAME or USER exist and differ from
1070 our euid. If so, look for a socket based on the UID
1071 associated with the name. This is reminiscent of the logic
1072 that init_editfns uses to set the global Vuser_full_name. */
1074 char *user_name = (char *) getenv ("LOGNAME");
1076 if (!user_name)
1077 user_name = (char *) getenv ("USER");
1079 if (user_name)
1081 struct passwd *pw = getpwnam (user_name);
1083 if (pw && (pw->pw_uid != geteuid ()))
1085 /* We're running under su, apparently. */
1086 socket_name = alloca (100 + strlen (server_name));
1087 sprintf (socket_name, "/tmp/emacs%d/%s",
1088 (int) pw->pw_uid, server_name);
1090 if (strlen (socket_name) < sizeof (server.sun_path))
1091 strcpy (server.sun_path, socket_name);
1092 else
1094 message (TRUE, "%s: socket-name %s too long",
1095 progname, socket_name);
1096 exit (EXIT_FAILURE);
1099 sock_status = socket_status (server.sun_path);
1100 saved_errno = errno;
1102 else
1103 errno = saved_errno;
1107 switch (sock_status)
1109 case 1:
1110 /* There's a socket, but it isn't owned by us. This is OK if
1111 we are root. */
1112 if (0 != geteuid ())
1114 message (TRUE, "%s: Invalid socket owner\n", progname);
1115 return INVALID_SOCKET;
1117 break;
1119 case 2:
1120 /* `stat' failed */
1121 if (saved_errno == ENOENT)
1122 message (TRUE,
1123 "%s: can't find socket; have you started the server?\n\
1124 To start the server in Emacs, type \"M-x server-start\".\n",
1125 progname);
1126 else
1127 message (TRUE, "%s: can't stat %s: %s\n",
1128 progname, server.sun_path, strerror (saved_errno));
1129 return INVALID_SOCKET;
1133 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
1134 < 0)
1136 message (TRUE, "%s: connect: %s\n", progname, strerror (errno));
1137 return INVALID_SOCKET;
1140 return s;
1142 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1144 HSOCKET
1145 set_socket ()
1147 HSOCKET s;
1149 INITIALIZE ();
1151 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1152 /* Explicit --socket-name argument. */
1153 if (socket_name)
1155 s = set_local_socket ();
1156 if ((s != INVALID_SOCKET) || alternate_editor)
1157 return s;
1158 message (TRUE, "%s: error accessing socket \"%s\"",
1159 progname, socket_name);
1160 exit (EXIT_FAILURE);
1162 #endif
1164 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1165 if (!server_file)
1166 server_file = getenv ("EMACS_SERVER_FILE");
1168 if (server_file)
1170 s = set_tcp_socket ();
1171 if ((s != INVALID_SOCKET) || alternate_editor)
1172 return s;
1174 message (TRUE, "%s: error accessing server file \"%s\"",
1175 progname, server_file);
1176 exit (EXIT_FAILURE);
1179 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1180 /* Implicit local socket. */
1181 s = set_local_socket ();
1182 if (s != INVALID_SOCKET)
1183 return s;
1184 #endif
1186 /* Implicit server file. */
1187 server_file = "server";
1188 s = set_tcp_socket ();
1189 if ((s != INVALID_SOCKET) || alternate_editor)
1190 return s;
1192 /* No implicit or explicit socket, and no alternate editor. */
1193 message (TRUE, "%s: No socket or alternate editor. Please use:\n\n"
1194 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1195 "\t--socket-name\n"
1196 #endif
1197 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1198 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1199 progname);
1200 exit (EXIT_FAILURE);
1203 #ifdef WINDOWSNT
1204 FARPROC set_fg; /* Pointer to AllowSetForegroundWindow. */
1205 FARPROC get_wc; /* Pointer to RealGetWindowClassA. */
1207 BOOL CALLBACK
1208 w32_find_emacs_process (hWnd, lParam)
1209 HWND hWnd;
1210 LPARAM lParam;
1212 DWORD pid;
1213 char class[6];
1215 /* Reject any window not of class "Emacs". */
1216 if (! get_wc (hWnd, class, sizeof (class))
1217 || strcmp (class, "Emacs"))
1218 return TRUE;
1220 /* We only need the process id, not the thread id. */
1221 (void) GetWindowThreadProcessId (hWnd, &pid);
1223 /* Not the one we're looking for. */
1224 if (pid != (DWORD) emacs_pid) return TRUE;
1226 /* OK, let's raise it. */
1227 set_fg (emacs_pid);
1229 /* Stop enumeration. */
1230 return FALSE;
1234 * Search for a window of class "Emacs" and owned by a process with
1235 * process id = emacs_pid. If found, allow it to grab the focus.
1237 void
1238 w32_give_focus ()
1240 HMODULE hUser32;
1242 /* It shouldn't happen when dealing with TCP sockets. */
1243 if (!emacs_pid) return;
1245 if (!(hUser32 = LoadLibrary ("user32.dll"))) return;
1247 /* Modern Windows restrict which processes can set the foreground window.
1248 emacsclient can allow Emacs to grab the focus by calling the function
1249 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1250 NT) lack this function, so we have to check its availability. */
1251 if ((set_fg = GetProcAddress (hUser32, "AllowSetForegroundWindow"))
1252 && (get_wc = GetProcAddress (hUser32, "RealGetWindowClassA")))
1253 EnumWindows (w32_find_emacs_process, (LPARAM) 0);
1255 FreeLibrary (hUser32);
1257 #endif
1260 main (argc, argv)
1261 int argc;
1262 char **argv;
1264 int i, rl, needlf = 0;
1265 char *cwd, *str;
1266 char string[BUFSIZ+1];
1268 main_argc = argc;
1269 main_argv = argv;
1270 progname = argv[0];
1272 /* Process options. */
1273 decode_options (argc, argv);
1275 if ((argc - optind < 1) && !eval && !tty && !window_system)
1277 message (TRUE, "%s: file name or argument required\n"
1278 "Try `%s --help' for more information\n",
1279 progname, progname);
1280 exit (EXIT_FAILURE);
1283 if ((emacs_socket = set_socket ()) == INVALID_SOCKET)
1284 fail ();
1287 cwd = get_current_dir_name ();
1288 if (cwd == 0)
1290 /* getwd puts message in STRING if it fails. */
1291 message (TRUE, "%s: %s\n", progname,
1292 "Cannot get current working directory");
1293 fail ();
1296 #ifdef WINDOWSNT
1297 w32_give_focus ();
1298 #endif
1300 /* First of all, send our version number for verification. */
1301 send_to_emacs (emacs_socket, "-version ");
1302 send_to_emacs (emacs_socket, VERSION);
1303 send_to_emacs (emacs_socket, " ");
1305 /* Send over our environment. */
1306 if (!current_frame)
1308 extern char **environ;
1309 int i;
1310 for (i = 0; environ[i]; i++)
1312 char *name = xstrdup (environ[i]);
1313 char *value = strchr (name, '=');
1314 send_to_emacs (emacs_socket, "-env ");
1315 quote_argument (emacs_socket, environ[i]);
1316 send_to_emacs (emacs_socket, " ");
1320 /* Send over our current directory. */
1321 if (!current_frame)
1323 send_to_emacs (emacs_socket, "-dir ");
1324 quote_argument (emacs_socket, cwd);
1325 send_to_emacs (emacs_socket, "/");
1326 send_to_emacs (emacs_socket, " ");
1329 retry:
1330 if (nowait)
1331 send_to_emacs (emacs_socket, "-nowait ");
1333 if (current_frame)
1334 send_to_emacs (emacs_socket, "-current-frame ");
1336 if (display)
1338 send_to_emacs (emacs_socket, "-display ");
1339 quote_argument (emacs_socket, display);
1340 send_to_emacs (emacs_socket, " ");
1343 if (tty)
1345 char *tty_name = NULL;
1346 #ifndef WINDOWSNT
1347 tty_name = ttyname (fileno (stdin));
1348 #endif
1349 char *type = getenv ("TERM");
1351 if (! tty_name)
1353 message (TRUE, "%s: could not get terminal name\n", progname);
1354 fail ();
1357 if (! type)
1359 message (TRUE, "%s: please set the TERM variable to your terminal type\n",
1360 progname);
1361 fail ();
1364 if (! strcmp (type, "eterm"))
1366 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1367 message (TRUE, "%s: opening a frame in an Emacs term buffer"
1368 " is not supported\n", progname);
1369 fail ();
1371 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1372 init_signals ();
1373 #endif
1375 send_to_emacs (emacs_socket, "-tty ");
1376 quote_argument (emacs_socket, tty_name);
1377 send_to_emacs (emacs_socket, " ");
1378 quote_argument (emacs_socket, type);
1379 send_to_emacs (emacs_socket, " ");
1382 if (window_system)
1383 send_to_emacs (emacs_socket, "-window-system ");
1385 if ((argc - optind > 0))
1387 for (i = optind; i < argc; i++)
1389 int relative = 0;
1391 if (eval)
1393 /* Don't prepend cwd or anything like that. */
1394 send_to_emacs (emacs_socket, "-eval ");
1395 quote_argument (emacs_socket, argv[i]);
1396 send_to_emacs (emacs_socket, " ");
1397 continue;
1400 if (*argv[i] == '+')
1402 char *p = argv[i] + 1;
1403 while (isdigit ((unsigned char) *p) || *p == ':') p++;
1404 if (*p == 0)
1406 send_to_emacs (emacs_socket, "-position ");
1407 quote_argument (emacs_socket, argv[i]);
1408 send_to_emacs (emacs_socket, " ");
1409 continue;
1411 else
1412 relative = 1;
1414 else if (! file_name_absolute_p (argv[i]))
1415 relative = 1;
1417 send_to_emacs (emacs_socket, "-file ");
1418 if (relative)
1420 quote_argument (emacs_socket, cwd);
1421 send_to_emacs (emacs_socket, "/");
1423 quote_argument (emacs_socket, argv[i]);
1424 send_to_emacs (emacs_socket, " ");
1427 else
1429 if (!tty && !window_system)
1431 while ((str = fgets (string, BUFSIZ, stdin)))
1433 if (eval)
1434 send_to_emacs (emacs_socket, "-eval ");
1435 else
1436 send_to_emacs (emacs_socket, "-file ");
1437 quote_argument (emacs_socket, str);
1439 send_to_emacs (emacs_socket, " ");
1443 send_to_emacs (emacs_socket, "\n");
1445 /* Wait for an answer. */
1446 if (!eval && !tty && !nowait)
1448 printf ("Waiting for Emacs...");
1449 needlf = 2;
1451 fflush (stdout);
1452 fsync (1);
1454 /* Now, wait for an answer and print any messages. */
1455 while ((rl = recv (emacs_socket, string, BUFSIZ, 0)) > 0)
1457 char *p;
1458 string[rl] = '\0';
1460 p = string + strlen (string) - 1;
1461 while (p > string && *p == '\n')
1462 *p-- = 0;
1464 if (strprefix ("-good-version ", string))
1466 /* -good-version: The versions match. */
1468 else if (strprefix ("-emacs-pid ", string))
1470 /* -emacs-pid PID: The process id of the Emacs process. */
1471 emacs_pid = strtol (string + strlen ("-emacs-pid"), NULL, 10);
1473 else if (strprefix ("-window-system-unsupported ", string))
1475 /* -window-system-unsupported: Emacs was compiled without X
1476 support. Try again on the terminal. */
1477 window_system = 0;
1478 nowait = 0;
1479 tty = 1;
1480 goto retry;
1482 else if (strprefix ("-print ", string))
1484 /* -print STRING: Print STRING on the terminal. */
1485 str = unquote_argument (string + strlen ("-print "));
1486 if (needlf)
1487 printf ("\n");
1488 printf ("%s", str);
1489 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1491 else if (strprefix ("-error ", string))
1493 /* -error DESCRIPTION: Signal an error on the terminal. */
1494 str = unquote_argument (string + strlen ("-error "));
1495 if (needlf)
1496 printf ("\n");
1497 fprintf (stderr, "*ERROR*: %s", str);
1498 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1500 #ifndef WINDOWSNT
1501 else if (strprefix ("-suspend ", string))
1503 /* -suspend: Suspend this terminal, i.e., stop the process. */
1504 if (needlf)
1505 printf ("\n");
1506 needlf = 0;
1507 kill (0, SIGSTOP);
1509 #endif
1510 else
1512 /* Unknown command. */
1513 if (needlf)
1514 printf ("\n");
1515 printf ("*ERROR*: Unknown message: %s", string);
1516 needlf = string[0] == '\0' ? needlf : string[strlen (string) - 1] != '\n';
1520 if (needlf)
1521 printf ("\n");
1522 fflush (stdout);
1523 fsync (1);
1525 CLOSE_SOCKET (emacs_socket);
1526 return EXIT_SUCCESS;
1529 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
1532 #ifndef HAVE_STRERROR
1533 char *
1534 strerror (errnum)
1535 int errnum;
1537 extern char *sys_errlist[];
1538 extern int sys_nerr;
1540 if (errnum >= 0 && errnum < sys_nerr)
1541 return sys_errlist[errnum];
1542 return (char *) "Unknown error";
1545 #endif /* ! HAVE_STRERROR */
1547 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
1548 (do not change this comment) */
1550 /* emacsclient.c ends here */