emacsclient.c 23.9 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
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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

/****************************************/

#include <errno.h>
#include <signal.h>

#ifndef INCLUDED_FCNTL
#define INCLUDED_FCNTL
#include <fcntl.h>
#endif

#ifdef HAVE_TERMIOS
#ifndef NO_TERMIO
#include <termio.h>
#endif
#include <termios.h>
#endif /* not HAVE_TERMIOS */

#ifdef __GNU_LIBRARY__
#include <sys/ioctl.h>
#include <termios.h>
#endif

#if (defined (POSIX) || defined (NEED_UNISTD_H)) && defined (HAVE_UNISTD_H)
#include <unistd.h>
#endif



/* Try to establish the correct character to disable terminal functions
   in a system-independent manner.  Note that USG (at least) define
   _POSIX_VDISABLE as 0!  */

#ifdef _POSIX_VDISABLE
#define CDISABLE _POSIX_VDISABLE
#else /* not _POSIX_VDISABLE */
#ifdef CDEL
#undef CDISABLE
#define CDISABLE CDEL
#else /* not CDEL */
#define CDISABLE 255
#endif /* not CDEL */
#endif /* not _POSIX_VDISABLE */



/****************************************/

92 93 94 95 96 97 98 99 100 101 102 103 104
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;

105
/* Nonzero means don't wait for a response from Emacs.  --no-wait.  */
106 107
int nowait = 0;

Stefan Monnier's avatar
Stefan Monnier committed
108 109 110 111 112 113
/* Nonzero means args are expressions to be evaluated.  --eval.  */
int eval = 0;

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

114 115 116
/* Nonzero means open a new Emacs frame on the current terminal. */
int here = 0;

Stefan Monnier's avatar
Stefan Monnier committed
117 118 119 120
/* 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
121
/* If non-NULL, the filename of the UNIX socket.  */
122 123
char *socket_name = NULL;

124 125
void print_help_and_exit ();

126 127
struct option longopts[] =
{
128
  { "no-wait",	no_argument,	   NULL, 'n' },
Stefan Monnier's avatar
Stefan Monnier committed
129
  { "eval",	no_argument,	   NULL, 'e' },
130 131
  { "help",	no_argument,	   NULL, 'H' },
  { "version",	no_argument,	   NULL, 'V' },
132
  { "here",	no_argument,       NULL, 'h' },
Stefan Monnier's avatar
Stefan Monnier committed
133
  { "alternate-editor", required_argument, NULL, 'a' },
134
  { "socket-name",	required_argument, NULL, 's' },
Stefan Monnier's avatar
Stefan Monnier committed
135 136
  { "display",	required_argument, NULL, 'd' },
  { 0, 0, 0, 0 }
137 138 139
};

/* Decode the options from argv and argc.
140
   The global variable `optind' will say how many arguments we used up.  */
141

142
void
143 144 145 146 147 148 149
decode_options (argc, argv)
     int argc;
     char **argv;
{
  while (1)
    {
      int opt = getopt_long (argc, argv,
150
			     "VHnea:s:d:h", longopts, 0);
151 152 153 154

      if (opt == EOF)
	break;

155
      alternate_editor = getenv ("ALTERNATE_EDITOR");
156

157 158 159 160 161 162
      switch (opt)
	{
	case 0:
	  /* If getopt returns 0, then it has already processed a
	     long-named option.  We should do nothing.  */
	  break;
163

164 165 166
	case 'a':
	  alternate_editor = optarg;
	  break;
167

168 169 170 171
	case 's':
	  socket_name = optarg;
	  break;

Stefan Monnier's avatar
Stefan Monnier committed
172 173 174 175
	case 'd':
	  display = optarg;
	  break;

176 177 178 179
	case 'n':
	  nowait = 1;
	  break;

Stefan Monnier's avatar
Stefan Monnier committed
180 181 182 183
	case 'e':
	  eval = 1;
	  break;

184
	case 'V':
185 186
	  printf ("emacsclient %s\n", VERSION);
	  exit (0);
187
	  break;
Richard M. Stallman's avatar
Richard M. Stallman committed
188

189 190 191 192
        case 'h':
          here = 1;
          break;
          
193 194
	case 'H':
	  print_help_and_exit ();
195 196 197 198 199 200
	  break;

	default:
	  fprintf (stderr, "Try `%s --help' for more information\n", progname);
	  exit (1);
	  break;
201 202
	}
    }
203 204 205 206 207 208

  if (here) {
    nowait = 0;
    display = 0;
  }
  
209 210
}

