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