emacsclient.c 42.7 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, 2008, 2009, 2010 Free Software Foundation, Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
4 5 6

This file is part of GNU Emacs.

7
GNU Emacs is free software: you can redistribute it and/or modify
Richard M. Stallman's avatar
Richard M. Stallman committed
8
it under the terms of the GNU General Public License as published by
9 10
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Richard M. Stallman's avatar
Richard M. Stallman committed
11 12 13 14 15 16 17

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
18
along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
Richard M. Stallman's avatar
Richard M. Stallman committed
19 20


21
#ifdef HAVE_CONFIG_H
Pavel Janík's avatar
Pavel Janík committed
22
#include <config.h>
23 24
#endif

25 26
#ifdef WINDOWSNT

27 28 29 30
/* config.h defines these, which disables sockets altogether! */
# undef _WINSOCKAPI_
# undef _WINSOCK_H

31 32
# include <malloc.h>
# include <stdlib.h>
Juanma Barranquero's avatar
Juanma Barranquero committed
33
# include <windows.h>
34
# include <commctrl.h>
35 36 37

# define NO_SOCKETS_IN_FILE_SYSTEM

38 39 40
# define HSOCKET SOCKET
# define CLOSE_SOCKET closesocket
# define INITIALIZE() (initialize_sockets ())
41 42 43

#else /* !WINDOWSNT */

44
# include "syswait.h"
45

46 47 48
# ifdef HAVE_INET_SOCKETS
#  include <netinet/in.h>
# endif
49

Dan Nicolaescu's avatar
Dan Nicolaescu committed
50
# include <arpa/inet.h>
Dan Nicolaescu's avatar
Dan Nicolaescu committed
51

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

57 58 59 60
# ifndef WCONTINUED
#  define WCONTINUED 8
# endif

61
#endif /* !WINDOWSNT */
62

63
#undef signal
Richard M. Stallman's avatar
Richard M. Stallman committed
64

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

73 74 75
#ifdef WINDOWSNT
# include <io.h>
#else /* not WINDOWSNT */
76
# include <pwd.h>
77
#endif /* not WINDOWSNT */
78
#include <sys/stat.h>
79

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


84
char *getenv (const char *), *getwd (char *);
85 86 87
#ifdef HAVE_GETCWD
char *(getcwd) (char *, size_t);
#endif
88

89
#ifdef WINDOWSNT
90
char *w32_getenv (char *);
91 92 93 94 95
#define egetenv(VAR) w32_getenv(VAR)
#else
#define egetenv(VAR) getenv(VAR)
#endif

96 97 98 99
#ifndef VERSION
#define VERSION "unspecified"
#endif

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

#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
120 121 122 123

/* Additional space when allocating buffers for filenames, etc.  */
#define EXTRA_SPACE 100

124

125 126 127
/* Name used to invoke this program.  */
char *progname;

Karoly Lorentey's avatar
Karoly Lorentey committed
128 129 130
/* The second argument to main. */
char **main_argv;

131
/* Nonzero means don't wait for a response from Emacs.  --no-wait.  */
132 133
int nowait = 0;

Stefan Monnier's avatar
Stefan Monnier committed
134 135 136
/* Nonzero means args are expressions to be evaluated.  --eval.  */
int eval = 0;

137 138
/* Nonzero means don't open a new frame.  Inverse of --create-frame.  */
int current_frame = 1;
139

Stefan Monnier's avatar
Stefan Monnier committed
140 141 142
/* The display on which Emacs should work.  --display.  */
char *display = NULL;

143 144 145
/* The parent window ID, if we are opening a frame via XEmbed.  */
char *parent_id = NULL;

146
/* Nonzero means open a new Emacs frame on the current terminal. */
147
int tty = 0;
148

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

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

156 157 158
/* If non-NULL, the filename of the authentication file.  */
char *server_file = NULL;

159 160 161
/* PID of the Emacs server process.  */
int emacs_pid = 0;

162
void print_help_and_exit (void) NO_RETURN;
163 164
void fail (void) NO_RETURN;

165