211
void
212 213
print_help_and_exit ()
{
214 215
  printf (
	  "Usage: %s [OPTIONS] FILE...\n\
Stefan Monnier's avatar
Stefan Monnier committed
216 217
Tell the Emacs server to visit the specified files.\n\
Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
218
\n\
Stefan Monnier's avatar
Stefan Monnier committed
219 220 221
The following OPTIONS are accepted:\n\
-V, --version           Just print a version info and return\n\
-H, --help              Print this usage information message\n\
222
-h, --here              Open a new Emacs frame on the current terminal\n\
Stefan Monnier's avatar
Stefan Monnier committed
223 224 225
-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\
226 227
-s, --socket-name=FILENAME\n\
                        Set the filename of the UNIX socket for communication\n\
Stefan Monnier's avatar
Stefan Monnier committed
228 229
-a, --alternate-editor=EDITOR\n\
                        Editor to fallback to if the server is not running\n\
230
\n\
Stefan Monnier's avatar
Stefan Monnier committed
231
Report bugs to bug-gnu-emacs@gnu.org.\n", progname);
232
  exit (0);
233
}
234

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

239 240
void
quote_file_name (name, stream)
241
     char *name;
242
     FILE *stream;
243 244 245 246 247 248 249 250 251 252
{
  char *copy = (char *) malloc (strlen (name) * 2 + 1);
  char *p, *q;

  p = name;
  q = copy;
  while (*p)
    {
      if (*p == ' ')
	{
253
	  *q++ = '&';
254 255 256
	  *q++ = '_';
	  p++;
	}
Stefan Monnier's avatar
Stefan Monnier committed
257 258 259 260 261 262
      else if (*p == '\n')
	{
	  *q++ = '&';
	  *q++ = 'n';
	  p++;
	}
263 264
      else
	{
265 266
	  if (*p == '&' || (*p == '-' && p == name))
	    *q++ = '&';
267 268 269
	  *q++ = *p++;
	}
    }
270
  *q++ = 0;
271

272 273 274
  fprintf (stream, copy);

  free (copy);
275
}
276 277 278

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

279
long *
280 281 282
xmalloc (size)
     unsigned int size;
{
283
  long *result = (long *) malloc (size);
284 285 286 287 288 289 290
  if (result == NULL)
  {
    perror ("malloc");
    exit (1);
  }
  return result;
}
291 292 293 294 295

/*
  Try to run a different command, or --if no alternate editor is
  defined-- exit with an errorcode.
*/
296
void
297 298 299 300 301 302
fail (argc, argv)
     int argc;
     char **argv;
{
  if (alternate_editor)
    {
Stefan Monnier's avatar
Stefan Monnier committed
303
      int i = optind - 1;
304
      execvp (alternate_editor, argv + i);
Dave Love's avatar
Dave Love committed
305
      return;
306 307 308 309 310 311 312
    }
  else
    {
      exit (1);
    }
}

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761

#ifdef HAVE_TERMIOS

/* Adapted from emacs_get_tty() in sysdep.c. */
int
ec_get_tty (int fd, struct termios *settings)
{
  bzero (settings, sizeof (struct termios));
  if (tcgetattr (fd, settings) < 0)
    return -1;
  return 0;
}

/* Adapted from emacs_set_tty() in sysdep.c. */
int
ec_set_tty (int fd, struct termios *settings, int flushp)
{
  /* Set the primary parameters - baud rate, character size, etcetera.  */

  int i;
  /* We have those nifty POSIX tcmumbleattr functions.
     William J. Smith <wjs@wiis.wang.com> writes:
     "POSIX 1003.1 defines tcsetattr to return success if it was
     able to perform any of the requested actions, even if some
     of the requested actions could not be performed.
     We must read settings back to ensure tty setup properly.
     AIX requires this to keep tty from hanging occasionally."  */
  /* This make sure that we don't loop indefinitely in here.  */
  for (i = 0 ; i < 10 ; i++)
    if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, settings) < 0)
      {
	if (errno == EINTR)
	  continue;
	else
	  return -1;
      }
    else
      {
	struct termios new;
        
	bzero (&new, sizeof (new));
	/* Get the current settings, and see if they're what we asked for.  */
	tcgetattr (fd, &new);
	/* We cannot use memcmp on the whole structure here because under
	 * aix386 the termios structure has some reserved field that may
	 * not be filled in.
	 */
	if (   new.c_iflag == settings->c_iflag
	    && new.c_oflag == settings->c_oflag
	    && new.c_cflag == settings->c_cflag
	    && new.c_lflag == settings->c_lflag
	    && memcmp (new.c_cc, settings->c_cc, NCCS) == 0)
	  break;
	else
	  continue;
      }
  return 0;
}

