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