emacsclient.c 49.3 KB
Newer Older
Jim Blandy's avatar
Jim Blandy committed
1
/* Client process that communicates with GNU Emacs acting as server.
2

Paul Eggert's avatar
Paul Eggert committed
3
Copyright (C) 1986-1987, 1994, 1999-2018 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 <https://www.gnu.org/licenses/>.  */
Richard M. Stallman's avatar
Richard M. Stallman committed
19 20


Pavel Janík's avatar
Pavel Janík committed
21
#include <config.h>
22

23 24
#ifdef WINDOWSNT

25
/* ms-w32.h defines these, which disables sockets altogether!  */
26 27 28
# undef _WINSOCKAPI_
# undef _WINSOCK_H

29
# include <malloc.h>
Juanma Barranquero's avatar
Juanma Barranquero committed
30
# include <windows.h>
31
# include <commctrl.h>
Dan Nicolaescu's avatar
Dan Nicolaescu committed
32 33
# include <io.h>
# include <winsock2.h>
34 35 36

# define NO_SOCKETS_IN_FILE_SYSTEM

37 38
# define HSOCKET SOCKET
# define CLOSE_SOCKET closesocket
39
# define INITIALIZE() initialize_sockets ()
40

41
char *w32_getenv (const char *);
42
# define egetenv(VAR) w32_getenv (VAR)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
43

44 45
#else /* !WINDOWSNT */

46 47 48 49
# ifdef HAVE_NTGUI
# include <windows.h>
# endif /* HAVE_NTGUI */

50
# include "syswait.h"
51

52 53
# ifdef HAVE_INET_SOCKETS
#  include <netinet/in.h>
Dan Nicolaescu's avatar
Dan Nicolaescu committed
54 55 56 57 58
#  ifdef HAVE_SOCKETS
#    include <sys/types.h>
#    include <sys/socket.h>
#    include <sys/un.h>
#  endif /* HAVE_SOCKETS */
59
# endif
Dan Nicolaescu's avatar
Dan Nicolaescu committed
60
# include <arpa/inet.h>
Dan Nicolaescu's avatar
Dan Nicolaescu committed
61

62
# define INVALID_SOCKET (-1)
63 64 65
# define HSOCKET int
# define CLOSE_SOCKET close
# define INITIALIZE()
66

67
# define egetenv(VAR) getenv (VAR)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
68

69
#endif /* !WINDOWSNT */
70

71
#undef signal
Richard M. Stallman's avatar
Richard M. Stallman committed
72

73
#include <ctype.h>
74
#include <errno.h>
75
#include <getopt.h>
76
#include <inttypes.h>
Dan Nicolaescu's avatar
Dan Nicolaescu committed
77
#include <pwd.h>
78
#include <signal.h>
79
#include <stdarg.h>
80
#include <stddef.h>
81 82 83 84
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
85

86
#include <dosname.h>
87
#include <min-max.h>
88 89
#include <unlocked-io.h>

90 91 92
#ifndef VERSION
#define VERSION "unspecified"
#endif
93

94 95
/* Additional space when allocating buffers for filenames, etc.  */
#define EXTRA_SPACE 100
96

97
/* Name used to invoke this program.  */
98
static char const *progname;
99

100
/* The first argument to main.  */
101
static int main_argc;
102

103
/* The second argument to main.  */
104
static char *const *main_argv;
Karoly Lorentey's avatar
Karoly Lorentey committed
105

106
/* True means don't wait for a response from Emacs.  --no-wait.  */
107
static bool nowait;
108

109
/* True means don't print messages for successful operations.  --quiet.  */
110
static bool quiet;
111

112
/* True means don't print values returned from emacs. --suppress-output.  */
113
static bool suppress_output;
114

115
/* True means args are expressions to be evaluated.  --eval.  */
116
static bool eval;
Stefan Monnier's avatar
Stefan Monnier committed
117

118 119
/* True means open a new frame.  --create-frame etc.  */
static bool create_frame;
120

Stefan Monnier's avatar
Stefan Monnier committed
121
/* The display on which Emacs should work.  --display.  */
122
static char const *display;
Stefan Monnier's avatar
Stefan Monnier committed
123

124
/* The alternate display we should try if Emacs does not support display.  */
125
static char const *alt_display;
126

127
/* The parent window ID, if we are opening a frame via XEmbed.  */
128
static char *parent_id;
129

