emacsclient.c 35.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, 2002, 2003, 2004,
Glenn Morris's avatar
Glenn Morris committed
3
                 2005, 2006, 2007 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 3, 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
Lute Kamstra's avatar
Lute Kamstra committed
19 20
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, 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 30
#ifdef WINDOWSNT

31 32 33 34
/* config.h defines these, which disables sockets altogether! */
# undef _WINSOCKAPI_
# undef _WINSOCK_H

35 36
# include <malloc.h>
# include <stdlib.h>
Juanma Barranquero's avatar
Juanma Barranquero committed
37
# include <windows.h>
38 39 40

# define NO_SOCKETS_IN_FILE_SYSTEM

41 42 43
# define HSOCKET SOCKET
# define CLOSE_SOCKET closesocket
# define INITIALIZE() (initialize_sockets ())
44 45 46

#else /* !WINDOWSNT */

47 48
# include <sys/types.h>

49 50 51
# ifdef HAVE_INET_SOCKETS
#  include <netinet/in.h>
# endif
52

53
# define INVALID_SOCKET -1
54 55 56
# define HSOCKET int
# define CLOSE_SOCKET close
# define INITIALIZE()
57 58

#endif /* !WINDOWSNT */
59

60
#undef signal
Richard M. Stallman's avatar
Richard M. Stallman committed
61

Juanma Barranquero's avatar
Juanma Barranquero committed
62
#include <stdarg.h>
63
#include <ctype.h>
64
#include <stdio.h>
65
#include "getopt.h"
66 67 68
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
69

70 71
#ifdef VMS
# include "vms-pwd.h"
72 73 74 75
#else /* not VMS */
#ifdef WINDOWSNT
# include <io.h>
#else /* not WINDOWSNT */
76
# include <pwd.h>
77
#endif /* not WINDOWSNT */
78
#endif /* not VMS */
79
#include <sys/stat.h>
80

81
#include <signal.h>
82
#include <errno.h>
83 84


85
char *getenv (), *getwd ();
86
char *(getcwd) ();
87 88 89 90 91

#ifndef VERSION
#define VERSION "unspecified"
#endif

92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112

#ifndef EXIT_SUCCESS
#define EXIT_SUCCESS 0
#endif

#ifndef EXIT_FAILURE
#define EXIT_FAILURE 1
#endif

#ifndef FALSE
#define FALSE 0
#endif

#ifndef TRUE
#define TRUE 1
#endif

#ifndef NO_RETURN
#define NO_RETURN
#endif

113 114 115
/* Name used to invoke this program.  */
char *progname;

Karoly Lorentey's avatar
Karoly Lorentey committed
116 117 118
/* The second argument to main. */
char **main_argv;

119
/* Nonzero means don't wait for a response from Emacs.  --no-wait.  */
120 121
int nowait = 0;

Stefan Monnier's avatar
Stefan Monnier committed
122 123 124
/* Nonzero means args are expressions to be evaluated.  --eval.  */
int eval = 0;

125 126
/* Nonzero means don't open a new frame.  Inverse of --create-frame.  */
int current_frame = 1;
127

128 129 130
/* Nonzero means open a new graphical frame. */
int window_system = 0;

Stefan Monnier's avatar
Stefan Monnier committed
131 132 133
/* The display on which Emacs should work.  --display.  */
char *display = NULL;

134
/* Nonzero means open a new Emacs frame on the current terminal. */
135
int tty = 0;
136

Stefan Monnier's avatar
Stefan Monnier committed
137 138
/* If non-NULL, the name of an editor to fallback to if the server
   is not running.  --alternate-editor.   */
139
const char *alternate_editor = NULL;
Stefan Monnier's avatar
Stefan Monnier committed
140

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

144 145 146
/* If non-NULL, the filename of the authentication file.  */
char *server_file = NULL;

147 148 149
/* PID of the Emacs server process.  */
int emacs_pid = 0;

150
void print_help_and_exit () NO_RETURN;
151