int master;
char *pty_name;

struct termios old_tty;
struct termios tty;
int old_tty_valid;

int tty_erase_char;
int flow_control = 0;
int meta_key = 0;
char _sobuf[BUFSIZ];

/* Adapted from init_sys_modes() in sysdep.c. */
int
init_tty ()
{
  if (! isatty (0))
    {
      fprintf (stderr, "%s: Input is not a terminal", "init_tty");
      return 0;
    }
  
  ec_get_tty (0, &old_tty);
  old_tty_valid = 1;
  tty = old_tty;
  
  tty_erase_char = old_tty.c_cc[VERASE];
  
  tty.c_iflag |= (IGNBRK);	/* Ignore break condition */
  tty.c_iflag &= ~ICRNL;	/* Disable map of CR to NL on input */
#ifdef INLCR
  tty.c_iflag &= ~INLCR;	/* Disable map of NL to CR on input */
#endif
#ifdef ISTRIP
  tty.c_iflag &= ~ISTRIP;	/* don't strip 8th bit on input */
#endif
  tty.c_lflag &= ~ECHO;         /* Disable echo */
  tty.c_lflag &= ~ICANON;	/* Disable erase/kill processing */
#ifdef IEXTEN
  tty.c_lflag &= ~IEXTEN;	/* Disable other editing characters.  */
#endif
  tty.c_lflag |= ISIG;          /* Enable signals */
  if (flow_control)
    {
      tty.c_iflag |= IXON;	/* Enable start/stop output control */
#ifdef IXANY
      tty.c_iflag &= ~IXANY;
#endif /* IXANY */
    }
  else
    tty.c_iflag &= ~IXON;	/* Disable start/stop output control */
  tty.c_oflag &= ~ONLCR;	/* Disable map of NL to CR-NL
                                   on output */
  tty.c_oflag &= ~TAB3;         /* Disable tab expansion */
#ifdef CS8
  if (meta_key)
    {
      tty.c_cflag |= CS8;	/* allow 8th bit on input */
      tty.c_cflag &= ~PARENB;   /* Don't check parity */
    }
#endif
  tty.c_cc[VINTR] = CDISABLE;
  tty.c_cc[VQUIT] = CDISABLE;
  tty.c_cc[VMIN] = 1;      /* Input should wait for at least 1 char */
  tty.c_cc[VTIME] = 0;          /* no matter how long that takes.  */
#ifdef VSWTCH
  tty.c_cc[VSWTCH] = CDISABLE;	/* Turn off shell layering use of C-z */
#endif

#ifdef VSUSP
  tty.c_cc[VSUSP] = CDISABLE;	/* Turn off mips handling of C-z.  */
#endif /* VSUSP */
#ifdef V_DSUSP
  tty.c_cc[V_DSUSP] = CDISABLE; /* Turn off mips handling of C-y.  */
#endif /* V_DSUSP */
#ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP.  */
  tty.c_cc[VDSUSP] = CDISABLE;
#endif /* VDSUSP */
#ifdef VLNEXT
  tty.c_cc[VLNEXT] = CDISABLE;
#endif /* VLNEXT */
#ifdef VREPRINT
  tty.c_cc[VREPRINT] = CDISABLE;
#endif /* VREPRINT */
#ifdef VWERASE
  tty.c_cc[VWERASE] = CDISABLE;
#endif /* VWERASE */
#ifdef VDISCARD
  tty.c_cc[VDISCARD] = CDISABLE;
#endif /* VDISCARD */

  if (flow_control)
    {
#ifdef VSTART
      tty.c_cc[VSTART] = '\021';
#endif /* VSTART */
#ifdef VSTOP
      tty.c_cc[VSTOP] = '\023';
#endif /* VSTOP */
    }
  else
    {
#ifdef VSTART
      tty.c_cc[VSTART] = CDISABLE;
#endif /* VSTART */
#ifdef VSTOP
      tty.c_cc[VSTOP] = CDISABLE;
#endif /* VSTOP */
    }
  
#ifdef SET_LINE_DISCIPLINE
  /* Need to explicitly request TERMIODISC line discipline or
     Ultrix's termios does not work correctly.  */
  tty.c_line = SET_LINE_DISCIPLINE;
#endif
  
#ifdef AIX
#ifndef IBMR2AIX
  /* AIX enhanced edit loses NULs, so disable it.  */
  tty.c_line = 0;
  tty.c_iflag &= ~ASCEDIT;
#else
  tty.c_cc[VSTRT] = 255;
  tty.c_cc[VSTOP] = 255;
  tty.c_cc[VSUSP] = 255;
  tty.c_cc[VDSUSP] = 255;
#endif /* IBMR2AIX */
  if (flow_control)
    {
#ifdef VSTART
      tty.c_cc[VSTART] = '\021';
#endif /* VSTART */
#ifdef VSTOP
      tty.c_cc[VSTOP] = '\023';
#endif /* VSTOP */
    }
  /* Also, PTY overloads NUL and BREAK.
     don't ignore break, but don't signal either, so it looks like NUL.
     This really serves a purpose only if running in an XTERM window
     or via TELNET or the like, but does no harm elsewhere.  */
  tty.c_iflag &= ~IGNBRK;
  tty.c_iflag &= ~BRKINT;
#endif /* AIX */
  
  ec_set_tty (0, &tty, 0);

      /* This code added to insure that, if flow-control is not to be used,
	 we have an unlocked terminal at the start. */

#ifdef TCXONC
  if (!flow_control) ioctl (0, TCXONC, 1);
#endif
#ifndef APOLLO
#ifdef TIOCSTART
  if (!flow_control) ioctl (0, TIOCSTART, 0);
#endif
#endif

#if defined (HAVE_TERMIOS) || defined (HPUX9)
#ifdef TCOON
  if (!flow_control) tcflow (0, TCOON);
#endif
#endif
  
#ifdef _IOFBF
  /* This symbol is defined on recent USG systems.
     Someone says without this call USG won't really buffer the file
     even with a call to setbuf. */
  setvbuf (stdout, (char *) _sobuf, _IOFBF, sizeof _sobuf);
#else
  setbuf (stdout, (char *) _sobuf);
#endif

  return 1;
}

