(XMARKBIT, XUNMARK): Remove.
[emacs.git] / lib-src / emacsclient.c
blob820d172a9a15b246a3af54ec91b57bda60b5f090
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.
5 This file is part of GNU Emacs.
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.
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.
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. */
23 #define NO_SHORTNAMES
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
29 #undef signal
31 #include <ctype.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #ifdef HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif
38 #ifdef VMS
39 # include "vms-pwd.h"
40 #else
41 # include <pwd.h>
42 #endif /* not VMS */
44 char *getenv (), *getwd ();
45 char *getcwd ();
47 /* This is defined with -D from the compilation command,
48 which extracts it from ../lisp/version.el. */
50 #ifndef VERSION
51 #define VERSION "unspecified"
52 #endif
54 /* Name used to invoke this program. */
55 char *progname;
57 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
58 int nowait = 0;
60 /* Nonzero means args are expressions to be evaluated. --eval. */
61 int eval = 0;
63 /* The display on which Emacs should work. --display. */
64 char *display = NULL;
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;
70 /* If non-NULL, thefilename of the UNIX socket */
71 char *socket_name = NULL;
73 void print_help_and_exit ();
75 struct option longopts[] =
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 }
87 /* Decode the options from argv and argc.
88 The global variable `optind' will say how many arguments we used up. */
90 void
91 decode_options (argc, argv)
92 int argc;
93 char **argv;
95 while (1)
97 int opt = getopt_long (argc, argv,
98 "VHnea:s:d:", longopts, 0);
100 if (opt == EOF)
101 break;
103 alternate_editor = getenv ("ALTERNATE_EDITOR");
105 switch (opt)
107 case 0:
108 /* If getopt returns 0, then it has already processed a
109 long-named option. We should do nothing. */
110 break;
112 case 'a':
113 alternate_editor = optarg;
114 break;
116 case 's':
117 socket_name = optarg;
118 break;
120 case 'd':
121 display = optarg;
122 break;
124 case 'n':
125 nowait = 1;
126 break;
128 case 'e':
129 eval = 1;
130 break;
132 case 'V':
133 printf ("emacsclient %s\n", VERSION);
134 exit (0);
135 break;
137 case 'H':
138 print_help_and_exit ();
139 break;
141 default:
142 fprintf (stderr, "Try `%s --help' for more information\n", progname);
143 exit (1);
144 break;
149 void
150 print_help_and_exit ()
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\
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\
168 Report bugs to bug-gnu-emacs@gnu.org.\n", progname);
169 exit (0);
172 /* Return a copy of NAME, inserting a &
173 before each &, each space, each newline, and any initial -.
174 Change spaces to underscores, too, so that the
175 return value never contains a space. */
177 char *
178 quote_file_name (name)
179 char *name;
181 char *copy = (char *) malloc (strlen (name) * 2 + 1);
182 char *p, *q;
184 p = name;
185 q = copy;
186 while (*p)
188 if (*p == ' ')
190 *q++ = '&';
191 *q++ = '_';
192 p++;
194 else if (*p == '\n')
196 *q++ = '&';
197 *q++ = 'n';
198 p++;
200 else
202 if (*p == '&' || (*p == '-' && p == name))
203 *q++ = '&';
204 *q++ = *p++;
207 *q++ = 0;
209 return copy;
212 /* Like malloc but get fatal error if memory is exhausted. */
214 long *
215 xmalloc (size)
216 unsigned int size;
218 long *result = (long *) malloc (size);
219 if (result == NULL)
221 perror ("malloc");
222 exit (1);
224 return result;
228 Try to run a different command, or --if no alternate editor is
229 defined-- exit with an errorcode.
231 void
232 fail (argc, argv)
233 int argc;
234 char **argv;
236 if (alternate_editor)
238 int i = optind - 1;
239 execvp (alternate_editor, argv + i);
240 return;
242 else
244 exit (1);
250 #if !defined (HAVE_SOCKETS) || defined (NO_SOCKETS_IN_FILE_SYSTEM)
253 main (argc, argv)
254 int argc;
255 char **argv;
257 fprintf (stderr, "%s: Sorry, the Emacs server is supported only\n",
258 argv[0]);
259 fprintf (stderr, "on systems with Berkeley sockets.\n");
261 fail (argc, argv);
264 #else /* HAVE_SOCKETS */
266 #include <sys/types.h>
267 #include <sys/socket.h>
268 #include <sys/un.h>
269 #include <sys/stat.h>
270 #include <errno.h>
272 extern char *strerror ();
273 extern int errno;
275 /* Three possibilities:
276 2 - can't be `stat'ed (sets errno)
277 1 - isn't owned by us
278 0 - success: none of the above */
280 static int
281 socket_status (socket_name)
282 char *socket_name;
284 struct stat statbfr;
286 if (stat (socket_name, &statbfr) == -1)
287 return 2;
289 if (statbfr.st_uid != geteuid ())
290 return 1;
292 return 0;
296 main (argc, argv)
297 int argc;
298 char **argv;
300 char *system_name;
301 int system_name_length;
302 int s, i, needlf = 0;
303 FILE *out, *in;
304 struct sockaddr_un server;
305 char *cwd, *str;
306 char string[BUFSIZ];
308 progname = argv[0];
310 /* Process options. */
311 decode_options (argc, argv);
313 if (argc - optind < 1)
315 fprintf (stderr, "%s: file name or argument required\n", progname);
316 fprintf (stderr, "Try `%s --help' for more information\n", progname);
317 exit (1);
321 * Open up an AF_UNIX socket in this person's home directory
324 if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
326 fprintf (stderr, "%s: ", argv[0]);
327 perror ("socket");
328 fail (argc, argv);
331 server.sun_family = AF_UNIX;
334 char *dot;
335 system_name_length = 32;
337 while (1)
339 system_name = (char *) xmalloc (system_name_length + 1);
341 /* system_name must be null-terminated string. */
342 system_name[system_name_length] = '\0';
344 if (gethostname (system_name, system_name_length) == 0)
345 break;
347 free (system_name);
348 system_name_length *= 2;
351 /* We always use the non-dotted host name, for simplicity. */
352 dot = index (system_name, '.');
353 if (dot)
354 *dot = '\0';
358 int sock_status = 0;
360 if (! socket_name)
362 socket_name = alloca (system_name_length + 100);
363 sprintf (socket_name, "/tmp/emacs%d-%s/server",
364 (int) geteuid (), system_name);
367 if (strlen (socket_name) < sizeof (server.sun_path))
368 strcpy (server.sun_path, socket_name);
369 else
370 fprintf (stderr, "%s: socket-name %s too long",
371 argv[0], socket_name);
373 /* See if the socket exists, and if it's owned by us. */
374 sock_status = socket_status (server.sun_path);
375 if (sock_status)
377 /* Failing that, see if LOGNAME or USER exist and differ from
378 our euid. If so, look for a socket based on the UID
379 associated with the name. This is reminiscent of the logic
380 that init_editfns uses to set the global Vuser_full_name. */
382 char *user_name = (char *) getenv ("LOGNAME");
383 if (!user_name)
384 user_name = (char *) getenv ("USER");
386 if (user_name)
388 struct passwd *pw = getpwnam (user_name);
389 if (pw && (pw->pw_uid != geteuid ()))
391 /* We're running under su, apparently. */
392 sprintf (server.sun_path, "/tmp/esrv%d-%s",
393 (int) pw->pw_uid, system_name);
394 sock_status = socket_status (server.sun_path);
399 switch (sock_status)
401 case 1:
402 /* There's a socket, but it isn't owned by us. This is OK if
403 we are root. */
404 if (0 != geteuid ())
406 fprintf (stderr, "%s: Invalid socket owner\n", argv[0]);
407 fail (argc, argv);
409 break;
411 case 2:
412 /* `stat' failed */
413 if (errno == ENOENT)
414 fprintf (stderr,
415 "%s: can't find socket; have you started the server?\n\
416 To start the server in Emacs, type \"M-x server-start\".\n",
417 argv[0]);
418 else
419 fprintf (stderr, "%s: can't stat %s: %s\n",
420 argv[0], server.sun_path, strerror (errno));
421 fail (argc, argv);
422 break;
426 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
427 < 0)
429 fprintf (stderr, "%s: ", argv[0]);
430 perror ("connect");
431 fail (argc, argv);
434 /* We use the stream OUT to send our command to the server. */
435 if ((out = fdopen (s, "r+")) == NULL)
437 fprintf (stderr, "%s: ", argv[0]);
438 perror ("fdopen");
439 fail (argc, argv);
442 /* We use the stream IN to read the response.
443 We used to use just one stream for both output and input
444 on the socket, but reversing direction works nonportably:
445 on some systems, the output appears as the first input;
446 on other systems it does not. */
447 if ((in = fdopen (s, "r+")) == NULL)
449 fprintf (stderr, "%s: ", argv[0]);
450 perror ("fdopen");
451 fail (argc, argv);
454 #ifdef HAVE_GETCWD
455 cwd = getcwd (string, sizeof string);
456 #else
457 cwd = getwd (string);
458 #endif
459 if (cwd == 0)
461 /* getwd puts message in STRING if it fails. */
463 #ifdef HAVE_GETCWD
464 fprintf (stderr, "%s: %s (%s)\n", argv[0],
465 "Cannot get current working directory", strerror (errno));
466 #else
467 fprintf (stderr, "%s: %s (%s)\n", argv[0], string, strerror (errno));
468 #endif
469 fail (argc, argv);
472 if (nowait)
473 fprintf (out, "-nowait ");
475 if (eval)
476 fprintf (out, "-eval ");
478 if (display)
479 fprintf (out, "-display %s ", quote_file_name (display));
481 for (i = optind; i < argc; i++)
483 if (eval)
484 ; /* Don't prepend any cwd or anything like that. */
485 else if (*argv[i] == '+')
487 char *p = argv[i] + 1;
488 while (isdigit ((unsigned char) *p) || *p == ':') p++;
489 if (*p != 0)
490 fprintf (out, "%s/", quote_file_name (cwd));
492 else if (*argv[i] != '/')
493 fprintf (out, "%s/", quote_file_name (cwd));
495 fprintf (out, "%s ", quote_file_name (argv[i]));
497 fprintf (out, "\n");
498 fflush (out);
500 /* Maybe wait for an answer. */
501 if (nowait)
502 return 0;
504 if (!eval)
506 printf ("Waiting for Emacs...");
507 needlf = 2;
509 fflush (stdout);
511 /* Now, wait for an answer and print any messages. */
512 while ((str = fgets (string, BUFSIZ, in)))
514 if (needlf == 2)
515 printf ("\n");
516 printf ("%s", str);
517 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
520 if (needlf)
521 printf ("\n");
522 fflush (stdout);
524 return 0;
527 #endif /* HAVE_SOCKETS */
529 #ifndef HAVE_STRERROR
530 char *
531 strerror (errnum)
532 int errnum;
534 extern char *sys_errlist[];
535 extern int sys_nerr;
537 if (errnum >= 0 && errnum < sys_nerr)
538 return sys_errlist[errnum];
539 return (char *) "Unknown error";
542 #endif /* ! HAVE_STRERROR */
544 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
545 (do not change this comment) */