152 153
struct option longopts[] =
{
154
  { "no-wait",	no_argument,	   NULL, 'n' },
Stefan Monnier's avatar
Stefan Monnier committed
155
  { "eval",	no_argument,	   NULL, 'e' },
156 157
  { "help",	no_argument,	   NULL, 'H' },
  { "version",	no_argument,	   NULL, 'V' },
158
  { "tty",	no_argument,       NULL, 't' },
159
  { "create-frame", no_argument,   NULL, 'c' },
Stefan Monnier's avatar
Stefan Monnier committed
160
  { "alternate-editor", required_argument, NULL, 'a' },
161
#ifndef NO_SOCKETS_IN_FILE_SYSTEM
162
  { "socket-name",	required_argument, NULL, 's' },
163
#endif
164
  { "server-file",	required_argument, NULL, 'f' },
Stefan Monnier's avatar
Stefan Monnier committed
165 166
  { "display",	required_argument, NULL, 'd' },
  { 0, 0, 0, 0 }
167 168
};

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201

/* Like malloc but get fatal error if memory is exhausted.  */

long *
xmalloc (size)
     unsigned int size;
{
  long *result = (long *) malloc (size);
  if (result == NULL)
    {
      perror ("malloc");
      exit (EXIT_FAILURE);
    }
  return result;
}

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

char *
xstrdup (const char *s)
{
  char *result = strdup (s);
  if (result == NULL)
    {
      perror ("strdup");
      exit (EXIT_FAILURE);
    }
  return result;
}

/* From sysdep.c */
#if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
/* From lisp.h */
#ifndef DIRECTORY_SEP
#define DIRECTORY_SEP '/'
#endif
#ifndef IS_DIRECTORY_SEP
#define IS_DIRECTORY_SEP(_c_) ((_c_) == DIRECTORY_SEP)
#endif
#ifndef IS_DEVICE_SEP
#ifndef DEVICE_SEP
#define IS_DEVICE_SEP(_c_) 0
#else
#define IS_DEVICE_SEP(_c_) ((_c_) == DEVICE_SEP)
#endif
#endif
#ifndef IS_ANY_SEP
#define IS_ANY_SEP(_c_) (IS_DIRECTORY_SEP (_c_))
#endif


221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
/* Return the current working directory.  Returns NULL on errors.
   Any other returned value must be freed with free. This is used
   only when get_current_dir_name is not defined on the system.  */
char*
get_current_dir_name ()
{
  char *buf;
  char *pwd;
  struct stat dotstat, pwdstat;
  /* If PWD is accurate, use it instead of calling getwd.  PWD is
     sometimes a nicer name, and using it may avoid a fatal error if a
     parent directory is searchable but not readable.  */
    if ((pwd = getenv ("PWD")) != 0
      && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
      && stat (pwd, &pwdstat) == 0
      && stat (".", &dotstat) == 0
      && dotstat.st_ino == pwdstat.st_ino
      && dotstat.st_dev == pwdstat.st_dev
#ifdef MAXPATHLEN
      && strlen (pwd) < MAXPATHLEN
#endif
      )
    {
      buf = (char *) xmalloc (strlen (pwd) + 1);
      if (!buf)
        return NULL;
      strcpy (buf, pwd);
    }
#ifdef HAVE_GETCWD
  else
    {
      size_t buf_size = 1024;
      buf = (char *) xmalloc (buf_size);
      if (!buf)
        return NULL;
      for (;;)
        {
          if (getcwd (buf, buf_size) == buf)
            break;
          if (errno != ERANGE)
            {
              int tmp_errno = errno;
              free (buf);
              errno = tmp_errno;
              return NULL;
            }
          buf_size *= 2;
          buf = (char *) realloc (buf, buf_size);
          if (!buf)
            return NULL;
        }
    }
#else
  else
    {
      /* We need MAXPATHLEN here.  */
      buf = (char *) xmalloc (MAXPATHLEN + 1);
      if (!buf)
        return NULL;
      if (getwd (buf) == NULL)
        {
          int tmp_errno = errno;
          free (buf);
          errno = tmp_errno;
          return NULL;
        }
    }
#endif
  return buf;
}
#endif

