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