emacs-buildstatus means reports of build failures are unlikely to be needed.
[bpt/emacs.git] / lib-src / emacsclient.c
CommitLineData
efb859b4 1/* Client process that communicates with GNU Emacs acting as server.
73b0cd50 2 Copyright (C) 1986-1987, 1994, 1999-2011 Free Software Foundation, Inc.
46cec291
RS
3
4This file is part of GNU Emacs.
5
294981c7 6GNU Emacs is free software: you can redistribute it and/or modify
46cec291 7it under the terms of the GNU General Public License as published by
294981c7
GM
8the Free Software Foundation, either version 3 of the License, or
9(at your option) any later version.
46cec291
RS
10
11GNU Emacs is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License
294981c7 17along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
46cec291
RS
18
19
2f8fe2f4 20#include <config.h>
e69233c2 21
aa0b6932 22#ifdef WINDOWSNT
aa0b6932 23
bc28de71
JB
24/* config.h defines these, which disables sockets altogether! */
25# undef _WINSOCKAPI_
26# undef _WINSOCK_H
27
411b80a5
JB
28# include <malloc.h>
29# include <stdlib.h>
42073bfb 30# include <windows.h>
dbf60b07 31# include <commctrl.h>
0613f5d5
DN
32# include <io.h>
33# include <winsock2.h>
411b80a5 34
411b80a5
JB
35# define NO_SOCKETS_IN_FILE_SYSTEM
36
aa0b6932
JB
37# define HSOCKET SOCKET
38# define CLOSE_SOCKET closesocket
aa0b6932 39# define INITIALIZE() (initialize_sockets ())
411b80a5 40
728a982d
DN
41char *w32_getenv (char *);
42#define egetenv(VAR) w32_getenv(VAR)
43
411b80a5
JB
44#else /* !WINDOWSNT */
45
67c1df01 46# include "syswait.h"
ed4a3730 47
1e7823d0
JB
48# ifdef HAVE_INET_SOCKETS
49# include <netinet/in.h>
0613f5d5
DN
50# ifdef HAVE_SOCKETS
51# include <sys/types.h>
52# include <sys/socket.h>
53# include <sys/un.h>
54# endif /* HAVE_SOCKETS */
1e7823d0 55# endif
18d2ad29 56# include <arpa/inet.h>
448d4085 57
e35fc962 58# define INVALID_SOCKET -1
aa0b6932
JB
59# define HSOCKET int
60# define CLOSE_SOCKET close
aa0b6932 61# define INITIALIZE()
411b80a5 62
5445ab06
DN
63# ifndef WCONTINUED
64# define WCONTINUED 8
65# endif
66
728a982d
DN
67#define egetenv(VAR) getenv(VAR)
68
411b80a5 69#endif /* !WINDOWSNT */
aa0b6932 70
4e23f2ba 71#undef signal
46cec291 72
42073bfb 73#include <stdarg.h>
e69233c2 74#include <ctype.h>
8f9aaa0a 75#include <stdio.h>
613f7bda 76#include <getopt.h>
4004364e 77#include <unistd.h>
8f9aaa0a 78
0613f5d5 79#include <pwd.h>
dc4a4a14 80#include <sys/stat.h>
9628b887 81#include <signal.h>
4d553a13 82#include <errno.h>
9628b887 83
0613f5d5 84
9628b887 85\f
873fbd0b 86char *getenv (const char *), *getwd (char *);
35a7804d
JB
87#ifdef HAVE_GETCWD
88char *(getcwd) (char *, size_t);
89#endif
8f9aaa0a 90
8f9aaa0a
RS
91#ifndef VERSION
92#define VERSION "unspecified"
93#endif
94\f
aa0b6932
JB
95
96#ifndef EXIT_SUCCESS
97#define EXIT_SUCCESS 0
98#endif
99
100#ifndef EXIT_FAILURE
101#define EXIT_FAILURE 1
102#endif
103
104#ifndef FALSE
105#define FALSE 0
106#endif
107
108#ifndef TRUE
109#define TRUE 1
110#endif
111
bc558f3e
JB
112/* Additional space when allocating buffers for filenames, etc. */
113#define EXTRA_SPACE 100
114
4be3dfc5
PE
115/* Use this to suppress gcc's `...may be used before initialized' warnings. */
116#ifdef lint
117# define IF_LINT(Code) Code
118#else
119# define IF_LINT(Code) /* empty */
120#endif
121
aa0b6932 122\f
8f9aaa0a 123/* Name used to invoke this program. */
728a982d 124const char *progname;
8f9aaa0a 125
0a125897
KL
126/* The second argument to main. */
127char **main_argv;
128
749ae770 129/* Nonzero means don't wait for a response from Emacs. --no-wait. */
8f9aaa0a
RS
130int nowait = 0;
131
0b973fc5
DW
132/* Nonzero means don't print messages for successful operations. --quiet. */
133int quiet = 0;
134
30be2360
SM
135/* Nonzero means args are expressions to be evaluated. --eval. */
136int eval = 0;
137
31fa6595
SM
138/* Nonzero means don't open a new frame. Inverse of --create-frame. */
139int current_frame = 1;
92071250 140
30be2360 141/* The display on which Emacs should work. --display. */
988e88ab 142const char *display = NULL;
30be2360 143
0191e222
CY
144/* The parent window ID, if we are opening a frame via XEmbed. */
145char *parent_id = NULL;
146
9628b887 147/* Nonzero means open a new Emacs frame on the current terminal. */
77134727 148int tty = 0;
9628b887 149
30be2360
SM
150/* If non-NULL, the name of an editor to fallback to if the server
151 is not running. --alternate-editor. */
b03d27bd 152const char *alternate_editor = NULL;
30be2360 153
3db926be 154/* If non-NULL, the filename of the UNIX socket. */
254107e4
RS
155char *socket_name = NULL;
156
aa0b6932 157/* If non-NULL, the filename of the authentication file. */
988e88ab 158const char *server_file = NULL;
aa0b6932 159
c66648e0
JB
160/* PID of the Emacs server process. */
161int emacs_pid = 0;
162
b23b5a5b
PE
163static void print_help_and_exit (void) NO_RETURN;
164static void fail (void) NO_RETURN;
68441b90 165
7f3bff3e 166
8f9aaa0a
RS
167struct option longopts[] =
168{
749ae770 169 { "no-wait", no_argument, NULL, 'n' },
0b973fc5 170 { "quiet", no_argument, NULL, 'q' },
30be2360 171 { "eval", no_argument, NULL, 'e' },
8f9aaa0a
RS
172 { "help", no_argument, NULL, 'H' },
173 { "version", no_argument, NULL, 'V' },
b28c910d 174 { "tty", no_argument, NULL, 't' },
dc1cd5f7 175 { "nw", no_argument, NULL, 't' },
31fa6595 176 { "create-frame", no_argument, NULL, 'c' },
3cf8c6aa 177 { "alternate-editor", required_argument, NULL, 'a' },
b03d27bd 178#ifndef NO_SOCKETS_IN_FILE_SYSTEM
254107e4 179 { "socket-name", required_argument, NULL, 's' },
b03d27bd 180#endif
aa0b6932 181 { "server-file", required_argument, NULL, 'f' },
0ebec7d3 182#ifndef WINDOWSNT
30be2360 183 { "display", required_argument, NULL, 'd' },
0ebec7d3 184#endif
0191e222 185 { "parent-id", required_argument, NULL, 'p' },
30be2360 186 { 0, 0, 0, 0 }
8f9aaa0a
RS
187};
188
974b73e8
KL
189\f
190/* Like malloc but get fatal error if memory is exhausted. */
191
b23b5a5b 192static long *
873fbd0b 193xmalloc (unsigned int size)
974b73e8
KL
194{
195 long *result = (long *) malloc (size);
196 if (result == NULL)
197 {
198 perror ("malloc");
199 exit (EXIT_FAILURE);
200 }
201 return result;
202}
203
974b73e8
KL
204/* From sysdep.c */
205#if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
206
cb06b8dc
SM
207/* From lisp.h */
208#ifndef DIRECTORY_SEP
209#define DIRECTORY_SEP '/'
210#endif
211#ifndef IS_DIRECTORY_SEP
212#define IS_DIRECTORY_SEP(_c_) ((_c_) == DIRECTORY_SEP)
213#endif
214#ifndef IS_DEVICE_SEP
215#ifndef DEVICE_SEP
216#define IS_DEVICE_SEP(_c_) 0
217#else
218#define IS_DEVICE_SEP(_c_) ((_c_) == DEVICE_SEP)
219#endif
220#endif
cb06b8dc 221
c5443aa5 222char *get_current_dir_name (void);
cb06b8dc 223
974b73e8 224/* Return the current working directory. Returns NULL on errors.
5ab73228 225 Any other returned value must be freed with free. This is used
974b73e8
KL
226 only when get_current_dir_name is not defined on the system. */
227char*
7c3320d8 228get_current_dir_name (void)
974b73e8
KL
229{
230 char *buf;
b9170155 231 const char *pwd;
974b73e8
KL
232 struct stat dotstat, pwdstat;
233 /* If PWD is accurate, use it instead of calling getwd. PWD is
234 sometimes a nicer name, and using it may avoid a fatal error if a
235 parent directory is searchable but not readable. */
7ce8671d 236 if ((pwd = egetenv ("PWD")) != 0
974b73e8
KL
237 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
238 && stat (pwd, &pwdstat) == 0
239 && stat (".", &dotstat) == 0
240 && dotstat.st_ino == pwdstat.st_ino
241 && dotstat.st_dev == pwdstat.st_dev
242#ifdef MAXPATHLEN
243 && strlen (pwd) < MAXPATHLEN
244#endif
245 )
246 {
247 buf = (char *) xmalloc (strlen (pwd) + 1);
248 if (!buf)
249 return NULL;
250 strcpy (buf, pwd);
251 }
252#ifdef HAVE_GETCWD
253 else
254 {
255 size_t buf_size = 1024;
256 buf = (char *) xmalloc (buf_size);
257 if (!buf)
258 return NULL;
259 for (;;)
260 {
261 if (getcwd (buf, buf_size) == buf)
262 break;
263 if (errno != ERANGE)
264 {
265 int tmp_errno = errno;
266 free (buf);
267 errno = tmp_errno;
268 return NULL;
269 }
270 buf_size *= 2;
271 buf = (char *) realloc (buf, buf_size);
272 if (!buf)
273 return NULL;
274 }
275 }
276#else
277 else
278 {
279 /* We need MAXPATHLEN here. */
280 buf = (char *) xmalloc (MAXPATHLEN + 1);
281 if (!buf)
282 return NULL;
283 if (getwd (buf) == NULL)
284 {
285 int tmp_errno = errno;
286 free (buf);
287 errno = tmp_errno;
288 return NULL;
289 }
290 }
291#endif
292 return buf;
293}
294#endif
295
42073bfb 296#ifdef WINDOWSNT
7ce8671d 297
a54af40e
EZ
298/* Like strdup but get a fatal error if memory is exhausted. */
299
300char *
301xstrdup (const char *s)
302{
303 char *result = strdup (s);
304 if (result == NULL)
305 {
306 perror ("strdup");
307 exit (EXIT_FAILURE);
308 }
309 return result;
310}
311
7ce8671d
JB
312#define REG_ROOT "SOFTWARE\\GNU\\Emacs"
313
314/* Retrieve an environment variable from the Emacs subkeys of the registry.
315 Return NULL if the variable was not found, or it was empty.
316 This code is based on w32_get_resource (w32.c). */
317char *
7c3320d8 318w32_get_resource (HKEY predefined, char *key, LPDWORD type)
7ce8671d
JB
319{
320 HKEY hrootkey = NULL;
321 char *result = NULL;
322 DWORD cbData;
323
324 if (RegOpenKeyEx (predefined, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
325 {
326 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS)
327 {
328 result = (char *) xmalloc (cbData);
329
bc558f3e
JB
330 if ((RegQueryValueEx (hrootkey, key, NULL, type, result, &cbData) != ERROR_SUCCESS)
331 || (*result == 0))
7ce8671d
JB
332 {
333 free (result);
334 result = NULL;
335 }
336 }
337
338 RegCloseKey (hrootkey);
339 }
340
341 return result;
342}
343
344/*
345 getenv wrapper for Windows
346
a54af40e
EZ
347 Value is allocated on the heap, and can be free'd.
348
349 This is needed to duplicate Emacs's behavior, which is to look for
350 environment variables in the registry if they don't appear in the
351 environment. */
7ce8671d 352char *
7c3320d8 353w32_getenv (char *envvar)
7ce8671d
JB
354{
355 char *value;
356 DWORD dwType;
357
358 if (value = getenv (envvar))
a54af40e
EZ
359 /* Found in the environment. strdup it, because values returned
360 by getenv cannot be free'd. */
361 return xstrdup (value);
7ce8671d
JB
362
363 if (! (value = w32_get_resource (HKEY_CURRENT_USER, envvar, &dwType)) &&
364 ! (value = w32_get_resource (HKEY_LOCAL_MACHINE, envvar, &dwType)))
d41784ee
EZ
365 {
366 /* "w32console" is what Emacs on Windows uses for tty-type under -nw. */
367 if (strcmp (envvar, "TERM") == 0)
a54af40e 368 return xstrdup ("w32console");
d41784ee
EZ
369 /* Found neither in the environment nor in the registry. */
370 return NULL;
371 }
7ce8671d
JB
372
373 if (dwType == REG_SZ)
374 /* Registry; no need to expand. */
375 return value;
376
377 if (dwType == REG_EXPAND_SZ)
378 {
379 DWORD size;
380
381 if (size = ExpandEnvironmentStrings (value, NULL, 0))
382 {
383 char *buffer = (char *) xmalloc (size);
384 if (ExpandEnvironmentStrings (value, buffer, size))
385 {
386 /* Found and expanded. */
387 free (value);
388 return buffer;
389 }
390
391 /* Error expanding. */
392 free (buffer);
393 }
394 }
395
396 /* Not the right type, or not correctly expanded. */
397 free (value);
398 return NULL;
399}
400
ff90fbde 401void
7c3320d8 402w32_set_user_model_id (void)
ff90fbde
JR
403{
404 HMODULE shell;
0a3472c7 405 HRESULT (WINAPI * set_user_model) (wchar_t * id);
ff90fbde
JR
406
407 /* On Windows 7 and later, we need to set the user model ID
408 to associate emacsclient launched files with Emacs frames
409 in the UI. */
361358ea 410 shell = LoadLibrary ("shell32.dll");
ff90fbde
JR
411 if (shell)
412 {
413 set_user_model
414 = (void *) GetProcAddress (shell,
415 "SetCurrentProcessExplicitAppUserModelID");
416 /* If the function is defined, then we are running on Windows 7
417 or newer, and the UI uses this to group related windows
418 together. Since emacs, runemacs, emacsclient are related, we
419 want them grouped even though the executables are different,
420 so we need to set a consistent ID between them. */
421 if (set_user_model)
422 set_user_model (L"GNU.Emacs");
423
424 FreeLibrary (shell);
425 }
426}
427
42073bfb 428int
7c3320d8 429w32_window_app (void)
42073bfb
JB
430{
431 static int window_app = -1;
432 char szTitle[MAX_PATH];
433
434 if (window_app < 0)
dbf60b07
JR
435 {
436 /* Checking for STDOUT does not work; it's a valid handle also in
437 nonconsole apps. Testing for the console title seems to work. */
438 window_app = (GetConsoleTitleA (szTitle, MAX_PATH) == 0);
439 if (window_app)
361358ea 440 InitCommonControls ();
dbf60b07 441 }
42073bfb
JB
442
443 return window_app;
444}
105faa84
DN
445
446/*
cb06b8dc 447 execvp wrapper for Windows. Quotes arguments with embedded spaces.
105faa84
DN
448
449 This is necessary due to the broken implementation of exec* routines in
450 the Microsoft libraries: they concatenate the arguments together without
451 quoting special characters, and pass the result to CreateProcess, with
7c3320d8 452 predictably bad results. By contrast, POSIX execvp passes the arguments
105faa84
DN
453 directly into the argv array of the child process.
454*/
455int
7c3320d8 456w32_execvp (const char *path, char **argv)
105faa84
DN
457{
458 int i;
459
460 /* Required to allow a .BAT script as alternate editor. */
461 argv[0] = (char *) alternate_editor;
462
463 for (i = 0; argv[i]; i++)
464 if (strchr (argv[i], ' '))
465 {
466 char *quoted = alloca (strlen (argv[i]) + 3);
467 sprintf (quoted, "\"%s\"", argv[i]);
468 argv[i] = quoted;
469 }
470
471 return execvp (path, argv);
472}
473
474#undef execvp
475#define execvp w32_execvp
476
d41784ee
EZ
477/* Emulation of ttyname for Windows. */
478char *
479ttyname (int fd)
480{
481 return "CONOUT$";
482}
483
105faa84 484#endif /* WINDOWSNT */
42073bfb 485
f387c1ee
JB
486/* Display a normal or error message.
487 On Windows, use a message box if compiled as a Windows app. */
72b04a8a 488static void message (int, const char *, ...) ATTRIBUTE_FORMAT_PRINTF (2, 3);
b23b5a5b 489static void
b0bbc07d 490message (int is_error, const char *format, ...)
42073bfb 491{
361358ea 492 char msg[2048];
42073bfb
JB
493 va_list args;
494
b0bbc07d
PE
495 va_start (args, format);
496 vsprintf (msg, format, args);
42073bfb
JB
497 va_end (args);
498
499#ifdef WINDOWSNT
500 if (w32_window_app ())
501 {
502 if (is_error)
503 MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
504 else
505 MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
506 }
507 else
508#endif
9219db75
JB
509 {
510 FILE *f = is_error ? stderr : stdout;
511
512 fputs (msg, f);
513 fflush (f);
514 }
42073bfb
JB
515}
516
8f9aaa0a 517/* Decode the options from argv and argc.
5212210c 518 The global variable `optind' will say how many arguments we used up. */
8f9aaa0a 519
b23b5a5b 520static void
873fbd0b 521decode_options (int argc, char **argv)
8f9aaa0a 522{
7ce8671d 523 alternate_editor = egetenv ("ALTERNATE_EDITOR");
0ea5797a 524
8f9aaa0a
RS
525 while (1)
526 {
dc1cd5f7 527 int opt = getopt_long_only (argc, argv,
b03d27bd 528#ifndef NO_SOCKETS_IN_FILE_SYSTEM
0b973fc5 529 "VHneqa:s:f:d:tc",
b03d27bd 530#else
0b973fc5 531 "VHneqa:f:d:tc",
b03d27bd 532#endif
974b73e8 533 longopts, 0);
8f9aaa0a
RS
534
535 if (opt == EOF)
536 break;
537
538 switch (opt)
539 {
540 case 0:
541 /* If getopt returns 0, then it has already processed a
542 long-named option. We should do nothing. */
543 break;
e69233c2 544
97e3214d
GM
545 case 'a':
546 alternate_editor = optarg;
547 break;
e69233c2 548
b03d27bd 549#ifndef NO_SOCKETS_IN_FILE_SYSTEM
254107e4
RS
550 case 's':
551 socket_name = optarg;
552 break;
b03d27bd 553#endif
254107e4 554
aa0b6932
JB
555 case 'f':
556 server_file = optarg;
557 break;
254107e4 558
0ea5797a
SM
559 /* We used to disallow this argument in w32, but it seems better
560 to allow it, for the occasional case where the user is
561 connecting with a w32 client to a server compiled with X11
562 support. */
30be2360
SM
563 case 'd':
564 display = optarg;
565 break;
566
8f9aaa0a
RS
567 case 'n':
568 nowait = 1;
569 break;
570
30be2360
SM
571 case 'e':
572 eval = 1;
573 break;
574
0b973fc5
DW
575 case 'q':
576 quiet = 1;
577 break;
578
8f9aaa0a 579 case 'V':
42073bfb 580 message (FALSE, "emacsclient %s\n", VERSION);
65396510 581 exit (EXIT_SUCCESS);
8f9aaa0a 582 break;
46cec291 583
819b8f00 584 case 't':
77134727 585 tty = 1;
c1b8e896 586 current_frame = 0;
77134727
KL
587 break;
588
e5299d8d 589 case 'c':
31fa6595 590 current_frame = 0;
9628b887 591 break;
0b0d3e0b 592
0191e222
CY
593 case 'p':
594 parent_id = optarg;
595 current_frame = 0;
596 break;
597
8f9aaa0a 598 case 'H':
8f9aaa0a 599 print_help_and_exit ();
20c396e8
JB
600 break;
601
602 default:
42073bfb 603 message (TRUE, "Try `%s --help' for more information\n", progname);
65396510 604 exit (EXIT_FAILURE);
20c396e8 605 break;
8f9aaa0a
RS
606 }
607 }
9628b887 608
273b9028
CY
609 /* If the -c option is used (without -t) and no --display argument
610 is provided, try $DISPLAY.
611 Without the -c option, we used to set `display' to $DISPLAY by
612 default, but this changed the default behavior and is sometimes
613 inconvenient. So we force users to use "--display $DISPLAY" if
614 they want Emacs to connect to their current display. */
09317bf4 615 if (!current_frame && !tty && !display)
e7534fc4
AR
616 {
617 display = egetenv ("DISPLAY");
618#ifdef NS_IMPL_COCOA
619 /* Under Cocoa, we don't really use displays the same way as in X,
620 so provide a dummy. */
621 if (!display || strlen (display) == 0)
622 display = "ns";
623#endif
624 }
9997dc15 625
273b9028 626 /* A null-string display is invalid. */
0ea5797a
SM
627 if (display && strlen (display) == 0)
628 display = NULL;
629
273b9028
CY
630 /* If no display is available, new frames are tty frames. */
631 if (!current_frame && !display)
92071250 632 tty = 1;
c0f342ab 633
b8ccaf6f 634 /* --no-wait implies --current-frame on ttys when there are file
273b9028 635 arguments or expressions given. */
b8ccaf6f 636 if (nowait && tty && argc - optind > 0)
92071250 637 current_frame = 1;
802bdb3c
DN
638
639#ifdef WINDOWSNT
69157c99 640 if (alternate_editor && alternate_editor[0] == '\0')
802bdb3c
DN
641 {
642 message (TRUE, "--alternate-editor argument or ALTERNATE_EDITOR variable cannot be\n\
643an empty string");
644 exit (EXIT_FAILURE);
645 }
646#endif /* WINDOWSNT */
8f9aaa0a
RS
647}
648
974b73e8 649\f
b23b5a5b 650static void
873fbd0b 651print_help_and_exit (void)
8f9aaa0a 652{
c0f342ab
JB
653 /* Spaces and tabs are significant in this message; they're chosen so the
654 message aligns properly both in a tty and in a Windows message box.
655 Please try to preserve them; otherwise the output is very hard to read
656 when using emacsclientw. */
42073bfb 657 message (FALSE,
974b73e8 658 "Usage: %s [OPTIONS] FILE...\n\
30be2360
SM
659Tell the Emacs server to visit the specified files.\n\
660Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
20c396e8 661\n\
30be2360 662The following OPTIONS are accepted:\n\
c0f342ab
JB
663-V, --version Just print version info and return\n\
664-H, --help Print this usage information message\n\
dc1cd5f7 665-nw, -t, --tty Open a new Emacs frame on the current terminal\n\
c4b858e3 666-c, --create-frame Create a new frame instead of trying to\n\
9dfda22f 667 use the current Emacs frame\n\
c0f342ab 668-e, --eval Evaluate the FILE arguments as ELisp expressions\n\
d07529f3 669-n, --no-wait Don't wait for the server to return\n\
0b973fc5 670-q, --quiet Don't display messages on success\n\
24d5010d 671-d DISPLAY, --display=DISPLAY\n\
0191e222
CY
672 Visit the file in the given display\n\
673--parent-id=ID Open in parent window ID, via XEmbed\n"
aa0b6932 674#ifndef NO_SOCKETS_IN_FILE_SYSTEM
24d5010d 675"-s SOCKET, --socket-name=SOCKET\n\
9dfda22f 676 Set filename of the UNIX socket for communication\n"
aa0b6932 677#endif
24d5010d 678"-f SERVER, --server-file=SERVER\n\
9dfda22f 679 Set filename of the TCP authentication file\n\
24d5010d 680-a EDITOR, --alternate-editor=EDITOR\n\
9dfda22f 681 Editor to fallback to if the server is not running\n"
6133a1a9 682#ifndef WINDOWSNT
c3f995a2
JB
683" If EDITOR is the empty string, start Emacs in daemon\n\
684 mode and try connecting again\n"
6133a1a9 685#endif /* not WINDOWSNT */
c3f995a2 686"\n\
5f54cae6 687Report bugs with M-x report-emacs-bug.\n", progname);
65396510 688 exit (EXIT_SUCCESS);
8f9aaa0a 689}
5212210c 690
aa0b6932
JB
691/*
692 Try to run a different command, or --if no alternate editor is
693 defined-- exit with an errorcode.
cb06b8dc 694 Uses argv, but gets it from the global variable main_argv.
aa0b6932 695*/
b23b5a5b 696static void
974b73e8 697fail (void)
9002956f 698{
aa0b6932 699 if (alternate_editor)
9002956f 700 {
aa0b6932 701 int i = optind - 1;
4472aef4 702
974b73e8 703 execvp (alternate_editor, main_argv + i);
42073bfb 704 message (TRUE, "%s: error executing alternate editor \"%s\"\n",
974b73e8 705 progname, alternate_editor);
9002956f 706 }
aa0b6932 707 exit (EXIT_FAILURE);
9002956f
KL
708}
709
aa0b6932 710\f
1e7823d0 711#if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
9002956f 712
aa0b6932 713int
0613f5d5 714main (int argc, char **argv)
9002956f 715{
974b73e8
KL
716 main_argv = argv;
717 progname = argv[0];
718 message (TRUE, "%s: Sorry, the Emacs server is supported only\n"
c0f342ab 719 "on systems with Berkeley sockets.\n",
aa0b6932 720 argv[0]);
974b73e8 721 fail ();
9002956f
KL
722}
723
1e7823d0 724#else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
2828d5f9 725
aa0b6932
JB
726#define AUTH_KEY_LENGTH 64
727#define SEND_BUFFER_SIZE 4096
728
873fbd0b 729extern char *strerror (int);
aa0b6932
JB
730
731/* Buffer to accumulate data to send in TCP connections. */
732char send_buffer[SEND_BUFFER_SIZE + 1];
733int sblen = 0; /* Fill pointer for the send buffer. */
4b7b77f6
JR
734/* Socket used to communicate with the Emacs server process. */
735HSOCKET emacs_socket = 0;
aa0b6932 736
d22b00e5
JR
737/* On Windows, the socket library was historically separate from the standard
738 C library, so errors are handled differently. */
b23b5a5b 739static void
988e88ab 740sock_err_message (const char *function_name)
d22b00e5
JR
741{
742#ifdef WINDOWSNT
743 char* msg = NULL;
744
745 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
746 | FORMAT_MESSAGE_ALLOCATE_BUFFER
747 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
748 NULL, WSAGetLastError (), 0, (LPTSTR)&msg, 0, NULL);
749
750 message (TRUE, "%s: %s: %s\n", progname, function_name, msg);
751
752 LocalFree (msg);
753#else
754 message (TRUE, "%s: %s: %s\n", progname, function_name, strerror (errno));
755#endif
756}
757
758
aa0b6932
JB
759/* Let's send the data to Emacs when either
760 - the data ends in "\n", or
761 - the buffer is full (but this shouldn't happen)
762 Otherwise, we just accumulate it. */
b23b5a5b 763static void
988e88ab 764send_to_emacs (HSOCKET s, const char *data)
aa0b6932
JB
765{
766 while (data)
2828d5f9 767 {
728a982d 768 size_t dlen = strlen (data);
aa0b6932
JB
769 if (dlen + sblen >= SEND_BUFFER_SIZE)
770 {
771 int part = SEND_BUFFER_SIZE - sblen;
772 strncpy (&send_buffer[sblen], data, part);
773 data += part;
774 sblen = SEND_BUFFER_SIZE;
775 }
776 else if (dlen)
777 {
778 strcpy (&send_buffer[sblen], data);
779 data = NULL;
780 sblen += dlen;
781 }
782 else
783 break;
784
785 if (sblen == SEND_BUFFER_SIZE
786 || (sblen > 0 && send_buffer[sblen-1] == '\n'))
787 {
788 int sent = send (s, send_buffer, sblen, 0);
789 if (sent != sblen)
790 strcpy (send_buffer, &send_buffer[sent]);
791 sblen -= sent;
792 }
2828d5f9 793 }
2828d5f9 794}
2828d5f9
KL
795
796\f
0b0d3e0b 797/* In STR, insert a & before each &, each space, each newline, and
a4cf2096 798 any initial -. Change spaces to underscores, too, so that the
0b0d3e0b
KL
799 return value never contains a space.
800
3a35a84c 801 Does not change the string. Outputs the result to S. */
b23b5a5b 802static void
988e88ab 803quote_argument (HSOCKET s, const char *str)
5212210c 804{
9002956f 805 char *copy = (char *) xmalloc (strlen (str) * 2 + 1);
988e88ab
J
806 const char *p;
807 char *q;
5212210c 808
0b0d3e0b 809 p = str;
5212210c
RS
810 q = copy;
811 while (*p)
812 {
813 if (*p == ' ')
814 {
f1db6a73 815 *q++ = '&';
5212210c
RS
816 *q++ = '_';
817 p++;
818 }
3cf8c6aa
SM
819 else if (*p == '\n')
820 {
821 *q++ = '&';
822 *q++ = 'n';
823 p++;
824 }
5212210c
RS
825 else
826 {
0b0d3e0b 827 if (*p == '&' || (*p == '-' && p == str))
f1db6a73 828 *q++ = '&';
5212210c
RS
829 *q++ = *p++;
830 }
831 }
f1db6a73 832 *q++ = 0;
5212210c 833
486ba65f 834 send_to_emacs (s, copy);
87209357
EZ
835
836 free (copy);
5212210c 837}
0c76956f 838
0b0d3e0b
KL
839
840/* The inverse of quote_argument. Removes quoting in string STR by
841 modifying the string in place. Returns STR. */
842
b23b5a5b 843static char *
873fbd0b 844unquote_argument (char *str)
0b0d3e0b
KL
845{
846 char *p, *q;
847
848 if (! str)
849 return str;
850
851 p = str;
852 q = str;
853 while (*p)
854 {
855 if (*p == '&')
856 {
857 p++;
858 if (*p == '&')
859 *p = '&';
860 else if (*p == '_')
861 *p = ' ';
862 else if (*p == 'n')
863 *p = '\n';
864 else if (*p == '-')
865 *p = '-';
866 }
867 *q++ = *p++;
868 }
869 *q = 0;
870 return str;
871}
872
8f9aaa0a 873\f
b23b5a5b 874static int
03fc768b 875file_name_absolute_p (const char *filename)
b03d27bd
JB
876{
877 /* Sanity check, it shouldn't happen. */
878 if (! filename) return FALSE;
879
880 /* /xxx is always an absolute path. */
881 if (filename[0] == '/') return TRUE;
882
883 /* Empty filenames (which shouldn't happen) are relative. */
884 if (filename[0] == '\0') return FALSE;
885
886#ifdef WINDOWSNT
71b8f735 887 /* X:\xxx is always absolute. */
03fc768b 888 if (isalpha ((unsigned char) filename[0])
cb0297bb 889 && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
b03d27bd
JB
890 return TRUE;
891
892 /* Both \xxx and \\xxx\yyy are absolute. */
893 if (filename[0] == '\\') return TRUE;
894#endif
895
896 return FALSE;
897}
898
aa0b6932 899#ifdef WINDOWSNT
f0384499 900/* Wrapper to make WSACleanup a cdecl, as required by atexit. */
7c3320d8
JB
901void __cdecl
902close_winsock (void)
aa0b6932
JB
903{
904 WSACleanup ();
905}
0c76956f 906
b03d27bd
JB
907/* Initialize the WinSock2 library. */
908void
7c3320d8 909initialize_sockets (void)
0c76956f 910{
aa0b6932
JB
911 WSADATA wsaData;
912
aa0b6932
JB
913 if (WSAStartup (MAKEWORD (2, 0), &wsaData))
914 {
78da39c6 915 message (TRUE, "%s: error initializing WinSock2\n", progname);
aa0b6932
JB
916 exit (EXIT_FAILURE);
917 }
918
919 atexit (close_winsock);
0c76956f 920}
e35fc962 921#endif /* WINDOWSNT */
974b73e8 922
8f9aaa0a 923\f
97e3214d 924/*
aa0b6932 925 * Read the information needed to set up a TCP comm channel with
968ef9b4 926 * the Emacs server: host, port, and authentication string.
0e0dced5 927 */
b23b5a5b 928static int
873fbd0b 929get_server_config (struct sockaddr_in *server, char *authentication)
97e3214d 930{
aa0b6932
JB
931 char dotted[32];
932 char *port;
b03d27bd 933 FILE *config = NULL;
aa0b6932 934
b03d27bd
JB
935 if (file_name_absolute_p (server_file))
936 config = fopen (server_file, "rb");
937 else
97e3214d 938 {
b9170155 939 const char *home = egetenv ("HOME");
88b46d84 940
aa0b6932
JB
941 if (home)
942 {
bc558f3e
JB
943 char *path = alloca (strlen (home) + strlen (server_file)
944 + EXTRA_SPACE);
aa0b6932
JB
945 sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
946 config = fopen (path, "rb");
947 }
88b46d84 948#ifdef WINDOWSNT
7ce8671d 949 if (!config && (home = egetenv ("APPDATA")))
88b46d84 950 {
bc558f3e
JB
951 char *path = alloca (strlen (home) + strlen (server_file)
952 + EXTRA_SPACE);
88b46d84
JB
953 sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
954 config = fopen (path, "rb");
955 }
956#endif
aa0b6932
JB
957 }
958
959 if (! config)
960 return FALSE;
961
962 if (fgets (dotted, sizeof dotted, config)
968ef9b4
JB
963 && (port = strchr (dotted, ':')))
964 *port++ = '\0';
97e3214d
GM
965 else
966 {
78da39c6 967 message (TRUE, "%s: invalid configuration info\n", progname);
65396510 968 exit (EXIT_FAILURE);
97e3214d 969 }
97e3214d 970
aa0b6932
JB
971 server->sin_family = AF_INET;
972 server->sin_addr.s_addr = inet_addr (dotted);
973 server->sin_port = htons (atoi (port));
97e3214d 974
aa0b6932
JB
975 if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
976 {
78da39c6 977 message (TRUE, "%s: cannot read authentication info\n", progname);
aa0b6932
JB
978 exit (EXIT_FAILURE);
979 }
46cec291 980
aa0b6932 981 fclose (config);
97e3214d 982
aa0b6932 983 return TRUE;
97e3214d
GM
984}
985
b23b5a5b 986static HSOCKET
873fbd0b 987set_tcp_socket (void)
aa0b6932
JB
988{
989 HSOCKET s;
990 struct sockaddr_in server;
aa0b6932
JB
991 struct linger l_arg = {1, 1};
992 char auth_string[AUTH_KEY_LENGTH + 1];
9628b887 993
aa0b6932
JB
994 if (! get_server_config (&server, auth_string))
995 return INVALID_SOCKET;
996
0b973fc5 997 if (server.sin_addr.s_addr != inet_addr ("127.0.0.1") && !quiet)
9219db75 998 message (FALSE, "%s: connected to remote socket at %s\n",
b03d27bd
JB
999 progname, inet_ntoa (server.sin_addr));
1000
aa0b6932
JB
1001 /*
1002 * Open up an AF_INET socket
1003 */
1004 if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
1005 {
d22b00e5 1006 sock_err_message ("socket");
aa0b6932
JB
1007 return INVALID_SOCKET;
1008 }
1009
1010 /*
1011 * Set up the socket
1012 */
1013 if (connect (s, (struct sockaddr *) &server, sizeof server) < 0)
1014 {
d22b00e5 1015 sock_err_message ("connect");
aa0b6932
JB
1016 return INVALID_SOCKET;
1017 }
1018
aa0b6932
JB
1019 setsockopt (s, SOL_SOCKET, SO_LINGER, (char *) &l_arg, sizeof l_arg);
1020
1021 /*
1022 * Send the authentication
1023 */
1024 auth_string[AUTH_KEY_LENGTH] = '\0';
1025
486ba65f
JR
1026 send_to_emacs (s, "-auth ");
1027 send_to_emacs (s, auth_string);
5ab73228 1028 send_to_emacs (s, " ");
aa0b6932
JB
1029
1030 return s;
1031}
1032
b2ff54a0
JR
1033
1034/* Returns 1 if PREFIX is a prefix of STRING. */
1035static int
988e88ab 1036strprefix (const char *prefix, const char *string)
b2ff54a0 1037{
cb06b8dc 1038 return !strncmp (prefix, string, strlen (prefix));
b2ff54a0
JR
1039}
1040
a336ee5b
CY
1041/* Get tty name and type. If successful, return the type in TTY_TYPE
1042 and the name in TTY_NAME, and return 1. Otherwise, fail if NOABORT
1043 is zero, or return 0 if NOABORT is non-zero. */
1044
b23b5a5b 1045static int
b9170155 1046find_tty (const char **tty_type, const char **tty_name, int noabort)
a336ee5b 1047{
b9170155
PE
1048 const char *type = egetenv ("TERM");
1049 const char *name = ttyname (fileno (stdout));
a336ee5b
CY
1050
1051 if (!name)
1052 {
1053 if (noabort)
1054 return 0;
1055 else
1056 {
1057 message (TRUE, "%s: could not get terminal name\n", progname);
1058 fail ();
1059 }
1060 }
1061
1062 if (!type)
1063 {
1064 if (noabort)
1065 return 0;
1066 else
1067 {
1068 message (TRUE, "%s: please set the TERM variable to your terminal type\n",
1069 progname);
1070 fail ();
1071 }
1072 }
1073
1074 if (strcmp (type, "eterm") == 0)
1075 {
1076 if (noabort)
1077 return 0;
1078 else
1079 {
1080 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1081 message (TRUE, "%s: opening a frame in an Emacs term buffer"
1082 " is not supported\n", progname);
1083 fail ();
1084 }
1085 }
1086
1087 *tty_name = name;
1088 *tty_type = type;
1089 return 1;
1090}
1091
b2ff54a0 1092
aa0b6932 1093#if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
46cec291 1094
9f637eea
GM
1095/* Three possibilities:
1096 2 - can't be `stat'ed (sets errno)
1097 1 - isn't owned by us
1098 0 - success: none of the above */
1099
1100static int
fe91f5a0 1101socket_status (const char *name)
9f637eea
GM
1102{
1103 struct stat statbfr;
1104
b0bbc07d 1105 if (stat (name, &statbfr) == -1)
9f637eea
GM
1106 return 2;
1107
1108 if (statbfr.st_uid != geteuid ())
1109 return 1;
0b0d3e0b 1110
9f637eea
GM
1111 return 0;
1112}
1113
974b73e8 1114\f
da8e1115
KL
1115/* A signal handler that passes the signal to the Emacs process.
1116 Useful for SIGWINCH. */
1117
9af30bdf 1118static void
428a555e 1119pass_signal_to_emacs (int signalnum)
9628b887
KL
1120{
1121 int old_errno = errno;
1122
9f729af5 1123 if (emacs_pid)
428a555e 1124 kill (emacs_pid, signalnum);
9f729af5 1125
428a555e 1126 signal (signalnum, pass_signal_to_emacs);
9f729af5
KL
1127 errno = old_errno;
1128}
1129
0b0d3e0b
KL
1130/* Signal handler for SIGCONT; notify the Emacs process that it can
1131 now resume our tty frame. */
1132
9af30bdf 1133static void
0b0d3e0b
KL
1134handle_sigcont (int signalnum)
1135{
1136 int old_errno = errno;
1137
1138 if (tcgetpgrp (1) == getpgrp ())
1139 {
1140 /* We are in the foreground. */
486ba65f 1141 send_to_emacs (emacs_socket, "-resume \n");
0b0d3e0b
KL
1142 }
1143 else
1144 {
1145 /* We are in the background; cancel the continue. */
1146 kill (getpid (), SIGSTOP);
1147 }
c6c53c3e
KL
1148
1149 signal (signalnum, handle_sigcont);
0b0d3e0b
KL
1150 errno = old_errno;
1151}
1152
1153/* Signal handler for SIGTSTP; notify the Emacs process that we are
1154 going to sleep. Normally the suspend is initiated by Emacs via
1155 server-handle-suspend-tty, but if the server gets out of sync with
1156 reality, we may get a SIGTSTP on C-z. Handling this signal and
1157 notifying Emacs about it should get things under control again. */
1158
9af30bdf 1159static void
0b0d3e0b
KL
1160handle_sigtstp (int signalnum)
1161{
1162 int old_errno = errno;
1163 sigset_t set;
c0f342ab 1164
90843190 1165 if (emacs_socket)
486ba65f 1166 send_to_emacs (emacs_socket, "-suspend \n");
0b0d3e0b 1167
5ab73228 1168 /* Unblock this signal and call the default handler by temporarily
0b0d3e0b
KL
1169 changing the handler and resignalling. */
1170 sigprocmask (SIG_BLOCK, NULL, &set);
1171 sigdelset (&set, signalnum);
1172 signal (signalnum, SIG_DFL);
1173 kill (getpid (), signalnum);
1174 sigprocmask (SIG_SETMASK, &set, NULL); /* Let's the above signal through. */
1175 signal (signalnum, handle_sigtstp);
1176
1177 errno = old_errno;
1178}
273b9028
CY
1179
1180
da8e1115 1181/* Set up signal handlers before opening a frame on the current tty. */
0b0d3e0b 1182
b23b5a5b 1183static void
4d553a13 1184init_signals (void)
9628b887
KL
1185{
1186 /* Set up signal handlers. */
428a555e 1187 signal (SIGWINCH, pass_signal_to_emacs);
4ca927b4
KL
1188
1189 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
1190 deciding which terminal the signal came from. C-g is now a
1191 normal input event on secondary terminals. */
1192#if 0
428a555e
KL
1193 signal (SIGINT, pass_signal_to_emacs);
1194 signal (SIGQUIT, pass_signal_to_emacs);
4ca927b4 1195#endif
0b0d3e0b
KL
1196
1197 signal (SIGCONT, handle_sigcont);
1198 signal (SIGTSTP, handle_sigtstp);
1199 signal (SIGTTOU, handle_sigtstp);
9628b887
KL
1200}
1201
46cec291 1202
b23b5a5b 1203static HSOCKET
873fbd0b 1204set_local_socket (void)
46cec291 1205{
aa0b6932 1206 HSOCKET s;
46cec291 1207 struct sockaddr_un server;
46cec291 1208
e69233c2 1209 /*
46cec291
RS
1210 * Open up an AF_UNIX socket in this person's home directory
1211 */
1212
1213 if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
1214 {
42073bfb 1215 message (TRUE, "%s: socket: %s\n", progname, strerror (errno));
aa0b6932 1216 return INVALID_SOCKET;
46cec291 1217 }
e69233c2 1218
46cec291 1219 server.sun_family = AF_UNIX;
c5fee545 1220
c5fee545 1221 {
9f637eea 1222 int sock_status = 0;
5c9659d3 1223 int default_sock = !socket_name;
b80bf66e 1224 int saved_errno = 0;
988e88ab 1225 const char *server_name = "server";
4be3dfc5 1226 const char *tmpdir IF_LINT ( = NULL);
0b0d3e0b 1227
8966b757
AS
1228 if (socket_name && !strchr (socket_name, '/')
1229 && !strchr (socket_name, '\\'))
1230 {
1231 /* socket_name is a file name component. */
d3a6748c
KL
1232 server_name = socket_name;
1233 socket_name = NULL;
1234 default_sock = 1; /* Try both UIDs. */
0734b0d0 1235 }
efb859b4 1236
5c9659d3 1237 if (default_sock)
254107e4 1238 {
f77b11a0
JB
1239 tmpdir = egetenv ("TMPDIR");
1240 if (!tmpdir)
b336bfcd
GM
1241 {
1242#ifdef DARWIN_OS
e6068ab3
YM
1243#ifndef _CS_DARWIN_USER_TEMP_DIR
1244#define _CS_DARWIN_USER_TEMP_DIR 65537
1245#endif
b336bfcd
GM
1246 size_t n = confstr (_CS_DARWIN_USER_TEMP_DIR, NULL, (size_t) 0);
1247 if (n > 0)
1248 {
1249 tmpdir = alloca (n);
1250 confstr (_CS_DARWIN_USER_TEMP_DIR, tmpdir, n);
1251 }
1252 else
1253#endif
1254 tmpdir = "/tmp";
1255 }
bc558f3e
JB
1256 socket_name = alloca (strlen (tmpdir) + strlen (server_name)
1257 + EXTRA_SPACE);
f77b11a0
JB
1258 sprintf (socket_name, "%s/emacs%d/%s",
1259 tmpdir, (int) geteuid (), server_name);
254107e4
RS
1260 }
1261
1262 if (strlen (socket_name) < sizeof (server.sun_path))
1263 strcpy (server.sun_path, socket_name);
1264 else
819b8f00 1265 {
78da39c6 1266 message (TRUE, "%s: socket-name %s too long\n",
974b73e8 1267 progname, socket_name);
819b8f00
KL
1268 fail ();
1269 }
efb859b4 1270
9f637eea
GM
1271 /* See if the socket exists, and if it's owned by us. */
1272 sock_status = socket_status (server.sun_path);
152b6e83 1273 saved_errno = errno;
5c9659d3 1274 if (sock_status && default_sock)
efb859b4 1275 {
9f637eea
GM
1276 /* Failing that, see if LOGNAME or USER exist and differ from
1277 our euid. If so, look for a socket based on the UID
1278 associated with the name. This is reminiscent of the logic
1279 that init_editfns uses to set the global Vuser_full_name. */
e69233c2 1280
b9170155 1281 const char *user_name = egetenv ("LOGNAME");
293f9f2a 1282
9f637eea 1283 if (!user_name)
b9170155 1284 user_name = egetenv ("USER");
e69233c2 1285
9f637eea
GM
1286 if (user_name)
1287 {
1288 struct passwd *pw = getpwnam (user_name);
293f9f2a 1289
9f637eea
GM
1290 if (pw && (pw->pw_uid != geteuid ()))
1291 {
1292 /* We're running under su, apparently. */
bc558f3e
JB
1293 socket_name = alloca (strlen (tmpdir) + strlen (server_name)
1294 + EXTRA_SPACE);
f77b11a0
JB
1295 sprintf (socket_name, "%s/emacs%d/%s",
1296 tmpdir, (int) pw->pw_uid, server_name);
5c9659d3
SM
1297
1298 if (strlen (socket_name) < sizeof (server.sun_path))
1299 strcpy (server.sun_path, socket_name);
1300 else
1301 {
78da39c6 1302 message (TRUE, "%s: socket-name %s too long\n",
aa0b6932 1303 progname, socket_name);
65396510 1304 exit (EXIT_FAILURE);
5c9659d3
SM
1305 }
1306
9f637eea 1307 sock_status = socket_status (server.sun_path);
b80bf66e 1308 saved_errno = errno;
9f637eea 1309 }
293f9f2a
RS
1310 else
1311 errno = saved_errno;
9f637eea 1312 }
efb859b4 1313 }
e69233c2 1314
aa0b6932
JB
1315 switch (sock_status)
1316 {
1317 case 1:
974b73e8
KL
1318 /* There's a socket, but it isn't owned by us. This is OK if
1319 we are root. */
1320 if (0 != geteuid ())
1321 {
1322 message (TRUE, "%s: Invalid socket owner\n", progname);
aa0b6932 1323 return INVALID_SOCKET;
974b73e8
KL
1324 }
1325 break;
aa0b6932
JB
1326
1327 case 2:
974b73e8
KL
1328 /* `stat' failed */
1329 if (saved_errno == ENOENT)
1330 message (TRUE,
1331 "%s: can't find socket; have you started the server?\n\
45adde32 1332To start the server in Emacs, type \"M-x server-start\".\n",
aa0b6932 1333 progname);
974b73e8
KL
1334 else
1335 message (TRUE, "%s: can't stat %s: %s\n",
aa0b6932 1336 progname, server.sun_path, strerror (saved_errno));
974b73e8 1337 return INVALID_SOCKET;
aa0b6932 1338 }
efb859b4 1339 }
46cec291 1340
4e23f2ba
JB
1341 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
1342 < 0)
46cec291 1343 {
42073bfb 1344 message (TRUE, "%s: connect: %s\n", progname, strerror (errno));
aa0b6932 1345 return INVALID_SOCKET;
46cec291 1346 }
23a7488d 1347
aa0b6932
JB
1348 return s;
1349}
1350#endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1351
b23b5a5b 1352static HSOCKET
636b507b 1353set_socket (int no_exit_if_error)
aa0b6932 1354{
b03d27bd 1355 HSOCKET s;
c0f342ab 1356
b03d27bd 1357 INITIALIZE ();
c0f342ab 1358
aa0b6932 1359#ifndef NO_SOCKETS_IN_FILE_SYSTEM
b03d27bd
JB
1360 /* Explicit --socket-name argument. */
1361 if (socket_name)
46cec291 1362 {
b03d27bd 1363 s = set_local_socket ();
636b507b 1364 if ((s != INVALID_SOCKET) || no_exit_if_error)
974b73e8 1365 return s;
355a326e 1366 message (TRUE, "%s: error accessing socket \"%s\"\n",
974b73e8 1367 progname, socket_name);
b03d27bd 1368 exit (EXIT_FAILURE);
46cec291 1369 }
b03d27bd
JB
1370#endif
1371
1372 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1373 if (!server_file)
7ce8671d 1374 server_file = egetenv ("EMACS_SERVER_FILE");
46cec291 1375
b03d27bd 1376 if (server_file)
23a7488d 1377 {
b03d27bd 1378 s = set_tcp_socket ();
636b507b 1379 if ((s != INVALID_SOCKET) || no_exit_if_error)
974b73e8 1380 return s;
c0f342ab 1381
78da39c6 1382 message (TRUE, "%s: error accessing server file \"%s\"\n",
974b73e8 1383 progname, server_file);
b03d27bd 1384 exit (EXIT_FAILURE);
23a7488d 1385 }
c0f342ab 1386
b03d27bd
JB
1387#ifndef NO_SOCKETS_IN_FILE_SYSTEM
1388 /* Implicit local socket. */
1389 s = set_local_socket ();
1390 if (s != INVALID_SOCKET)
1391 return s;
1392#endif
23a7488d 1393
b03d27bd
JB
1394 /* Implicit server file. */
1395 server_file = "server";
1396 s = set_tcp_socket ();
636b507b 1397 if ((s != INVALID_SOCKET) || no_exit_if_error)
b03d27bd
JB
1398 return s;
1399
1400 /* No implicit or explicit socket, and no alternate editor. */
42073bfb 1401 message (TRUE, "%s: No socket or alternate editor. Please use:\n\n"
b03d27bd
JB
1402#ifndef NO_SOCKETS_IN_FILE_SYSTEM
1403"\t--socket-name\n"
ee6a193c 1404#endif
b03d27bd
JB
1405"\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1406\t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1407 progname);
1408 exit (EXIT_FAILURE);
aa0b6932 1409}
46cec291 1410
0e0dced5
JB
1411#ifdef WINDOWSNT
1412FARPROC set_fg; /* Pointer to AllowSetForegroundWindow. */
1413FARPROC get_wc; /* Pointer to RealGetWindowClassA. */
1414
1415BOOL CALLBACK
7c3320d8 1416w32_find_emacs_process (HWND hWnd, LPARAM lParam)
0e0dced5
JB
1417{
1418 DWORD pid;
1419 char class[6];
1420
1421 /* Reject any window not of class "Emacs". */
1422 if (! get_wc (hWnd, class, sizeof (class))
1423 || strcmp (class, "Emacs"))
1424 return TRUE;
1425
1426 /* We only need the process id, not the thread id. */
1427 (void) GetWindowThreadProcessId (hWnd, &pid);
1428
1429 /* Not the one we're looking for. */
1430 if (pid != (DWORD) emacs_pid) return TRUE;
1431
1432 /* OK, let's raise it. */
1433 set_fg (emacs_pid);
1434
1435 /* Stop enumeration. */
1436 return FALSE;
1437}
1438
1439/*
1440 * Search for a window of class "Emacs" and owned by a process with
1441 * process id = emacs_pid. If found, allow it to grab the focus.
1442 */
1443void
7c3320d8 1444w32_give_focus (void)
0e0dced5 1445{
ff90fbde 1446 HANDLE user32;
0e0dced5 1447
71b8f735 1448 /* It shouldn't happen when dealing with TCP sockets. */
0e0dced5
JB
1449 if (!emacs_pid) return;
1450
ff90fbde
JR
1451 user32 = GetModuleHandle ("user32.dll");
1452
1453 if (!user32)
1454 return;
0e0dced5
JB
1455
1456 /* Modern Windows restrict which processes can set the foreground window.
1457 emacsclient can allow Emacs to grab the focus by calling the function
1458 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1459 NT) lack this function, so we have to check its availability. */
ff90fbde
JR
1460 if ((set_fg = GetProcAddress (user32, "AllowSetForegroundWindow"))
1461 && (get_wc = GetProcAddress (user32, "RealGetWindowClassA")))
0e0dced5 1462 EnumWindows (w32_find_emacs_process, (LPARAM) 0);
0e0dced5
JB
1463}
1464#endif
1465
636b507b
DN
1466/* Start the emacs daemon and try to connect to it. */
1467
b23b5a5b 1468static void
636b507b
DN
1469start_daemon_and_retry_set_socket (void)
1470{
802bdb3c 1471#ifndef WINDOWSNT
636b507b
DN
1472 pid_t dpid;
1473 int status;
636b507b
DN
1474
1475 dpid = fork ();
1476
1477 if (dpid > 0)
1478 {
fd95644b
DN
1479 pid_t w;
1480 w = waitpid (dpid, &status, WUNTRACED | WCONTINUED);
636b507b 1481
361358ea 1482 if ((w == -1) || !WIFEXITED (status) || WEXITSTATUS (status))
fd95644b
DN
1483 {
1484 message (TRUE, "Error: Could not start the Emacs daemon\n");
1485 exit (EXIT_FAILURE);
1486 }
1487
1488 /* Try connecting, the daemon should have started by now. */
1489 message (TRUE, "Emacs daemon should have started, trying to connect again\n");
636b507b 1490 if ((emacs_socket = set_socket (1)) == INVALID_SOCKET)
fd95644b
DN
1491 {
1492 message (TRUE, "Error: Cannot connect even after starting the Emacs daemon\n");
1493 exit (EXIT_FAILURE);
1494 }
636b507b
DN
1495 }
1496 else if (dpid < 0)
1497 {
fd95644b 1498 fprintf (stderr, "Error: Cannot fork!\n");
6ab88e02 1499 exit (EXIT_FAILURE);
636b507b
DN
1500 }
1501 else
1502 {
988e88ab 1503 char emacs[] = "emacs";
b0bbc07d
PE
1504 char daemon_option[] = "--daemon";
1505 char *d_argv[] = {emacs, daemon_option, 0 };
636b507b
DN
1506 if (socket_name != NULL)
1507 {
1508 /* Pass --daemon=socket_name as argument. */
988e88ab 1509 const char *deq = "--daemon=";
636b507b
DN
1510 char *daemon_arg = alloca (strlen (deq)
1511 + strlen (socket_name) + 1);
1512 strcpy (daemon_arg, deq);
1513 strcat (daemon_arg, socket_name);
1514 d_argv[1] = daemon_arg;
1515 }
1516 execvp ("emacs", d_argv);
1517 message (TRUE, "%s: error starting emacs daemon\n", progname);
1518 }
802bdb3c 1519#endif /* WINDOWSNT */
636b507b
DN
1520}
1521
aa0b6932 1522int
873fbd0b 1523main (int argc, char **argv)
aa0b6932 1524{
c5443aa5 1525 int rl = 0, needlf = 0;
974b73e8 1526 char *cwd, *str;
aa0b6932 1527 char string[BUFSIZ+1];
4be3dfc5
PE
1528 int null_socket_name IF_LINT ( = 0);
1529 int null_server_file IF_LINT ( = 0);
1530 int start_daemon_if_needed;
3ecb8d93 1531 int exit_status = EXIT_SUCCESS;
aa0b6932 1532
974b73e8 1533 main_argv = argv;
aa0b6932
JB
1534 progname = argv[0];
1535
ff90fbde
JR
1536#ifdef WINDOWSNT
1537 /* On Windows 7 and later, we need to explicitly associate emacsclient
1538 with emacs so the UI behaves sensibly. */
1539 w32_set_user_model_id ();
1540#endif
1541
aa0b6932
JB
1542 /* Process options. */
1543 decode_options (argc, argv);
1544
273b9028 1545 if ((argc - optind < 1) && !eval && current_frame)
23a7488d 1546 {
974b73e8
KL
1547 message (TRUE, "%s: file name or argument required\n"
1548 "Try `%s --help' for more information\n",
1549 progname, progname);
aa0b6932 1550 exit (EXIT_FAILURE);
23a7488d
RS
1551 }
1552
636b507b
DN
1553 /* If alternate_editor is the empty string, start the emacs daemon
1554 in case of failure to connect. */
1555 start_daemon_if_needed = (alternate_editor
1556 && (alternate_editor[0] == '\0'));
1557 if (start_daemon_if_needed)
1558 {
1559 /* set_socket changes the values for socket_name and
1560 server_file, we need to reset them, if they were NULL before
1561 for the second call to set_socket. */
1562 null_socket_name = (socket_name == NULL);
1563 null_server_file = (server_file == NULL);
1564 }
aa0b6932 1565
7e6bb4c9
PE
1566 emacs_socket = set_socket (alternate_editor || start_daemon_if_needed);
1567 if (emacs_socket == INVALID_SOCKET)
1568 {
1569 if (! start_daemon_if_needed)
1570 fail ();
1571
1572 /* Reset socket_name and server_file if they were NULL
1573 before the set_socket call. */
1574 if (null_socket_name)
1575 socket_name = NULL;
1576 if (null_server_file)
1577 server_file = NULL;
1578
1579 start_daemon_and_retry_set_socket ();
1580 }
974b73e8
KL
1581
1582 cwd = get_current_dir_name ();
46cec291
RS
1583 if (cwd == 0)
1584 {
1585 /* getwd puts message in STRING if it fails. */
974b73e8
KL
1586 message (TRUE, "%s: %s\n", progname,
1587 "Cannot get current working directory");
819b8f00 1588 fail ();
46cec291
RS
1589 }
1590
c66648e0 1591#ifdef WINDOWSNT
0e0dced5 1592 w32_give_focus ();
c66648e0
JB
1593#endif
1594
273b9028 1595 /* Send over our environment and current directory. */
59e085e0
KL
1596 if (!current_frame)
1597 {
1598 extern char **environ;
1599 int i;
1600 for (i = 0; environ[i]; i++)
1601 {
486ba65f
JR
1602 send_to_emacs (emacs_socket, "-env ");
1603 quote_argument (emacs_socket, environ[i]);
1604 send_to_emacs (emacs_socket, " ");
59e085e0 1605 }
2828d5f9 1606 }
ba528748
SM
1607 send_to_emacs (emacs_socket, "-dir ");
1608 quote_argument (emacs_socket, cwd);
1609 send_to_emacs (emacs_socket, "/");
1610 send_to_emacs (emacs_socket, " ");
2828d5f9 1611
6afdd335 1612 retry:
5212210c 1613 if (nowait)
486ba65f 1614 send_to_emacs (emacs_socket, "-nowait ");
292d74a3 1615
92071250 1616 if (current_frame)
486ba65f 1617 send_to_emacs (emacs_socket, "-current-frame ");
c0f342ab 1618
30be2360 1619 if (display)
87209357 1620 {
486ba65f
JR
1621 send_to_emacs (emacs_socket, "-display ");
1622 quote_argument (emacs_socket, display);
1623 send_to_emacs (emacs_socket, " ");
87209357 1624 }
30be2360 1625
0191e222
CY
1626 if (parent_id)
1627 {
1628 send_to_emacs (emacs_socket, "-parent-id ");
1629 quote_argument (emacs_socket, parent_id);
1630 send_to_emacs (emacs_socket, " ");
1631 }
1632
8536c0f5
CY
1633 /* If using the current frame, send tty information to Emacs anyway.
1634 In daemon mode, Emacs may need to occupy this tty if no other
1635 frame is available. */
322ca650 1636 if (tty || (current_frame && !eval))
9628b887 1637 {
b9170155 1638 const char *tty_type, *tty_name;
0b0d3e0b 1639
273b9028
CY
1640 if (find_tty (&tty_type, &tty_name, !tty))
1641 {
b2ff54a0 1642#if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
273b9028 1643 init_signals ();
b2ff54a0 1644#endif
273b9028
CY
1645 send_to_emacs (emacs_socket, "-tty ");
1646 quote_argument (emacs_socket, tty_name);
1647 send_to_emacs (emacs_socket, " ");
1648 quote_argument (emacs_socket, tty_type);
1649 send_to_emacs (emacs_socket, " ");
1650 }
9628b887 1651 }
77134727 1652
273b9028 1653 if (!current_frame && !tty)
486ba65f 1654 send_to_emacs (emacs_socket, "-window-system ");
0b0d3e0b 1655
87209357 1656 if ((argc - optind > 0))
5212210c 1657 {
b0bbc07d 1658 int i;
87209357 1659 for (i = optind; i < argc; i++)
46cec291 1660 {
0b0d3e0b 1661
87209357 1662 if (eval)
0b0d3e0b 1663 {
974b73e8 1664 /* Don't prepend cwd or anything like that. */
486ba65f
JR
1665 send_to_emacs (emacs_socket, "-eval ");
1666 quote_argument (emacs_socket, argv[i]);
1667 send_to_emacs (emacs_socket, " ");
0b0d3e0b
KL
1668 continue;
1669 }
1670
1671 if (*argv[i] == '+')
1672 {
87209357
EZ
1673 char *p = argv[i] + 1;
1674 while (isdigit ((unsigned char) *p) || *p == ':') p++;
0b0d3e0b
KL
1675 if (*p == 0)
1676 {
486ba65f
JR
1677 send_to_emacs (emacs_socket, "-position ");
1678 quote_argument (emacs_socket, argv[i]);
1679 send_to_emacs (emacs_socket, " ");
0b0d3e0b
KL
1680 continue;
1681 }
0b0d3e0b 1682 }
6cde1b21
JB
1683#ifdef WINDOWSNT
1684 else if (! file_name_absolute_p (argv[i])
1685 && (isalpha (argv[i][0]) && argv[i][1] == ':'))
1686 /* Windows can have a different default directory for each
1687 drive, so the cwd passed via "-dir" is not sufficient
1688 to account for that.
1689 If the user uses <drive>:<relpath>, we hence need to be
1690 careful to expand <relpath> with the default directory
1691 corresponding to <drive>. */
1692 {
1693 char *filename = (char *) xmalloc (MAX_PATH);
1694 DWORD size;
1695
1696 size = GetFullPathName (argv[i], MAX_PATH, filename, NULL);
1697 if (size > 0 && size < MAX_PATH)
1698 argv[i] = filename;
1699 else
1700 free (filename);
1701 }
1702#endif
0b0d3e0b 1703
486ba65f 1704 send_to_emacs (emacs_socket, "-file ");
486ba65f
JR
1705 quote_argument (emacs_socket, argv[i]);
1706 send_to_emacs (emacs_socket, " ");
0b0d3e0b 1707 }
46cec291 1708 }
273b9028 1709 else if (eval)
87209357 1710 {
273b9028
CY
1711 /* Read expressions interactively. */
1712 while ((str = fgets (string, BUFSIZ, stdin)))
1713 {
1714 send_to_emacs (emacs_socket, "-eval ");
1715 quote_argument (emacs_socket, str);
1716 }
1717 send_to_emacs (emacs_socket, " ");
87209357 1718 }
0b0d3e0b 1719
486ba65f 1720 send_to_emacs (emacs_socket, "\n");
46cec291 1721
fc2040c0 1722 /* Wait for an answer. */
0b973fc5 1723 if (!eval && !tty && !nowait && !quiet)
30be2360
SM
1724 {
1725 printf ("Waiting for Emacs...");
1726 needlf = 2;
1727 }
46cec291 1728 fflush (stdout);
0b0d3e0b 1729 fsync (1);
46cec291 1730
3cf8c6aa 1731 /* Now, wait for an answer and print any messages. */
b166dcd8 1732 while (exit_status == EXIT_SUCCESS)
3cf8c6aa 1733 {
974b73e8 1734 char *p;
b166dcd8
KC
1735 do
1736 {
1737 errno = 0;
1738 rl = recv (emacs_socket, string, BUFSIZ, 0);
1739 }
1740 /* If we receive a signal (e.g. SIGWINCH, which we pass
1741 through to Emacs), on some OSes we get EINTR and must retry. */
1742 while (rl < 0 && errno == EINTR);
1743
1744 if (rl <= 0)
1745 break;
b23b5a5b 1746
974b73e8
KL
1747 string[rl] = '\0';
1748
1749 p = string + strlen (string) - 1;
1750 while (p > string && *p == '\n')
0b0d3e0b
KL
1751 *p-- = 0;
1752
31fa6595 1753 if (strprefix ("-emacs-pid ", string))
4d553a13 1754 {
6afdd335 1755 /* -emacs-pid PID: The process id of the Emacs process. */
77134727
KL
1756 emacs_pid = strtol (string + strlen ("-emacs-pid"), NULL, 10);
1757 }
974b73e8 1758 else if (strprefix ("-window-system-unsupported ", string))
6afdd335
KL
1759 {
1760 /* -window-system-unsupported: Emacs was compiled without X
1761 support. Try again on the terminal. */
6afdd335
KL
1762 nowait = 0;
1763 tty = 1;
1764 goto retry;
1765 }
974b73e8 1766 else if (strprefix ("-print ", string))
77134727 1767 {
6afdd335 1768 /* -print STRING: Print STRING on the terminal. */
974b73e8 1769 str = unquote_argument (string + strlen ("-print "));
0b0d3e0b 1770 if (needlf)
77134727 1771 printf ("\n");
0b0d3e0b
KL
1772 printf ("%s", str);
1773 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
77134727 1774 }
974b73e8 1775 else if (strprefix ("-error ", string))
77134727 1776 {
6afdd335 1777 /* -error DESCRIPTION: Signal an error on the terminal. */
974b73e8 1778 str = unquote_argument (string + strlen ("-error "));
0b0d3e0b
KL
1779 if (needlf)
1780 printf ("\n");
974b73e8 1781 fprintf (stderr, "*ERROR*: %s", str);
0b0d3e0b 1782 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
3ecb8d93 1783 exit_status = EXIT_FAILURE;
0b0d3e0b 1784 }
c801ad51 1785#ifdef SIGSTOP
382707ec 1786 else if (strprefix ("-suspend ", string))
0b0d3e0b 1787 {
6afdd335 1788 /* -suspend: Suspend this terminal, i.e., stop the process. */
0b0d3e0b 1789 if (needlf)
77134727 1790 printf ("\n");
0b0d3e0b
KL
1791 needlf = 0;
1792 kill (0, SIGSTOP);
4d553a13 1793 }
b2ff54a0 1794#endif
4d553a13
KL
1795 else
1796 {
6afdd335 1797 /* Unknown command. */
0b0d3e0b 1798 if (needlf)
4d553a13 1799 printf ("\n");
974b73e8 1800 printf ("*ERROR*: Unknown message: %s", string);
3ecb8d93
WS
1801 needlf = string[0]
1802 == '\0' ? needlf : string[strlen (string) - 1] != '\n';
4d553a13 1803 }
3cf8c6aa
SM
1804 }
1805
1806 if (needlf)
1807 printf ("\n");
1808 fflush (stdout);
0b0d3e0b 1809 fsync (1);
23a7488d 1810
3ecb8d93
WS
1811 if (rl < 0)
1812 exit_status = EXIT_FAILURE;
1813
4b7b77f6 1814 CLOSE_SOCKET (emacs_socket);
3ecb8d93 1815 return exit_status;
46cec291
RS
1816}
1817
1e7823d0 1818#endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
aa0b6932 1819
27711600
RM
1820\f
1821#ifndef HAVE_STRERROR
1822char *
1823strerror (errnum)
1824 int errnum;
1825{
1826 extern char *sys_errlist[];
1827 extern int sys_nerr;
1828
1829 if (errnum >= 0 && errnum < sys_nerr)
1830 return sys_errlist[errnum];
1831 return (char *) "Unknown error";
1832}
1833
1834#endif /* ! HAVE_STRERROR */
ab5796a9 1835
65396510
TTN
1836
1837/* emacsclient.c ends here */