emacsclient.c 12.5 KB
Newer Older
Jim Blandy's avatar
Jim Blandy committed
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.
Richard M. Stallman's avatar
Richard M. Stallman committed
4 5 6 7 8

This file is part of GNU Emacs.

GNU Emacs is free software; you can redistribute it and/or modify
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)
Richard M. Stallman's avatar
Richard M. Stallman committed
10 11 12 13 14 15 16 17 18
any later version.

GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Emacs; see the file COPYING.  If not, write to
19 20
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.  */
Richard M. Stallman's avatar
Richard M. Stallman committed
21 22 23


#define NO_SHORTNAMES
24 25

#ifdef HAVE_CONFIG_H
Pavel Janík's avatar
Pavel Janík committed
26
#include <config.h>
27 28
#endif

29
#undef signal
Richard M. Stallman's avatar
Richard M. Stallman committed
30

31
#include <ctype.h>
32 33
#include <stdio.h>
#include <getopt.h>
34 35 36
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
37

38 39 40 41 42 43
#ifdef VMS
# include "vms-pwd.h"
#else
# include <pwd.h>
#endif /* not VMS */

44 45 46 47 48 49 50 51 52 53 54 55 56
char *getenv (), *getwd ();
char *getcwd ();

/* This is defined with -D from the compilation command,
   which extracts it from ../lisp/version.el.  */

#ifndef VERSION
#define VERSION "unspecified"
#endif

/* Name used to invoke this program.  */
char *progname;

57
/* Nonzero means don't wait for a response from Emacs.  --no-wait.  */
58 59
int nowait = 0;

Stefan Monnier's avatar
Stefan Monnier committed
60 61 62 63 64 65 66 67 68 69
/* Nonzero means args are expressions to be evaluated.  --eval.  */
int eval = 0;

/* The display on which Emacs should work.  --display.  */
char *display = NULL;

/* If non-NULL, the name of an editor to fallback to if the server
   is not running.  --alternate-editor.   */
const char * alternate_editor = NULL;

Richard M. Stallman's avatar
Richard M. Stallman committed
70
/* If non-NULL, the filename of the UNIX socket.  */
71 72
char *socket_name = NULL;

73 74
void print_help_and_exit ();