166 167
struct option longopts[] =
{
168
  { "no-wait",	no_argument,	   NULL, 'n' },
Stefan Monnier's avatar
Stefan Monnier committed
169
  { "eval",	no_argument,	   NULL, 'e' },
170 171
  { "help",	no_argument,	   NULL, 'H' },
  { "version",	no_argument,	   NULL, 'V' },
172
  { "tty",	no_argument,       NULL, 't' },
173
  { "nw",	no_argument,       NULL, 't' },
174
  { "create-frame", no_argument,   NULL, 'c' },
Stefan Monnier's avatar
Stefan Monnier committed
175
  { "alternate-editor", required_argument, NULL, 'a' },
176
#ifndef NO_SOCKETS_IN_FILE_SYSTEM
177
  { "socket-name",	required_argument, NULL, 's' },
178
#endif
179
  { "server-file",	required_argument, NULL, 'f' },
180
#ifndef WINDOWSNT
Stefan Monnier's avatar
Stefan Monnier committed
181
  { "display",	required_argument, NULL, 'd' },
182
#endif
183
  { "parent-id", required_argument, NULL, 'p' },
Stefan Monnier's avatar
Stefan Monnier committed
184
  { 0, 0, 0, 0 }
185 186
};

187 188 189 190

/* Like malloc but get fatal error if memory is exhausted.  */

long *
191
xmalloc (unsigned int size)
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
{
  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)

219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
/* 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


238
/* Return the current working directory.  Returns NULL on errors.
239
   Any other returned value must be freed with free.  This is used
240 241
   only when get_current_dir_name is not defined on the system.  */
