Merged in changes from CVS HEAD
[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, 2003
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 /* The display on which Emacs should work. --display. */
74 char *display = NULL;
75
76 /* Nonzero means open a new Emacs frame on the current terminal. */
77 int frame = 0;
78
79 /* If non-NULL, the name of an editor to fallback to if the server
80 is not running. --alternate-editor. */
81 const char * alternate_editor = NULL;
82
83 /* If non-NULL, the filename of the UNIX socket. */
84 char *socket_name = NULL;
85
86 void print_help_and_exit ();
87
88 struct option longopts[] =
89 {
90 { "no-wait", no_argument, NULL, 'n' },
91 { "eval", no_argument, NULL, 'e' },
92 { "help", no_argument, NULL, 'H' },
93 { "version", no_argument, NULL, 'V' },
94 { "tty", no_argument, NULL, 't' },
95 { "alternate-editor", required_argument, NULL, 'a' },
96 { "socket-name", required_argument, NULL, 's' },
97 { "display", required_argument, NULL, 'd' },
98 { 0, 0, 0, 0 }
99 };
100
101 /* Decode the options from argv and argc.
102 The global variable `optind' will say how many arguments we used up. */
103
104 void
105 decode_options (argc, argv)
106 int argc;
107 char **argv;
108 {
109 while (1)
110 {
111 int opt = getopt_long (argc, argv,
112 "VHnea:s:d:t", longopts, 0);
113
114 if (opt == EOF)
115 break;
116
117 alternate_editor = getenv ("ALTERNATE_EDITOR");
118
119 switch (opt)
120 {
121 case 0:
122 /* If getopt returns 0, then it has already processed a
123 long-named option. We should do nothing. */
124 break;
125
126 case 'a':
127 alternate_editor = optarg;
128 break;
129
130 case 's':
131 socket_name = optarg;
132 break;
133
134 case 'd':
135 display = optarg;
136 break;
137
138 case 'n':
139 nowait = 1;
140 break;
141
142 case 'e':
143 eval = 1;
144 break;
145
146 case 'V':
147 printf ("emacsclient %s\n", VERSION);
148 exit (0);
149 break;
150
151 case 't':
152 frame = 1;
153 break;
154
155 case 'H':
156 print_help_and_exit ();
157 break;
158
159 default:
160 fprintf (stderr, "Try `%s --help' for more information\n", progname);
161 exit (1);
162 break;
163 }
164 }
165
166 if (frame) {
167 nowait = 0;
168 display = 0;
169 }
170
171 }
172
173 void
174 print_help_and_exit ()
175 {
176 printf (
177 "Usage: %s [OPTIONS] FILE...\n\
178 Tell the Emacs server to visit the specified files.\n\
179 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
180 \n\
181 The following OPTIONS are accepted:\n\
182 -V, --version Just print a version info and return\n\
183 -H, --help Print this usage information message\n\
184 -t, --tty Open a new Emacs frame on the current terminal\n\
185 -n, --no-wait Don't wait for the server to return\n\
186 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
187 -d, --display=DISPLAY Visit the file in the given display\n\
188 -s, --socket-name=FILENAME\n\
189 Set the filename of the UNIX socket for communication\n\
190 -a, --alternate-editor=EDITOR\n\
191 Editor to fallback to if the server is not running\n\
192 \n\
193 Report bugs to bug-gnu-emacs@gnu.org.\n", progname);
194 exit (0);
195 }
196
197 /* In NAME, insert a & before each &, each space, each newline, and
198 any initial -. Change spaces to underscores, too, so that the
199 return value never contains a space. */
200
201 void
202 quote_file_name (name, stream)
203 char *name;
204 FILE *stream;
205 {
206 char *copy = (char *) malloc (strlen (name) * 2 + 1);
207 char *p, *q;
208
209 p = name;
210 q = copy;
211 while (*p)
212 {
213 if (*p == ' ')
214 {
215 *q++ = '&';
216 *q++ = '_';
217 p++;
218 }
219 else if (*p == '\n')
220 {
221 *q++ = '&';
222 *q++ = 'n';
223 p++;
224 }
225 else
226 {
227 if (*p == '&' || (*p == '-' && p == name))
228 *q++ = '&';
229 *q++ = *p++;
230 }
231 }
232 *q++ = 0;
233
234 fprintf (stream, copy);
235
236 free (copy);
237 }
238
239 /* Like malloc but get fatal error if memory is exhausted. */
240
241 long *
242 xmalloc (size)
243 unsigned int size;
244 {
245 long *result = (long *) malloc (size);
246 if (result == NULL)
247 {
248 perror ("malloc");
249 exit (1);
250 }
251 return result;
252 }
253 \f
254 /*
255 Try to run a different command, or --if no alternate editor is
256 defined-- exit with an errorcode.
257 */
258 void
259 fail (void)
260 {
261 if (alternate_editor)
262 {
263 int i = optind - 1;
264 execvp (alternate_editor, main_argv + i);
265 return;
266 }
267 else
268 {
269 exit (1);
270 }
271 }
272
273 int emacs_pid;
274
275 #ifdef nec_ews_svr4
276 extern char *_sobuf ;
277 #else
278 #if defined (USG) || defined (DGUX)
279 unsigned char _sobuf[BUFSIZ+8];
280 #else
281 char _sobuf[BUFSIZ];
282 #endif
283 #endif
284
285 SIGTYPE
286 pass_signal_to_emacs (int signalnum)
287 {
288 int old_errno = errno;
289
290 if (emacs_pid)
291 kill (emacs_pid, signalnum);
292
293 signal (signalnum, pass_signal_to_emacs);
294 errno = old_errno;
295 }
296
297 void
298 init_signals (void)
299 {
300 /* Set up signal handlers. */
301 signal (SIGWINCH, pass_signal_to_emacs);
302
303 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
304 deciding which terminal the signal came from. C-g is now a
305 normal input event on secondary terminals. */
306 #if 0
307 signal (SIGINT, pass_signal_to_emacs);
308 signal (SIGQUIT, pass_signal_to_emacs);
309 #endif
310 }
311
312 \f
313 #if !defined (HAVE_SOCKETS) || defined (NO_SOCKETS_IN_FILE_SYSTEM)
314
315 int
316 main (argc, argv)
317 int argc;
318 char **argv;
319 {
320 fprintf (stderr, "%s: Sorry, the Emacs server is supported only\n",
321 argv[0]);
322 fprintf (stderr, "on systems with Berkeley sockets.\n");
323
324 fail ();
325 }
326
327 #else /* HAVE_SOCKETS */
328
329 #include <sys/types.h>
330 #include <sys/socket.h>
331 #include <sys/un.h>
332 #include <sys/stat.h>
333 #include <errno.h>
334
335 extern char *strerror ();
336 extern int errno;
337
338 /* Three possibilities:
339 2 - can't be `stat'ed (sets errno)
340 1 - isn't owned by us
341 0 - success: none of the above */
342
343 static int
344 socket_status (socket_name)
345 char *socket_name;
346 {
347 struct stat statbfr;
348
349 if (stat (socket_name, &statbfr) == -1)
350 return 2;
351
352 if (statbfr.st_uid != geteuid ())
353 return 1;
354
355 return 0;
356 }
357
358 /* Returns 1 if PREFIX is a prefix of STRING. */
359 static int
360 strprefix (char *prefix, char *string)
361 {
362 int i;
363 if (! prefix)
364 return 1;
365
366 if (!string)
367 return 0;
368
369 for (i = 0; prefix[i]; i++)
370 if (!string[i] || string[i] != prefix[i])
371 return 0;
372 return 1;
373 }
374
375 int
376 main (argc, argv)
377 int argc;
378 char **argv;
379 {
380 char *system_name;
381 int system_name_length;
382 int s, i, needlf = 0;
383 FILE *out, *in;
384 struct sockaddr_un server;
385 char *cwd, *str;
386 char string[BUFSIZ];
387
388 main_argc = argc;
389 main_argv = argv;
390 progname = argv[0];
391
392 /* Process options. */
393 decode_options (argc, argv);
394
395 if ((argc - optind < 1) && !eval && !frame)
396 {
397 fprintf (stderr, "%s: file name or argument required\n", progname);
398 fprintf (stderr, "Try `%s --help' for more information\n", progname);
399 exit (1);
400 }
401
402 /*
403 * Open up an AF_UNIX socket in this person's home directory
404 */
405
406 if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
407 {
408 fprintf (stderr, "%s: ", argv[0]);
409 perror ("socket");
410 fail ();
411 }
412
413 server.sun_family = AF_UNIX;
414
415 {
416 char *dot;
417 system_name_length = 32;
418
419 while (1)
420 {
421 system_name = (char *) xmalloc (system_name_length + 1);
422
423 /* system_name must be null-terminated string. */
424 system_name[system_name_length] = '\0';
425
426 if (gethostname (system_name, system_name_length) == 0)
427 break;
428
429 free (system_name);
430 system_name_length *= 2;
431 }
432
433 /* We always use the non-dotted host name, for simplicity. */
434 dot = index (system_name, '.');
435 if (dot)
436 *dot = '\0';
437 }
438
439 {
440 int sock_status = 0;
441 int saved_errno = 0;
442
443 if (! socket_name)
444 {
445 socket_name = alloca (system_name_length + 100);
446 sprintf (socket_name, "/tmp/emacs%d-%s/server",
447 (int) geteuid (), system_name);
448 }
449
450 if (strlen (socket_name) < sizeof (server.sun_path))
451 strcpy (server.sun_path, socket_name);
452 else
453 {
454 fprintf (stderr, "%s: socket-name %s too long",
455 argv[0], socket_name);
456 fail ();
457 }
458
459 /* See if the socket exists, and if it's owned by us. */
460 sock_status = socket_status (server.sun_path);
461 saved_errno = errno;
462 if (sock_status)
463 {
464 /* Failing that, see if LOGNAME or USER exist and differ from
465 our euid. If so, look for a socket based on the UID
466 associated with the name. This is reminiscent of the logic
467 that init_editfns uses to set the global Vuser_full_name. */
468
469 char *user_name = (char *) getenv ("LOGNAME");
470 if (!user_name)
471 user_name = (char *) getenv ("USER");
472
473 if (user_name)
474 {
475 struct passwd *pw = getpwnam (user_name);
476 if (pw && (pw->pw_uid != geteuid ()))
477 {
478 /* We're running under su, apparently. */
479 sprintf (server.sun_path, "/tmp/emacs%d-%s/server",
480 (int) pw->pw_uid, system_name);
481 sock_status = socket_status (server.sun_path);
482 saved_errno = errno;
483 }
484 }
485 }
486
487 switch (sock_status)
488 {
489 case 1:
490 /* There's a socket, but it isn't owned by us. This is OK if
491 we are root. */
492 if (0 != geteuid ())
493 {
494 fprintf (stderr, "%s: Invalid socket owner\n", argv[0]);
495 fail ();
496 }
497 break;
498
499 case 2:
500 /* `stat' failed */
501 if (saved_errno == ENOENT)
502 fprintf (stderr,
503 "%s: Can't find socket; have you started the server?\n\
504 To start the server in Emacs, type \"M-x server-start\".\n",
505 argv[0]);
506 else
507 fprintf (stderr, "%s: Can't stat %s: %s\n",
508 argv[0], server.sun_path, strerror (saved_errno));
509 fail ();
510 break;
511 }
512 }
513
514 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
515 < 0)
516 {
517 fprintf (stderr, "%s: ", argv[0]);
518 perror ("connect");
519 fail ();
520 }
521
522 /* We use the stream OUT to send our command to the server. */
523 if ((out = fdopen (s, "r+")) == NULL)
524 {
525 fprintf (stderr, "%s: ", argv[0]);
526 perror ("fdopen");
527 fail ();
528 }
529
530 /* We use the stream IN to read the response.
531 We used to use just one stream for both output and input
532 on the socket, but reversing direction works nonportably:
533 on some systems, the output appears as the first input;
534 on other systems it does not. */
535 if ((in = fdopen (s, "r+")) == NULL)
536 {
537 fprintf (stderr, "%s: ", argv[0]);
538 perror ("fdopen");
539 fail ();
540 }
541
542 #ifdef HAVE_GETCWD
543 cwd = getcwd (string, sizeof string);
544 #else
545 cwd = getwd (string);
546 #endif
547 if (cwd == 0)
548 {
549 /* getwd puts message in STRING if it fails. */
550
551 #ifdef HAVE_GETCWD
552 fprintf (stderr, "%s: %s (%s)\n", argv[0],
553 "Cannot get current working directory", strerror (errno));
554 #else
555 fprintf (stderr, "%s: %s (%s)\n", argv[0], string, strerror (errno));
556 #endif
557 fail ();
558 }
559
560 if (nowait)
561 fprintf (out, "-nowait ");
562
563 if (eval)
564 fprintf (out, "-eval ");
565
566 if (display)
567 {
568 fprintf (out, "-display ");
569 quote_file_name (display, out);
570 fprintf (out, " ");
571 }
572
573 if (frame)
574 {
575 char *tty_name = ttyname (fileno (stdin));
576 if (! tty_name)
577 fail ();
578
579 init_signals ();
580
581 fprintf (out, "-tty ");
582 quote_file_name (tty_name, out);
583 fprintf (out, " ");
584 quote_file_name (getenv("TERM"), out);
585 fprintf (out, " ");
586 }
587
588 if ((argc - optind > 0))
589 {
590 for (i = optind; i < argc; i++)
591 {
592 if (eval)
593 ; /* Don't prepend any cwd or anything like that. */
594 else if (*argv[i] == '+')
595 {
596 char *p = argv[i] + 1;
597 while (isdigit ((unsigned char) *p) || *p == ':') p++;
598 if (*p != 0)
599 {
600 quote_file_name (cwd, out);
601 fprintf (out, "/");
602 }
603 }
604 else if (*argv[i] != '/')
605 {
606 quote_file_name (cwd, out);
607 fprintf (out, "/");
608 }
609
610 quote_file_name (argv[i], out);
611 fprintf (out, " ");
612 }
613 }
614 else
615 {
616 if (!frame)
617 {
618 while ((str = fgets (string, BUFSIZ, stdin)))
619 {
620 quote_file_name (str, out);
621 }
622 fprintf (out, " ");
623 }
624 }
625
626 fprintf (out, "\n");
627 fflush (out);
628
629 /* Maybe wait for an answer. */
630 if (nowait)
631 {
632 return 0;
633 }
634
635 if (!eval && !frame)
636 {
637 printf ("Waiting for Emacs...");
638 needlf = 2;
639 }
640 fflush (stdout);
641
642 /* Now, wait for an answer and print any messages. */
643 while ((str = fgets (string, BUFSIZ, in)))
644 {
645 if (frame)
646 {
647 if (strprefix ("emacs-pid ", str))
648 {
649 emacs_pid = strtol (string + strlen ("emacs-pid"), NULL, 10);
650 }
651 }
652 else
653 {
654 if (needlf == 2)
655 printf ("\n");
656 printf ("%s", str);
657 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
658 }
659 }
660
661 if (needlf)
662 printf ("\n");
663 fflush (stdout);
664
665 return 0;
666 }
667
668 #endif /* HAVE_SOCKETS */
669 \f
670 #ifndef HAVE_STRERROR
671 char *
672 strerror (errnum)
673 int errnum;
674 {
675 extern char *sys_errlist[];
676 extern int sys_nerr;
677
678 if (errnum >= 0 && errnum < sys_nerr)
679 return sys_errlist[errnum];
680 return (char *) "Unknown error";
681 }
682
683 #endif /* ! HAVE_STRERROR */
684
685 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
686 (do not change this comment) */