Juanma Barranquero's avatar
Juanma Barranquero committed
293 294 295 296
/* Message functions. */

#ifdef WINDOWSNT
int
297
w32_window_app ()
Juanma Barranquero's avatar
Juanma Barranquero committed
298 299 300 301 302
{
  static int window_app = -1;
  char szTitle[MAX_PATH];

  if (window_app < 0)
Juanma Barranquero's avatar
Juanma Barranquero committed
303 304
    /* Checking for STDOUT does not work; it's a valid handle also in
       nonconsole apps.  Testing for the console title seems to work. */
Juanma Barranquero's avatar
Juanma Barranquero committed
305 306 307 308
    window_app = (GetConsoleTitleA (szTitle, MAX_PATH) == 0);

  return window_app;
}
Dan Nicolaescu's avatar
Dan Nicolaescu committed
309 310

/*
311
  execvp wrapper for Windows.  Quotes arguments with embedded spaces.
Dan Nicolaescu's avatar
Dan Nicolaescu committed
312 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

  This is necessary due to the broken implementation of exec* routines in
  the Microsoft libraries: they concatenate the arguments together without
  quoting special characters, and pass the result to CreateProcess, with
  predictably bad results.  By contrast, Posix execvp passes the arguments
  directly into the argv array of the child process.
*/
int
w32_execvp (path, argv)
     char *path;
     char **argv;
{
  int i;

  /* Required to allow a .BAT script as alternate editor.  */
  argv[0] = (char *) alternate_editor;

  for (i = 0; argv[i]; i++)
    if (strchr (argv[i], ' '))
      {
	char *quoted = alloca (strlen (argv[i]) + 3);
	sprintf (quoted, "\"%s\"", argv[i]);
	argv[i] = quoted;
      }

  return execvp (path, argv);
}

#undef execvp
#define execvp w32_execvp

#endif /* WINDOWSNT */
Juanma Barranquero's avatar
Juanma Barranquero committed
344 345 346 347

void
message (int is_error, char *message, ...)
{
348
  char msg [2048];
Juanma Barranquero's avatar
Juanma Barranquero committed
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
  va_list args;

  va_start (args, message);
  vsprintf (msg, message, args);
  va_end (args);

#ifdef WINDOWSNT
  if (w32_window_app ())
    {
      if (is_error)
	MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
      else
	MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
    }
  else
#endif
365 366 367 368 369 370
    {
      FILE *f = is_error ? stderr : stdout;

      fputs (msg, f);
      fflush (f);
    }
Juanma Barranquero's avatar
Juanma Barranquero committed
371 372
}

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