void
window_change ()
{
  int width, height;

#ifdef TIOCGWINSZ
  {
    /* BSD-style.  */
    struct winsize size;
    
    if (ioctl (0, TIOCGWINSZ, &size) == -1)
      width = height = 0;
    else
      {
        width = size.ws_col;
        height = size.ws_row;
      }
  }
#else
#ifdef TIOCGSIZE
  {
    /* SunOS - style.  */
    struct ttysize size;
    
    if (ioctl (0, TIOCGSIZE, &size) == -1)
      width = height = 0;
    else
      {
        width = size.ts_cols;
        height = size.ts_lines;
      }
  }
#endif /* not SunOS-style */
#endif /* not BSD-style */

#ifdef TIOCSWINSZ
  {
    /* BSD-style.  */
    struct winsize size;
    size.ws_row = height;
    size.ws_col = width;
    
    ioctl (master, TIOCSWINSZ, &size);
  }
#else
#ifdef TIOCSSIZE
  {
    /* SunOS - style.  */
    struct ttysize size;
    size.ts_lines = height;
    size.ts_cols = width;
    
    ioctl (master, TIOCGSIZE, &size);
  }
#endif /* not SunOS-style */
#endif /* not BSD-style */
}

int in_conversation = 0;
int quit_conversation = 0;

