]> code.delx.au - gnu-emacs/blob - lib-src/emacsclient.c
Merged in changes from CVS trunk.
[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, 2003, 2004
3 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., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
21
22
23 #define NO_SHORTNAMES
24
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
28
29 #undef signal
30
31 #include <ctype.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #ifdef HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif
37
38 #ifdef VMS
39 # include "vms-pwd.h"
40 #else
41 # include <pwd.h>
42 #endif /* not VMS */
43
44 #include <signal.h>
45 #include <errno.h>
46
47 \f
48 char *getenv (), *getwd ();
49 char *getcwd ();
50
51 /* This is defined with -D from the compilation command,
52 which extracts it from ../lisp/version.el. */
53
54 #ifndef VERSION
55 #define VERSION "unspecified"
56 #endif
57 \f
58 /* Name used to invoke this program. */
59 char *progname;
60
61 /* The first argument to main. */
62 int main_argc;
63
64 /* The second argument to main. */
65 char **main_argv;
66
67 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
68 int nowait = 0;
69
70 /* Nonzero means args are expressions to be evaluated. --eval. */
71 int eval = 0;
72
73 /* Nonzero means open a new graphical frame. */
74 int window_system = 0;
75
76 /* The display on which Emacs should work. --display. */
77 char *display = NULL;
78
79 /* Nonzero means open a new Emacs frame on the current terminal. */
80 int tty = 0;
81
82 /* If non-NULL, the name of an editor to fallback to if the server
83 is not running. --alternate-editor. */
84 const char * alternate_editor = NULL;
85
86 /* If non-NULL, the filename of the UNIX socket. */
87 char *socket_name = NULL;
88
89 void print_help_and_exit ();
90
91 struct option longopts[] =
92 {
93 { "no-wait", no_argument, NULL, 'n' },
94 { "eval", no_argument, NULL, 'e' },
95 { "help", no_argument, NULL, 'H' },
96 { "version", no_argument, NULL, 'V' },
97 { "tty", no_argument, NULL, 't' },
98 { "current-frame", no_argument, NULL, 'c' },
99 { "alternate-editor", required_argument, NULL, 'a' },
100 { "socket-name", required_argument, NULL, 's' },
101 { "display", required_argument, NULL, 'd' },
102 { 0, 0, 0, 0 }
103 };
104
105 /* Decode the options from argv and argc.
106 The global variable `optind' will say how many arguments we used up. */
107
108 void
109 decode_options (argc, argv)
110 int argc;
111 char **argv;
112 {
113 alternate_editor = getenv ("ALTERNATE_EDITOR");
114 display = getenv ("DISPLAY");
115 if (display && strlen (display) == 0)
116 display = NULL;
117
118 if (display)
119 window_system = 1;
120 else
121 tty = 1;
122
123 while (1)
124 {
125 int opt = getopt_long (argc, argv,
126 "VHnea:s:d:tc", longopts, 0);
127
128 if (opt == EOF)
129 break;
130
131 switch (opt)
132 {
133 case 0:
134 /* If getopt returns 0, then it has already processed a
135 long-named option. We should do nothing. */
136 break;
137
138 case 'a':
139 alternate_editor = optarg;
140 break;
141
142 case 's':
143 socket_name = optarg;
144 break;
145
146 case 'd':
147 display = optarg;
148 break;
149
150 case 'n':
151 nowait = 1;
152 break;
153
154 case 'e':
155 eval = 1;
156 break;
157
158 case 'V':
159 printf ("emacsclient %s\n", VERSION);
160 exit (0);
161 break;
162
163 case 't':
164 tty = 1;
165 window_system = 0;
166 break;
167
168 case 'c':
169 window_system = 0;
170 tty = 0;
171 break;
172
173 case 'H':
174 print_help_and_exit ();
175 break;
176
177 default:
178 fprintf (stderr, "Try `%s --help' for more information\n", progname);
179 exit (1);
180 break;
181 }
182 }
183
184 if (tty) {
185 nowait = 0;
186 display = 0;
187 }
188 }
189
190 void
191 print_help_and_exit ()
192 {
193 printf (
194 "Usage: %s [OPTIONS] FILE...\n\
195 Tell the Emacs server to visit the specified files.\n\
196 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
197 \n\
198 The following OPTIONS are accepted:\n\
199 -V, --version Just print a version info and return\n\
200 -H, --help Print this usage information message\n\
201 -t, --tty Open a new Emacs frame on the current terminal\n\
202 -c, --current-frame Do not create a new frame; use the current Emacs frame\n\
203 -n, --no-wait Don't wait for the server to return\n\
204 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
205 -d, --display=DISPLAY Visit the file in the given display\n\
206 -s, --socket-name=FILENAME\n\
207 Set the filename of the UNIX socket for communication\n\
208 -a, --alternate-editor=EDITOR\n\
209 Editor to fallback to if the server is not running\n\
210 \n\
211 Report bugs to bug-gnu-emacs@gnu.org.\n", progname);
212 exit (0);
213 }
214
215 /* Like malloc but get fatal error if memory is exhausted. */
216
217 long *
218 xmalloc (size)
219 unsigned int size;
220 {
221 long *result = (long *) malloc (size);
222 if (result == NULL)
223 {
224 perror ("malloc");
225 exit (1);
226 }
227 return result;
228 }
229
230 /* Like strdup but get a fatal error if memory is exhausted. */
231
232 char *
233 xstrdup (const char *s)
234 {
235 char *result = strdup (s);
236 if (result == NULL)
237 {
238 perror ("strdup");
239 exit (1);
240 }
241 return result;
242 }
243
244 /* In STR, insert a & before each &, each space, each newline, and
245 any initial -. Change spaces to underscores, too, so that the
246 return value never contains a space.
247
248 Does not change the string. Outputs the result to STREAM. */
249
250 void
251 quote_argument (str, stream)
252 char *str;
253 FILE *stream;
254 {
255 char *copy = (char *) xmalloc (strlen (str) * 2 + 1);
256 char *p, *q;
257
258 p = str;
259 q = copy;
260 while (*p)
261 {
262 if (*p == ' ')
263 {
264 *q++ = '&';
265 *q++ = '_';
266 p++;
267 }
268 else if (*p == '\n')
269 {
270 *q++ = '&';
271 *q++ = 'n';
272 p++;
273 }
274 else
275 {
276 if (*p == '&' || (*p == '-' && p == str))
277 *q++ = '&';
278 *q++ = *p++;
279 }
280 }
281 *q++ = 0;
282
283 fprintf (stream, "%s", copy);
284
285 free (copy);
286 }
287
288
289 /* The inverse of quote_argument. Removes quoting in string STR by
290 modifying the string in place. Returns STR. */
291
292 char *
293 unquote_argument (str)
294 char *str;
295 {
296 char *p, *q;
297
298 if (! str)
299 return str;
300
301 p = str;
302 q = str;
303 while (*p)
304 {
305 if (*p == '&')
306 {
307 p++;
308 if (*p == '&')
309 *p = '&';
310 else if (*p == '_')
311 *p = ' ';
312 else if (*p == 'n')
313 *p = '\n';
314 else if (*p == '-')
315 *p = '-';
316 }
317 *q++ = *p++;
318 }
319 *q = 0;
320 return str;
321 }
322
323 \f
324 /*
325 Try to run a different command, or --if no alternate editor is
326 defined-- exit with an errorcode.
327 */
328 void
329 fail (void)
330 {
331 if (alternate_editor)
332 {
333 int i = optind - 1;
334 execvp (alternate_editor, main_argv + i);
335 return;
336 }
337 else
338 {
339 exit (1);
340 }
341 }
342
343 /* The process id of Emacs. */
344 int emacs_pid;
345
346 /* File handles for communicating with Emacs. */
347 FILE *out, *in;
348
349 /* A signal handler that passes the signal to the Emacs process.
350 Useful for SIGWINCH. */
351
352 SIGTYPE
353 pass_signal_to_emacs (int signalnum)
354 {
355 int old_errno = errno;
356
357 if (emacs_pid)
358 kill (emacs_pid, signalnum);
359
360 signal (signalnum, pass_signal_to_emacs);
361 errno = old_errno;
362 }
363
364 /* Signal handler for SIGCONT; notify the Emacs process that it can
365 now resume our tty frame. */
366
367 SIGTYPE
368 handle_sigcont (int signalnum)
369 {
370 int old_errno = errno;
371
372 if (tcgetpgrp (1) == getpgrp ())
373 {
374 /* We are in the foreground. */
375 fprintf (out, "-resume \n");
376 fflush (out);
377 fsync (fileno (out));
378 }
379 else
380 {
381 /* We are in the background; cancel the continue. */
382 kill (getpid (), SIGSTOP);
383 }
384 errno = old_errno;
385 }
386
387 /* Signal handler for SIGTSTP; notify the Emacs process that we are
388 going to sleep. Normally the suspend is initiated by Emacs via
389 server-handle-suspend-tty, but if the server gets out of sync with
390 reality, we may get a SIGTSTP on C-z. Handling this signal and
391 notifying Emacs about it should get things under control again. */
392
393 SIGTYPE
394 handle_sigtstp (int signalnum)
395 {
396 int old_errno = errno;
397 sigset_t set;
398
399 if (out)
400 {
401 fprintf (out, "-suspend \n");
402 fflush (out);
403 fsync (fileno (out));
404 }
405
406 /* Unblock this signal and call the default handler by temprarily
407 changing the handler and resignalling. */
408 sigprocmask (SIG_BLOCK, NULL, &set);
409 sigdelset (&set, signalnum);
410 signal (signalnum, SIG_DFL);
411 kill (getpid (), signalnum);
412 sigprocmask (SIG_SETMASK, &set, NULL); /* Let's the above signal through. */
413 signal (signalnum, handle_sigtstp);
414
415 errno = old_errno;
416 }
417
418 /* Set up signal handlers before opening a frame on the current tty. */
419
420 void
421 init_signals (void)
422 {
423 /* Set up signal handlers. */
424 signal (SIGWINCH, pass_signal_to_emacs);
425
426 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
427 deciding which terminal the signal came from. C-g is now a
428 normal input event on secondary terminals. */
429 #if 0
430 signal (SIGINT, pass_signal_to_emacs);
431 signal (SIGQUIT, pass_signal_to_emacs);
432 #endif
433
434 signal (SIGCONT, handle_sigcont);
435 signal (SIGTSTP, handle_sigtstp);
436 signal (SIGTTOU, handle_sigtstp);
437 }
438
439 \f
440 #if !defined (HAVE_SOCKETS) || defined (NO_SOCKETS_IN_FILE_SYSTEM)
441
442 int
443 main (argc, argv)
444 int argc;
445 char **argv;
446 {
447 fprintf (stderr, "%s: Sorry, the Emacs server is supported only\n",
448 argv[0]);
449 fprintf (stderr, "on systems with Berkeley sockets.\n");
450
451 fail ();
452 }
453
454 #else /* HAVE_SOCKETS */
455
456 #include <sys/types.h>
457 #include <sys/socket.h>
458 #include <sys/un.h>
459 #include <sys/stat.h>
460 #include <errno.h>
461
462 extern char *strerror ();
463 extern int errno;
464
465 /* Three possibilities:
466 2 - can't be `stat'ed (sets errno)
467 1 - isn't owned by us
468 0 - success: none of the above */
469
470 static int
471 socket_status (socket_name)
472 char *socket_name;
473 {
474 struct stat statbfr;
475
476 if (stat (socket_name, &statbfr) == -1)
477 return 2;
478
479 if (statbfr.st_uid != geteuid ())
480 return 1;
481
482 return 0;
483 }
484
485 /* Returns 1 if PREFIX is a prefix of STRING. */
486 static int
487 strprefix (char *prefix, char *string)
488 {
489 int i;
490 if (! prefix)
491 return 1;
492
493 if (!string)
494 return 0;
495
496 for (i = 0; prefix[i]; i++)
497 if (!string[i] || string[i] != prefix[i])
498 return 0;
499 return 1;
500 }
501
502 int
503 main (argc, argv)
504 int argc;
505 char **argv;
506 {
507 int s, i, needlf = 0;
508 struct sockaddr_un server;
509 char *cwd, *str;
510 char string[BUFSIZ];
511
512 main_argc = argc;
513 main_argv = argv;
514 progname = argv[0];
515
516 /* Process options. */
517 decode_options (argc, argv);
518
519 if ((argc - optind < 1) && !eval && !tty && !window_system)
520 {
521 fprintf (stderr, "%s: file name or argument required\n", progname);
522 fprintf (stderr, "Try `%s --help' for more information\n", progname);
523 exit (1);
524 }
525
526 /*
527 * Open up an AF_UNIX socket in this person's home directory
528 */
529
530 if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
531 {
532 fprintf (stderr, "%s: ", argv[0]);
533 perror ("socket");
534 fail ();
535 }
536
537 server.sun_family = AF_UNIX;
538
539 {
540 int sock_status = 0;
541 int default_sock = !socket_name;
542 int saved_errno = 0;
543
544 char *server_name = "server";
545
546 if (socket_name && !index (socket_name, '/') && !index (socket_name, '\\'))
547 { /* socket_name is a file name component. */
548 server_name = socket_name;
549 socket_name = NULL;
550 default_sock = 1; /* Try both UIDs. */
551 }
552
553 if (default_sock)
554 {
555 socket_name = alloca (100 + strlen (server_name));
556 sprintf (socket_name, "/tmp/emacs%d/%s",
557 (int) geteuid (), server_name);
558 }
559
560 if (strlen (socket_name) < sizeof (server.sun_path))
561 strcpy (server.sun_path, socket_name);
562 else
563 {
564 fprintf (stderr, "%s: socket-name %s too long",
565 argv[0], socket_name);
566 fail ();
567 }
568
569 /* See if the socket exists, and if it's owned by us. */
570 sock_status = socket_status (server.sun_path);
571 saved_errno = errno;
572 if (sock_status && default_sock)
573 {
574 /* Failing that, see if LOGNAME or USER exist and differ from
575 our euid. If so, look for a socket based on the UID
576 associated with the name. This is reminiscent of the logic
577 that init_editfns uses to set the global Vuser_full_name. */
578
579 char *user_name = (char *) getenv ("LOGNAME");
580
581 if (!user_name)
582 user_name = (char *) getenv ("USER");
583
584 if (user_name)
585 {
586 struct passwd *pw = getpwnam (user_name);
587
588 if (pw && (pw->pw_uid != geteuid ()))
589 {
590 /* We're running under su, apparently. */
591 socket_name = alloca (100 + strlen (server_name));
592 sprintf (socket_name, "/tmp/emacs%d/%s",
593 (int) pw->pw_uid, server_name);
594
595 if (strlen (socket_name) < sizeof (server.sun_path))
596 strcpy (server.sun_path, socket_name);
597 else
598 {
599 fprintf (stderr, "%s: socket-name %s too long",
600 argv[0], socket_name);
601 exit (1);
602 }
603
604 sock_status = socket_status (server.sun_path);
605 saved_errno = errno;
606 }
607 else
608 errno = saved_errno;
609 }
610 }
611
612 switch (sock_status)
613 {
614 case 1:
615 /* There's a socket, but it isn't owned by us. This is OK if
616 we are root. */
617 if (0 != geteuid ())
618 {
619 fprintf (stderr, "%s: Invalid socket owner\n", argv[0]);
620 fail ();
621 }
622 break;
623
624 case 2:
625 /* `stat' failed */
626 if (saved_errno == ENOENT)
627 fprintf (stderr,
628 "%s: can't find socket; have you started the server?\n\
629 To start the server in Emacs, type \"M-x server-start\".\n",
630 argv[0]);
631 else
632 fprintf (stderr, "%s: can't stat %s: %s\n",
633 argv[0], server.sun_path, strerror (saved_errno));
634 fail ();
635 break;
636 }
637 }
638
639 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
640 < 0)
641 {
642 fprintf (stderr, "%s: ", argv[0]);
643 perror ("connect");
644 fail ();
645 }
646
647 /* We use the stream OUT to send our commands to the server. */
648 if ((out = fdopen (s, "r+")) == NULL)
649 {
650 fprintf (stderr, "%s: ", argv[0]);
651 perror ("fdopen");
652 fail ();
653 }
654
655 /* We use the stream IN to read the responses.
656 We used to use just one stream for both output and input
657 on the socket, but reversing direction works nonportably:
658 on some systems, the output appears as the first input;
659 on other systems it does not. */
660 if ((in = fdopen (s, "r+")) == NULL)
661 {
662 fprintf (stderr, "%s: ", argv[0]);
663 perror ("fdopen");
664 fail ();
665 }
666
667 #ifdef HAVE_GETCWD
668 cwd = getcwd (string, sizeof string);
669 #else
670 cwd = getwd (string);
671 #endif
672 if (cwd == 0)
673 {
674 /* getwd puts message in STRING if it fails. */
675
676 #ifdef HAVE_GETCWD
677 fprintf (stderr, "%s: %s (%s)\n", argv[0],
678 "cannot get current working directory", strerror (errno));
679 #else
680 fprintf (stderr, "%s: %s (%s)\n", argv[0], string, strerror (errno));
681 #endif
682 fail ();
683 }
684
685 /* First of all, send our version number for verification. */
686 fprintf (out, "-version %s ", VERSION);
687
688 /* Send over our environment. */
689 {
690 extern char **environ;
691 int i;
692 for (i = 0; environ[i]; i++)
693 {
694 char *name = xstrdup (environ[i]);
695 char *value = strchr (name, '=');
696 if (value && strlen (value) > 1)
697 {
698 *value++ = 0;
699 fprintf (out, "-env ");
700 quote_argument (name, out);
701 fprintf (out, " ");
702 quote_argument (value, out);
703 fprintf (out, " ");
704 fflush (out);
705 }
706 free (name);
707 }
708 }
709
710 if (nowait)
711 fprintf (out, "-nowait ");
712
713 if (display)
714 {
715 fprintf (out, "-display ");
716 quote_argument (display, out);
717 fprintf (out, " ");
718 }
719
720 if (tty)
721 {
722 char *tty_name = ttyname (fileno (stdin));
723 char *type = getenv ("TERM");
724
725 if (! tty_name)
726 {
727 fprintf (stderr, "%s: could not get terminal name\n", progname);
728 fail ();
729 }
730
731 if (! type)
732 {
733 fprintf (stderr, "%s: please set the TERM variable to your terminal type\n",
734 progname);
735 fail ();
736 }
737
738 if (! strcmp (type, "eterm"))
739 {
740 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
741 fprintf (stderr, "%s: opening a frame in an Emacs term buffer"
742 " is not supported\n", progname);
743 fail ();
744 }
745
746 init_signals ();
747
748 fprintf (out, "-tty ");
749 quote_argument (tty_name, out);
750 fprintf (out, " ");
751 quote_argument (type, out);
752 fprintf (out, " ");
753 }
754
755 if (window_system)
756 fprintf (out, "-window-system ");
757
758 if ((argc - optind > 0))
759 {
760 for (i = optind; i < argc; i++)
761 {
762 int relative = 0;
763
764 if (eval)
765 {
766 /* Don't prepend any cwd or anything like that. */
767 fprintf (out, "-eval ");
768 quote_argument (argv[i], out);
769 fprintf (out, " ");
770 continue;
771 }
772
773 if (*argv[i] == '+')
774 {
775 char *p = argv[i] + 1;
776 while (isdigit ((unsigned char) *p) || *p == ':') p++;
777 if (*p == 0)
778 {
779 fprintf (out, "-position ");
780 quote_argument (argv[i], out);
781 fprintf (out, " ");
782 continue;
783 }
784 else
785 relative = 1;
786 }
787 else if (*argv[i] != '/')
788 relative = 1;
789
790 fprintf (out, "-file ");
791 if (relative)
792 {
793 quote_argument (cwd, out);
794 fprintf (out, "/");
795 }
796 quote_argument (argv[i], out);
797 fprintf (out, " ");
798 }
799 }
800 else
801 {
802 if (!tty && !window_system)
803 {
804 while ((str = fgets (string, BUFSIZ, stdin)))
805 {
806 if (eval)
807 fprintf (out, "-eval ");
808 else
809 fprintf (out, "-file ");
810 quote_argument (str, out);
811 }
812 fprintf (out, " ");
813 }
814 }
815
816 fprintf (out, "\n");
817 fflush (out);
818 fsync (fileno (out));
819
820 /* Maybe wait for an answer. */
821 if (nowait)
822 {
823 return 0;
824 }
825
826 if (!eval && !tty)
827 {
828 printf ("Waiting for Emacs...");
829 needlf = 2;
830 }
831 fflush (stdout);
832 fsync (1);
833
834 /* Now, wait for an answer and print any messages. */
835 while ((str = fgets (string, BUFSIZ, in)))
836 {
837 char *p = str + strlen (str) - 1;
838 while (p > str && *p == '\n')
839 *p-- = 0;
840
841 if (strprefix ("-good-version ", str))
842 {
843 /* OK, we got the green light. */
844 }
845 else if (strprefix ("-emacs-pid ", str))
846 {
847 emacs_pid = strtol (string + strlen ("-emacs-pid"), NULL, 10);
848 }
849 else if (strprefix ("-print ", str))
850 {
851 str = unquote_argument (str + strlen ("-print "));
852 if (needlf)
853 printf ("\n");
854 printf ("%s", str);
855 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
856 }
857 else if (strprefix ("-error ", str))
858 {
859 str = unquote_argument (str + strlen ("-error "));
860 if (needlf)
861 printf ("\n");
862 printf ("*ERROR*: %s", str);
863 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
864 }
865 else if (strprefix ("-suspend ", str))
866 {
867 if (needlf)
868 printf ("\n");
869 needlf = 0;
870 kill (0, SIGSTOP);
871 }
872 else
873 {
874 if (needlf)
875 printf ("\n");
876 printf ("*ERROR*: Unknown message: %s", str);
877 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
878 }
879 }
880
881 if (needlf)
882 printf ("\n");
883 fflush (stdout);
884 fsync (1);
885
886 return 0;
887 }
888
889 #endif /* HAVE_SOCKETS */
890 \f
891 #ifndef HAVE_STRERROR
892 char *
893 strerror (errnum)
894 int errnum;
895 {
896 extern char *sys_errlist[];
897 extern int sys_nerr;
898
899 if (errnum >= 0 && errnum < sys_nerr)
900 return sys_errlist[errnum];
901 return (char *) "Unknown error";
902 }
903
904 #endif /* ! HAVE_STRERROR */
905
906 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
907 (do not change this comment) */