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