376
void
377 378 379 380
decode_options (argc, argv)
     int argc;
     char **argv;
{
381
  alternate_editor = getenv ("ALTERNATE_EDITOR");
382
  display = getenv ("DISPLAY");
383
  if (display && strlen (display) == 0)
384
    display = NULL;
385

386 387 388
  while (1)
    {
      int opt = getopt_long (argc, argv,
389
#ifndef NO_SOCKETS_IN_FILE_SYSTEM
390
			     "VHnea:s:f:d:tc",
391
#else
392
			     "VHnea:f:d:tc",
393
#endif
394
			     longopts, 0);
395 396 397 398 399 400 401 402 403 404

      if (opt == EOF)
	break;

      switch (opt)
	{
	case 0:
	  /* If getopt returns 0, then it has already processed a
	     long-named option.  We should do nothing.  */
	  break;
405

406 407 408
	case 'a':
	  alternate_editor = optarg;
	  break;
409

410
#ifndef NO_SOCKETS_IN_FILE_SYSTEM
411 412 413
	case 's':
	  socket_name = optarg;
	  break;
414
#endif
415

416 417 418
	case 'f':
	  server_file = optarg;
	  break;
419

Stefan Monnier's avatar
Stefan Monnier committed
420 421 422 423
	case 'd':
	  display = optarg;
	  break;

424 425 426 427
	case 'n':
	  nowait = 1;
	  break;

Stefan Monnier's avatar
Stefan Monnier committed
428 429 430 431
	case 'e':
	  eval = 1;
	  break;

432
	case 'V':
Juanma Barranquero's avatar
Juanma Barranquero committed
433
	  message (FALSE, "emacsclient %s\n", VERSION);
434
	  exit (EXIT_SUCCESS);
435
	  break;
Richard M. Stallman's avatar
Richard M. Stallman committed
436

437
        case 't':
438
          tty = 1;
439
	  current_frame = 0;
440 441
          break;

442
        case 'c':
443
          current_frame = 0;
444
          break;
445

446 447
	case 'H':
	  print_help_and_exit ();
448 449 450
	  break;

	default:
Juanma Barranquero's avatar
Juanma Barranquero committed
451
	  message (TRUE, "Try `%s --help' for more information\n", progname);
452
	  exit (EXIT_FAILURE);
453
	  break;
454 455
	}
    }
456

457 458
  if (!tty && display)
    window_system = 1;
459
#if !defined (WINDOWSNT) && !defined (HAVE_CARBON)
460 461
  else
    tty = 1;
462
#endif
463

464 465 466
  /* --no-wait implies --current-frame on ttys when there are file
       arguments or expressions given.  */
  if (nowait && tty && argc - optind > 0)
467 468 469 470 471 472 473 474 475 476
    current_frame = 1;

  if (current_frame)
    {
      tty = 0;
      window_system = 0;
    }

  if (tty)
    window_system = 0;
477 478
}

479