char*
242
get_current_dir_name (void)
243 244 245 246 247 248 249
{
  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.  */
250
    if ((pwd = egetenv ("PWD")) != 0
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 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
      && (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
310
#ifdef WINDOWSNT
311 312 313 314 315 316 317

#define REG_ROOT "SOFTWARE\\GNU\\Emacs"

/* Retrieve an environment variable from the Emacs subkeys of the registry.
   Return NULL if the variable was not found, or it was empty.
   This code is based on w32_get_resource (w32.c).  */
char *
318
w32_get_resource (HKEY predefined, char *key, LPDWORD type)
319 320 321 322 323 324 325 326 327 328 329
{
  HKEY hrootkey = NULL;
  char *result = NULL;
  DWORD cbData;

  if (RegOpenKeyEx (predefined, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
    {
      if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS)
	{
	  result = (char *) xmalloc (cbData);

330 331
	  if ((RegQueryValueEx (hrootkey, key, NULL, type, result, &cbData) != ERROR_SUCCESS)
	      || (*result == 0))
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
	    {
	      free (result);
	      result = NULL;
	    }
	}

      RegCloseKey (hrootkey);
    }

  return result;
}

/*
  getenv wrapper for Windows

347
  This is needed to duplicate Emacs's behavior, which is to look for environment
348 349 350
  variables in the registry if they don't appear in the environment.
*/
char *
351
w32_getenv (char *envvar)
352 353 354 355 356 357 358 359 360 361
{
  char *value;
  DWORD dwType;

  if (value = getenv (envvar))
    /* Found in the environment.  */
    return value;

  if (! (value = w32_get_resource (HKEY_CURRENT_USER, envvar, &dwType)) &&
      ! (value = w32_get_resource (HKEY_LOCAL_MACHINE, envvar, &dwType)))
362 363 364 365 366 367 368
    {
      /* "w32console" is what Emacs on Windows uses for tty-type under -nw.  */
      if (strcmp (envvar, "TERM") == 0)
	return xstrdup ("w32console");
      /* Found neither in the environment nor in the registry.  */
      return NULL;
    }
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

  if (dwType == REG_SZ)
    /* Registry; no need to expand.  */
    return value;

  if (dwType == REG_EXPAND_SZ)
    {
      DWORD size;

      if (size = ExpandEnvironmentStrings (value, NULL, 0))
	{
	  char *buffer = (char *) xmalloc (size);
	  if (ExpandEnvironmentStrings (value, buffer, size))
	    {
	      /* Found and expanded.  */
	      free (value);
	      return buffer;
	    }

	  /* Error expanding.  */
	  free (buffer);
	}
    }

  /* Not the right type, or not correctly expanded.  */
  free (value);
  return NULL;
}

398
void
399
w32_set_user_model_id (void)
400 401
{
  HMODULE shell;
402
  HRESULT (WINAPI * set_user_model) (wchar_t * id);
403 404 405 406

  /* On Windows 7 and later, we need to set the user model ID
     to associate emacsclient launched files with Emacs frames
     in the UI.  */
407
  shell = LoadLibrary ("shell32.dll");
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
  if (shell)
    {
      set_user_model
	= (void *) GetProcAddress (shell,
				   "SetCurrentProcessExplicitAppUserModelID");
      /* If the function is defined, then we are running on Windows 7
	 or newer, and the UI uses this to group related windows
	 together.  Since emacs, runemacs, emacsclient are related, we
	 want them grouped even though the executables are different,
	 so we need to set a consistent ID between them.  */
      if (set_user_model)
	set_user_model (L"GNU.Emacs");

      FreeLibrary (shell);
    }
}

Juanma Barranquero's avatar
Juanma Barranquero committed
425
int
426
w32_window_app (void)
Juanma Barranquero's avatar
Juanma Barranquero committed
427 428 429 430 431
{
  static int window_app = -1;
  char szTitle[MAX_PATH];

  if (window_app < 0)
432 433 434 435 436
    {
      /* Checking for STDOUT does not work; it's a valid handle also in
         nonconsole apps.  Testing for the console title seems to work. */
      window_app = (GetConsoleTitleA (szTitle, MAX_PATH) == 0);
      if (window_app)
437
        InitCommonControls ();
438
    }
Juanma Barranquero's avatar
Juanma Barranquero committed
439 440 441

  return window_app;
}
Dan Nicolaescu's avatar
Dan Nicolaescu committed
442 443

/*
444
  execvp wrapper for Windows.  Quotes arguments with embedded spaces.
Dan Nicolaescu's avatar
Dan Nicolaescu committed
445 446 447 448

  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
449
  predictably bad results.  By contrast, POSIX execvp passes the arguments
Dan Nicolaescu's avatar
Dan Nicolaescu committed
450 451 452
  directly into the argv array of the child process.
*/
int
453
w32_execvp (const char *path, char **argv)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
{
  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

474 475 476 477 478 479 480
/* Emulation of ttyname for Windows.  */
char *
ttyname (int fd)
{
  return "CONOUT$";
}

Dan Nicolaescu's avatar
Dan Nicolaescu committed
481
#endif /* WINDOWSNT */
Juanma Barranquero's avatar
Juanma Barranquero committed
482

Juanma Barranquero's avatar
Juanma Barranquero committed
483 484
/* Display a normal or error message.
   On Windows, use a message box if compiled as a Windows app.  */
Juanma Barranquero's avatar
Juanma Barranquero committed
485 486 487
void
message (int is_error, char *message, ...)
{
488
  char msg[2048];
Juanma Barranquero's avatar
Juanma Barranquero committed
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
  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
505 506 507 508 509 510
    {
      FILE *f = is_error ? stderr : stdout;

      fputs (msg, f);
      fflush (f);
    }
Juanma Barranquero's avatar
Juanma Barranquero committed
511 512
}

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

516
void
517
decode_options (int argc, char **argv)
518
{
519
  alternate_editor = egetenv ("ALTERNATE_EDITOR");
520

521 522
  while (1)
    {
523
      int opt = getopt_long_only (argc, argv,
524
#ifndef NO_SOCKETS_IN_FILE_SYSTEM
525
			     "VHnea:s:f:d:tc",
526
#else
527
			     "VHnea:f:d:tc",
528
#endif
529
			     longopts, 0);
530 531 532 533 534 535 536 537 538 539

      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;
540

541 542 543
	case 'a':
	  alternate_editor = optarg;
	  break;
544

545
#ifndef NO_SOCKETS_IN_FILE_SYSTEM
546 547 548
	case 's':
	  socket_name = optarg;
	  break;
549
#endif
550

551 552 553
	case 'f':
	  server_file = optarg;
	  break;
554

555 556 557 558
	  /* We used to disallow this argument in w32, but it seems better
	     to allow it, for the occasional case where the user is
	     connecting with a w32 client to a server compiled with X11
	     support.  */
Stefan Monnier's avatar
Stefan Monnier committed
559 560 561 562
	case 'd':
	  display = optarg;
	  break;

563 564 565 566
	case 'n':
	  nowait = 1;
	  break;

Stefan Monnier's avatar
Stefan Monnier committed
567 568 569 570
	case 'e':
	  eval = 1;
	  break;

571
	case 'V':
Juanma Barranquero's avatar
Juanma Barranquero committed
572
	  message (FALSE, "emacsclient %s\n", VERSION);
573
	  exit (EXIT_SUCCESS);
574
	  break;
Richard M. Stallman's avatar
Richard M. Stallman committed
575

576
        case 't':
577
          tty = 1;
578
	  current_frame = 0;
579 580
          break;

581
        case 'c':
582
          current_frame = 0;
583
          break;
584

585 586 587 588 589
	case 'p':
	  parent_id = optarg;
          current_frame = 0;
	  break;

590 591
	case 'H':
	  print_help_and_exit ();
592 593 594
	  break;

	default:
Juanma Barranquero's avatar
Juanma Barranquero committed
595
	  message (TRUE, "Try `%s --help' for more information\n", progname);
596
	  exit (EXIT_FAILURE);
597
	  break;
598 599
	}
    }
600

601 602 603 604 605 606
  /* If the -c option is used (without -t) and no --display argument
     is provided, try $DISPLAY.
     Without the -c option, we used to set `display' to $DISPLAY by
     default, but this changed the default behavior and is sometimes
     inconvenient.  So we force users to use "--display $DISPLAY" if
     they want Emacs to connect to their current display.  */
607
  if (!current_frame && !tty && !display)
608 609 610 611 612 613 614 615 616
    {
      display = egetenv ("DISPLAY");
#ifdef NS_IMPL_COCOA
      /* Under Cocoa, we don't really use displays the same way as in X,
         so provide a dummy. */
      if (!display || strlen (display) == 0)
        display = "ns";
#endif
    }
617

618
  /* A null-string display is invalid.  */
619 620 621
  if (display && strlen (display) == 0)
    display = NULL;

622 623
  /* If no display is available, new frames are tty frames.  */
  if (!current_frame && !display)
624
    tty = 1;
625

626
  /* --no-wait implies --current-frame on ttys when there are file
627
     arguments or expressions given.  */
628
  if (nowait && tty && argc - optind > 0)
629
    current_frame = 1;
630 631

#ifdef WINDOWSNT
Dan Nicolaescu's avatar
Dan Nicolaescu committed
632
  if (alternate_editor && alternate_editor[0] == '\0')
633 634 635 636 637 638
    {
      message (TRUE, "--alternate-editor argument or ALTERNATE_EDITOR variable cannot be\n\
an empty string");
      exit (EXIT_FAILURE);
    }
#endif /* WINDOWSNT */
639 640
}

641

642
void
643
print_help_and_exit (void)
644
{
645 646 647 648
  /* 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
649
  message (FALSE,
650
	   "Usage: %s [OPTIONS] FILE...\n\
Stefan Monnier's avatar
Stefan Monnier committed
651 652
Tell the Emacs server to visit the specified files.\n\
Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
653
\n\
Stefan Monnier's avatar
Stefan Monnier committed
654
The following OPTIONS are accepted:\n\
655 656
-V, --version		Just print version info and return\n\
-H, --help    		Print this usage information message\n\
657
-nw, -t, --tty 		Open a new Emacs frame on the current terminal\n\
658
-c, --create-frame    	Create a new frame instead of trying to\n\
659
			use the current Emacs frame\n\
660
-e, --eval    		Evaluate the FILE arguments as ELisp expressions\n\
661
-n, --no-wait		Don't wait for the server to return\n\
662
-d DISPLAY, --display=DISPLAY\n\
663 664
			Visit the file in the given display\n\
--parent-id=ID          Open in parent window ID, via XEmbed\n"
665
#ifndef NO_SOCKETS_IN_FILE_SYSTEM
666
"-s SOCKET, --socket-name=SOCKET\n\
667
			Set filename of the UNIX socket for communication\n"
668
#endif
669
"-f SERVER, --server-file=SERVER\n\
670
			Set filename of the TCP authentication file\n\
671
-a EDITOR, --alternate-editor=EDITOR\n\
672
			Editor to fallback to if the server is not running\n"
673
#ifndef WINDOWSNT
674 675
"			If EDITOR is the empty string, start Emacs in daemon\n\
			mode and try connecting again\n"
676
#endif /* not WINDOWSNT */
677
"\n\
678
Report bugs with M-x report-emacs-bug.\n", progname);
679
  exit (EXIT_SUCCESS);
680
}
681

682 683 684
/*
  Try to run a different command, or --if no alternate editor is
  defined-- exit with an errorcode.
685
  Uses argv, but gets it from the global variable main_argv.
686 687
*/
void
688
fail (void)
Karoly Lorentey's avatar
Karoly Lorentey committed
689
{
690
  if (alternate_editor)
Karoly Lorentey's avatar
Karoly Lorentey committed
691
    {
692
      int i = optind - 1;
693

694
      execvp (alternate_editor, main_argv + i);
Juanma Barranquero's avatar
Juanma Barranquero committed
695
      message (TRUE, "%s: error executing alternate editor \"%s\"\n",
696
	       progname, alternate_editor);
Karoly Lorentey's avatar
Karoly Lorentey committed
697
    }
698
  exit (EXIT_FAILURE);
Karoly Lorentey's avatar
Karoly Lorentey committed
699 700
}

701

702
#if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
Karoly Lorentey's avatar
Karoly Lorentey committed
703

704 705 706 707
int
main (argc, argv)
     int argc;
     char **argv;
Karoly Lorentey's avatar
Karoly Lorentey committed
708
{
709 710 711
  main_argv = argv;
  progname = argv[0];
  message (TRUE, "%s: Sorry, the Emacs server is supported only\n"
712
	   "on systems with Berkeley sockets.\n",
713
	   argv[0]);
714
  fail ();
Karoly Lorentey's avatar
Karoly Lorentey committed
715 716
}

717
#else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
718

719 720
#ifdef WINDOWSNT
# include <winsock2.h>
721
#else
722 723 724 725 726 727 728 729
# include <sys/types.h>
# include <sys/socket.h>
# include <sys/un.h>
#endif

#define AUTH_KEY_LENGTH      64
#define SEND_BUFFER_SIZE   4096

730
extern char *strerror (int);
731 732 733 734

/* 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
735 736
/* Socket used to communicate with the Emacs server process.  */
HSOCKET emacs_socket = 0;
737

738 739 740
/* On Windows, the socket library was historically separate from the standard
   C library, so errors are handled differently.  */
void
741
sock_err_message (char *function_name)
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
{
#ifdef WINDOWSNT
  char* msg = NULL;

  FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
                 | FORMAT_MESSAGE_ALLOCATE_BUFFER
                 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
                 NULL, WSAGetLastError (), 0, (LPTSTR)&msg, 0, NULL);

  message (TRUE, "%s: %s: %s\n", progname, function_name, msg);

  LocalFree (msg);
#else
  message (TRUE, "%s: %s: %s\n", progname, function_name, strerror (errno));
#endif
}


760 761 762 763
/* 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.  */
764
void
Juanma Barranquero's avatar
Juanma Barranquero committed
765
send_to_emacs (HSOCKET s, char *data)
766 767
{
  while (data)
768
    {
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
      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;
	}
794 795 796 797
    }
}

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

Juanma Barranquero's avatar
Juanma Barranquero committed
802
   Does not change the string.  Outputs the result to S.  */
803
void
Juanma Barranquero's avatar
Juanma Barranquero committed
804
quote_argument (HSOCKET s, char *str)
805
{
Karoly Lorentey's avatar
Karoly Lorentey committed
806
  char *copy = (char *) xmalloc (strlen (str) * 2 + 1);
807 808
  char *p, *q;

809
  p = str;
810 811 812 813 814
  q = copy;
  while (*p)
    {
      if (*p == ' ')
	{
815
	  *q++ = '&';
816 817 818
	  *q++ = '_';
	  p++;
	}
Stefan Monnier's avatar
Stefan Monnier committed
819 820 821 822 823 824
      else if (*p == '\n')
	{
	  *q++ = '&';
	  *q++ = 'n';
	  p++;
	}
825 826
      else
	{
827
	  if (*p == '&' || (*p == '-' && p == str))
828
	    *q++ = '&';
829 830 831
	  *q++ = *p++;
	}
    }
832
  *q++ = 0;
833

Jason Rumney's avatar
Jason Rumney committed
834
  send_to_emacs (s, copy);
835 836

  free (copy);
837
}
838

839 840 841 842 843

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

char *
844
unquote_argument (char *str)
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
{
  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;
}

873

874
int
875
file_name_absolute_p (const unsigned char *filename)
876 877 878 879 880 881 882 883 884 885 886
{
  /* 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
887
  /* X:\xxx is always absolute.  */
888
  if (isalpha (filename[0])
889
      && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
890 891 892 893 894 895 896 897 898
    return TRUE;

  /* Both \xxx and \\xxx\yyy are absolute.  */
  if (filename[0] == '\\') return TRUE;
#endif

  return FALSE;
}

899
#ifdef WINDOWSNT
900
/* Wrapper to make WSACleanup a cdecl, as required by atexit.  */
901 902
void __cdecl
close_winsock (void)
903 904 905
{
  WSACleanup ();
}
906

907 908
/* Initialize the WinSock2 library.  */
void
909
initialize_sockets (void)
910
{
911 912 913 914
  WSADATA wsaData;

  if (WSAStartup (MAKEWORD (2, 0), &wsaData))
    {
915
      message (TRUE, "%s: error initializing WinSock2\n", progname);
916 917 918 919
      exit (EXIT_FAILURE);
    }

  atexit (close_winsock);
920
}
921
#endif /* WINDOWSNT */
922

923 924

/*
925
 * Read the information needed to set up a TCP comm channel with
926
 * the Emacs server: host, port, pid and authentication string.
927
 */
928
int
929
get_server_config (struct sockaddr_in *server, char *authentication)
930
{
931 932
  char dotted[32];
  char *port;
933
  char *pid;
934
  FILE *config = NULL;
935

936 937 938
  if (file_name_absolute_p (server_file))
    config = fopen (server_file, "rb");
  else
939
    {
940
      char *home = egetenv ("HOME");
941

942 943
      if (home)
        {
944 945
          char *path = alloca (strlen (home) + strlen (server_file)
			       + EXTRA_SPACE);
946 947 948
          sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
          config = fopen (path, "rb");
        }
949
#ifdef WINDOWSNT
950
      if (!config && (home = egetenv ("APPDATA")))
951
        {
952 953
          char *path = alloca (strlen (home) + strlen (server_file)
			       + EXTRA_SPACE);
954 955 956 957
          sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
          config = fopen (path, "rb");
        }
#endif
958 959 960 961 962 963
    }

  if (! config)
    return FALSE;

  if (fgets (dotted, sizeof dotted, config)
964 965
      && (port = strchr (dotted, ':'))
      && (pid = strchr (port, ' ')))
966 967
    {
      *port++ = '\0';
968
      *pid++  = '\0';
969 970 971
    }
  else
    {
972
      message (TRUE, "%s: invalid configuration info\n", progname);
973
      exit (EXIT_FAILURE);
974 975
    }

976 977 978
  server->sin_family = AF_INET;
  server->sin_addr.s_addr = inet_addr (dotted);
  server->sin_port = htons (atoi (port));
979