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