SIGTYPE
hang_up_signal (int signalnum)
{
  int old_errno = errno;
  
  if (! in_conversation)
    return;

  quit_conversation = 1;
  
  errno = old_errno;
}

SIGTYPE
window_change_signal (int signalnum)
{
  int old_errno = errno;

  if (! in_conversation)
    goto end;

  window_change();

 end:
  signal (SIGWINCH, window_change_signal);
  errno = old_errno;
}

int
init_signals ()
{
  /* Set up signal handlers. */
  signal (SIGWINCH, window_change_signal);
  signal (SIGHUP, hang_up_signal);

  return 1;
}



/* Adapted from reset_sys_modes in sysdep.c. */
int
reset_tty ()
{
  fflush (stdout);
#ifdef BSD_SYSTEM
#ifndef BSD4_1
  /* Avoid possible loss of output when changing terminal modes.  */
  fsync (fileno (stdout));
#endif
#endif

#ifdef F_SETFL
#ifdef O_NDELAY
  fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~O_NDELAY);
#endif
#endif /* F_SETFL */

  if (old_tty_valid)
    while (ec_set_tty (0, &old_tty, 0) < 0 && errno == EINTR)
      ;

  return 1;
}


int
init_pty ()
{
  master = getpt ();
  if (master < 0)
    return 0;

  if (grantpt (master) < 0 || unlockpt (master) < 0)
    goto close_master;
  pty_name = strdup (ptsname (master));
  if (! pty_name)
    goto close_master;

  /* Propagate window size. */
  window_change ();
  
  return 1;
  
 close_master:
  close (master);
  return 0;
}

int
copy_from_to (int in, int out)
{
  static char buf[BUFSIZ];
  int nread = read (in, &buf, BUFSIZ);
  if (nread == 0)
    return 1;                   /* EOF */
  else if (nread < 0 && errno != EAGAIN)
    return 0;                   /* Error */
  else if (nread > 0)
    {
      int r = 0;
      int written = 0;

      do {
        r = write (out, &buf, nread);
      } while ((r < 0 && errno == EAGAIN)
               || (r > 0 && (written += r) && written != nread));
      
      if (r < 0)
        return 0;               /* Error */
    }
  return 1;
}

int
pty_conversation ()
{
  fd_set set;

  in_conversation = 1;
  
  while (! quit_conversation) {
    int res;
    
    FD_ZERO (&set);
    FD_SET (master, &set);
    FD_SET (1, &set);
    res = select (FD_SETSIZE, &set, NULL, NULL, NULL);
    if (res < 0)
      {
        if (errno != EINTR)
          return 0;
      }
    else if (res > 0)
      {
        if (FD_ISSET (master, &set))
          {
            /* Copy Emacs output to stdout. */
            if (! copy_from_to (master, 0))
              return 1;
          }
        if (FD_ISSET (1, &set))
          {
            /* Forward user input to Emacs. */
            if (! copy_from_to (1, master))
              return 1;
          }
      }
  }
  return 1;
}

#endif /* HAVE_TERMIOS */
762

763

Stefan Monnier's avatar
Stefan Monnier committed
764
#if !defined (HAVE_SOCKETS) || defined (NO_SOCKETS_IN_FILE_SYSTEM)
Richard M. Stallman's avatar
Richard M. Stallman committed
765

766
int
Richard M. Stallman's avatar
Richard M. Stallman committed
767 768 769 770 771 772
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
773
  fprintf (stderr, "on systems with Berkeley sockets.\n");
774 775

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

Stefan Monnier's avatar
Stefan Monnier committed
778
#else /* HAVE_SOCKETS */
Richard M. Stallman's avatar
Richard M. Stallman committed
779 780 781 782

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
Jim Blandy's avatar
Jim Blandy committed
783
#include <sys/stat.h>
Richard M. Stallman's avatar
Richard M. Stallman committed
784 785
#include <errno.h>

786
extern char *strerror ();
Richard M. Stallman's avatar
Richard M. Stallman committed
787 788
extern int errno;