75 76
struct option longopts[] =
{
77
  { "no-wait",	no_argument,	   NULL, 'n' },
Stefan Monnier's avatar
Stefan Monnier committed
78
  { "eval",	no_argument,	   NULL, 'e' },
79 80
  { "help",	no_argument,	   NULL, 'H' },
  { "version",	no_argument,	   NULL, 'V' },
Stefan Monnier's avatar
Stefan Monnier committed
81
  { "alternate-editor", required_argument, NULL, 'a' },
82
  { "socket-name",	required_argument, NULL, 's' },
Stefan Monnier's avatar
Stefan Monnier committed
83 84
  { "display",	required_argument, NULL, 'd' },
  { 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 92 93 94 95 96 97
decode_options (argc, argv)
     int argc;
     char **argv;
{
  while (1)
    {
      int opt = getopt_long (argc, argv,
98
			     "VHnea:s:d:", longopts, 0);
99 100 101 102

      if (opt == EOF)
	break;

103
      alternate_editor = getenv ("ALTERNATE_EDITOR");
104

105 106 107 108 109 110
      switch (opt)
	{
	case 0:
	  /* If getopt returns 0, then it has already processed a
	     long-named option.  We should do nothing.  */
	  break;
111

112 113 114
	case 'a':
	  alternate_editor = optarg;
	  break;
115

116 117 118 119
	case 's':
	  socket_name = optarg;
	  break;

Stefan Monnier's avatar
Stefan Monnier committed
120 121 122 123
	case 'd':
	  display = optarg;
	  break;

124 125 126 127
	case 'n':
	  nowait = 1;
	  break;

Stefan Monnier's avatar
Stefan Monnier committed
128 129 130 131
	case 'e':
	  eval = 1;
	  break;

132
	case 'V':
133 134
	  printf ("emacsclient %s\n", VERSION);
	  exit (0);
135
	  break;
Richard M. Stallman's avatar
Richard M. Stallman committed
136

137 138
	case 'H':
	  print_help_and_exit ();
139 140 141 142 143 144
	  break;

	default:
	  fprintf (stderr, "Try `%s --help' for more information\n", progname);
	  exit (1);
	  break;
145 146 147 148
	}
    }
}

149
void
150 151
print_help_and_exit ()
{
152 153
  printf (
	  "Usage: %s [OPTIONS] FILE...\n\
Stefan Monnier's avatar
Stefan Monnier committed
154 155
Tell the Emacs server to visit the specified files.\n\
Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
156
\n\
Stefan Monnier's avatar
Stefan Monnier committed
157 158 159 160 161 162
The following OPTIONS are accepted:\n\
-V, --version           Just print a version info and return\n\
-H, --help              Print this usage information message\n\
-n, --no-wait           Don't wait for the server to return\n\
-e, --eval              Evaluate the FILE arguments as ELisp expressions\n\
-d, --display=DISPLAY   Visit the file in the given display\n\
163 164
-s, --socket-name=FILENAME\n\
                        Set the filename of the UNIX socket for communication\n\
Stefan Monnier's avatar
Stefan Monnier committed
165 166
-a, --alternate-editor=EDITOR\n\
                        Editor to fallback to if the server is not running\n\
167
\n\
Stefan Monnier's avatar
Stefan Monnier committed
168
Report bugs to bug-gnu-emacs@gnu.org.\n", progname);
169
  exit (0);
170
}
171

Richard M. Stallman's avatar
Richard M. Stallman committed
172 173
/* In NAME, insert a & before each &, each space, each newline, and
   any initial -.  Change spaces to underscores, too, so that the
174 175
   return value never contains a space.  */

176 177
void
quote_file_name (name, stream)
178
     char *name;
179
     FILE *stream;
180 181 182 183 184 185 186 187 188 189
{
  char *copy = (char *) malloc (strlen (name) * 2 + 1);
  char *p, *q;

  p = name;
  q = copy;
  while (*p)
    {
      if (*p == ' ')
	{
190
	  *q++ = '&';
191 192 193
	  *q++ = '_';
	  p++;
	}
Stefan Monnier's avatar
Stefan Monnier committed
194 195 196 197 198 199
      else if (*p == '\n')
	{
	  *q++ = '&';
	  *q++ = 'n';
	  p++;
	}
200 201
      else
	{
202 203
	  if (*p == '&' || (*p == '-' && p == name))
	    *q++ = '&';
204 205 206
	  *q++ = *p++;
	}
    }
207
  *q++ = 0;
208

209 210 211
  fprintf (stream, copy);

  free (copy);
212
}
213 214 215

/* Like malloc but get fatal error if memory is exhausted.  */

216
long *
217 218 219
xmalloc (size)
     unsigned int size;
{
220
  long *result = (long *) malloc (size);
221 222 223 224 225 226 227
  if (result == NULL)
  {
    perror ("malloc");
    exit (1);
  }
  return result;
}
228 229 230 231 232

/*
  Try to run a different command, or --if no alternate editor is
  defined-- exit with an errorcode.
*/
233
void
234 235 236 237 238 239
fail (argc, argv)
     int argc;
     char **argv;
{
  if (alternate_editor)
    {
Stefan Monnier's avatar
Stefan Monnier committed
240
      int i = optind - 1;
241
      execvp (alternate_editor, argv + i);
Dave Love's avatar
Dave Love committed
242
      return;
243 244 245 246 247 248 249 250
    }
  else
    {
      exit (1);
    }
}


251

Stefan Monnier's avatar
Stefan Monnier committed
252
#if !defined (HAVE_SOCKETS) || defined (NO_SOCKETS_IN_FILE_SYSTEM)
Richard M. Stallman's avatar
Richard M. Stallman committed
253

254
int
Richard M. Stallman's avatar
Richard M. Stallman committed
255 256 257 258 259 260
main (argc, argv)
     int argc;
     char **argv;
{
  fprintf (stderr, "%s: Sorry, the Emacs server is supported only\n",
	   argv[0]);
Stefan Monnier's avatar
Stefan Monnier committed
261
  fprintf (stderr, "on systems with Berkeley sockets.\n");
262 263

  fail (argc, argv);
Richard M. Stallman's avatar
Richard M. Stallman committed
264 265
}

Stefan Monnier's avatar
Stefan Monnier committed
266
#else /* HAVE_SOCKETS */
Richard M. Stallman's avatar
Richard M. Stallman committed
267 268 269 270

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
Jim Blandy's avatar
Jim Blandy committed
271
#include <sys/stat.h>
Richard M. Stallman's avatar
Richard M. Stallman committed
272 273
#include <errno.h>

274
extern char *strerror ();
Richard M. Stallman's avatar
Richard M. Stallman committed
275 276
extern int errno;

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
/* Three possibilities:
   2 - can't be `stat'ed		(sets errno)
   1 - isn't owned by us
   0 - success: none of the above */

static int
socket_status (socket_name)
     char *socket_name;
{
  struct stat statbfr;

  if (stat (socket_name, &statbfr) == -1)
    return 2;

  if (statbfr.st_uid != geteuid ())
    return 1;

  return 0;
}

297
int
Richard M. Stallman's avatar
Richard M. Stallman committed
298 299 300 301
main (argc, argv)
     int argc;
     char **argv;
{
302 303
  char *system_name;
  int system_name_length;
Stefan Monnier's avatar
Stefan Monnier committed
304
  int s, i, needlf = 0;
305
  FILE *out, *in;
Richard M. Stallman's avatar
Richard M. Stallman committed
306
  struct sockaddr_un server;
307
  char *cwd, *str;
Richard M. Stallman's avatar
Richard M. Stallman committed
308
  char string[BUFSIZ];
309 310

  progname = argv[0];
Richard M. Stallman's avatar
Richard M. Stallman committed
311

312
  /* Process options.  */
313
  decode_options (argc, argv);
Richard M. Stallman's avatar
Richard M. Stallman committed
314

315
  if ((argc - optind < 1) && !eval)
316 317 318 319 320
    {
      fprintf (stderr, "%s: file name or argument required\n", progname);
      fprintf (stderr, "Try `%s --help' for more information\n", progname);
      exit (1);
    }
Richard M. Stallman's avatar
Richard M. Stallman committed
321

322
  /*
Richard M. Stallman's avatar
Richard M. Stallman committed
323 324 325 326 327 328 329
   * Open up an AF_UNIX socket in this person's home directory
   */

  if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
    {
      fprintf (stderr, "%s: ", argv[0]);
      perror ("socket");
330
      fail (argc, argv);
Richard M. Stallman's avatar
Richard M. Stallman committed
331
    }
332

Richard M. Stallman's avatar
Richard M. Stallman committed
333
  server.sun_family = AF_UNIX;
334

Jim Blandy's avatar
Jim Blandy committed
335
  {
336
    char *dot;
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
    system_name_length = 32;

    while (1)
      {
	system_name = (char *) xmalloc (system_name_length + 1);

	/* system_name must be null-terminated string.  */
	system_name[system_name_length] = '\0';

 	if (gethostname (system_name, system_name_length) == 0)
	  break;

	free (system_name);
	system_name_length *= 2;
      }
352 353 354 355 356

    /* We always use the non-dotted host name, for simplicity.  */
    dot = index (system_name, '.');
    if (dot)
      *dot = '\0';
357 358 359
  }

  {
360
    int sock_status = 0;
361
    int default_sock = !socket_name;
362
    int saved_errno;
Jim Blandy's avatar
Jim Blandy committed
363

364
    if (default_sock)
365 366 367 368 369 370 371 372 373
      {
	socket_name = alloca (system_name_length + 100);
	sprintf (socket_name, "/tmp/emacs%d-%s/server",
		 (int) geteuid (), system_name);
      }

    if (strlen (socket_name) < sizeof (server.sun_path))
      strcpy (server.sun_path, socket_name);
    else
374 375 376 377 378
      {
	fprintf (stderr, "%s: socket-name %s too long",
		 argv[0], socket_name);
	exit (1);
      }
Jim Blandy's avatar
Jim Blandy committed
379

380 381
    /* See if the socket exists, and if it's owned by us. */
    sock_status = socket_status (server.sun_path);
382
    saved_errno = errno;
383
    if (sock_status && default_sock)
Jim Blandy's avatar
Jim Blandy committed
384
      {
385 386 387 388
	/* Failing that, see if LOGNAME or USER exist and differ from
	   our euid.  If so, look for a socket based on the UID
	   associated with the name.  This is reminiscent of the logic
	   that init_editfns uses to set the global Vuser_full_name.  */
389

390
	char *user_name = (char *) getenv ("LOGNAME");
391

392 393
	if (!user_name)
	  user_name = (char *) getenv ("USER");
394

395 396 397
	if (user_name)
	  {
	    struct passwd *pw = getpwnam (user_name);
398

399 400 401
	    if (pw && (pw->pw_uid != geteuid ()))
	      {
		/* We're running under su, apparently. */
402
		sprintf (socket_name, "/tmp/emacs%d-%s/server",
Dave Love's avatar
Dave Love committed
403
			 (int) pw->pw_uid, system_name);
404 405 406 407 408 409 410 411 412 413

		if (strlen (socket_name) < sizeof (server.sun_path))
		  strcpy (server.sun_path, socket_name);
		else
		  {
		    fprintf (stderr, "%s: socket-name %s too long",
			     argv[0], socket_name);
		    exit (1);
		  }

414
		sock_status = socket_status (server.sun_path);
415
		saved_errno = errno;
416
	      }
417 418
	    else
	      errno = saved_errno;
419
	  }
Jim Blandy's avatar
Jim Blandy committed
420
      }
421

422 423 424 425 426 427 428 429 430 431 432
     switch (sock_status)
       {
       case 1:
	 /* There's a socket, but it isn't owned by us.  This is OK if
	    we are root. */
	 if (0 != geteuid ())
	   {
	     fprintf (stderr, "%s: Invalid socket owner\n", argv[0]);
	     fail (argc, argv);
	   }
	 break;
433

434 435
       case 2:
	 /* `stat' failed */
436
	 if (saved_errno == ENOENT)
437
	   fprintf (stderr,
438 439
		    "%s: can't find socket; have you started the server?\n\
To start the server in Emacs, type \"M-x server-start\".\n",
440 441 442
		    argv[0]);
	 else
	   fprintf (stderr, "%s: can't stat %s: %s\n",
443
		    argv[0], server.sun_path, strerror (saved_errno));
444 445 446
	 fail (argc, argv);
	 break;
       }
Jim Blandy's avatar
Jim Blandy committed
447
  }
Richard M. Stallman's avatar
Richard M. Stallman committed
448

449 450
  if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
      < 0)
Richard M. Stallman's avatar
Richard M. Stallman committed
451 452 453
    {
      fprintf (stderr, "%s: ", argv[0]);
      perror ("connect");
454
      fail (argc, argv);
Richard M. Stallman's avatar
Richard M. Stallman committed
455
    }
456 457

  /* We use the stream OUT to send our command to the server.  */
Richard M. Stallman's avatar
Richard M. Stallman committed
458 459 460 461
  if ((out = fdopen (s, "r+")) == NULL)
    {
      fprintf (stderr, "%s: ", argv[0]);
      perror ("fdopen");
462
      fail (argc, argv);
Richard M. Stallman's avatar
Richard M. Stallman committed
463 464
    }

465 466 467 468 469 470 471 472 473
  /* We use the stream IN to read the response.
     We used to use just one stream for both output and input
     on the socket, but reversing direction works nonportably:
     on some systems, the output appears as the first input;
     on other systems it does not.  */
  if ((in = fdopen (s, "r+")) == NULL)
    {
      fprintf (stderr, "%s: ", argv[0]);
      perror ("fdopen");
474
      fail (argc, argv);
475 476
    }

477
#ifdef HAVE_GETCWD
478
  cwd = getcwd (string, sizeof string);
479 480
#else
  cwd = getwd (string);
481
#endif
Richard M. Stallman's avatar
Richard M. Stallman committed
482 483 484
  if (cwd == 0)
    {
      /* getwd puts message in STRING if it fails.  */
485

486
#ifdef HAVE_GETCWD
487 488
      fprintf (stderr, "%s: %s (%s)\n", argv[0],
	       "Cannot get current working directory", strerror (errno));
489
#else
490
      fprintf (stderr, "%s: %s (%s)\n", argv[0], string, strerror (errno));
491
#endif
492
      fail (argc, argv);
Richard M. Stallman's avatar
Richard M. Stallman committed
493 494
    }

495 496
  if (nowait)
    fprintf (out, "-nowait ");
497

Stefan Monnier's avatar
Stefan Monnier committed
498 499 500 501
  if (eval)
    fprintf (out, "-eval ");

  if (display)
502 503 504 505 506
    {
      fprintf (out, "-display ");
      quote_file_name (display, out);
      fprintf (out, " ");
    }
Stefan Monnier's avatar
Stefan Monnier committed
507

508
  if ((argc - optind > 0))
509
    {
510
      for (i = optind; i < argc; i++)
Richard M. Stallman's avatar
Richard M. Stallman committed
511
	{
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
	  if (eval)
	    ; /* Don't prepend any cwd or anything like that.  */
	  else if (*argv[i] == '+')
	    {
	      char *p = argv[i] + 1;
	      while (isdigit ((unsigned char) *p) || *p == ':') p++;
	      if (*p != 0)
		{
		  quote_file_name (cwd, out);
		  fprintf (out, "/");
		}
	    }
	  else if (*argv[i] != '/')
	    {
	      quote_file_name (cwd, out);
	      fprintf (out, "/");
	    }

	  quote_file_name (argv[i], out);
	  fprintf (out, " ");
Richard M. Stallman's avatar
Richard M. Stallman committed
532 533
	}
    }
534 535 536 537 538 539 540 541 542
  else
    {
      while ((str = fgets (string, BUFSIZ, stdin)))
	{
	  quote_file_name (str, out);
	}
      fprintf (out, " ");
    }
  
Richard M. Stallman's avatar
Richard M. Stallman committed
543 544 545
  fprintf (out, "\n");
  fflush (out);

546 547 548 549
  /* Maybe wait for an answer.   */
  if (nowait)
    return 0;

Stefan Monnier's avatar
Stefan Monnier committed
550 551 552 553 554
  if (!eval)
    {
      printf ("Waiting for Emacs...");
      needlf = 2;
    }
Richard M. Stallman's avatar
Richard M. Stallman committed
555 556
  fflush (stdout);

Stefan Monnier's avatar
Stefan Monnier committed
557
  /* Now, wait for an answer and print any messages.  */
558
  while ((str = fgets (string, BUFSIZ, in)))
Stefan Monnier's avatar
Stefan Monnier committed
559 560 561 562 563 564 565 566 567 568
    {
      if (needlf == 2)
	printf ("\n");
      printf ("%s", str);
      needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
    }

  if (needlf)
    printf ("\n");
  fflush (stdout);
569

570
  return 0;
Richard M. Stallman's avatar
Richard M. Stallman committed
571 572
}

Stefan Monnier's avatar
Stefan Monnier committed
573
#endif /* HAVE_SOCKETS */
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588

#ifndef HAVE_STRERROR
char *
strerror (errnum)
     int errnum;
{
  extern char *sys_errlist[];
  extern int sys_nerr;

  if (errnum >= 0 && errnum < sys_nerr)
    return sys_errlist[errnum];
  return (char *) "Unknown error";
}

#endif /* ! HAVE_STRERROR */
Miles Bader's avatar
Miles Bader committed
589 590 591

/* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
   (do not change this comment) */