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