789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
/* 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;
}

809
int
Richard M. Stallman's avatar
Richard M. Stallman committed
810 811 812 813
main (argc, argv)
     int argc;
     char **argv;
{
814 815
  char *system_name;
  int system_name_length;
Stefan Monnier's avatar
Stefan Monnier committed
816
  int s, i, needlf = 0;
817
  FILE *out, *in;
Richard M. Stallman's avatar
Richard M. Stallman committed
818
  struct sockaddr_un server;
819
  char *cwd, *str;
Richard M. Stallman's avatar
Richard M. Stallman committed
820
  char string[BUFSIZ];
821 822

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

824
  /* Process options.  */
825
  decode_options (argc, argv);
Richard M. Stallman's avatar
Richard M. Stallman committed
826

827
  if ((argc - optind < 1) && !eval && !here)
828 829 830 831 832
    {
      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
833

834
  /*
Richard M. Stallman's avatar
Richard M. Stallman committed
835 836 837 838 839 840 841
   * 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");
842
      fail (argc, argv);
Richard M. Stallman's avatar
Richard M. Stallman committed
843
    }
844

Richard M. Stallman's avatar
Richard M. Stallman committed
845
  server.sun_family = AF_UNIX;
846

Jim Blandy's avatar
Jim Blandy committed
847
  {
848
    char *dot;
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
    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;
      }
864 865 866 867 868

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

  {
872
    int sock_status = 0;
Jim Blandy's avatar
Jim Blandy committed
873

874 875 876 877 878 879 880 881 882 883 884 885
    if (! socket_name)
      {
	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
      fprintf (stderr, "%s: socket-name %s too long",
	       argv[0], socket_name);
Jim Blandy's avatar
Jim Blandy committed
886

887 888 889
    /* See if the socket exists, and if it's owned by us. */
    sock_status = socket_status (server.sun_path);
    if (sock_status)
Jim Blandy's avatar
Jim Blandy committed
890
      {
891 892 893 894
	/* 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.  */
895

896 897 898
	char *user_name = (char *) getenv ("LOGNAME");
	if (!user_name)
	  user_name = (char *) getenv ("USER");
899

900 901 902 903 904 905 906
	if (user_name)
	  {
	    struct passwd *pw = getpwnam (user_name);
	    if (pw && (pw->pw_uid != geteuid ()))
	      {
		/* We're running under su, apparently. */
		sprintf (server.sun_path, "/tmp/esrv%d-%s",
Dave Love's avatar
Dave Love committed
907
			 (int) pw->pw_uid, system_name);
908 909 910
		sock_status = socket_status (server.sun_path);
	      }
	  }
Jim Blandy's avatar
Jim Blandy committed
911
      }
912

913 914 915 916 917 918 919 920 921 922 923
     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;
924

925 926 927 928
       case 2:
	 /* `stat' failed */
	 if (errno == ENOENT)
	   fprintf (stderr,
929 930
		    "%s: can't find socket; have you started the server?\n\
To start the server in Emacs, type \"M-x server-start\".\n",
931 932 933 934 935 936 937
		    argv[0]);
	 else
	   fprintf (stderr, "%s: can't stat %s: %s\n",
		    argv[0], server.sun_path, strerror (errno));
	 fail (argc, argv);
	 break;
       }
Jim Blandy's avatar
Jim Blandy committed
938
  }
Richard M. Stallman's avatar
Richard M. Stallman committed
939

940 941
  if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
      < 0)
Richard M. Stallman's avatar
Richard M. Stallman committed
942 943 944
    {
      fprintf (stderr, "%s: ", argv[0]);
      perror ("connect");
945
      fail (argc, argv);
Richard M. Stallman's avatar
Richard M. Stallman committed
946
    }
947 948

  /* We use the stream OUT to send our command to the server.  */
Richard M. Stallman's avatar
Richard M. Stallman committed
949 950 951 952
  if ((out = fdopen (s, "r+")) == NULL)
    {
      fprintf (stderr, "%s: ", argv[0]);
      perror ("fdopen");
953
      fail (argc, argv);
Richard M. Stallman's avatar
Richard M. Stallman committed
954 955
    }