130
/* True means open a new Emacs frame on the current terminal.  */
131
static bool tty;
132

Stefan Monnier's avatar
Stefan Monnier committed
133 134
/* If non-NULL, the name of an editor to fallback to if the server
   is not running.  --alternate-editor.   */
135
static char *alternate_editor;
Stefan Monnier's avatar
Stefan Monnier committed
136

137
#ifndef NO_SOCKETS_IN_FILE_SYSTEM
Richard M. Stallman's avatar
Richard M. Stallman committed
138
/* If non-NULL, the filename of the UNIX socket.  */
139
static char const *socket_name;
140
#endif
141

142
/* If non-NULL, the filename of the authentication file.  */
143
static char const *server_file;
144

145
/* If non-NULL, the tramp prefix emacs must use to find the files.  */
146
static char const *tramp_prefix;
147

148
/* PID of the Emacs server process.  */
149
static pid_t emacs_pid;
150

151
/* If non-NULL, a string that should form a frame parameter alist to
152
   be used for the new frame.  */
153
static char const *frame_parameters;
154

155
static _Noreturn void print_help_and_exit (void);
156

157

158
static struct option const longopts[] =
159
{
160
  { "no-wait",	no_argument,	   NULL, 'n' },
161
  { "quiet",	no_argument,	   NULL, 'q' },
162
  { "suppress-output", no_argument, NULL, 'u' },
Stefan Monnier's avatar
Stefan Monnier committed
163
  { "eval",	no_argument,	   NULL, 'e' },
164 165
  { "help",	no_argument,	   NULL, 'H' },
  { "version",	no_argument,	   NULL, 'V' },
166
  { "tty",	no_argument,       NULL, 't' },
167
  { "nw",	no_argument,       NULL, 't' },
168
  { "create-frame", no_argument,   NULL, 'c' },
Stefan Monnier's avatar
Stefan Monnier committed
169
  { "alternate-editor", required_argument, NULL, 'a' },
170
  { "frame-parameters", required_argument, NULL, 'F' },
171
#ifndef NO_SOCKETS_IN_FILE_SYSTEM
172
  { "socket-name",	required_argument, NULL, 's' },
173
#endif
174
  { "server-file",	required_argument, NULL, 'f' },
Stefan Monnier's avatar
Stefan Monnier committed
175
  { "display",	required_argument, NULL, 'd' },
176
  { "parent-id", required_argument, NULL, 'p' },
177
  { "tramp",	required_argument, NULL, 'T' },
Stefan Monnier's avatar
Stefan Monnier committed
178
  { 0, 0, 0, 0 }
179 180
};

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

184
static void * ATTRIBUTE_MALLOC
185
xmalloc (size_t size)
186
{
187
  void *result = malloc (size);
188 189 190 191 192 193 194 195
  if (result == NULL)
    {
      perror ("malloc");
      exit (EXIT_FAILURE);
    }
  return result;
}

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
/* Like realloc but get fatal error if memory is exhausted.  */

static void *
xrealloc (void *ptr, size_t size)
{
  void *result = realloc (ptr, size);
  if (result == NULL)
    {
      perror ("realloc");
      exit (EXIT_FAILURE);
    }
  return result;
}

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

212
static char * ATTRIBUTE_MALLOC
213 214 215 216 217 218 219 220 221 222 223
xstrdup (const char *s)
{
  char *result = strdup (s);
  if (result == NULL)
    {
      perror ("strdup");
      exit (EXIT_FAILURE);
    }
  return result;
}

224
/* From sysdep.c */
225
#if !defined HAVE_GET_CURRENT_DIR_NAME || defined BROKEN_GET_CURRENT_DIR_NAME
226

227
char *get_current_dir_name (void);
228

229
/* Return the current working directory.  Returns NULL on errors.
230
   Any other returned value must be freed with free.  This is used
231
   only when get_current_dir_name is not defined on the system.  */
