]> code.delx.au - gnu-emacs/blob - lib-src/emacsclient.c
Merge 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 3, 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 /* Spaces and tabs are significant in this message; they're chosen so the
486 message aligns properly both in a tty and in a Windows message box.
487 Please try to preserve them; otherwise the output is very hard to read
488 when using emacsclientw. */
489 message (FALSE,
490 "Usage: %s [OPTIONS] FILE...\n\
491 Tell the Emacs server to visit the specified files.\n\
492 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
493 \n\
494 The following OPTIONS are accepted:\n\
495 -V, --version Just print version info and return\n\
496 -H, --help Print this usage information message\n\
497 -t, --tty Open a new Emacs frame on the current terminal\n\
498 -c, --current-frame Do not create a new frame;\n\
499 use the current Emacs frame\n\
500 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
501 -n, --no-wait Don't wait for the server to return\n\
502 -d, --display=DISPLAY Visit the file in the given display\n"
503 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
504 "-s, --socket-name=FILENAME\n\
505 Set filename of the UNIX socket for communication\n"
506 #endif
507 "-f, --server-file=FILENAME\n\
508 Set filename of the TCP authentication file\n\
509 -a, --alternate-editor=EDITOR\n\
510 Editor to fallback to if the server is not running\n\
511 \n\
512 Report bugs to bug-gnu-emacs@gnu.org.\n", progname);
513 exit (EXIT_SUCCESS);
514 }
515
516 /*
517 Try to run a different command, or --if no alternate editor is
518 defined-- exit with an errorcode.
519 */
520 void
521 fail (void)
522 {
523 if (alternate_editor)
524 {
525 int i = optind - 1;
526
527 execvp (alternate_editor, main_argv + i);
528 message (TRUE, "%s: error executing alternate editor \"%s\"\n",
529 progname, alternate_editor);
530 }
531 exit (EXIT_FAILURE);
532 }
533
534 \f
535 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
536
537 int
538 main (argc, argv)
539 int argc;
540 char **argv;
541 {
542 main_argc = argc;
543 main_argv = argv;
544 progname = argv[0];
545 message (TRUE, "%s: Sorry, the Emacs server is supported only\n"
546 "on systems with Berkeley sockets.\n",
547 argv[0]);
548 fail ();
549 }
550
551 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
552
553 #ifdef WINDOWSNT
554 # include <winsock2.h>
555 #else
556 # include <sys/types.h>
557 # include <sys/socket.h>
558 # include <sys/un.h>
559 # include <sys/stat.h>
560 # include <errno.h>
561 #endif
562
563 #define AUTH_KEY_LENGTH 64
564 #define SEND_BUFFER_SIZE 4096
565
566 extern char *strerror ();
567 extern int errno;
568
569 /* Buffer to accumulate data to send in TCP connections. */
570 char send_buffer[SEND_BUFFER_SIZE + 1];
571 int sblen = 0; /* Fill pointer for the send buffer. */
572 /* Socket used to communicate with the Emacs server process. */
573 HSOCKET emacs_socket = 0;
574
575 /* Let's send the data to Emacs when either
576 - the data ends in "\n", or
577 - the buffer is full (but this shouldn't happen)
578 Otherwise, we just accumulate it. */
579 void
580 send_to_emacs (s, data)
581 HSOCKET s;
582 char *data;
583 {
584 while (data)
585 {
586 int dlen = strlen (data);
587 if (dlen + sblen >= SEND_BUFFER_SIZE)
588 {
589 int part = SEND_BUFFER_SIZE - sblen;
590 strncpy (&send_buffer[sblen], data, part);
591 data += part;
592 sblen = SEND_BUFFER_SIZE;
593 }
594 else if (dlen)
595 {
596 strcpy (&send_buffer[sblen], data);
597 data = NULL;
598 sblen += dlen;
599 }
600 else
601 break;
602
603 if (sblen == SEND_BUFFER_SIZE
604 || (sblen > 0 && send_buffer[sblen-1] == '\n'))
605 {
606 int sent = send (s, send_buffer, sblen, 0);
607 if (sent != sblen)
608 strcpy (send_buffer, &send_buffer[sent]);
609 sblen -= sent;
610 }
611 }
612 }
613
614 \f
615 /* In STR, insert a & before each &, each space, each newline, and
616 any initial -. Change spaces to underscores, too, so that the
617 return value never contains a space.
618
619 Does not change the string. Outputs the result to STREAM. */
620 void
621 quote_argument (s, str)
622 HSOCKET s;
623 char *str;
624 {
625 char *copy = (char *) xmalloc (strlen (str) * 2 + 1);
626 char *p, *q;
627
628 p = str;
629 q = copy;
630 while (*p)
631 {
632 if (*p == ' ')
633 {
634 *q++ = '&';
635 *q++ = '_';
636 p++;
637 }
638 else if (*p == '\n')
639 {
640 *q++ = '&';
641 *q++ = 'n';
642 p++;
643 }
644 else
645 {
646 if (*p == '&' || (*p == '-' && p == str))
647 *q++ = '&';
648 *q++ = *p++;
649 }
650 }
651 *q++ = 0;
652
653 send_to_emacs (s, copy);
654
655 free (copy);
656 }
657
658
659 /* The inverse of quote_argument. Removes quoting in string STR by
660 modifying the string in place. Returns STR. */
661
662 char *
663 unquote_argument (str)
664 char *str;
665 {
666 char *p, *q;
667
668 if (! str)
669 return str;
670
671 p = str;
672 q = str;
673 while (*p)
674 {
675 if (*p == '&')
676 {
677 p++;
678 if (*p == '&')
679 *p = '&';
680 else if (*p == '_')
681 *p = ' ';
682 else if (*p == 'n')
683 *p = '\n';
684 else if (*p == '-')
685 *p = '-';
686 }
687 *q++ = *p++;
688 }
689 *q = 0;
690 return str;
691 }
692
693 \f
694 int
695 file_name_absolute_p (filename)
696 const unsigned char *filename;
697 {
698 /* Sanity check, it shouldn't happen. */
699 if (! filename) return FALSE;
700
701 /* /xxx is always an absolute path. */
702 if (filename[0] == '/') return TRUE;
703
704 /* Empty filenames (which shouldn't happen) are relative. */
705 if (filename[0] == '\0') return FALSE;
706
707 #ifdef WINDOWSNT
708 /* X:\xxx is always absolute. */
709 if (isalpha (filename[0])
710 && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
711 return TRUE;
712
713 /* Both \xxx and \\xxx\yyy are absolute. */
714 if (filename[0] == '\\') return TRUE;
715
716 /*
717 FIXME: There's a corner case not dealt with, "x:y", where:
718
719 1) x is a valid drive designation (usually a letter in the A-Z range)
720 and y is a path, relative to the current directory on drive x. This
721 is absolute, *after* fixing the y part to include the current
722 directory in x.
723
724 2) x is a relative file name, and y is an NTFS stream name. This is a
725 correct relative path, but it is very unusual.
726
727 The trouble is that first case items are also valid examples of the
728 second case, i.e., "c:test" can be understood as drive:path or as
729 file:stream.
730
731 The "right" fix would involve checking whether
732 - the current drive/partition is NTFS,
733 - x is a valid (and accesible) drive designator,
734 - x:y already exists as a file:stream in the current directory,
735 - y already exists on the current directory of drive x,
736 - the auspices are favorable,
737 and then taking an "informed decision" based on the above.
738
739 Whatever the result, Emacs currently does a very bad job of dealing
740 with NTFS file:streams: it cannot visit them, and the only way to
741 create one is by setting `buffer-file-name' to point to it (either
742 manually or with emacsclient). So perhaps resorting to 1) and ignoring
743 2) for now is the right thing to do.
744
745 Anyway, something to decide After the Release.
746 */
747 #endif
748
749 return FALSE;
750 }
751
752 #ifdef WINDOWSNT
753 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
754 void
755 __cdecl close_winsock ()
756 {
757 WSACleanup ();
758 }
759
760 /* Initialize the WinSock2 library. */
761 void
762 initialize_sockets ()
763 {
764 WSADATA wsaData;
765
766 if (WSAStartup (MAKEWORD (2, 0), &wsaData))
767 {
768 message (TRUE, "%s: error initializing WinSock2", progname);
769 exit (EXIT_FAILURE);
770 }
771
772 atexit (close_winsock);
773 }
774 #endif /* WINDOWSNT */
775
776 \f
777 /*
778 * Read the information needed to set up a TCP comm channel with
779 * the Emacs server: host, port, pid and authentication string.
780 */
781 int
782 get_server_config (server, authentication)
783 struct sockaddr_in *server;
784 char *authentication;
785 {
786 char dotted[32];
787 char *port;
788 char *pid;
789 FILE *config = NULL;
790
791 if (file_name_absolute_p (server_file))
792 config = fopen (server_file, "rb");
793 else
794 {
795 char *home = getenv ("HOME");
796
797 if (home)
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 #ifdef WINDOWSNT
804 if (!config && (home = getenv ("APPDATA")))
805 {
806 char *path = alloca (32 + strlen (home) + strlen (server_file));
807 sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
808 config = fopen (path, "rb");
809 }
810 #endif
811 }
812
813 if (! config)
814 return FALSE;
815
816 if (fgets (dotted, sizeof dotted, config)
817 && (port = strchr (dotted, ':'))
818 && (pid = strchr (port, ' ')))
819 {
820 *port++ = '\0';
821 *pid++ = '\0';
822 }
823 else
824 {
825 message (TRUE, "%s: invalid configuration info", progname);
826 exit (EXIT_FAILURE);
827 }
828
829 server->sin_family = AF_INET;
830 server->sin_addr.s_addr = inet_addr (dotted);
831 server->sin_port = htons (atoi (port));
832
833 if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
834 {
835 message (TRUE, "%s: cannot read authentication info", progname);
836 exit (EXIT_FAILURE);
837 }
838
839 fclose (config);
840
841 emacs_pid = atoi (pid);
842
843 return TRUE;
844 }
845
846 HSOCKET
847 set_tcp_socket ()
848 {
849 HSOCKET s;
850 struct sockaddr_in server;
851 struct linger l_arg = {1, 1};
852 char auth_string[AUTH_KEY_LENGTH + 1];
853
854 if (! get_server_config (&server, auth_string))
855 return INVALID_SOCKET;
856
857 if (server.sin_addr.s_addr != inet_addr ("127.0.0.1"))
858 message (FALSE, "%s: connected to remote socket at %s\n",
859 progname, inet_ntoa (server.sin_addr));
860
861 /*
862 * Open up an AF_INET socket
863 */
864 if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
865 {
866 message (TRUE, "%s: socket: %s\n", progname, strerror (errno));
867 return INVALID_SOCKET;
868 }
869
870 /*
871 * Set up the socket
872 */
873 if (connect (s, (struct sockaddr *) &server, sizeof server) < 0)
874 {
875 message (TRUE, "%s: connect: %s\n", progname, strerror (errno));
876 return INVALID_SOCKET;
877 }
878
879 setsockopt (s, SOL_SOCKET, SO_LINGER, (char *) &l_arg, sizeof l_arg);
880
881 /*
882 * Send the authentication
883 */
884 auth_string[AUTH_KEY_LENGTH] = '\0';
885
886 send_to_emacs (s, "-auth ");
887 send_to_emacs (s, auth_string);
888 send_to_emacs (s, "\n");
889
890 return s;
891 }
892
893
894 /* Returns 1 if PREFIX is a prefix of STRING. */
895 static int
896 strprefix (char *prefix, char *string)
897 {
898 int i;
899 if (! prefix)
900 return 1;
901
902 if (!string)
903 return 0;
904
905 for (i = 0; prefix[i]; i++)
906 if (!string[i] || string[i] != prefix[i])
907 return 0;
908 return 1;
909 }
910
911
912 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
913
914 /* Three possibilities:
915 2 - can't be `stat'ed (sets errno)
916 1 - isn't owned by us
917 0 - success: none of the above */
918
919 static int
920 socket_status (socket_name)
921 char *socket_name;
922 {
923 struct stat statbfr;
924
925 if (stat (socket_name, &statbfr) == -1)
926 return 2;
927
928 if (statbfr.st_uid != geteuid ())
929 return 1;
930
931 return 0;
932 }
933
934 \f
935 /* A signal handler that passes the signal to the Emacs process.
936 Useful for SIGWINCH. */
937
938 SIGTYPE
939 pass_signal_to_emacs (int signalnum)
940 {
941 int old_errno = errno;
942
943 if (emacs_pid)
944 kill (emacs_pid, signalnum);
945
946 signal (signalnum, pass_signal_to_emacs);
947 errno = old_errno;
948 }
949
950 /* Signal handler for SIGCONT; notify the Emacs process that it can
951 now resume our tty frame. */
952
953 SIGTYPE
954 handle_sigcont (int signalnum)
955 {
956 int old_errno = errno;
957
958 if (tcgetpgrp (1) == getpgrp ())
959 {
960 /* We are in the foreground. */
961 send_to_emacs (emacs_socket, "-resume \n");
962 }
963 else
964 {
965 /* We are in the background; cancel the continue. */
966 kill (getpid (), SIGSTOP);
967 }
968
969 signal (signalnum, handle_sigcont);
970 errno = old_errno;
971 }
972
973 /* Signal handler for SIGTSTP; notify the Emacs process that we are
974 going to sleep. Normally the suspend is initiated by Emacs via
975 server-handle-suspend-tty, but if the server gets out of sync with
976 reality, we may get a SIGTSTP on C-z. Handling this signal and
977 notifying Emacs about it should get things under control again. */
978
979 SIGTYPE
980 handle_sigtstp (int signalnum)
981 {
982 int old_errno = errno;
983 sigset_t set;
984
985 if (emacs_socket)
986 send_to_emacs (emacs_socket, "-suspend \n");
987
988 /* Unblock this signal and call the default handler by temprarily
989 changing the handler and resignalling. */
990 sigprocmask (SIG_BLOCK, NULL, &set);
991 sigdelset (&set, signalnum);
992 signal (signalnum, SIG_DFL);
993 kill (getpid (), signalnum);
994 sigprocmask (SIG_SETMASK, &set, NULL); /* Let's the above signal through. */
995 signal (signalnum, handle_sigtstp);
996
997 errno = old_errno;
998 }
999 /* Set up signal handlers before opening a frame on the current tty. */
1000
1001 void
1002 init_signals (void)
1003 {
1004 /* Set up signal handlers. */
1005 signal (SIGWINCH, pass_signal_to_emacs);
1006
1007 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
1008 deciding which terminal the signal came from. C-g is now a
1009 normal input event on secondary terminals. */
1010 #if 0
1011 signal (SIGINT, pass_signal_to_emacs);
1012 signal (SIGQUIT, pass_signal_to_emacs);
1013 #endif
1014
1015 signal (SIGCONT, handle_sigcont);
1016 signal (SIGTSTP, handle_sigtstp);
1017 signal (SIGTTOU, handle_sigtstp);
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 ((emacs_socket = 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_to_emacs (emacs_socket, "-version ");
1307 send_to_emacs (emacs_socket, VERSION);
1308 send_to_emacs (emacs_socket, " ");
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_to_emacs (emacs_socket, "-env ");
1320 quote_argument (emacs_socket, environ[i]);
1321 send_to_emacs (emacs_socket, " ");
1322 }
1323 }
1324
1325 /* Send over our current directory. */
1326 if (!current_frame)
1327 {
1328 send_to_emacs (emacs_socket, "-dir ");
1329 quote_argument (emacs_socket, cwd);
1330 send_to_emacs (emacs_socket, "/");
1331 send_to_emacs (emacs_socket, " ");
1332 }
1333
1334 retry:
1335 if (nowait)
1336 send_to_emacs (emacs_socket, "-nowait ");
1337
1338 if (current_frame)
1339 send_to_emacs (emacs_socket, "-current-frame ");
1340
1341 if (display)
1342 {
1343 send_to_emacs (emacs_socket, "-display ");
1344 quote_argument (emacs_socket, display);
1345 send_to_emacs (emacs_socket, " ");
1346 }
1347
1348 if (tty)
1349 {
1350 char *type = getenv ("TERM");
1351 char *tty_name = NULL;
1352 #ifndef WINDOWSNT
1353 tty_name = ttyname (fileno (stdin));
1354 #endif
1355
1356 if (! tty_name)
1357 {
1358 message (TRUE, "%s: could not get terminal name\n", progname);
1359 fail ();
1360 }
1361
1362 if (! type)
1363 {
1364 message (TRUE, "%s: please set the TERM variable to your terminal type\n",
1365 progname);
1366 fail ();
1367 }
1368
1369 if (! strcmp (type, "eterm"))
1370 {
1371 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1372 message (TRUE, "%s: opening a frame in an Emacs term buffer"
1373 " is not supported\n", progname);
1374 fail ();
1375 }
1376 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1377 init_signals ();
1378 #endif
1379
1380 send_to_emacs (emacs_socket, "-tty ");
1381 quote_argument (emacs_socket, tty_name);
1382 send_to_emacs (emacs_socket, " ");
1383 quote_argument (emacs_socket, type);
1384 send_to_emacs (emacs_socket, " ");
1385 }
1386
1387 if (window_system)
1388 send_to_emacs (emacs_socket, "-window-system ");
1389
1390 if ((argc - optind > 0))
1391 {
1392 for (i = optind; i < argc; i++)
1393 {
1394 int relative = 0;
1395
1396 if (eval)
1397 {
1398 /* Don't prepend cwd or anything like that. */
1399 send_to_emacs (emacs_socket, "-eval ");
1400 quote_argument (emacs_socket, argv[i]);
1401 send_to_emacs (emacs_socket, " ");
1402 continue;
1403 }
1404
1405 if (*argv[i] == '+')
1406 {
1407 char *p = argv[i] + 1;
1408 while (isdigit ((unsigned char) *p) || *p == ':') p++;
1409 if (*p == 0)
1410 {
1411 send_to_emacs (emacs_socket, "-position ");
1412 quote_argument (emacs_socket, argv[i]);
1413 send_to_emacs (emacs_socket, " ");
1414 continue;
1415 }
1416 else
1417 relative = 1;
1418 }
1419 else if (! file_name_absolute_p (argv[i]))
1420 relative = 1;
1421
1422 send_to_emacs (emacs_socket, "-file ");
1423 if (relative)
1424 {
1425 quote_argument (emacs_socket, cwd);
1426 send_to_emacs (emacs_socket, "/");
1427 }
1428 quote_argument (emacs_socket, argv[i]);
1429 send_to_emacs (emacs_socket, " ");
1430 }
1431 }
1432 else
1433 {
1434 if (!tty && !window_system)
1435 {
1436 while ((str = fgets (string, BUFSIZ, stdin)))
1437 {
1438 if (eval)
1439 send_to_emacs (emacs_socket, "-eval ");
1440 else
1441 send_to_emacs (emacs_socket, "-file ");
1442 quote_argument (emacs_socket, str);
1443 }
1444 send_to_emacs (emacs_socket, " ");
1445 }
1446 }
1447
1448 send_to_emacs (emacs_socket, "\n");
1449
1450 /* Wait for an answer. */
1451 if (!eval && !tty && !nowait)
1452 {
1453 printf ("Waiting for Emacs...");
1454 needlf = 2;
1455 }
1456 fflush (stdout);
1457 fsync (1);
1458
1459 /* Now, wait for an answer and print any messages. */
1460 while ((rl = recv (emacs_socket, string, BUFSIZ, 0)) > 0)
1461 {
1462 char *p;
1463 string[rl] = '\0';
1464
1465 p = string + strlen (string) - 1;
1466 while (p > string && *p == '\n')
1467 *p-- = 0;
1468
1469 if (strprefix ("-good-version ", string))
1470 {
1471 /* -good-version: The versions match. */
1472 }
1473 else if (strprefix ("-emacs-pid ", string))
1474 {
1475 /* -emacs-pid PID: The process id of the Emacs process. */
1476 emacs_pid = strtol (string + strlen ("-emacs-pid"), NULL, 10);
1477 }
1478 else if (strprefix ("-window-system-unsupported ", string))
1479 {
1480 /* -window-system-unsupported: Emacs was compiled without X
1481 support. Try again on the terminal. */
1482 window_system = 0;
1483 nowait = 0;
1484 tty = 1;
1485 goto retry;
1486 }
1487 else if (strprefix ("-print ", string))
1488 {
1489 /* -print STRING: Print STRING on the terminal. */
1490 str = unquote_argument (string + strlen ("-print "));
1491 if (needlf)
1492 printf ("\n");
1493 printf ("%s", str);
1494 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1495 }
1496 else if (strprefix ("-error ", string))
1497 {
1498 /* -error DESCRIPTION: Signal an error on the terminal. */
1499 str = unquote_argument (string + strlen ("-error "));
1500 if (needlf)
1501 printf ("\n");
1502 fprintf (stderr, "*ERROR*: %s", str);
1503 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1504 }
1505 #ifndef WINDOWSNT
1506 else if (strprefix ("-suspend ", string))
1507 {
1508 /* -suspend: Suspend this terminal, i.e., stop the process. */
1509 if (needlf)
1510 printf ("\n");
1511 needlf = 0;
1512 kill (0, SIGSTOP);
1513 }
1514 #endif
1515 else
1516 {
1517 /* Unknown command. */
1518 if (needlf)
1519 printf ("\n");
1520 printf ("*ERROR*: Unknown message: %s", string);
1521 needlf = string[0] == '\0' ? needlf : string[strlen (string) - 1] != '\n';
1522 }
1523 }
1524
1525 if (needlf)
1526 printf ("\n");
1527 fflush (stdout);
1528 fsync (1);
1529
1530 CLOSE_SOCKET (emacs_socket);
1531 return EXIT_SUCCESS;
1532 }
1533
1534 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
1535
1536 \f
1537 #ifndef HAVE_STRERROR
1538 char *
1539 strerror (errnum)
1540 int errnum;
1541 {
1542 extern char *sys_errlist[];
1543 extern int sys_nerr;
1544
1545 if (errnum >= 0 && errnum < sys_nerr)
1546 return sys_errlist[errnum];
1547 return (char *) "Unknown error";
1548 }
1549
1550 #endif /* ! HAVE_STRERROR */
1551
1552 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
1553 (do not change this comment) */
1554
1555 /* emacsclient.c ends here */