]> code.delx.au - gnu-emacs/blob - lib-src/emacsclient.c
Merged from emacs@sv.gnu.org.
[gnu-emacs] / lib-src / emacsclient.c
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 Free Software Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
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.
11
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.
16
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. */
21
22
23 #define NO_SHORTNAMES
24
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
28
29 #ifdef WINDOWSNT
30
31 /* config.h defines these, which disables sockets altogether! */
32 # undef _WINSOCKAPI_
33 # undef _WINSOCK_H
34
35 # include <malloc.h>
36 # include <stdlib.h>
37 # include <windows.h>
38
39 # define NO_SOCKETS_IN_FILE_SYSTEM
40
41 # define HSOCKET SOCKET
42 # define CLOSE_SOCKET closesocket
43 # define INITIALIZE() (initialize_sockets ())
44
45 #else /* !WINDOWSNT */
46
47 # include <sys/types.h>
48
49 # ifdef HAVE_INET_SOCKETS
50 # include <netinet/in.h>
51 # endif
52
53 # define INVALID_SOCKET -1
54 # define HSOCKET int
55 # define CLOSE_SOCKET close
56 # define INITIALIZE()
57
58 #endif /* !WINDOWSNT */
59
60 #undef signal
61
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
69
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>
80
81 #include <signal.h>
82 #include <errno.h>
83
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
101
102
103 \f
104 char *getenv (), *getwd ();
105 char *(getcwd) ();
106
107 #ifndef VERSION
108 #define VERSION "unspecified"
109 #endif
110 \f
111 #define SEND_STRING(data) (send_to_emacs (s, (data)))
112 #define SEND_QUOTED(data) (quote_argument (s, (data)))
113
114 #ifndef EXIT_SUCCESS
115 #define EXIT_SUCCESS 0
116 #endif
117
118 #ifndef EXIT_FAILURE
119 #define EXIT_FAILURE 1
120 #endif
121
122 #ifndef FALSE
123 #define FALSE 0
124 #endif
125
126 #ifndef TRUE
127 #define TRUE 1
128 #endif
129
130 #ifndef NO_RETURN
131 #define NO_RETURN
132 #endif
133 \f
134 /* Name used to invoke this program. */
135 char *progname;
136
137 /* The first argument to main. */
138 int main_argc;
139
140 /* The second argument to main. */
141 char **main_argv;
142
143 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
144 int nowait = 0;
145
146 /* Nonzero means args are expressions to be evaluated. --eval. */
147 int eval = 0;
148
149 /* Nonzero means don't open a new frame. --current-frame. */
150 int current_frame = 0;
151
152 /* Nonzero means open a new graphical frame. */
153 int window_system = 0;
154
155 /* The display on which Emacs should work. --display. */
156 char *display = NULL;
157
158 /* Nonzero means open a new Emacs frame on the current terminal. */
159 int tty = 0;
160
161 /* If non-NULL, the name of an editor to fallback to if the server
162 is not running. --alternate-editor. */
163 const char *alternate_editor = NULL;
164
165 /* If non-NULL, the filename of the UNIX socket. */
166 char *socket_name = NULL;
167
168 /* If non-NULL, the filename of the authentication file. */
169 char *server_file = NULL;
170
171 /* PID of the Emacs server process. */
172 int emacs_pid = 0;
173
174 /* File handles for communicating with Emacs. */
175 FILE *out, *in;
176
177 void print_help_and_exit () NO_RETURN;
178
179 struct option longopts[] =
180 {
181 { "no-wait", no_argument, NULL, 'n' },
182 { "eval", no_argument, NULL, 'e' },
183 { "help", no_argument, NULL, 'H' },
184 { "version", no_argument, NULL, 'V' },
185 { "tty", no_argument, NULL, 't' },
186 { "current-frame", no_argument, NULL, 'c' },
187 { "alternate-editor", required_argument, NULL, 'a' },
188 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
189 { "socket-name", required_argument, NULL, 's' },
190 #endif
191 { "server-file", required_argument, NULL, 'f' },
192 { "display", required_argument, NULL, 'd' },
193 { 0, 0, 0, 0 }
194 };
195
196 \f
197 /* Like malloc but get fatal error if memory is exhausted. */
198
199 long *
200 xmalloc (size)
201 unsigned int size;
202 {
203 long *result = (long *) malloc (size);
204 if (result == NULL)
205 {
206 perror ("malloc");
207 exit (EXIT_FAILURE);
208 }
209 return result;
210 }
211
212 /* Like strdup but get a fatal error if memory is exhausted. */
213
214 char *
215 xstrdup (const char *s)
216 {
217 char *result = strdup (s);
218 if (result == NULL)
219 {
220 perror ("strdup");
221 exit (EXIT_FAILURE);
222 }
223 return result;
224 }
225
226 /* From sysdep.c */
227 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
228
229 /* Return the current working directory. Returns NULL on errors.
230 Any other returned value must be freed with free. This is used
231 only when get_current_dir_name is not defined on the system. */
232 char*
233 get_current_dir_name ()
234 {
235 char *buf;
236 char *pwd;
237 struct stat dotstat, pwdstat;
238 /* If PWD is accurate, use it instead of calling getwd. PWD is
239 sometimes a nicer name, and using it may avoid a fatal error if a
240 parent directory is searchable but not readable. */
241 if ((pwd = getenv ("PWD")) != 0
242 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
243 && stat (pwd, &pwdstat) == 0
244 && stat (".", &dotstat) == 0
245 && dotstat.st_ino == pwdstat.st_ino
246 && dotstat.st_dev == pwdstat.st_dev
247 #ifdef MAXPATHLEN
248 && strlen (pwd) < MAXPATHLEN
249 #endif
250 )
251 {
252 buf = (char *) xmalloc (strlen (pwd) + 1);
253 if (!buf)
254 return NULL;
255 strcpy (buf, pwd);
256 }
257 #ifdef HAVE_GETCWD
258 else
259 {
260 size_t buf_size = 1024;
261 buf = (char *) xmalloc (buf_size);
262 if (!buf)
263 return NULL;
264 for (;;)
265 {
266 if (getcwd (buf, buf_size) == buf)
267 break;
268 if (errno != ERANGE)
269 {
270 int tmp_errno = errno;
271 free (buf);
272 errno = tmp_errno;
273 return NULL;
274 }
275 buf_size *= 2;
276 buf = (char *) realloc (buf, buf_size);
277 if (!buf)
278 return NULL;
279 }
280 }
281 #else
282 else
283 {
284 /* We need MAXPATHLEN here. */
285 buf = (char *) xmalloc (MAXPATHLEN + 1);
286 if (!buf)
287 return NULL;
288 if (getwd (buf) == NULL)
289 {
290 int tmp_errno = errno;
291 free (buf);
292 errno = tmp_errno;
293 return NULL;
294 }
295 }
296 #endif
297 return buf;
298 }
299 #endif
300
301 /* Message functions. */
302
303 #ifdef WINDOWSNT
304 int
305 w32_window_app ()
306 {
307 static int window_app = -1;
308 char szTitle[MAX_PATH];
309
310 if (window_app < 0)
311 /* Checking for STDOUT does not work; it's a valid handle also in
312 nonconsole apps. Testing for the console title seems to work. */
313 window_app = (GetConsoleTitleA (szTitle, MAX_PATH) == 0);
314
315 return window_app;
316 }
317 #endif
318
319 void
320 message (int is_error, char *message, ...)
321 {
322 char msg [2048];
323 va_list args;
324
325 va_start (args, message);
326 vsprintf (msg, message, args);
327 va_end (args);
328
329 #ifdef WINDOWSNT
330 if (w32_window_app ())
331 {
332 if (is_error)
333 MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
334 else
335 MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
336 }
337 else
338 #endif
339 {
340 FILE *f = is_error ? stderr : stdout;
341
342 fputs (msg, f);
343 fflush (f);
344 }
345 }
346
347 /* Decode the options from argv and argc.
348 The global variable `optind' will say how many arguments we used up. */
349
350 void
351 decode_options (argc, argv)
352 int argc;
353 char **argv;
354 {
355 alternate_editor = getenv ("ALTERNATE_EDITOR");
356 display = getenv ("DISPLAY");
357 if (display && strlen (display) == 0)
358 display = NULL;
359
360 while (1)
361 {
362 int opt = getopt_long (argc, argv,
363 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
364 "VHnea:s:f:d:tc",
365 #else
366 "VHnea:f:d:tc",
367 #endif
368 longopts, 0);
369
370 if (opt == EOF)
371 break;
372
373 switch (opt)
374 {
375 case 0:
376 /* If getopt returns 0, then it has already processed a
377 long-named option. We should do nothing. */
378 break;
379
380 case 'a':
381 alternate_editor = optarg;
382 break;
383
384 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
385 case 's':
386 socket_name = optarg;
387 break;
388 #endif
389
390 case 'f':
391 server_file = optarg;
392 break;
393
394 case 'd':
395 display = optarg;
396 break;
397
398 case 'n':
399 nowait = 1;
400 break;
401
402 case 'e':
403 eval = 1;
404 break;
405
406 case 'V':
407 message (FALSE, "emacsclient %s\n", VERSION);
408 exit (EXIT_SUCCESS);
409 break;
410
411 case 't':
412 tty = 1;
413 break;
414
415 case 'c':
416 current_frame = 1;
417 break;
418
419 case 'H':
420 print_help_and_exit ();
421 break;
422
423 default:
424 message (TRUE, "Try `%s --help' for more information\n", progname);
425 exit (EXIT_FAILURE);
426 break;
427 }
428 }
429
430 if (!tty && display)
431 window_system = 1;
432 else
433 tty = 1;
434
435 /* --no-wait implies --current-frame on ttys when there are file
436 arguments or expressions given. */
437 if (nowait && tty && argc - optind > 0)
438 current_frame = 1;
439
440 if (current_frame)
441 {
442 tty = 0;
443 window_system = 0;
444 }
445
446 if (tty)
447 window_system = 0;
448 }
449
450 \f
451 void
452 print_help_and_exit ()
453 {
454 message (FALSE,
455 "Usage: %s [OPTIONS] FILE...\n\
456 Tell the Emacs server to visit the specified files.\n\
457 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
458 \n\
459 The following OPTIONS are accepted:\n\
460 -V, --version Just print version info and return\n\
461 -H, --help Print this usage information message\n\
462 -t, --tty Open a new Emacs frame on the current terminal\n\
463 -c, --current-frame Do not create a new frame; use the current Emacs frame\n\
464 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
465 -n, --no-wait Don't wait for the server to return\n\
466 -d, --display=DISPLAY Visit the file in the given display\n"
467 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
468 "-s, --socket-name=FILENAME\n\
469 Set filename of the UNIX socket for communication\n"
470 #endif
471 "-f, --server-file=FILENAME\n\
472 Set filename of the TCP authentication file\n\
473 -a, --alternate-editor=EDITOR\n\
474 Editor to fallback to if the server is not running\n\
475 \n\
476 Report bugs to bug-gnu-emacs@gnu.org.\n", progname);
477 exit (EXIT_SUCCESS);
478 }
479
480 /*
481 Try to run a different command, or --if no alternate editor is
482 defined-- exit with an errorcode.
483 */
484 void
485 fail (void)
486 {
487 if (alternate_editor)
488 {
489 int i = optind - 1;
490
491 execvp (alternate_editor, main_argv + i);
492 message (TRUE, "%s: error executing alternate editor \"%s\"\n",
493 progname, alternate_editor);
494 }
495 exit (EXIT_FAILURE);
496 }
497
498 \f
499 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
500
501 int
502 main (argc, argv)
503 int argc;
504 char **argv;
505 {
506 main_argc = argc;
507 main_argv = argv;
508 progname = argv[0];
509 message (TRUE, "%s: Sorry, the Emacs server is supported only\n"
510 "on systems with Berkeley sockets.\n",
511 argv[0]);
512 fail ();
513 }
514
515 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
516
517 #ifdef WINDOWSNT
518 # include <winsock2.h>
519 #else
520 # include <sys/types.h>
521 # include <sys/socket.h>
522 # include <sys/un.h>
523 # include <sys/stat.h>
524 # include <errno.h>
525 #endif
526
527 #define AUTH_KEY_LENGTH 64
528 #define SEND_BUFFER_SIZE 4096
529
530 extern char *strerror ();
531 extern int errno;
532
533 /* Buffer to accumulate data to send in TCP connections. */
534 char send_buffer[SEND_BUFFER_SIZE + 1];
535 int sblen = 0; /* Fill pointer for the send buffer. */
536
537 /* Let's send the data to Emacs when either
538 - the data ends in "\n", or
539 - the buffer is full (but this shouldn't happen)
540 Otherwise, we just accumulate it. */
541 void
542 send_to_emacs (s, data)
543 HSOCKET s;
544 char *data;
545 {
546 while (data)
547 {
548 int dlen = strlen (data);
549 if (dlen + sblen >= SEND_BUFFER_SIZE)
550 {
551 int part = SEND_BUFFER_SIZE - sblen;
552 strncpy (&send_buffer[sblen], data, part);
553 data += part;
554 sblen = SEND_BUFFER_SIZE;
555 }
556 else if (dlen)
557 {
558 strcpy (&send_buffer[sblen], data);
559 data = NULL;
560 sblen += dlen;
561 }
562 else
563 break;
564
565 if (sblen == SEND_BUFFER_SIZE
566 || (sblen > 0 && send_buffer[sblen-1] == '\n'))
567 {
568 int sent = send (s, send_buffer, sblen, 0);
569 if (sent != sblen)
570 strcpy (send_buffer, &send_buffer[sent]);
571 sblen -= sent;
572 }
573 }
574 }
575
576 \f
577 /* In STR, insert a & before each &, each space, each newline, and
578 any initial -. Change spaces to underscores, too, so that the
579 return value never contains a space.
580
581 Does not change the string. Outputs the result to STREAM. */
582 void
583 quote_argument (s, str)
584 HSOCKET s;
585 char *str;
586 {
587 char *copy = (char *) xmalloc (strlen (str) * 2 + 1);
588 char *p, *q;
589
590 p = str;
591 q = copy;
592 while (*p)
593 {
594 if (*p == ' ')
595 {
596 *q++ = '&';
597 *q++ = '_';
598 p++;
599 }
600 else if (*p == '\n')
601 {
602 *q++ = '&';
603 *q++ = 'n';
604 p++;
605 }
606 else
607 {
608 if (*p == '&' || (*p == '-' && p == str))
609 *q++ = '&';
610 *q++ = *p++;
611 }
612 }
613 *q++ = 0;
614
615 SEND_STRING (copy);
616
617 free (copy);
618 }
619
620
621 /* The inverse of quote_argument. Removes quoting in string STR by
622 modifying the string in place. Returns STR. */
623
624 char *
625 unquote_argument (str)
626 char *str;
627 {
628 char *p, *q;
629
630 if (! str)
631 return str;
632
633 p = str;
634 q = str;
635 while (*p)
636 {
637 if (*p == '&')
638 {
639 p++;
640 if (*p == '&')
641 *p = '&';
642 else if (*p == '_')
643 *p = ' ';
644 else if (*p == 'n')
645 *p = '\n';
646 else if (*p == '-')
647 *p = '-';
648 }
649 *q++ = *p++;
650 }
651 *q = 0;
652 return str;
653 }
654
655 \f
656 int
657 file_name_absolute_p (filename)
658 const unsigned char *filename;
659 {
660 /* Sanity check, it shouldn't happen. */
661 if (! filename) return FALSE;
662
663 /* /xxx is always an absolute path. */
664 if (filename[0] == '/') return TRUE;
665
666 /* Empty filenames (which shouldn't happen) are relative. */
667 if (filename[0] == '\0') return FALSE;
668
669 #ifdef WINDOWSNT
670 /* X:\xxx is always absolute; X:xxx is an error and will fail. */
671 if (isalpha (filename[0])
672 && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
673 return TRUE;
674
675 /* Both \xxx and \\xxx\yyy are absolute. */
676 if (filename[0] == '\\') return TRUE;
677 #endif
678
679 return FALSE;
680 }
681
682 #ifdef WINDOWSNT
683 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
684 void
685 __cdecl close_winsock ()
686 {
687 WSACleanup ();
688 }
689
690 /* Initialize the WinSock2 library. */
691 void
692 initialize_sockets ()
693 {
694 WSADATA wsaData;
695
696 if (WSAStartup (MAKEWORD (2, 0), &wsaData))
697 {
698 message (TRUE, "%s: error initializing WinSock2", progname);
699 exit (EXIT_FAILURE);
700 }
701
702 atexit (close_winsock);
703 }
704 #endif /* WINDOWSNT */
705
706 \f
707 #ifdef WINDOWSNT
708
709 /*
710 execvp wrapper for Windows. Quotes arguments with embedded spaces.
711
712 This is necessary due to the broken implementation of exec* routines in
713 the Microsoft libraries: they concatenate the arguments together without
714 quoting special characters, and pass the result to CreateProcess, with
715 predictably bad results. By contrast, Posix execvp passes the arguments
716 directly into the argv array of the child process.
717 */
718 int
719 w32_execvp (path, argv)
720 char *path;
721 char **argv;
722 {
723 int i;
724
725 /* Required to allow a .BAT script as alternate editor. */
726 argv[0] = (char *) alternate_editor;
727
728 for (i = 0; argv[i]; i++)
729 if (strchr (argv[i], ' '))
730 {
731 char *quoted = alloca (strlen (argv[i]) + 3);
732 sprintf (quoted, "\"%s\"", argv[i]);
733 argv[i] = quoted;
734 }
735
736 return execvp (path, argv);
737 }
738
739 #undef execvp
740 #define execvp w32_execvp
741
742 #endif /* WINDOWSNT */
743
744 /*
745 * Read the information needed to set up a TCP comm channel with
746 * the Emacs server: host, port, pid and authentication string.
747 */
748 int
749 get_server_config (server, authentication)
750 struct sockaddr_in *server;
751 char *authentication;
752 {
753 char dotted[32];
754 char *port;
755 char *pid;
756 FILE *config = NULL;
757
758 if (file_name_absolute_p (server_file))
759 config = fopen (server_file, "rb");
760 else
761 {
762 char *home = getenv ("HOME");
763
764 if (home)
765 {
766 char *path = alloca (32 + strlen (home) + strlen (server_file));
767 sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
768 config = fopen (path, "rb");
769 }
770 #ifdef WINDOWSNT
771 if (!config && (home = getenv ("APPDATA")))
772 {
773 char *path = alloca (32 + strlen (home) + strlen (server_file));
774 sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
775 config = fopen (path, "rb");
776 }
777 #endif
778 }
779
780 if (! config)
781 return FALSE;
782
783 if (fgets (dotted, sizeof dotted, config)
784 && (port = strchr (dotted, ':'))
785 && (pid = strchr (port, ' ')))
786 {
787 *port++ = '\0';
788 *pid++ = '\0';
789 }
790 else
791 {
792 message (TRUE, "%s: invalid configuration info", progname);
793 exit (EXIT_FAILURE);
794 }
795
796 server->sin_family = AF_INET;
797 server->sin_addr.s_addr = inet_addr (dotted);
798 server->sin_port = htons (atoi (port));
799
800 if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
801 {
802 message (TRUE, "%s: cannot read authentication info", progname);
803 exit (EXIT_FAILURE);
804 }
805
806 fclose (config);
807
808 emacs_pid = atoi (pid);
809
810 return TRUE;
811 }
812
813 HSOCKET
814 set_tcp_socket ()
815 {
816 HSOCKET s;
817 struct sockaddr_in server;
818 struct linger l_arg = {1, 1};
819 char auth_string[AUTH_KEY_LENGTH + 1];
820
821 if (! get_server_config (&server, auth_string))
822 return INVALID_SOCKET;
823
824 if (server.sin_addr.s_addr != inet_addr ("127.0.0.1"))
825 message (FALSE, "%s: connected to remote socket at %s\n",
826 progname, inet_ntoa (server.sin_addr));
827
828 /*
829 * Open up an AF_INET socket
830 */
831 if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
832 {
833 message (TRUE, "%s: socket: %s\n", progname, strerror (errno));
834 return INVALID_SOCKET;
835 }
836
837 /*
838 * Set up the socket
839 */
840 if (connect (s, (struct sockaddr *) &server, sizeof server) < 0)
841 {
842 message (TRUE, "%s: connect: %s\n", progname, strerror (errno));
843 return INVALID_SOCKET;
844 }
845
846 setsockopt (s, SOL_SOCKET, SO_LINGER, (char *) &l_arg, sizeof l_arg);
847
848 /*
849 * Send the authentication
850 */
851 auth_string[AUTH_KEY_LENGTH] = '\0';
852
853 SEND_STRING ("-auth ");
854 SEND_STRING (auth_string);
855 SEND_STRING ("\n");
856
857 return s;
858 }
859
860 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
861
862 /* Three possibilities:
863 2 - can't be `stat'ed (sets errno)
864 1 - isn't owned by us
865 0 - success: none of the above */
866
867 static int
868 socket_status (socket_name)
869 char *socket_name;
870 {
871 struct stat statbfr;
872
873 if (stat (socket_name, &statbfr) == -1)
874 return 2;
875
876 if (statbfr.st_uid != geteuid ())
877 return 1;
878
879 return 0;
880 }
881
882 \f
883 /* A signal handler that passes the signal to the Emacs process.
884 Useful for SIGWINCH. */
885
886 SIGTYPE
887 pass_signal_to_emacs (int signalnum)
888 {
889 int old_errno = errno;
890
891 if (emacs_pid)
892 kill (emacs_pid, signalnum);
893
894 signal (signalnum, pass_signal_to_emacs);
895 errno = old_errno;
896 }
897
898 /* Signal handler for SIGCONT; notify the Emacs process that it can
899 now resume our tty frame. */
900
901 SIGTYPE
902 handle_sigcont (int signalnum)
903 {
904 int old_errno = errno;
905
906 if (tcgetpgrp (1) == getpgrp ())
907 {
908 /* We are in the foreground. */
909 fprintf (out, "-resume \n");
910 fflush (out);
911 fsync (fileno (out));
912 }
913 else
914 {
915 /* We are in the background; cancel the continue. */
916 kill (getpid (), SIGSTOP);
917 }
918
919 signal (signalnum, handle_sigcont);
920 errno = old_errno;
921 }
922
923 /* Signal handler for SIGTSTP; notify the Emacs process that we are
924 going to sleep. Normally the suspend is initiated by Emacs via
925 server-handle-suspend-tty, but if the server gets out of sync with
926 reality, we may get a SIGTSTP on C-z. Handling this signal and
927 notifying Emacs about it should get things under control again. */
928
929 SIGTYPE
930 handle_sigtstp (int signalnum)
931 {
932 int old_errno = errno;
933 sigset_t set;
934
935 if (out)
936 {
937 fprintf (out, "-suspend \n");
938 fflush (out);
939 fsync (fileno (out));
940 }
941
942 /* Unblock this signal and call the default handler by temprarily
943 changing the handler and resignalling. */
944 sigprocmask (SIG_BLOCK, NULL, &set);
945 sigdelset (&set, signalnum);
946 signal (signalnum, SIG_DFL);
947 kill (getpid (), signalnum);
948 sigprocmask (SIG_SETMASK, &set, NULL); /* Let's the above signal through. */
949 signal (signalnum, handle_sigtstp);
950
951 errno = old_errno;
952 }
953
954 /* Set up signal handlers before opening a frame on the current tty. */
955
956 void
957 init_signals (void)
958 {
959 /* Set up signal handlers. */
960 signal (SIGWINCH, pass_signal_to_emacs);
961
962 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
963 deciding which terminal the signal came from. C-g is now a
964 normal input event on secondary terminals. */
965 #if 0
966 signal (SIGINT, pass_signal_to_emacs);
967 signal (SIGQUIT, pass_signal_to_emacs);
968 #endif
969
970 signal (SIGCONT, handle_sigcont);
971 signal (SIGTSTP, handle_sigtstp);
972 signal (SIGTTOU, handle_sigtstp);
973 }
974
975
976
977 /* Returns 1 if PREFIX is a prefix of STRING. */
978 static int
979 strprefix (char *prefix, char *string)
980 {
981 int i;
982 if (! prefix)
983 return 1;
984
985 if (!string)
986 return 0;
987
988 for (i = 0; prefix[i]; i++)
989 if (!string[i] || string[i] != prefix[i])
990 return 0;
991 return 1;
992 }
993
994
995 HSOCKET
996 set_local_socket ()
997 {
998 HSOCKET s;
999 struct sockaddr_un server;
1000
1001 /*
1002 * Open up an AF_UNIX socket in this person's home directory
1003 */
1004
1005 if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
1006 {
1007 message (TRUE, "%s: socket: %s\n", progname, strerror (errno));
1008 return INVALID_SOCKET;
1009 }
1010
1011 server.sun_family = AF_UNIX;
1012
1013 {
1014 int sock_status = 0;
1015 int default_sock = !socket_name;
1016 int saved_errno = 0;
1017
1018 char *server_name = "server";
1019
1020 if (socket_name && !index (socket_name, '/') && !index (socket_name, '\\'))
1021 { /* socket_name is a file name component. */
1022 server_name = socket_name;
1023 socket_name = NULL;
1024 default_sock = 1; /* Try both UIDs. */
1025 }
1026
1027 if (default_sock)
1028 {
1029 socket_name = alloca (100 + strlen (server_name));
1030 sprintf (socket_name, "/tmp/emacs%d/%s",
1031 (int) geteuid (), server_name);
1032 }
1033
1034 if (strlen (socket_name) < sizeof (server.sun_path))
1035 strcpy (server.sun_path, socket_name);
1036 else
1037 {
1038 message (TRUE, "%s: socket-name %s too long",
1039 progname, socket_name);
1040 fail ();
1041 }
1042
1043 /* See if the socket exists, and if it's owned by us. */
1044 sock_status = socket_status (server.sun_path);
1045 saved_errno = errno;
1046 if (sock_status && default_sock)
1047 {
1048 /* Failing that, see if LOGNAME or USER exist and differ from
1049 our euid. If so, look for a socket based on the UID
1050 associated with the name. This is reminiscent of the logic
1051 that init_editfns uses to set the global Vuser_full_name. */
1052
1053 char *user_name = (char *) getenv ("LOGNAME");
1054
1055 if (!user_name)
1056 user_name = (char *) getenv ("USER");
1057
1058 if (user_name)
1059 {
1060 struct passwd *pw = getpwnam (user_name);
1061
1062 if (pw && (pw->pw_uid != geteuid ()))
1063 {
1064 /* We're running under su, apparently. */
1065 socket_name = alloca (100 + strlen (server_name));
1066 sprintf (socket_name, "/tmp/emacs%d/%s",
1067 (int) pw->pw_uid, server_name);
1068
1069 if (strlen (socket_name) < sizeof (server.sun_path))
1070 strcpy (server.sun_path, socket_name);
1071 else
1072 {
1073 message (TRUE, "%s: socket-name %s too long",
1074 progname, socket_name);
1075 exit (EXIT_FAILURE);
1076 }
1077
1078 sock_status = socket_status (server.sun_path);
1079 saved_errno = errno;
1080 }
1081 else
1082 errno = saved_errno;
1083 }
1084 }
1085
1086 switch (sock_status)
1087 {
1088 case 1:
1089 /* There's a socket, but it isn't owned by us. This is OK if
1090 we are root. */
1091 if (0 != geteuid ())
1092 {
1093 message (TRUE, "%s: Invalid socket owner\n", progname);
1094 return INVALID_SOCKET;
1095 }
1096 break;
1097
1098 case 2:
1099 /* `stat' failed */
1100 if (saved_errno == ENOENT)
1101 message (TRUE,
1102 "%s: can't find socket; have you started the server?\n\
1103 To start the server in Emacs, type \"M-x server-start\".\n",
1104 progname);
1105 else
1106 message (TRUE, "%s: can't stat %s: %s\n",
1107 progname, server.sun_path, strerror (saved_errno));
1108 return INVALID_SOCKET;
1109 }
1110 }
1111
1112 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
1113 < 0)
1114 {
1115 message (TRUE, "%s: connect: %s\n", progname, strerror (errno));
1116 return INVALID_SOCKET;
1117 }
1118
1119 return s;
1120 }
1121 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1122
1123 HSOCKET
1124 set_socket ()
1125 {
1126 HSOCKET s;
1127
1128 INITIALIZE ();
1129
1130 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1131 /* Explicit --socket-name argument. */
1132 if (socket_name)
1133 {
1134 s = set_local_socket ();
1135 if ((s != INVALID_SOCKET) || alternate_editor)
1136 return s;
1137 message (TRUE, "%s: error accessing socket \"%s\"",
1138 progname, socket_name);
1139 exit (EXIT_FAILURE);
1140 }
1141 #endif
1142
1143 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1144 if (!server_file)
1145 server_file = getenv ("EMACS_SERVER_FILE");
1146
1147 if (server_file)
1148 {
1149 s = set_tcp_socket ();
1150 if ((s != INVALID_SOCKET) || alternate_editor)
1151 return s;
1152
1153 message (TRUE, "%s: error accessing server file \"%s\"",
1154 progname, server_file);
1155 exit (EXIT_FAILURE);
1156 }
1157
1158 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1159 /* Implicit local socket. */
1160 s = set_local_socket ();
1161 if (s != INVALID_SOCKET)
1162 return s;
1163 #endif
1164
1165 /* Implicit server file. */
1166 server_file = "server";
1167 s = set_tcp_socket ();
1168 if ((s != INVALID_SOCKET) || alternate_editor)
1169 return s;
1170
1171 /* No implicit or explicit socket, and no alternate editor. */
1172 message (TRUE, "%s: No socket or alternate editor. Please use:\n\n"
1173 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1174 "\t--socket-name\n"
1175 #endif
1176 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1177 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1178 progname);
1179 exit (EXIT_FAILURE);
1180 }
1181
1182 #ifdef WINDOWSNT
1183 FARPROC set_fg; /* Pointer to AllowSetForegroundWindow. */
1184 FARPROC get_wc; /* Pointer to RealGetWindowClassA. */
1185
1186 BOOL CALLBACK
1187 w32_find_emacs_process (hWnd, lParam)
1188 HWND hWnd;
1189 LPARAM lParam;
1190 {
1191 DWORD pid;
1192 char class[6];
1193
1194 /* Reject any window not of class "Emacs". */
1195 if (! get_wc (hWnd, class, sizeof (class))
1196 || strcmp (class, "Emacs"))
1197 return TRUE;
1198
1199 /* We only need the process id, not the thread id. */
1200 (void) GetWindowThreadProcessId (hWnd, &pid);
1201
1202 /* Not the one we're looking for. */
1203 if (pid != (DWORD) emacs_pid) return TRUE;
1204
1205 /* OK, let's raise it. */
1206 set_fg (emacs_pid);
1207
1208 /* Stop enumeration. */
1209 return FALSE;
1210 }
1211
1212 /*
1213 * Search for a window of class "Emacs" and owned by a process with
1214 * process id = emacs_pid. If found, allow it to grab the focus.
1215 */
1216 void
1217 w32_give_focus ()
1218 {
1219 HMODULE hUser32;
1220
1221 /* It should'nt happen when dealing with TCP sockets. */
1222 if (!emacs_pid) return;
1223
1224 if (!(hUser32 = LoadLibrary ("user32.dll"))) return;
1225
1226 /* Modern Windows restrict which processes can set the foreground window.
1227 emacsclient can allow Emacs to grab the focus by calling the function
1228 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1229 NT) lack this function, so we have to check its availability. */
1230 if ((set_fg = GetProcAddress (hUser32, "AllowSetForegroundWindow"))
1231 && (get_wc = GetProcAddress (hUser32, "RealGetWindowClassA")))
1232 EnumWindows (w32_find_emacs_process, (LPARAM) 0);
1233
1234 FreeLibrary (hUser32);
1235 }
1236 #endif
1237
1238 int
1239 main (argc, argv)
1240 int argc;
1241 char **argv;
1242 {
1243 HSOCKET s;
1244 int i, rl, needlf = 0;
1245 char *cwd, *str;
1246 char string[BUFSIZ+1];
1247
1248 main_argc = argc;
1249 main_argv = argv;
1250 progname = argv[0];
1251
1252 /* Process options. */
1253 decode_options (argc, argv);
1254
1255 if ((argc - optind < 1) && !eval && !tty && !window_system)
1256 {
1257 message (TRUE, "%s: file name or argument required\n"
1258 "Try `%s --help' for more information\n",
1259 progname, progname);
1260 exit (EXIT_FAILURE);
1261 }
1262
1263 if ((s = set_socket ()) == INVALID_SOCKET)
1264 fail ();
1265
1266
1267 cwd = get_current_dir_name ();
1268 if (cwd == 0)
1269 {
1270 /* getwd puts message in STRING if it fails. */
1271 message (TRUE, "%s: %s\n", progname,
1272 "Cannot get current working directory");
1273 fail ();
1274 }
1275
1276 #ifdef WINDOWSNT
1277 w32_give_focus ();
1278 #endif
1279
1280 /* First of all, send our version number for verification. */
1281 SEND_STRING ("-version ");
1282 SEND_STRING (VERSION);
1283 SEND_STRING (" ");
1284
1285 /* Send over our environment. */
1286 if (!current_frame)
1287 {
1288 extern char **environ;
1289 int i;
1290 for (i = 0; environ[i]; i++)
1291 {
1292 char *name = xstrdup (environ[i]);
1293 char *value = strchr (name, '=');
1294 SEND_STRING ("-env ");
1295 SEND_QUOTED (environ[i]);
1296 SEND_STRING (" ");
1297 }
1298 }
1299
1300 /* Send over our current directory. */
1301 if (!current_frame)
1302 {
1303 SEND_STRING ("-dir ");
1304 SEND_QUOTED (cwd);
1305 SEND_STRING ("/");
1306 SEND_STRING (" ");
1307 }
1308
1309 retry:
1310 if (nowait)
1311 SEND_STRING ("-nowait ");
1312
1313 if (current_frame)
1314 SEND_STRING ("-current-frame ");
1315
1316 if (display)
1317 {
1318 SEND_STRING ("-display ");
1319 SEND_QUOTED (display);
1320 SEND_STRING (" ");
1321 }
1322
1323 if (tty)
1324 {
1325 char *tty_name = ttyname (fileno (stdin));
1326 char *type = getenv ("TERM");
1327
1328 if (! tty_name)
1329 {
1330 message (TRUE, "%s: could not get terminal name\n", progname);
1331 fail ();
1332 }
1333
1334 if (! type)
1335 {
1336 message (TRUE, "%s: please set the TERM variable to your terminal type\n",
1337 progname);
1338 fail ();
1339 }
1340
1341 if (! strcmp (type, "eterm"))
1342 {
1343 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1344 message (TRUE, "%s: opening a frame in an Emacs term buffer"
1345 " is not supported\n", progname);
1346 fail ();
1347 }
1348
1349 init_signals ();
1350
1351 SEND_STRING ("-tty ");
1352 SEND_QUOTED (tty_name);
1353 SEND_STRING (" ");
1354 SEND_QUOTED (type);
1355 SEND_STRING (" ");
1356 }
1357
1358 if (window_system)
1359 SEND_STRING ("-window-system ");
1360
1361 if ((argc - optind > 0))
1362 {
1363 for (i = optind; i < argc; i++)
1364 {
1365 int relative = 0;
1366
1367 if (eval)
1368 {
1369 /* Don't prepend cwd or anything like that. */
1370 SEND_STRING ("-eval ");
1371 SEND_QUOTED (argv[i]);
1372 SEND_STRING (" ");
1373 continue;
1374 }
1375
1376 if (*argv[i] == '+')
1377 {
1378 char *p = argv[i] + 1;
1379 while (isdigit ((unsigned char) *p) || *p == ':') p++;
1380 if (*p == 0)
1381 {
1382 SEND_STRING ("-position ");
1383 SEND_QUOTED (argv[i]);
1384 SEND_STRING (" ");
1385 continue;
1386 }
1387 else
1388 relative = 1;
1389 }
1390 else if (! file_name_absolute_p (argv[i]))
1391 relative = 1;
1392
1393 SEND_STRING ("-file ");
1394 if (relative)
1395 {
1396 SEND_QUOTED (cwd);
1397 SEND_STRING ("/");
1398 }
1399 SEND_QUOTED (argv[i]);
1400 SEND_STRING (" ");
1401 }
1402 }
1403 else
1404 {
1405 if (!tty && !window_system)
1406 {
1407 while ((str = fgets (string, BUFSIZ, stdin)))
1408 {
1409 if (eval)
1410 SEND_STRING ("-eval ");
1411 else
1412 SEND_STRING ("-file ");
1413 SEND_QUOTED (out);
1414 }
1415 SEND_STRING (" ");
1416 }
1417 }
1418
1419 SEND_STRING ("\n");
1420
1421 /* Wait for an answer. */
1422 if (!eval && !tty && !nowait)
1423 {
1424 printf ("Waiting for Emacs...");
1425 needlf = 2;
1426 }
1427 fflush (stdout);
1428 fsync (1);
1429
1430 /* Now, wait for an answer and print any messages. */
1431 while ((rl = recv (s, string, BUFSIZ, 0)) > 0)
1432 {
1433 char *p;
1434 string[rl] = '\0';
1435
1436 p = string + strlen (string) - 1;
1437 while (p > string && *p == '\n')
1438 *p-- = 0;
1439
1440 if (strprefix ("-good-version ", string))
1441 {
1442 /* -good-version: The versions match. */
1443 }
1444 else if (strprefix ("-emacs-pid ", string))
1445 {
1446 /* -emacs-pid PID: The process id of the Emacs process. */
1447 emacs_pid = strtol (string + strlen ("-emacs-pid"), NULL, 10);
1448 }
1449 else if (strprefix ("-window-system-unsupported ", string))
1450 {
1451 /* -window-system-unsupported: Emacs was compiled without X
1452 support. Try again on the terminal. */
1453 window_system = 0;
1454 nowait = 0;
1455 tty = 1;
1456 goto retry;
1457 }
1458 else if (strprefix ("-print ", string))
1459 {
1460 /* -print STRING: Print STRING on the terminal. */
1461 str = unquote_argument (string + strlen ("-print "));
1462 if (needlf)
1463 printf ("\n");
1464 printf ("%s", str);
1465 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1466 }
1467 else if (strprefix ("-error ", string))
1468 {
1469 /* -error DESCRIPTION: Signal an error on the terminal. */
1470 str = unquote_argument (string + strlen ("-error "));
1471 if (needlf)
1472 printf ("\n");
1473 fprintf (stderr, "*ERROR*: %s", str);
1474 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1475 }
1476 else if (strprefix ("-suspend ", str))
1477 {
1478 /* -suspend: Suspend this terminal, i.e., stop the process. */
1479 if (needlf)
1480 printf ("\n");
1481 needlf = 0;
1482 kill (0, SIGSTOP);
1483 }
1484 else
1485 {
1486 /* Unknown command. */
1487 if (needlf)
1488 printf ("\n");
1489 printf ("*ERROR*: Unknown message: %s", string);
1490 needlf = string[0] == '\0' ? needlf : string[strlen (string) - 1] != '\n';
1491 }
1492 }
1493
1494 if (needlf)
1495 printf ("\n");
1496 fflush (stdout);
1497 fsync (1);
1498
1499 CLOSE_SOCKET (s);
1500 return EXIT_SUCCESS;
1501 }
1502
1503 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
1504
1505 \f
1506 #ifndef HAVE_STRERROR
1507 char *
1508 strerror (errnum)
1509 int errnum;
1510 {
1511 extern char *sys_errlist[];
1512 extern int sys_nerr;
1513
1514 if (errnum >= 0 && errnum < sys_nerr)
1515 return sys_errlist[errnum];
1516 return (char *) "Unknown error";
1517 }
1518
1519 #endif /* ! HAVE_STRERROR */
1520
1521 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
1522 (do not change this comment) */
1523
1524 /* emacsclient.c ends here */