480
void
481 482
print_help_and_exit ()
{
483 484 485 486
  /* Spaces and tabs are significant in this message; they're chosen so the
     message aligns properly both in a tty and in a Windows message box.
     Please try to preserve them; otherwise the output is very hard to read
     when using emacsclientw.  */
Juanma Barranquero's avatar
Juanma Barranquero committed
487
  message (FALSE,
488
	   "Usage: %s [OPTIONS] FILE...\n\
Stefan Monnier's avatar
Stefan Monnier committed
489 490
Tell the Emacs server to visit the specified files.\n\
Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
491
\n\
Stefan Monnier's avatar
Stefan Monnier committed
492
The following OPTIONS are accepted:\n\
493 494 495
-V, --version		Just print version info and return\n\
-H, --help    		Print this usage information message\n\
-t, --tty    		Open a new Emacs frame on the current terminal\n\
496
-c, --create-frame  	Create a new frame instead of trying to\n\
497 498 499 500
			use the current Emacs frame\n\
-e, --eval    		Evaluate the FILE arguments as ELisp expressions\n\
-n, --no-wait		Don't wait for the server to return\n\
-d, --display=DISPLAY	Visit the file in the given display\n"
501 502
#ifndef NO_SOCKETS_IN_FILE_SYSTEM
"-s, --socket-name=FILENAME\n\
503
			Set filename of the UNIX socket for communication\n"
504 505
#endif
"-f, --server-file=FILENAME\n\
506
			Set filename of the TCP authentication file\n\
Stefan Monnier's avatar
Stefan Monnier committed
507
-a, --alternate-editor=EDITOR\n\
508
			Editor to fallback to if the server is not running\n\
509
\n\
Stefan Monnier's avatar
Stefan Monnier committed
510
Report bugs to bug-gnu-emacs@gnu.org.\n", progname);
511
  exit (EXIT_SUCCESS);
512
}
513

514 515 516
/*
  Try to run a different command, or --if no alternate editor is
  defined-- exit with an errorcode.
517
  Uses argv, but gets it from the global variable main_argv.
518 519
*/
void
520
fail (void)
Karoly Lorentey's avatar
Karoly Lorentey committed
521
{
522
  if (alternate_editor)
Karoly Lorentey's avatar
Karoly Lorentey committed
523
    {
524
      int i = optind - 1;
525

526
      execvp (alternate_editor, main_argv + i);
Juanma Barranquero's avatar
Juanma Barranquero committed
527
      message (TRUE, "%s: error executing alternate editor \"%s\"\n",
528
	       progname, alternate_editor);
Karoly Lorentey's avatar
Karoly Lorentey committed
529
    }
530
  exit (EXIT_FAILURE);
Karoly Lorentey's avatar
Karoly Lorentey committed
531 532
}

533

534
#if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
Karoly Lorentey's avatar
Karoly Lorentey committed
535

536 537 538 539
int
main (argc, argv)
     int argc;
     char **argv;
Karoly Lorentey's avatar
Karoly Lorentey committed
540
{
541 542 543
  main_argv = argv;
  progname = argv[0];
  message (TRUE, "%s: Sorry, the Emacs server is supported only\n"
544
	   "on systems with Berkeley sockets.\n",
545
	   argv[0]);
546
  fail ();
Karoly Lorentey's avatar
Karoly Lorentey committed
547 548
}

549
#else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
550

551 552
#ifdef WINDOWSNT
# include <winsock2.h>
553
#else
554 555 556 557 558 559 560 561 562 563 564 565 566 567
# include <sys/types.h>
# include <sys/socket.h>
# include <sys/un.h>
#endif

#define AUTH_KEY_LENGTH      64
#define SEND_BUFFER_SIZE   4096

extern char *strerror ();
extern int errno;

/* Buffer to accumulate data to send in TCP connections.  */
char send_buffer[SEND_BUFFER_SIZE + 1];
int sblen = 0;	/* Fill pointer for the send buffer.  */
Jason Rumney's avatar
Jason Rumney committed
568 569
/* Socket used to communicate with the Emacs server process.  */
HSOCKET emacs_socket = 0;
570 571 572 573 574

/* Let's send the data to Emacs when either
   - the data ends in "\n", or
   - the buffer is full (but this shouldn't happen)
   Otherwise, we just accumulate it.  */
575 576
void
send_to_emacs (s, data)
577 578 579 580
     HSOCKET s;
     char *data;
{
  while (data)
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
      int dlen = strlen (data);
      if (dlen + sblen >= SEND_BUFFER_SIZE)
	{
	  int part = SEND_BUFFER_SIZE - sblen;
	  strncpy (&send_buffer[sblen], data, part);
	  data += part;
	  sblen = SEND_BUFFER_SIZE;
	}
      else if (dlen)
	{
	  strcpy (&send_buffer[sblen], data);
	  data = NULL;
	  sblen += dlen;
	}
      else
	break;

      if (sblen == SEND_BUFFER_SIZE
	  || (sblen > 0 && send_buffer[sblen-1] == '\n'))
	{
	  int sent = send (s, send_buffer, sblen, 0);
	  if (sent != sblen)
	    strcpy (send_buffer, &send_buffer[sent]);
	  sblen -= sent;
	}
607 608 609 610
    }
}


611
/* In STR, insert a & before each &, each space, each newline, and
Richard M. Stallman's avatar
Richard M. Stallman committed
612
   any initial -.  Change spaces to underscores, too, so that the
613 614 615
   return value never contains a space.

   Does not change the string.  Outputs the result to STREAM.  */
616
void
617
quote_argument (s, str)
618
     HSOCKET s;
619
     char *str;
