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