]> 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, 2007 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. */
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
678 /*
679 FIXME: There's a corner case not dealt with, "x:y", where:
680
681 1) x is a valid drive designation (usually a letter in the A-Z range)
682 and y is a path, relative to the current directory on drive x. This
683 is absolute, *after* fixing the y part to include the current
684 directory in x.
685
686 2) x is a relative file name, and y is an NTFS stream name. This is a
687 correct relative path, but it is very unusual.
688
689 The trouble is that first case items are also valid examples of the
690 second case, i.e., "c:test" can be understood as drive:path or as
691 file:stream.
692
693 The "right" fix would involve checking whether
694 - the current drive/partition is NTFS,
695 - x is a valid (and accesible) drive designator,
696 - x:y already exists as a file:stream in the current directory,
697 - y already exists on the current directory of drive x,
698 - the auspices are favorable,
699 and then taking an "informed decision" based on the above.
700
701 Whatever the result, Emacs currently does a very bad job of dealing
702 with NTFS file:streams: it cannot visit them, and the only way to
703 create one is by setting `buffer-file-name' to point to it (either
704 manually or with emacsclient). So perhaps resorting to 1) and ignoring
705 2) for now is the right thing to do.
706
707 Anyway, something to decide After the Release.
708 */
709 #endif
710
711 return FALSE;
712 }
713
714 #ifdef WINDOWSNT
715 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
716 void
717 __cdecl close_winsock ()
718 {
719 WSACleanup ();
720 }
721
722 /* Initialize the WinSock2 library. */
723 void
724 initialize_sockets ()
725 {
726 WSADATA wsaData;
727
728 if (WSAStartup (MAKEWORD (2, 0), &wsaData))
729 {
730 message (TRUE, "%s: error initializing WinSock2", progname);
731 exit (EXIT_FAILURE);
732 }
733
734 atexit (close_winsock);
735 }
736 #endif /* WINDOWSNT */
737
738 \f
739 #ifdef WINDOWSNT
740
741 /*
742 execvp wrapper for Windows. Quotes arguments with embedded spaces.
743
744 This is necessary due to the broken implementation of exec* routines in
745 the Microsoft libraries: they concatenate the arguments together without
746 quoting special characters, and pass the result to CreateProcess, with
747 predictably bad results. By contrast, Posix execvp passes the arguments
748 directly into the argv array of the child process.
749 */
750 int
751 w32_execvp (path, argv)
752 char *path;
753 char **argv;
754 {
755 int i;
756
757 /* Required to allow a .BAT script as alternate editor. */
758 argv[0] = (char *) alternate_editor;
759
760 for (i = 0; argv[i]; i++)
761 if (strchr (argv[i], ' '))
762 {
763 char *quoted = alloca (strlen (argv[i]) + 3);
764 sprintf (quoted, "\"%s\"", argv[i]);
765 argv[i] = quoted;
766 }
767
768 return execvp (path, argv);
769 }
770
771 #undef execvp
772 #define execvp w32_execvp
773
774 #endif /* WINDOWSNT */
775
776 /*
777 * Read the information needed to set up a TCP comm channel with
778 * the Emacs server: host, port, pid and authentication string.
779 */
780 int
781 get_server_config (server, authentication)
782 struct sockaddr_in *server;
783 char *authentication;
784 {
785 char dotted[32];
786 char *port;
787 char *pid;
788 FILE *config = NULL;
789
790 if (file_name_absolute_p (server_file))
791 config = fopen (server_file, "rb");
792 else
793 {
794 char *home = getenv ("HOME");
795
796 if (home)
797 {
798 char *path = alloca (32 + strlen (home) + strlen (server_file));
799 sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
800 config = fopen (path, "rb");
801 }
802 #ifdef WINDOWSNT
803 if (!config && (home = getenv ("APPDATA")))
804 {
805 char *path = alloca (32 + strlen (home) + strlen (server_file));
806 sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
807 config = fopen (path, "rb");
808 }
809 #endif
810 }
811
812 if (! config)
813 return FALSE;
814
815 if (fgets (dotted, sizeof dotted, config)
816 && (port = strchr (dotted, ':'))
817 && (pid = strchr (port, ' ')))
818 {
819 *port++ = '\0';
820 *pid++ = '\0';
821 }
822 else
823 {
824 message (TRUE, "%s: invalid configuration info", progname);
825 exit (EXIT_FAILURE);
826 }
827
828 server->sin_family = AF_INET;
829 server->sin_addr.s_addr = inet_addr (dotted);
830 server->sin_port = htons (atoi (port));
831
832 if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
833 {
834 message (TRUE, "%s: cannot read authentication info", progname);
835 exit (EXIT_FAILURE);
836 }
837
838 fclose (config);
839
840 emacs_pid = atoi (pid);
841
842 return TRUE;
843 }
844
845 HSOCKET
846 set_tcp_socket ()
847 {
848 HSOCKET s;
849 struct sockaddr_in server;
850 struct linger l_arg = {1, 1};
851 char auth_string[AUTH_KEY_LENGTH + 1];
852
853 if (! get_server_config (&server, auth_string))
854 return INVALID_SOCKET;
855
856 if (server.sin_addr.s_addr != inet_addr ("127.0.0.1"))
857 message (FALSE, "%s: connected to remote socket at %s\n",
858 progname, inet_ntoa (server.sin_addr));
859
860 /*
861 * Open up an AF_INET socket
862 */
863 if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
864 {
865 message (TRUE, "%s: socket: %s\n", progname, strerror (errno));
866 return INVALID_SOCKET;
867 }
868
869 /*
870 * Set up the socket
871 */
872 if (connect (s, (struct sockaddr *) &server, sizeof server) < 0)
873 {
874 message (TRUE, "%s: connect: %s\n", progname, strerror (errno));
875 return INVALID_SOCKET;
876 }
877
878 setsockopt (s, SOL_SOCKET, SO_LINGER, (char *) &l_arg, sizeof l_arg);
879
880 /*
881 * Send the authentication
882 */
883 auth_string[AUTH_KEY_LENGTH] = '\0';
884
885 SEND_STRING ("-auth ");
886 SEND_STRING (auth_string);
887 SEND_STRING ("\n");
888
889 return s;
890 }
891
892 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
893
894 /* Three possibilities:
895 2 - can't be `stat'ed (sets errno)
896 1 - isn't owned by us
897 0 - success: none of the above */
898
899 static int
900 socket_status (socket_name)
901 char *socket_name;
902 {
903 struct stat statbfr;
904
905 if (stat (socket_name, &statbfr) == -1)
906 return 2;
907
908 if (statbfr.st_uid != geteuid ())
909 return 1;
910
911 return 0;
912 }
913
914 \f
915 /* A signal handler that passes the signal to the Emacs process.
916 Useful for SIGWINCH. */
917
918 SIGTYPE
919 pass_signal_to_emacs (int signalnum)
920 {
921 int old_errno = errno;
922
923 if (emacs_pid)
924 kill (emacs_pid, signalnum);
925
926 signal (signalnum, pass_signal_to_emacs);
927 errno = old_errno;
928 }
929
930 /* Signal handler for SIGCONT; notify the Emacs process that it can
931 now resume our tty frame. */
932
933 SIGTYPE
934 handle_sigcont (int signalnum)
935 {
936 int old_errno = errno;
937
938 if (tcgetpgrp (1) == getpgrp ())
939 {
940 /* We are in the foreground. */
941 SEND_STRING ("-resume \n");
942 }
943 else
944 {
945 /* We are in the background; cancel the continue. */
946 kill (getpid (), SIGSTOP);
947 }
948
949 signal (signalnum, handle_sigcont);
950 errno = old_errno;
951 }
952
953 /* Signal handler for SIGTSTP; notify the Emacs process that we are
954 going to sleep. Normally the suspend is initiated by Emacs via
955 server-handle-suspend-tty, but if the server gets out of sync with
956 reality, we may get a SIGTSTP on C-z. Handling this signal and
957 notifying Emacs about it should get things under control again. */
958
959 SIGTYPE
960 handle_sigtstp (int signalnum)
961 {
962 int old_errno = errno;
963 sigset_t set;
964
965 if (s)
966 SEND_STRING ("-suspend \n");
967
968 /* Unblock this signal and call the default handler by temprarily
969 changing the handler and resignalling. */
970 sigprocmask (SIG_BLOCK, NULL, &set);
971 sigdelset (&set, signalnum);
972 signal (signalnum, SIG_DFL);
973 kill (getpid (), signalnum);
974 sigprocmask (SIG_SETMASK, &set, NULL); /* Let's the above signal through. */
975 signal (signalnum, handle_sigtstp);
976
977 errno = old_errno;
978 }
979
980 /* Set up signal handlers before opening a frame on the current tty. */
981
982 void
983 init_signals (void)
984 {
985 /* Set up signal handlers. */
986 signal (SIGWINCH, pass_signal_to_emacs);
987
988 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
989 deciding which terminal the signal came from. C-g is now a
990 normal input event on secondary terminals. */
991 #if 0
992 signal (SIGINT, pass_signal_to_emacs);
993 signal (SIGQUIT, pass_signal_to_emacs);
994 #endif
995
996 signal (SIGCONT, handle_sigcont);
997 signal (SIGTSTP, handle_sigtstp);
998 signal (SIGTTOU, handle_sigtstp);
999 }
1000
1001
1002
1003 /* Returns 1 if PREFIX is a prefix of STRING. */
1004 static int
1005 strprefix (char *prefix, char *string)
1006 {
1007 int i;
1008 if (! prefix)
1009 return 1;
1010
1011 if (!string)
1012 return 0;
1013
1014 for (i = 0; prefix[i]; i++)
1015 if (!string[i] || string[i] != prefix[i])
1016 return 0;
1017 return 1;
1018 }
1019
1020
1021 HSOCKET
1022 set_local_socket ()
1023 {
1024 HSOCKET s;
1025 struct sockaddr_un server;
1026
1027 /*
1028 * Open up an AF_UNIX socket in this person's home directory
1029 */
1030
1031 if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
1032 {
1033 message (TRUE, "%s: socket: %s\n", progname, strerror (errno));
1034 return INVALID_SOCKET;
1035 }
1036
1037 server.sun_family = AF_UNIX;
1038
1039 {
1040 int sock_status = 0;
1041 int default_sock = !socket_name;
1042 int saved_errno = 0;
1043
1044 char *server_name = "server";
1045
1046 if (socket_name && !index (socket_name, '/') && !index (socket_name, '\\'))
1047 { /* socket_name is a file name component. */
1048 server_name = socket_name;
1049 socket_name = NULL;
1050 default_sock = 1; /* Try both UIDs. */
1051 }
1052
1053 if (default_sock)
1054 {
1055 socket_name = alloca (100 + strlen (server_name));
1056 sprintf (socket_name, "/tmp/emacs%d/%s",
1057 (int) geteuid (), server_name);
1058 }
1059
1060 if (strlen (socket_name) < sizeof (server.sun_path))
1061 strcpy (server.sun_path, socket_name);
1062 else
1063 {
1064 message (TRUE, "%s: socket-name %s too long",
1065 progname, socket_name);
1066 fail ();
1067 }
1068
1069 /* See if the socket exists, and if it's owned by us. */
1070 sock_status = socket_status (server.sun_path);
1071 saved_errno = errno;
1072 if (sock_status && default_sock)
1073 {
1074 /* Failing that, see if LOGNAME or USER exist and differ from
1075 our euid. If so, look for a socket based on the UID
1076 associated with the name. This is reminiscent of the logic
1077 that init_editfns uses to set the global Vuser_full_name. */
1078
1079 char *user_name = (char *) getenv ("LOGNAME");
1080
1081 if (!user_name)
1082 user_name = (char *) getenv ("USER");
1083
1084 if (user_name)
1085 {
1086 struct passwd *pw = getpwnam (user_name);
1087
1088 if (pw && (pw->pw_uid != geteuid ()))
1089 {
1090 /* We're running under su, apparently. */
1091 socket_name = alloca (100 + strlen (server_name));
1092 sprintf (socket_name, "/tmp/emacs%d/%s",
1093 (int) pw->pw_uid, server_name);
1094
1095 if (strlen (socket_name) < sizeof (server.sun_path))
1096 strcpy (server.sun_path, socket_name);
1097 else
1098 {
1099 message (TRUE, "%s: socket-name %s too long",
1100 progname, socket_name);
1101 exit (EXIT_FAILURE);
1102 }
1103
1104 sock_status = socket_status (server.sun_path);
1105 saved_errno = errno;
1106 }
1107 else
1108 errno = saved_errno;
1109 }
1110 }
1111
1112 switch (sock_status)
1113 {
1114 case 1:
1115 /* There's a socket, but it isn't owned by us. This is OK if
1116 we are root. */
1117 if (0 != geteuid ())
1118 {
1119 message (TRUE, "%s: Invalid socket owner\n", progname);
1120 return INVALID_SOCKET;
1121 }
1122 break;
1123
1124 case 2:
1125 /* `stat' failed */
1126 if (saved_errno == ENOENT)
1127 message (TRUE,
1128 "%s: can't find socket; have you started the server?\n\
1129 To start the server in Emacs, type \"M-x server-start\".\n",
1130 progname);
1131 else
1132 message (TRUE, "%s: can't stat %s: %s\n",
1133 progname, server.sun_path, strerror (saved_errno));
1134 return INVALID_SOCKET;
1135 }
1136 }
1137
1138 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
1139 < 0)
1140 {
1141 message (TRUE, "%s: connect: %s\n", progname, strerror (errno));
1142 return INVALID_SOCKET;
1143 }
1144
1145 return s;
1146 }
1147 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1148
1149 HSOCKET
1150 set_socket ()
1151 {
1152 HSOCKET s;
1153
1154 INITIALIZE ();
1155
1156 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1157 /* Explicit --socket-name argument. */
1158 if (socket_name)
1159 {
1160 s = set_local_socket ();
1161 if ((s != INVALID_SOCKET) || alternate_editor)
1162 return s;
1163 message (TRUE, "%s: error accessing socket \"%s\"",
1164 progname, socket_name);
1165 exit (EXIT_FAILURE);
1166 }
1167 #endif
1168
1169 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1170 if (!server_file)
1171 server_file = getenv ("EMACS_SERVER_FILE");
1172
1173 if (server_file)
1174 {
1175 s = set_tcp_socket ();
1176 if ((s != INVALID_SOCKET) || alternate_editor)
1177 return s;
1178
1179 message (TRUE, "%s: error accessing server file \"%s\"",
1180 progname, server_file);
1181 exit (EXIT_FAILURE);
1182 }
1183
1184 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1185 /* Implicit local socket. */
1186 s = set_local_socket ();
1187 if (s != INVALID_SOCKET)
1188 return s;
1189 #endif
1190
1191 /* Implicit server file. */
1192 server_file = "server";
1193 s = set_tcp_socket ();
1194 if ((s != INVALID_SOCKET) || alternate_editor)
1195 return s;
1196
1197 /* No implicit or explicit socket, and no alternate editor. */
1198 message (TRUE, "%s: No socket or alternate editor. Please use:\n\n"
1199 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1200 "\t--socket-name\n"
1201 #endif
1202 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1203 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1204 progname);
1205 exit (EXIT_FAILURE);
1206 }
1207
1208 #ifdef WINDOWSNT
1209 FARPROC set_fg; /* Pointer to AllowSetForegroundWindow. */
1210 FARPROC get_wc; /* Pointer to RealGetWindowClassA. */
1211
1212 BOOL CALLBACK
1213 w32_find_emacs_process (hWnd, lParam)
1214 HWND hWnd;
1215 LPARAM lParam;
1216 {
1217 DWORD pid;
1218 char class[6];
1219
1220 /* Reject any window not of class "Emacs". */
1221 if (! get_wc (hWnd, class, sizeof (class))
1222 || strcmp (class, "Emacs"))
1223 return TRUE;
1224
1225 /* We only need the process id, not the thread id. */
1226 (void) GetWindowThreadProcessId (hWnd, &pid);
1227
1228 /* Not the one we're looking for. */
1229 if (pid != (DWORD) emacs_pid) return TRUE;
1230
1231 /* OK, let's raise it. */
1232 set_fg (emacs_pid);
1233
1234 /* Stop enumeration. */
1235 return FALSE;
1236 }
1237
1238 /*
1239 * Search for a window of class "Emacs" and owned by a process with
1240 * process id = emacs_pid. If found, allow it to grab the focus.
1241 */
1242 void
1243 w32_give_focus ()
1244 {
1245 HMODULE hUser32;
1246
1247 /* It shouldn't happen when dealing with TCP sockets. */
1248 if (!emacs_pid) return;
1249
1250 if (!(hUser32 = LoadLibrary ("user32.dll"))) return;
1251
1252 /* Modern Windows restrict which processes can set the foreground window.
1253 emacsclient can allow Emacs to grab the focus by calling the function
1254 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1255 NT) lack this function, so we have to check its availability. */
1256 if ((set_fg = GetProcAddress (hUser32, "AllowSetForegroundWindow"))
1257 && (get_wc = GetProcAddress (hUser32, "RealGetWindowClassA")))
1258 EnumWindows (w32_find_emacs_process, (LPARAM) 0);
1259
1260 FreeLibrary (hUser32);
1261 }
1262 #endif
1263
1264 int
1265 main (argc, argv)
1266 int argc;
1267 char **argv;
1268 {
1269 int i, rl, needlf = 0;
1270 char *cwd, *str;
1271 char string[BUFSIZ+1];
1272
1273 main_argc = argc;
1274 main_argv = argv;
1275 progname = argv[0];
1276
1277 /* Process options. */
1278 decode_options (argc, argv);
1279
1280 if ((argc - optind < 1) && !eval && !tty && !window_system)
1281 {
1282 message (TRUE, "%s: file name or argument required\n"
1283 "Try `%s --help' for more information\n",
1284 progname, progname);
1285 exit (EXIT_FAILURE);
1286 }
1287
1288 if ((s = set_socket ()) == INVALID_SOCKET)
1289 fail ();
1290
1291
1292 cwd = get_current_dir_name ();
1293 if (cwd == 0)
1294 {
1295 /* getwd puts message in STRING if it fails. */
1296 message (TRUE, "%s: %s\n", progname,
1297 "Cannot get current working directory");
1298 fail ();
1299 }
1300
1301 #ifdef WINDOWSNT
1302 w32_give_focus ();
1303 #endif
1304
1305 /* First of all, send our version number for verification. */
1306 SEND_STRING ("-version ");
1307 SEND_STRING (VERSION);
1308 SEND_STRING (" ");
1309
1310 /* Send over our environment. */
1311 if (!current_frame)
1312 {
1313 extern char **environ;
1314 int i;
1315 for (i = 0; environ[i]; i++)
1316 {
1317 char *name = xstrdup (environ[i]);
1318 char *value = strchr (name, '=');
1319 SEND_STRING ("-env ");
1320 SEND_QUOTED (environ[i]);
1321 SEND_STRING (" ");
1322 }
1323 }
1324
1325 /* Send over our current directory. */
1326 if (!current_frame)
1327 {
1328 SEND_STRING ("-dir ");
1329 SEND_QUOTED (cwd);
1330 SEND_STRING ("/");
1331 SEND_STRING (" ");
1332 }
1333
1334 retry:
1335 if (nowait)
1336 SEND_STRING ("-nowait ");
1337
1338 if (current_frame)
1339 SEND_STRING ("-current-frame ");
1340
1341 if (display)
1342 {
1343 SEND_STRING ("-display ");
1344 SEND_QUOTED (display);
1345 SEND_STRING (" ");
1346 }
1347
1348 if (tty)
1349 {
1350 char *tty_name = ttyname (fileno (stdin));
1351 char *type = getenv ("TERM");
1352
1353 if (! tty_name)
1354 {
1355 message (TRUE, "%s: could not get terminal name\n", progname);
1356 fail ();
1357 }
1358
1359 if (! type)
1360 {
1361 message (TRUE, "%s: please set the TERM variable to your terminal type\n",
1362 progname);
1363 fail ();
1364 }
1365
1366 if (! strcmp (type, "eterm"))
1367 {
1368 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1369 message (TRUE, "%s: opening a frame in an Emacs term buffer"
1370 " is not supported\n", progname);
1371 fail ();
1372 }
1373
1374 init_signals ();
1375
1376 SEND_STRING ("-tty ");
1377 SEND_QUOTED (tty_name);
1378 SEND_STRING (" ");
1379 SEND_QUOTED (type);
1380 SEND_STRING (" ");
1381 }
1382
1383 if (window_system)
1384 SEND_STRING ("-window-system ");
1385
1386 if ((argc - optind > 0))
1387 {
1388 for (i = optind; i < argc; i++)
1389 {
1390 int relative = 0;
1391
1392 if (eval)
1393 {
1394 /* Don't prepend cwd or anything like that. */
1395 SEND_STRING ("-eval ");
1396 SEND_QUOTED (argv[i]);
1397 SEND_STRING (" ");
1398 continue;
1399 }
1400
1401 if (*argv[i] == '+')
1402 {
1403 char *p = argv[i] + 1;
1404 while (isdigit ((unsigned char) *p) || *p == ':') p++;
1405 if (*p == 0)
1406 {
1407 SEND_STRING ("-position ");
1408 SEND_QUOTED (argv[i]);
1409 SEND_STRING (" ");
1410 continue;
1411 }
1412 else
1413 relative = 1;
1414 }
1415 else if (! file_name_absolute_p (argv[i]))
1416 relative = 1;
1417
1418 SEND_STRING ("-file ");
1419 if (relative)
1420 {
1421 SEND_QUOTED (cwd);
1422 SEND_STRING ("/");
1423 }
1424 SEND_QUOTED (argv[i]);
1425 SEND_STRING (" ");
1426 }
1427 }
1428 else
1429 {
1430 if (!tty && !window_system)
1431 {
1432 while ((str = fgets (string, BUFSIZ, stdin)))
1433 {
1434 if (eval)
1435 SEND_STRING ("-eval ");
1436 else
1437 SEND_STRING ("-file ");
1438 SEND_QUOTED (str);
1439 }
1440 SEND_STRING (" ");
1441 }
1442 }
1443
1444 SEND_STRING ("\n");
1445
1446 /* Wait for an answer. */
1447 if (!eval && !tty && !nowait)
1448 {
1449 printf ("Waiting for Emacs...");
1450 needlf = 2;
1451 }
1452 fflush (stdout);
1453 fsync (1);
1454
1455 /* Now, wait for an answer and print any messages. */
1456 while ((rl = recv (s, string, BUFSIZ, 0)) > 0)
1457 {
1458 char *p;
1459 string[rl] = '\0';
1460
1461 p = string + strlen (string) - 1;
1462 while (p > string && *p == '\n')
1463 *p-- = 0;
1464
1465 if (strprefix ("-good-version ", string))
1466 {
1467 /* -good-version: The versions match. */
1468 }
1469 else if (strprefix ("-emacs-pid ", string))
1470 {
1471 /* -emacs-pid PID: The process id of the Emacs process. */
1472 emacs_pid = strtol (string + strlen ("-emacs-pid"), NULL, 10);
1473 }
1474 else if (strprefix ("-window-system-unsupported ", string))
1475 {
1476 /* -window-system-unsupported: Emacs was compiled without X
1477 support. Try again on the terminal. */
1478 window_system = 0;
1479 nowait = 0;
1480 tty = 1;
1481 goto retry;
1482 }
1483 else if (strprefix ("-print ", string))
1484 {
1485 /* -print STRING: Print STRING on the terminal. */
1486 str = unquote_argument (string + strlen ("-print "));
1487 if (needlf)
1488 printf ("\n");
1489 printf ("%s", str);
1490 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1491 }
1492 else if (strprefix ("-error ", string))
1493 {
1494 /* -error DESCRIPTION: Signal an error on the terminal. */
1495 str = unquote_argument (string + strlen ("-error "));
1496 if (needlf)
1497 printf ("\n");
1498 fprintf (stderr, "*ERROR*: %s", str);
1499 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1500 }
1501 else if (strprefix ("-suspend ", string))
1502 {
1503 /* -suspend: Suspend this terminal, i.e., stop the process. */
1504 if (needlf)
1505 printf ("\n");
1506 needlf = 0;
1507 kill (0, SIGSTOP);
1508 }
1509 else
1510 {
1511 /* Unknown command. */
1512 if (needlf)
1513 printf ("\n");
1514 printf ("*ERROR*: Unknown message: %s", string);
1515 needlf = string[0] == '\0' ? needlf : string[strlen (string) - 1] != '\n';
1516 }
1517 }
1518
1519 if (needlf)
1520 printf ("\n");
1521 fflush (stdout);
1522 fsync (1);
1523
1524 CLOSE_SOCKET (s);
1525 return EXIT_SUCCESS;
1526 }
1527
1528 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
1529
1530 \f
1531 #ifndef HAVE_STRERROR
1532 char *
1533 strerror (errnum)
1534 int errnum;
1535 {
1536 extern char *sys_errlist[];
1537 extern int sys_nerr;
1538
1539 if (errnum >= 0 && errnum < sys_nerr)
1540 return sys_errlist[errnum];
1541 return (char *) "Unknown error";
1542 }
1543
1544 #endif /* ! HAVE_STRERROR */
1545
1546 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
1547 (do not change this comment) */
1548
1549 /* emacsclient.c ends here */