620
{
Karoly Lorentey's avatar
Karoly Lorentey committed
621
  char *copy = (char *) xmalloc (strlen (str) * 2 + 1);
622 623
  char *p, *q;

624
  p = str;
625 626 627 628 629
  q = copy;
  while (*p)
    {
      if (*p == ' ')
	{
630
	  *q++ = '&';
631 632 633
	  *q++ = '_';
	  p++;
	}
Stefan Monnier's avatar
Stefan Monnier committed
634 635 636 637 638 639
      else if (*p == '\n')
	{
	  *q++ = '&';
	  *q++ = 'n';
	  p++;
	}
640 641
      else
	{
642
	  if (*p == '&' || (*p == '-' && p == str))
643
	    *q++ = '&';
644 645 646
	  *q++ = *p++;
	}
    }
647
  *q++ = 0;
648

Jason Rumney's avatar
Jason Rumney committed
649
  send_to_emacs (s, copy);
650 651

  free (copy);
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

/* The inverse of quote_argument.  Removes quoting in string STR by
   modifying the string in place.   Returns STR. */

char *
unquote_argument (str)
     char *str;
{
  char *p, *q;

  if (! str)
    return str;

  p = str;
  q = str;
  while (*p)
    {
      if (*p == '&')
        {
          p++;
          if (*p == '&')
            *p = '&';
          else if (*p == '_')
            *p = ' ';
          else if (*p == 'n')
            *p = '\n';
          else if (*p == '-')
            *p = '-';
        }
      *q++ = *p++;
    }
  *q = 0;
  return str;
}

689

690 691 692 693 694 695 696 697 698 699 700 701 702 703
int
file_name_absolute_p (filename)
     const unsigned char *filename;
{
  /* Sanity check, it shouldn't happen.  */
  if (! filename) return FALSE;

  /* /xxx is always an absolute path.  */
  if (filename[0] == '/') return TRUE;

  /* Empty filenames (which shouldn't happen) are relative.  */
  if (filename[0] == '\0') return FALSE;

#ifdef WINDOWSNT
704
  /* X:\xxx is always absolute.  */
705
  if (isalpha (filename[0])
706
      && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
707 708 709 710
    return TRUE;

  /* Both \xxx and \\xxx\yyy are absolute.  */
  if (filename[0] == '\\') return TRUE;
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

  /*
    FIXME:  There's a corner case not dealt with, "x:y", where:

    1) x is a valid drive designation (usually a letter in the A-Z range)
       and y is a path, relative to the current directory on drive x.  This
       is absolute, *after* fixing the y part to include the current
       directory in x.

    2) x is a relative file name, and y is an NTFS stream name.  This is a
       correct relative path, but it is very unusual.

    The trouble is that first case items are also valid examples of the
    second case, i.e., "c:test" can be understood as drive:path or as
    file:stream.

    The "right" fix would involve checking whether
    - the current drive/partition is NTFS,
    - x is a valid (and accesible) drive designator,
    - x:y already exists as a file:stream in the current directory,
    - y already exists on the current directory of drive x,
    - the auspices are favorable,
    and then taking an "informed decision" based on the above.

    Whatever the result, Emacs currently does a very bad job of dealing
    with NTFS file:streams: it cannot visit them, and the only way to
    create one is by setting `buffer-file-name' to point to it (either
    manually or with emacsclient). So perhaps resorting to 1) and ignoring
    2) for now is the right thing to do.

    Anyway, something to decide After the Release.
  */
743 744 745 746 747
#endif

  return FALSE;
}

748
#ifdef WINDOWSNT
749
/* Wrapper to make WSACleanup a cdecl, as required by atexit.  */
750 751
void
__cdecl close_winsock ()
752 753 754
{
  WSACleanup ();
}
755

756 757 758
/* Initialize the WinSock2 library.  */
void
initialize_sockets ()
759
{
760 761 762 763
  WSADATA wsaData;

  if (WSAStartup (MAKEWORD (2, 0), &wsaData))
    {
Juanma Barranquero's avatar
Juanma Barranquero committed
764
      message (TRUE, "%s: error initializing WinSock2", progname);
765 766 767 768
      exit (EXIT_FAILURE);
    }

  atexit (close_winsock);
769
}
770
#endif /* WINDOWSNT */
771

772 773

/*
774
 * Read the information needed to set up a TCP comm channel with
775
 * the Emacs server: host, port, pid and authentication string.
776
 */
777 778
int
get_server_config (server, authentication)
779 780
     struct sockaddr_in *server;
     char *authentication;
781
{
782 783
  char dotted[32];
  char *port;
784
  char *pid;
785
  FILE *config = NULL;
786

787 788 789
  if (file_name_absolute_p (server_file))
    config = fopen (server_file, "rb");
  else
790
    {
791
      char *home = getenv ("HOME");
792

793 794 795 796 797 798
      if (home)
        {
          char *path = alloca (32 + strlen (home) + strlen (server_file));
          sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
          config = fopen (path, "rb");
        }
799 800 801 802 803 804 805 806
#ifdef WINDOWSNT
      if (!config && (home = getenv ("APPDATA")))
        {
          char *path = alloca (32 + strlen (home) + strlen (server_file));
          sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
          config = fopen (path, "rb");
        }
#endif
807 808 809 810 811 812
    }

  if (! config)
    return FALSE;

  if (fgets (dotted, sizeof dotted, config)
813 814
      && (port = strchr (dotted, ':'))
      && (pid = strchr (port, ' ')))
815 816
    {
      *port++ = '\0';
817
      *pid++  = '\0';
818 819 820
    }
  else
    {
Juanma Barranquero's avatar
Juanma Barranquero committed
821
      message (TRUE, "%s: invalid configuration info", progname);
822
      exit (EXIT_FAILURE);
823 824
    }

825 826 827
  server->sin_family = AF_INET;
  server->sin_addr.s_addr = inet_addr (dotted);
  server->sin_port = htons (atoi (port));
828

829 830
  if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
    {
Juanma Barranquero's avatar
Juanma Barranquero committed
831
      message (TRUE, "%s: cannot read authentication info", progname);
832 833
      exit (EXIT_FAILURE);
    }
Richard M. Stallman's avatar
Richard M. Stallman committed
834

835
  fclose (config);
836

837
  emacs_pid = atoi (pid);
838

839
  return TRUE;
840 841
}

842 843 844 845 846 847 848
HSOCKET
set_tcp_socket ()
{
  HSOCKET s;
  struct sockaddr_in server;
  struct linger l_arg = {1, 1};
  char auth_string[AUTH_KEY_LENGTH + 1];
849

850 851 852
  if (! get_server_config (&server, auth_string))
    return INVALID_SOCKET;

853
  if (server.sin_addr.s_addr != inet_addr ("127.0.0.1"))
854
    message (FALSE, "%s: connected to remote socket at %s\n",
855 856
             progname, inet_ntoa (server.sin_addr));

857 858 859 860 861
  /*
   * Open up an AF_INET socket
   */
  if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
    {
Juanma Barranquero's avatar
Juanma Barranquero committed
862
      message (TRUE, "%s: socket: %s\n", progname, strerror (errno));
863 864 865 866 867 868 869 870
      return INVALID_SOCKET;
    }

  /*
   * Set up the socket
   */
  if (connect (s, (struct sockaddr *) &server, sizeof server) < 0)
    {
Juanma Barranquero's avatar
Juanma Barranquero committed
871
      message (TRUE, "%s: connect: %s\n", progname, strerror (errno));
872 873 874 875 876 877 878 879 880 881
      return INVALID_SOCKET;
    }

  setsockopt (s, SOL_SOCKET, SO_LINGER, (char *) &l_arg, sizeof l_arg);

  /*
   * Send the authentication
   */
  auth_string[AUTH_KEY_LENGTH] = '\0';

Jason Rumney's avatar
Jason Rumney committed
882 883 884
  send_to_emacs (s, "-auth ");
  send_to_emacs (s, auth_string);
  send_to_emacs (s, "\n");
885 886 887 888

  return s;
}

Jason Rumney's avatar
Jason Rumney committed
889 890 891 892 893

/* Returns 1 if PREFIX is a prefix of STRING. */
static int
strprefix (char *prefix, char *string)
{
894
  return !strncmp (prefix, string, strlen (prefix));
Jason Rumney's avatar
Jason Rumney committed
895 896 897
}


898
#if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
Richard M. Stallman's avatar
Richard M. Stallman committed
899

900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
/* 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;
916

917 918 919
  return 0;
}

920

921 922 923
/* A signal handler that passes the signal to the Emacs process.
   Useful for SIGWINCH.  */

924
SIGTYPE
925
pass_signal_to_emacs (int signalnum)
926 927 928
{
  int old_errno = errno;

Karoly Lorentey's avatar
Karoly Lorentey committed
929
  if (emacs_pid)
930
    kill (emacs_pid, signalnum);
Karoly Lorentey's avatar
Karoly Lorentey committed
931

932
  signal (signalnum, pass_signal_to_emacs);
Karoly Lorentey's avatar
Karoly Lorentey committed
933 934 935
  errno = old_errno;
}

936 937 938 939 940 941 942 943 944 945 946
/* Signal handler for SIGCONT; notify the Emacs process that it can
   now resume our tty frame.  */

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

  if (tcgetpgrp (1) == getpgrp ())
    {
      /* We are in the foreground. */
Jason Rumney's avatar
Jason Rumney committed
947
      send_to_emacs (emacs_socket, "-resume \n");
948 949 950 951 952 953
    }
  else
    {
      /* We are in the background; cancel the continue. */
      kill (getpid (), SIGSTOP);
    }
954 955

  signal (signalnum, handle_sigcont);
956 957 958 959 960 961 962 963 964 965 966 967 968 969
  errno = old_errno;
}

/* Signal handler for SIGTSTP; notify the Emacs process that we are
   going to sleep.  Normally the suspend is initiated by Emacs via
   server-handle-suspend-tty, but if the server gets out of sync with
   reality, we may get a SIGTSTP on C-z.  Handling this signal and
   notifying Emacs about it should get things under control again. */

SIGTYPE
handle_sigtstp (int signalnum)
{
  int old_errno = errno;
  sigset_t set;
970

971
  if (emacs_socket)
Jason Rumney's avatar
Jason Rumney committed
972
    send_to_emacs (emacs_socket, "-suspend \n");
973 974 975 976 977 978 979 980 981 982 983 984

  /* Unblock this signal and call the default handler by temprarily
     changing the handler and resignalling. */
  sigprocmask (SIG_BLOCK, NULL, &set);
  sigdelset (&set, signalnum);
  signal (signalnum, SIG_DFL);
  kill (getpid (), signalnum);
  sigprocmask (SIG_SETMASK, &set, NULL); /* Let's the above signal through. */
  signal (signalnum, handle_sigtstp);

  errno = old_errno;
}
985
/* Set up signal handlers before opening a frame on the current tty.  */
986

987 988
void
init_signals (void)
989 990
{
  /* Set up signal handlers. */
991
  signal (SIGWINCH, pass_signal_to_emacs);
992 993 994 995 996

  /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
     deciding which terminal the signal came from.  C-g is now a
     normal input event on secondary terminals.  */
#if 0
997 998
  signal (SIGINT, pass_signal_to_emacs);
  signal (SIGQUIT, pass_signal_to_emacs);
999
#endif
1000 1001 1002 1003

  signal (SIGCONT, handle_sigcont);
  signal (SIGTSTP, handle_sigtstp);
  signal (SIGTTOU, handle_sigtstp);
1004 1005
}

Richard M. Stallman's avatar
Richard M. Stallman committed
1006

1007 1008
HSOCKET
set_local_socket ()
Richard M. Stallman's avatar
Richard M. Stallman committed
1009
{
1010
  HSOCKET s;
Richard M. Stallman's avatar
Richard M. Stallman committed
1011 1012
  struct sockaddr_un server;

1013
  /*
Richard M. Stallman's avatar
Richard M. Stallman committed
1014 1015 1016 1017 1018
   * Open up an AF_UNIX socket in this person's home directory
   */

  if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
    {
Juanma Barranquero's avatar
Juanma Barranquero committed
1019
      message (TRUE, "%s: socket: %s\n", progname, strerror (errno));
1020
      return INVALID_SOCKET;
Richard M. Stallman's avatar
Richard M. Stallman committed
1021
    }
1022

Richard M. Stallman's avatar
Richard M. Stallman committed
1023
  server.sun_family = AF_UNIX;
1024 1025

  {
1026
    int sock_status = 0;
1027
    int default_sock = !socket_name;
1028
    int saved_errno = 0;
1029
    char *server_name = "server";
1030

1031 1032
    if (socket_name && !index (socket_name, '/') && !index (socket_name, '\\'))
      { /* socket_name is a file name component.  */