956 957 958 959 960 961 962 963 964
  /* 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");
965
      fail (argc, argv);
966 967
    }

968
#ifdef HAVE_GETCWD
969
  cwd = getcwd (string, sizeof string);
970 971
#else
  cwd = getwd (string);
972
#endif
Richard M. Stallman's avatar
Richard M. Stallman committed
973 974 975
  if (cwd == 0)
    {
      /* getwd puts message in STRING if it fails.  */
976

977
#ifdef HAVE_GETCWD
978 979
      fprintf (stderr, "%s: %s (%s)\n", argv[0],
	       "Cannot get current working directory", strerror (errno));
980
#else
981
      fprintf (stderr, "%s: %s (%s)\n", argv[0], string, strerror (errno));
982
#endif
983
      fail (argc, argv);
Richard M. Stallman's avatar
Richard M. Stallman committed
984 985
    }

986 987
  if (nowait)
    fprintf (out, "-nowait ");
988

Stefan Monnier's avatar
Stefan Monnier committed
989 990 991 992
  if (eval)
    fprintf (out, "-eval ");

  if (display)
993 994 995 996 997
    {
      fprintf (out, "-display ");
      quote_file_name (display, out);
      fprintf (out, " ");
    }
Stefan Monnier's avatar
Stefan Monnier committed
998

999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
  if (here)
    {
      if (! init_signals ())
        {
          fprintf (stderr, "%s: ", argv[0]);
          perror ("fdopen");
          fail (argc, argv);
        }
        
      if (! init_tty ())
        {
          reset_tty ();
          fprintf (stderr, "%s: ", argv[0]);
          perror ("fdopen");
          fail (argc, argv);
        }
      
      if (! init_pty ())
        {
          reset_tty ();
          fprintf (stderr, "%s: ", argv[0]);
          perror ("fdopen");
          fail (argc, argv);
        }
      
      fprintf (out, "-pty ");
      quote_file_name (pty_name, out);
      fprintf (out, " ");
      quote_file_name (getenv("TERM"), out);
      fprintf (out, " ");
    }
  
1031
  if ((argc - optind > 0))
1032
    {
1033
      for (i = optind; i < argc; i++)
Richard M. Stallman's avatar
Richard M. Stallman committed
1034
	{
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
	  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
1055 1056
	}
    }
1057 1058
  else
    {
1059 1060 1061 1062 1063 1064 1065 1066
      if (!here)
        {
          while ((str = fgets (string, BUFSIZ, stdin)))
            {
              quote_file_name (str, out);
            }
          fprintf (out, " ");
        }
1067 1068
    }
  
Richard M. Stallman's avatar
Richard M. Stallman committed
1069 1070 1071
  fprintf (out, "\n");
  fflush (out);

1072 1073
  /* Maybe wait for an answer.   */
  if (nowait)
1074 1075 1076 1077
    {
      reset_tty ();
      return 0;
    }
1078

1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
  if (here)
    {
      if (! pty_conversation ())
        {
          reset_tty ();
          fprintf (stderr, "%s: ", argv[0]);
          perror ("fdopen");
          fail (argc, argv);
        }
      close (master);
      reset_tty ();
      return 0;
    }
  
Stefan Monnier's avatar
Stefan Monnier committed
1093 1094 1095 1096 1097
  if (!eval)
    {
      printf ("Waiting for Emacs...");
      needlf = 2;
    }
Richard M. Stallman's avatar
Richard M. Stallman committed
1098 1099
  fflush (stdout);

Stefan Monnier's avatar
Stefan Monnier committed
1100
  /* Now, wait for an answer and print any messages.  */
1101
  while ((str = fgets (string, BUFSIZ, in)))
Stefan Monnier's avatar
Stefan Monnier committed
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
    {
      if (needlf == 2)
	printf ("\n");
      printf ("%s", str);
      needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
    }

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

1113
  reset_tty ();
1114
  return 0;
Richard M. Stallman's avatar
Richard M. Stallman committed
1115 1116
}

Stefan Monnier's avatar
Stefan Monnier committed
1117
#endif /* HAVE_SOCKETS */
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132

#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
1133 1134 1135

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