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