Paul Eggert's avatar
Paul Eggert committed
232
char *
233
get_current_dir_name (void)
234 235 236
{
  char *buf;
  struct stat dotstat, pwdstat;
237
  /* If PWD is accurate, use it instead of calling getcwd.  PWD is
238 239
     sometimes a nicer name, and using it may avoid a fatal error if a
     parent directory is searchable but not readable.  */
Paul Eggert's avatar
Paul Eggert committed
240 241
  char const *pwd = egetenv ("PWD");
  if (pwd
242 243 244 245 246
      && (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
247
# ifdef MAXPATHLEN
248
      && strlen (pwd) < MAXPATHLEN
249
# endif
250 251
      )
    {
252
      buf = xmalloc (strlen (pwd) + 1);
253 254 255 256 257 258 259
      strcpy (buf, pwd);
    }
  else
    {
      size_t buf_size = 1024;
      for (;;)
        {
260 261 262 263
	  int tmp_errno;
	  buf = malloc (buf_size);
	  if (! buf)
	    break;
264 265
          if (getcwd (buf, buf_size) == buf)
            break;
266 267 268
	  tmp_errno = errno;
	  free (buf);
	  if (tmp_errno != ERANGE)
269 270 271 272 273
            {
              errno = tmp_errno;
              return NULL;
            }
          buf_size *= 2;
274 275 276 277 278
	  if (! buf_size)
	    {
	      errno = ENOMEM;
	      return NULL;
	    }
279 280 281 282 283 284
        }
    }
  return buf;
}
#endif

Juanma Barranquero's avatar
Juanma Barranquero committed
285
#ifdef WINDOWSNT
286

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

289 290
char *w32_get_resource (HKEY, const char *, LPDWORD);

291 292 293 294
/* 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 *
295
w32_get_resource (HKEY predefined, const char *key, LPDWORD type)
296 297 298 299 300
{
  HKEY hrootkey = NULL;
  char *result = NULL;
  DWORD cbData;

301 302
  if (RegOpenKeyEx (predefined, REG_ROOT, 0, KEY_READ, &hrootkey)
      == ERROR_SUCCESS)
303
    {
304 305
      if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData)
	  == ERROR_SUCCESS)
306
	{
307
	  result = xmalloc (cbData);
308

309 310 311 312
	  if ((RegQueryValueEx (hrootkey, key, NULL, type, (LPBYTE) result,
				&cbData)
	       != ERROR_SUCCESS)
	      || *result == 0)
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
	    {
	      free (result);
	      result = NULL;
	    }
	}

      RegCloseKey (hrootkey);
    }

  return result;
}

/*
  getenv wrapper for Windows

328 329 330 331 332
  Value is allocated on the heap, and can be free'd.

  This is needed to duplicate Emacs's behavior, which is to look for
  environment variables in the registry if they don't appear in the
  environment.  */
333
char *
334
w32_getenv (const char *envvar)
335 336 337 338
{
  char *value;
  DWORD dwType;

339
  if ((value = getenv (envvar)))
340 341 342
    /* Found in the environment.  strdup it, because values returned
       by getenv cannot be free'd.  */
    return xstrdup (value);
343 344 345

  if (! (value = w32_get_resource (HKEY_CURRENT_USER, envvar, &dwType)) &&
      ! (value = w32_get_resource (HKEY_LOCAL_MACHINE, envvar, &dwType)))
346 347 348
    {
      /* "w32console" is what Emacs on Windows uses for tty-type under -nw.  */
      if (strcmp (envvar, "TERM") == 0)
349
	return xstrdup ("w32console");
350 351 352
      /* Found neither in the environment nor in the registry.  */
      return NULL;
    }
353 354 355 356 357 358 359 360 361

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

  if (dwType == REG_EXPAND_SZ)
    {
      DWORD size;

362
      if ((size = ExpandEnvironmentStrings (value, NULL, 0)))
363
	{
364
	  char *buffer = xmalloc (size);
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
	  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;
}

382
int w32_window_app (void);
383

Juanma Barranquero's avatar
Juanma Barranquero committed
384
int
385
w32_window_app (void)
Juanma Barranquero's avatar
Juanma Barranquero committed
386 387 388 389 390
{
  static int window_app = -1;
  char szTitle[MAX_PATH];

  if (window_app < 0)
391 392 393 394 395
    {
      /* 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)
396
        InitCommonControls ();
397
    }
Juanma Barranquero's avatar
Juanma Barranquero committed
398 399 400

  return window_app;
}
Dan Nicolaescu's avatar
Dan Nicolaescu committed
401

402
/* execvp wrapper for Windows.  Quotes arguments with embedded spaces.
Dan Nicolaescu's avatar
Dan Nicolaescu committed
403 404 405 406

  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
407
  predictably bad results.  By contrast, POSIX execvp passes the arguments
408 409
  directly into the argv array of the child process.  */

410 411
int w32_execvp (const char *, char **);

Dan Nicolaescu's avatar
Dan Nicolaescu committed
412
int
413
w32_execvp (const char *path, char **argv)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
{
  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);
}

431 432
# undef execvp
# define execvp w32_execvp
Dan Nicolaescu's avatar
Dan Nicolaescu committed
433

434
/* Emulation of ttyname for Windows.  */
435 436
const char *ttyname (int);
const char *
437 438 439 440 441
ttyname (int fd)
{
  return "CONOUT$";
}

Dan Nicolaescu's avatar
Dan Nicolaescu committed
442
#endif /* WINDOWSNT */
Juanma Barranquero's avatar
Juanma Barranquero committed
443

Juanma Barranquero's avatar
Juanma Barranquero committed
444 445
/* Display a normal or error message.
   On Windows, use a message box if compiled as a Windows app.  */
446
static void message (bool, const char *, ...) ATTRIBUTE_FORMAT_PRINTF (2, 3);
447
static void
448
message (bool is_error, const char *format, ...)
Juanma Barranquero's avatar
Juanma Barranquero committed
449 450 451
{
  va_list args;

452
  va_start (args, format);
Juanma Barranquero's avatar
Juanma Barranquero committed
453 454 455 456

#ifdef WINDOWSNT
  if (w32_window_app ())
    {
457 458 459 460
      char msg[2048];
      vsnprintf (msg, sizeof msg, format, args);
      msg[sizeof msg - 1] = '\0';

Juanma Barranquero's avatar
Juanma Barranquero committed
461 462 463 464 465 466 467
      if (is_error)
	MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
      else
	MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
    }
  else
#endif
468 469 470
    {
      FILE *f = is_error ? stderr : stdout;

471
      vfprintf (f, format, args);
472 473
      fflush (f);
    }
474 475

  va_end (args);
Juanma Barranquero's avatar
Juanma Barranquero committed
476 477
}

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

481
static void
482
decode_options (int argc, char **argv)
483
{
484
  alternate_editor = egetenv ("ALTERNATE_EDITOR");
485
  tramp_prefix = egetenv ("EMACSCLIENT_TRAMP");
486

487
  while (true)
488
    {
489
      int opt = getopt_long_only (argc, argv,
490
#ifndef NO_SOCKETS_IN_FILE_SYSTEM
491
			     "VHnequa:s:f:d:F:tcT:",
492
#else
493
			     "VHnequa:f:d:F:tcT:",
494
#endif
495
			     longopts, 0);
496 497 498 499 500 501 502 503 504 505

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

507 508 509
	case 'a':
	  alternate_editor = optarg;
	  break;
510

511
#ifndef NO_SOCKETS_IN_FILE_SYSTEM
512 513 514
	case 's':
	  socket_name = optarg;
	  break;
515
#endif
516

517 518 519
	case 'f':
	  server_file = optarg;
	  break;
520

521 522 523 524
	  /* 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
525 526 527 528
	case 'd':
	  display = optarg;
	  break;

529
	case 'n':
530
	  nowait = true;
531 532
	  break;

Stefan Monnier's avatar
Stefan Monnier committed
533
	case 'e':
534
	  eval = true;
Stefan Monnier's avatar
Stefan Monnier committed
535 536
	  break;

537
	case 'q':
538
	  quiet = true;
539 540
	  break;

541
	case 'u':
542
	  suppress_output = true;
543 544
	  break;

545
	case 'V':
546
	  message (false, "emacsclient %s\n", VERSION);
547
	  exit (EXIT_SUCCESS);
548
	  break;
Richard M. Stallman's avatar
Richard M. Stallman committed
549

550
        case 't':
551 552
	  tty = true;
	  create_frame = true;
553 554
          break;

555
        case 'c':
556
	  create_frame = true;
557
          break;
558

559 560
	case 'p':
	  parent_id = optarg;
561
	  create_frame = true;
562 563
	  break;

564 565
	case 'H':
	  print_help_and_exit ();
566 567
	  break;

568 569 570 571
        case 'F':
          frame_parameters = optarg;
          break;

572 573 574 575
        case 'T':
          tramp_prefix = optarg;
          break;

576
	default:
577
	  message (true, "Try '%s --help' for more information\n", progname);
578
	  exit (EXIT_FAILURE);
579
	  break;
580 581
	}
    }
582

583 584 585 586 587
  /* 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
588 589 590 591 592 593
     they want Emacs to connect to their current display.

     Some window systems have a notion of default display not
     reflected in the DISPLAY variable.  If the user didn't give us an
     explicit display, try this platform-specific after trying the
     display in DISPLAY (if any).  */
594
  if (create_frame && !tty && !display)
595
    {
596 597 598 599 600
      /* Set these here so we use a default_display only when the user
         didn't give us an explicit display.  */
#if defined (NS_IMPL_COCOA)
      alt_display = "ns";
#elif defined (HAVE_NTGUI)
601
      alt_display = "w32";
602
#endif
603 604 605 606 607 608 609 610

      display = egetenv ("DISPLAY");
    }

  if (!display)
    {
      display = alt_display;
      alt_display = NULL;
611
    }
612

613
  /* A null-string display is invalid.  */
614
  if (display && !display[0])
615 616
    display = NULL;

617
  /* If no display is available, new frames are tty frames.  */
618 619
  if (create_frame && !display)
    tty = true;
620

621
#ifdef WINDOWSNT
622 623 624
  /* Emacs on Windows does not support graphical and text terminal
     frames in the same instance.  So, treat the -t and -c options as
     equivalent, and open a new frame on the server's terminal.
625
     Ideally, we would set tty = true only if the server is running in a
626 627
     console, but alas we don't know that.  As a workaround, always
     ask for a tty frame, and let server.el figure it out.  */
628
  if (create_frame)
629 630
    {
      display = NULL;
631
      tty = true;
632
    }
633
#endif /* WINDOWSNT */
634 635
}

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

684
/* Try to run a different command, or --if no alternate editor is
685
   defined-- exit with an error code.
686 687
   Uses argv, but gets it from the global variable main_argv.  */

688
static _Noreturn void
689
fail (void)
Karoly Lorentey's avatar
Karoly Lorentey committed
690
{
691
  if (alternate_editor)
Karoly Lorentey's avatar
Karoly Lorentey committed
692
    {
693 694
      size_t extra_args_size = (main_argc - optind + 1) * sizeof (char *);
      size_t new_argv_size = extra_args_size;
695
      char **new_argv = xmalloc (new_argv_size);
696
      char *s = xstrdup (alternate_editor);
697
      ptrdiff_t toks = 0;
698 699 700 701 702 703

      /* Unpack alternate_editor's space-separated tokens into new_argv.  */
      for (char *tok = s; tok != NULL && *tok != '\0';)
        {
          /* Allocate new token.  */
          ++toks;
704 705
          new_argv = xrealloc (new_argv,
			       new_argv_size + toks * sizeof (char *));
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723

          /* Skip leading delimiters, and set separator, skipping any
             opening quote.  */
          size_t skip = strspn (tok, " \"");
          tok += skip;
          char sep = (skip > 0 && tok[-1] == '"') ? '"' : ' ';

          /* Record start of token.  */
          new_argv[toks - 1] = tok;

          /* Find end of token and overwrite it with NUL.  */
          tok = strchr (tok, sep);
          if (tok != NULL)
            *tok++ = '\0';
        }

      /* Append main_argv arguments to new_argv.  */
      memcpy (&new_argv[toks], main_argv + optind, extra_args_size);
724

725
      execvp (*new_argv, new_argv);
726
      message (true, "%s: error executing alternate editor \"%s\"\n",
727
	       progname, alternate_editor);
Karoly Lorentey's avatar
Karoly Lorentey committed
728
    }
729
  exit (EXIT_FAILURE);
Karoly Lorentey's avatar
Karoly Lorentey committed
730 731
}

732

733
#if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
Karoly Lorentey's avatar
Karoly Lorentey committed
734

735
int
Dan Nicolaescu's avatar
Dan Nicolaescu committed
736
main (int argc, char **argv)
Karoly Lorentey's avatar
Karoly Lorentey committed
737
{
738
  main_argc = argc;
739 740
  main_argv = argv;
  progname = argv[0];
741 742
  message (true, ("%s: Sorry, the Emacs server is supported only\n"
		  "on systems with Berkeley sockets.\n"),
743
	   argv[0]);
744
  fail ();
Karoly Lorentey's avatar
Karoly Lorentey committed
745 746
}

747
#else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
748

749
enum { AUTH_KEY_LENGTH = 64 };
750

Jason Rumney's avatar
Jason Rumney committed
751
/* Socket used to communicate with the Emacs server process.  */
752
static HSOCKET emacs_socket = 0;
753

754 755 756
/* On Windows, the socket library was historically separate from the
   standard C library, so errors are handled differently.  */

757
static void
758
sock_err_message (const char *function_name)
759
{
760
# ifdef WINDOWSNT
761 762 763 764 765 766 767
  char* msg = NULL;

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

768
  message (true, "%s: %s: %s\n", progname, function_name, msg);
769 770

  LocalFree (msg);
771
# else
772
  message (true, "%s: %s: %s\n", progname, function_name, strerror (errno));
773
# endif
774 775 776
}


777 778
/* Send to S the data in *DATA when either
   - the data's last byte is '\n', or
779
   - the buffer is full (but this shouldn't happen)
780
   Otherwise, just accumulate the data.  */
781
static void
782
send_to_emacs (HSOCKET s, const char *data)
783
{
784 785 786 787 788 789 790 791
  enum { SEND_BUFFER_SIZE = 4096 };

  /* Buffer to accumulate data to send in TCP connections.  */
  static char send_buffer[SEND_BUFFER_SIZE + 1];

  /* Fill pointer for the send buffer.  */
  static int sblen;

Paul Eggert's avatar
Paul Eggert committed
792
  for (ptrdiff_t dlen = strlen (data); dlen != 0; )
793
    {
Paul Eggert's avatar
Paul Eggert committed
794
      int part = min (dlen, SEND_BUFFER_SIZE - sblen);
795 796 797
      memcpy (&send_buffer[sblen], data, part);
      data += part;
      sblen += part;
798 799

      if (sblen == SEND_BUFFER_SIZE
Paul Eggert's avatar
Paul Eggert committed
800
	  || (0 < sblen && send_buffer[sblen - 1] == '\n'))
801 802
	{
	  int sent = send (s, send_buffer, sblen, 0);
803 804
	  if (sent < 0)
	    {
805
	      message (true, "%s: failed to send %d bytes to socket: %s\n",
806 807 808
		       progname, sblen, strerror (errno));
	      fail ();
	    }
809
	  if (sent != sblen)
810
	    memmove (send_buffer, &send_buffer[sent], sblen - sent);
811 812
	  sblen -= sent;
	}
813 814

      dlen -= part;
815 816 817 818
    }
}

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

Juanma Barranquero's avatar
Juanma Barranquero committed
823
   Does not change the string.  Outputs the result to S.  */
824
static void
825
quote_argument (HSOCKET s, const char *str)
826
{
827
  char *copy = xmalloc (strlen (str) * 2 + 1);
828 829 830 831
  char *q = copy;
  if (*str == '-')
    *q++ = '&', *q++ = *str++;
  for (; *str; str++)
832
    {
833 834 835 836 837 838 839 840
      char c = *str;
      if (c == ' ')
	*q++ = '&', c = '_';
      else if (c == '\n')
	*q++ = '&', c = 'n';
      else if (c == '&')
	*q++ = '&';
      *q++ = c;
841
    }
842
  *q = 0;
843

Jason Rumney's avatar
Jason Rumney committed
844
  send_to_emacs (s, copy);
845 846

  free (copy);
847
}
848

849

850 851
/* The inverse of quote_argument.  Remove quoting in string STR by
   modifying the addressed string in place.  Return STR.  */
852

853
static char *
854
unquote_argument (char *str)
855
{
856 857 858
  char const *p = str;
  char *q = str;
  char c;
859

860
  do
861
    {
862 863 864 865 866 867 868 869 870 871
      c = *p++;
      if (c == '&')
	{
	  c = *p++;
	  if (c == '_')
	    c = ' ';
	  else if (c == 'n')
	    c = '\n';
	}
      *q++ = c;
872
    }
873 874
  while (c);

875 876 877
  return str;
}

878

879
# ifdef WINDOWSNT
880
/* Wrapper to make WSACleanup a cdecl, as required by atexit.  */
881
void __cdecl close_winsock (void);
882 883
void __cdecl
close_winsock (void)
884 885 886
{
  WSACleanup ();
}
887

888
/* Initialize the WinSock2 library.  */
Eli Zaretskii's avatar