]> 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 /* Socket used to communicate with the Emacs server process. */
175 HSOCKET s;
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 SEND_STRING ("-resume \n");
910 }
911 else
912 {
913 /* We are in the background; cancel the continue. */
914 kill (getpid (), SIGSTOP);
915 }
916
917 signal (signalnum, handle_sigcont);
918 errno = old_errno;
919 }
920
921 /* Signal handler for SIGTSTP; notify the Emacs process that we are
922 going to sleep. Normally the suspend is initiated by Emacs via
923 server-handle-suspend-tty, but if the server gets out of sync with
924 reality, we may get a SIGTSTP on C-z. Handling this signal and
925 notifying Emacs about it should get things under control again. */
926
927 SIGTYPE
928 handle_sigtstp (int signalnum)
929 {
930 int old_errno = errno;
931 sigset_t set;
932
933 if (s)
934 SEND_STRING ("-suspend \n");
935
936 /* Unblock this signal and call the default handler by temprarily
937 changing the handler and resignalling. */
938 sigprocmask (SIG_BLOCK, NULL, &set);
939 sigdelset (&set, signalnum);
940 signal (signalnum, SIG_DFL);
941 kill (getpid (), signalnum);
942 sigprocmask (SIG_SETMASK, &set, NULL); /* Let's the above signal through. */
943 signal (signalnum, handle_sigtstp);
944
945 errno = old_errno;
946 }
947
948 /* Set up signal handlers before opening a frame on the current tty. */
949
950 void
951 init_signals (void)
952 {
953 /* Set up signal handlers. */
954 signal (SIGWINCH, pass_signal_to_emacs);
955
956 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
957 deciding which terminal the signal came from. C-g is now a
958 normal input event on secondary terminals. */
959 #if 0
960 signal (SIGINT, pass_signal_to_emacs);
961 signal (SIGQUIT, pass_signal_to_emacs);
962 #endif
963
964 signal (SIGCONT, handle_sigcont);
965 signal (SIGTSTP, handle_sigtstp);
966 signal (SIGTTOU, handle_sigtstp);
967 }
968
969
970
971 /* Returns 1 if PREFIX is a prefix of STRING. */
972 static int
973 strprefix (char *prefix, char *string)
974 {
975 int i;
976 if (! prefix)
977 return 1;
978
979 if (!string)
980 return 0;
981
982 for (i = 0; prefix[i]; i++)
983 if (!string[i] || string[i] != prefix[i])
984 return 0;
985 return 1;
986 }
987
988
989 HSOCKET
990 set_local_socket ()
991 {
992 HSOCKET s;
993 struct sockaddr_un server;
994
995 /*
996 * Open up an AF_UNIX socket in this person's home directory
997 */
998
999 if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
1000 {
1001 message (TRUE, "%s: socket: %s\n", progname, strerror (errno));
1002 return INVALID_SOCKET;
1003 }
1004
1005 server.sun_family = AF_UNIX;
1006
1007 {
1008 int sock_status = 0;
1009 int default_sock = !socket_name;
1010 int saved_errno = 0;
1011
1012 char *server_name = "server";
1013
1014 if (socket_name && !index (socket_name, '/') && !index (socket_name, '\\'))
1015 { /* socket_name is a file name component. */
1016 server_name = socket_name;
1017 socket_name = NULL;
1018 default_sock = 1; /* Try both UIDs. */
1019 }
1020
1021 if (default_sock)
1022 {
1023 socket_name = alloca (100 + strlen (server_name));
1024 sprintf (socket_name, "/tmp/emacs%d/%s",
1025 (int) geteuid (), server_name);
1026 }
1027
1028 if (strlen (socket_name) < sizeof (server.sun_path))
1029 strcpy (server.sun_path, socket_name);
1030 else
1031 {
1032 message (TRUE, "%s: socket-name %s too long",
1033 progname, socket_name);
1034 fail ();
1035 }
1036
1037 /* See if the socket exists, and if it's owned by us. */
1038 sock_status = socket_status (server.sun_path);
1039 saved_errno = errno;
1040 if (sock_status && default_sock)
1041 {
1042 /* Failing that, see if LOGNAME or USER exist and differ from
1043 our euid. If so, look for a socket based on the UID
1044 associated with the name. This is reminiscent of the logic
1045 that init_editfns uses to set the global Vuser_full_name. */
1046
1047 char *user_name = (char *) getenv ("LOGNAME");
1048
1049 if (!user_name)
1050 user_name = (char *) getenv ("USER");
1051
1052 if (user_name)
1053 {
1054 struct passwd *pw = getpwnam (user_name);
1055
1056 if (pw && (pw->pw_uid != geteuid ()))
1057 {
1058 /* We're running under su, apparently. */
1059 socket_name = alloca (100 + strlen (server_name));
1060 sprintf (socket_name, "/tmp/emacs%d/%s",
1061 (int) pw->pw_uid, server_name);
1062
1063 if (strlen (socket_name) < sizeof (server.sun_path))
1064 strcpy (server.sun_path, socket_name);
1065 else
1066 {
1067 message (TRUE, "%s: socket-name %s too long",
1068 progname, socket_name);
1069 exit (EXIT_FAILURE);
1070 }
1071
1072 sock_status = socket_status (server.sun_path);
1073 saved_errno = errno;
1074 }
1075 else
1076 errno = saved_errno;
1077 }
1078 }
1079
1080 switch (sock_status)
1081 {
1082 case 1:
1083 /* There's a socket, but it isn't owned by us. This is OK if
1084 we are root. */
1085 if (0 != geteuid ())
1086 {
1087 message (TRUE, "%s: Invalid socket owner\n", progname);
1088 return INVALID_SOCKET;
1089 }
1090 break;
1091
1092 case 2:
1093 /* `stat' failed */
1094 if (saved_errno == ENOENT)
1095 message (TRUE,
1096 "%s: can't find socket; have you started the server?\n\
1097 To start the server in Emacs, type \"M-x server-start\".\n",
1098 progname);
1099 else
1100 message (TRUE, "%s: can't stat %s: %s\n",
1101 progname, server.sun_path, strerror (saved_errno));
1102 return INVALID_SOCKET;
1103 }
1104 }
1105
1106 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
1107 < 0)
1108 {
1109 message (TRUE, "%s: connect: %s\n", progname, strerror (errno));
1110 return INVALID_SOCKET;
1111 }
1112
1113 return s;
1114 }
1115 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1116
1117 HSOCKET
1118 set_socket ()
1119 {
1120 HSOCKET s;
1121
1122 INITIALIZE ();
1123
1124 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1125 /* Explicit --socket-name argument. */
1126 if (socket_name)
1127 {
1128 s = set_local_socket ();
1129 if ((s != INVALID_SOCKET) || alternate_editor)
1130 return s;
1131 message (TRUE, "%s: error accessing socket \"%s\"",
1132 progname, socket_name);
1133 exit (EXIT_FAILURE);
1134 }
1135 #endif
1136
1137 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1138 if (!server_file)
1139 server_file = getenv ("EMACS_SERVER_FILE");
1140
1141 if (server_file)
1142 {
1143 s = set_tcp_socket ();
1144 if ((s != INVALID_SOCKET) || alternate_editor)
1145 return s;
1146
1147 message (TRUE, "%s: error accessing server file \"%s\"",
1148 progname, server_file);
1149 exit (EXIT_FAILURE);
1150 }
1151
1152 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1153 /* Implicit local socket. */
1154 s = set_local_socket ();
1155 if (s != INVALID_SOCKET)
1156 return s;
1157 #endif
1158
1159 /* Implicit server file. */
1160 server_file = "server";
1161 s = set_tcp_socket ();
1162 if ((s != INVALID_SOCKET) || alternate_editor)
1163 return s;
1164
1165 /* No implicit or explicit socket, and no alternate editor. */
1166 message (TRUE, "%s: No socket or alternate editor. Please use:\n\n"
1167 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1168 "\t--socket-name\n"
1169 #endif
1170 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1171 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1172 progname);
1173 exit (EXIT_FAILURE);
1174 }
1175
1176 #ifdef WINDOWSNT
1177 FARPROC set_fg; /* Pointer to AllowSetForegroundWindow. */
1178 FARPROC get_wc; /* Pointer to RealGetWindowClassA. */
1179
1180 BOOL CALLBACK
1181 w32_find_emacs_process (hWnd, lParam)
1182 HWND hWnd;
1183 LPARAM lParam;
1184 {
1185 DWORD pid;
1186 char class[6];
1187
1188 /* Reject any window not of class "Emacs". */
1189 if (! get_wc (hWnd, class, sizeof (class))
1190 || strcmp (class, "Emacs"))
1191 return TRUE;
1192
1193 /* We only need the process id, not the thread id. */
1194 (void) GetWindowThreadProcessId (hWnd, &pid);
1195
1196 /* Not the one we're looking for. */
1197 if (pid != (DWORD) emacs_pid) return TRUE;
1198
1199 /* OK, let's raise it. */
1200 set_fg (emacs_pid);
1201
1202 /* Stop enumeration. */
1203 return FALSE;
1204 }
1205
1206 /*
1207 * Search for a window of class "Emacs" and owned by a process with
1208 * process id = emacs_pid. If found, allow it to grab the focus.
1209 */
1210 void
1211 w32_give_focus ()
1212 {
1213 HMODULE hUser32;
1214
1215 /* It should'nt happen when dealing with TCP sockets. */
1216 if (!emacs_pid) return;
1217
1218 if (!(hUser32 = LoadLibrary ("user32.dll"))) return;
1219
1220 /* Modern Windows restrict which processes can set the foreground window.
1221 emacsclient can allow Emacs to grab the focus by calling the function
1222 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1223 NT) lack this function, so we have to check its availability. */
1224 if ((set_fg = GetProcAddress (hUser32, "AllowSetForegroundWindow"))
1225 && (get_wc = GetProcAddress (hUser32, "RealGetWindowClassA")))
1226 EnumWindows (w32_find_emacs_process, (LPARAM) 0);
1227
1228 FreeLibrary (hUser32);
1229 }
1230 #endif
1231
1232 int
1233 main (argc, argv)
1234 int argc;
1235 char **argv;
1236 {
1237 int i, rl, needlf = 0;
1238 char *cwd, *str;
1239 char string[BUFSIZ+1];
1240
1241 main_argc = argc;
1242 main_argv = argv;
1243 progname = argv[0];
1244
1245 /* Process options. */
1246 decode_options (argc, argv);
1247
1248 if ((argc - optind < 1) && !eval && !tty && !window_system)
1249 {
1250 message (TRUE, "%s: file name or argument required\n"
1251 "Try `%s --help' for more information\n",
1252 progname, progname);
1253 exit (EXIT_FAILURE);
1254 }
1255
1256 if ((s = set_socket ()) == INVALID_SOCKET)
1257 fail ();
1258
1259
1260 cwd = get_current_dir_name ();
1261 if (cwd == 0)
1262 {
1263 /* getwd puts message in STRING if it fails. */
1264 message (TRUE, "%s: %s\n", progname,
1265 "Cannot get current working directory");
1266 fail ();
1267 }
1268
1269 #ifdef WINDOWSNT
1270 w32_give_focus ();
1271 #endif
1272
1273 /* First of all, send our version number for verification. */
1274 SEND_STRING ("-version ");
1275 SEND_STRING (VERSION);
1276 SEND_STRING (" ");
1277
1278 /* Send over our environment. */
1279 if (!current_frame)
1280 {
1281 extern char **environ;
1282 int i;
1283 for (i = 0; environ[i]; i++)
1284 {
1285 char *name = xstrdup (environ[i]);
1286 char *value = strchr (name, '=');
1287 SEND_STRING ("-env ");
1288 SEND_QUOTED (environ[i]);
1289 SEND_STRING (" ");
1290 }
1291 }
1292
1293 /* Send over our current directory. */
1294 if (!current_frame)
1295 {
1296 SEND_STRING ("-dir ");
1297 SEND_QUOTED (cwd);
1298 SEND_STRING ("/");
1299 SEND_STRING (" ");
1300 }
1301
1302 retry:
1303 if (nowait)
1304 SEND_STRING ("-nowait ");
1305
1306 if (current_frame)
1307 SEND_STRING ("-current-frame ");
1308
1309 if (display)
1310 {
1311 SEND_STRING ("-display ");
1312 SEND_QUOTED (display);
1313 SEND_STRING (" ");
1314 }
1315
1316 if (tty)
1317 {
1318 char *tty_name = ttyname (fileno (stdin));
1319 char *type = getenv ("TERM");
1320
1321 if (! tty_name)
1322 {
1323 message (TRUE, "%s: could not get terminal name\n", progname);
1324 fail ();
1325 }
1326
1327 if (! type)
1328 {
1329 message (TRUE, "%s: please set the TERM variable to your terminal type\n",
1330 progname);
1331 fail ();
1332 }
1333
1334 if (! strcmp (type, "eterm"))
1335 {
1336 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1337 message (TRUE, "%s: opening a frame in an Emacs term buffer"
1338 " is not supported\n", progname);
1339 fail ();
1340 }
1341
1342 init_signals ();
1343
1344 SEND_STRING ("-tty ");
1345 SEND_QUOTED (tty_name);
1346 SEND_STRING (" ");
1347 SEND_QUOTED (type);
1348 SEND_STRING (" ");
1349 }
1350
1351 if (window_system)
1352 SEND_STRING ("-window-system ");
1353
1354 if ((argc - optind > 0))
1355 {
1356 for (i = optind; i < argc; i++)
1357 {
1358 int relative = 0;
1359
1360 if (eval)
1361 {
1362 /* Don't prepend cwd or anything like that. */
1363 SEND_STRING ("-eval ");
1364 SEND_QUOTED (argv[i]);
1365 SEND_STRING (" ");
1366 continue;
1367 }
1368
1369 if (*argv[i] == '+')
1370 {
1371 char *p = argv[i] + 1;
1372 while (isdigit ((unsigned char) *p) || *p == ':') p++;
1373 if (*p == 0)
1374 {
1375 SEND_STRING ("-position ");
1376 SEND_QUOTED (argv[i]);
1377 SEND_STRING (" ");
1378 continue;
1379 }
1380 else
1381 relative = 1;
1382 }
1383 else if (! file_name_absolute_p (argv[i]))
1384 relative = 1;
1385
1386 SEND_STRING ("-file ");
1387 if (relative)
1388 {
1389 SEND_QUOTED (cwd);
1390 SEND_STRING ("/");
1391 }
1392 SEND_QUOTED (argv[i]);
1393 SEND_STRING (" ");
1394 }
1395 }
1396 else
1397 {
1398 if (!tty && !window_system)
1399 {
1400 while ((str = fgets (string, BUFSIZ, stdin)))
1401 {
1402 if (eval)
1403 SEND_STRING ("-eval ");
1404 else
1405 SEND_STRING ("-file ");
1406 SEND_QUOTED (str);
1407 }
1408 SEND_STRING (" ");
1409 }
1410 }
1411
1412 SEND_STRING ("\n");
1413
1414 /* Wait for an answer. */
1415 if (!eval && !tty && !nowait)
1416 {
1417 printf ("Waiting for Emacs...");
1418 needlf = 2;
1419 }
1420 fflush (stdout);
1421 fsync (1);
1422
1423 /* Now, wait for an answer and print any messages. */
1424 while ((rl = recv (s, string, BUFSIZ, 0)) > 0)
1425 {
1426 char *p;
1427 string[rl] = '\0';
1428
1429 p = string + strlen (string) - 1;
1430 while (p > string && *p == '\n')
1431 *p-- = 0;
1432
1433 if (strprefix ("-good-version ", string))
1434 {
1435 /* -good-version: The versions match. */
1436 }
1437 else if (strprefix ("-emacs-pid ", string))
1438 {
1439 /* -emacs-pid PID: The process id of the Emacs process. */
1440 emacs_pid = strtol (string + strlen ("-emacs-pid"), NULL, 10);
1441 }
1442 else if (strprefix ("-window-system-unsupported ", string))
1443 {
1444 /* -window-system-unsupported: Emacs was compiled without X
1445 support. Try again on the terminal. */
1446 window_system = 0;
1447 nowait = 0;
1448 tty = 1;
1449 goto retry;
1450 }
1451 else if (strprefix ("-print ", string))
1452 {
1453 /* -print STRING: Print STRING on the terminal. */
1454 str = unquote_argument (string + strlen ("-print "));
1455 if (needlf)
1456 printf ("\n");
1457 printf ("%s", str);
1458 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1459 }
1460 else if (strprefix ("-error ", string))
1461 {
1462 /* -error DESCRIPTION: Signal an error on the terminal. */
1463 str = unquote_argument (string + strlen ("-error "));
1464 if (needlf)
1465 printf ("\n");
1466 fprintf (stderr, "*ERROR*: %s", str);
1467 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1468 }
1469 else if (strprefix ("-suspend ", string))
1470 {
1471 /* -suspend: Suspend this terminal, i.e., stop the process. */
1472 if (needlf)
1473 printf ("\n");
1474 needlf = 0;
1475 kill (0, SIGSTOP);
1476 }
1477 else
1478 {
1479 /* Unknown command. */
1480 if (needlf)
1481 printf ("\n");
1482 printf ("*ERROR*: Unknown message: %s", string);
1483 needlf = string[0] == '\0' ? needlf : string[strlen (string) - 1] != '\n';
1484 }
1485 }
1486
1487 if (needlf)
1488 printf ("\n");
1489 fflush (stdout);
1490 fsync (1);
1491
1492 CLOSE_SOCKET (s);
1493 return EXIT_SUCCESS;
1494 }
1495
1496 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
1497
1498 \f
1499 #ifndef HAVE_STRERROR
1500 char *
1501 strerror (errnum)
1502 int errnum;
1503 {
1504 extern char *sys_errlist[];
1505 extern int sys_nerr;
1506
1507 if (errnum >= 0 && errnum < sys_nerr)
1508 return sys_errlist[errnum];
1509 return (char *) "Unknown error";
1510 }
1511
1512 #endif /* ! HAVE_STRERROR */
1513
1514 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
1515 (do not change this comment) */
1516
1517 /* emacsclient.c ends here */