Add 2008 to copyright years.
[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,
4e6835db 3 2005, 2006, 2007 Free Software Foundation, Inc.
46cec291
RS
4
5This file is part of GNU Emacs.
6
7GNU Emacs is free software; you can redistribute it and/or modify
8it under the terms of the GNU General Public License as published by
4a9f99bd 9the Free Software Foundation; either version 3, or (at your option)
46cec291
RS
10any later version.
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
18along with GNU Emacs; see the file COPYING. If not, write to
364c38d3
LK
19the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20Boston, MA 02110-1301, USA. */
46cec291
RS
21
22
23#define NO_SHORTNAMES
e69233c2
PJ
24
25#ifdef HAVE_CONFIG_H
2f8fe2f4 26#include <config.h>
e69233c2
PJ
27#endif
28
aa0b6932 29#ifdef WINDOWSNT
aa0b6932 30
bc28de71
JB
31/* config.h defines these, which disables sockets altogether! */
32# undef _WINSOCKAPI_
33# undef _WINSOCK_H
34
411b80a5
JB
35# include <malloc.h>
36# include <stdlib.h>
42073bfb 37# include <windows.h>
dbf60b07 38# include <commctrl.h>
411b80a5 39
411b80a5
JB
40# define NO_SOCKETS_IN_FILE_SYSTEM
41
aa0b6932
JB
42# define HSOCKET SOCKET
43# define CLOSE_SOCKET closesocket
aa0b6932 44# define INITIALIZE() (initialize_sockets ())
411b80a5
JB
45
46#else /* !WINDOWSNT */
47
ed4a3730
JB
48# include <sys/types.h>
49
1e7823d0
JB
50# ifdef HAVE_INET_SOCKETS
51# include <netinet/in.h>
52# endif
411b80a5 53
e35fc962 54# define INVALID_SOCKET -1
aa0b6932
JB
55# define HSOCKET int
56# define CLOSE_SOCKET close
aa0b6932 57# define INITIALIZE()
411b80a5
JB
58
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
9f637eea
GM
71#ifdef VMS
72# include "vms-pwd.h"
aa0b6932
JB
73#else /* not VMS */
74#ifdef WINDOWSNT
75# include <io.h>
76#else /* not WINDOWSNT */
9f637eea 77# include <pwd.h>
aa0b6932 78#endif /* not WINDOWSNT */
9f637eea
GM
79#endif /* not VMS */
80
8f9aaa0a 81char *getenv (), *getwd ();
5b9562c3 82char *(getcwd) ();
8f9aaa0a 83
70cd9104
JB
84#ifdef WINDOWSNT
85char *w32_getenv ();
86#define egetenv(VAR) w32_getenv(VAR)
87#else
88#define egetenv(VAR) getenv(VAR)
89#endif
90
8f9aaa0a
RS
91#ifndef VERSION
92#define VERSION "unspecified"
93#endif
94\f
aa0b6932
JB
95#define SEND_STRING(data) (send_to_emacs (s, (data)))
96#define SEND_QUOTED(data) (quote_file_name (s, (data)))
97
98#ifndef EXIT_SUCCESS
99#define EXIT_SUCCESS 0
100#endif
101
102#ifndef EXIT_FAILURE
103#define EXIT_FAILURE 1
104#endif
105
106#ifndef FALSE
107#define FALSE 0
108#endif
109
110#ifndef TRUE
111#define TRUE 1
112#endif
113
114#ifndef NO_RETURN
115#define NO_RETURN
116#endif
117\f
8f9aaa0a
RS
118/* Name used to invoke this program. */
119char *progname;
120
749ae770 121/* Nonzero means don't wait for a response from Emacs. --no-wait. */
8f9aaa0a
RS
122int nowait = 0;
123
30be2360
SM
124/* Nonzero means args are expressions to be evaluated. --eval. */
125int eval = 0;
126
127/* The display on which Emacs should work. --display. */
128char *display = NULL;
129
130/* If non-NULL, the name of an editor to fallback to if the server
131 is not running. --alternate-editor. */
b03d27bd 132const char *alternate_editor = NULL;
30be2360 133
3db926be 134/* If non-NULL, the filename of the UNIX socket. */
254107e4
RS
135char *socket_name = NULL;
136
aa0b6932
JB
137/* If non-NULL, the filename of the authentication file. */
138char *server_file = NULL;
139
c66648e0
JB
140/* PID of the Emacs server process. */
141int emacs_pid = 0;
142
2381d38d 143void print_help_and_exit () NO_RETURN;
7f3bff3e 144
8f9aaa0a
RS
145struct option longopts[] =
146{
749ae770 147 { "no-wait", no_argument, NULL, 'n' },
30be2360 148 { "eval", no_argument, NULL, 'e' },
8f9aaa0a
RS
149 { "help", no_argument, NULL, 'H' },
150 { "version", no_argument, NULL, 'V' },
3cf8c6aa 151 { "alternate-editor", required_argument, NULL, 'a' },
b03d27bd 152#ifndef NO_SOCKETS_IN_FILE_SYSTEM
254107e4 153 { "socket-name", required_argument, NULL, 's' },
b03d27bd 154#endif
aa0b6932 155 { "server-file", required_argument, NULL, 'f' },
30be2360
SM
156 { "display", required_argument, NULL, 'd' },
157 { 0, 0, 0, 0 }
8f9aaa0a
RS
158};
159
70cd9104
JB
160\f
161/* Like malloc but get fatal error if memory is exhausted. */
162
163long *
164xmalloc (size)
165 unsigned int size;
166{
167 long *result = (long *) malloc (size);
168 if (result == NULL)
169 {
170 perror ("malloc");
171 exit (EXIT_FAILURE);
172 }
173 return result;
174}
175
42073bfb
JB
176/* Message functions. */
177
178#ifdef WINDOWSNT
70cd9104
JB
179
180#define REG_ROOT "SOFTWARE\\GNU\\Emacs"
181
182/* Retrieve an environment variable from the Emacs subkeys of the registry.
183 Return NULL if the variable was not found, or it was empty.
184 This code is based on w32_get_resource (w32.c). */
185char *
186w32_get_resource (predefined, key, type)
187 HKEY predefined;
188 char *key;
189 LPDWORD type;
190{
191 HKEY hrootkey = NULL;
192 char *result = NULL;
193 DWORD cbData;
194
195 if (RegOpenKeyEx (predefined, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
196 {
197 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS)
198 {
199 result = (char *) xmalloc (cbData);
200
201 if ((RegQueryValueEx (hrootkey, key, NULL, type, result, &cbData) != ERROR_SUCCESS) ||
202 (*result == 0))
203 {
204 free (result);
205 result = NULL;
206 }
207 }
208
209 RegCloseKey (hrootkey);
210 }
211
212 return result;
213}
214
215/*
216 getenv wrapper for Windows
217
218 This is needed to duplicate Emacs's behavior, which is to look for enviroment
219 variables in the registry if they don't appear in the environment.
220*/
221char *
222w32_getenv (envvar)
223 char *envvar;
224{
225 char *value;
226 DWORD dwType;
227
228 if (value = getenv (envvar))
229 /* Found in the environment. */
230 return value;
231
232 if (! (value = w32_get_resource (HKEY_CURRENT_USER, envvar, &dwType)) &&
233 ! (value = w32_get_resource (HKEY_LOCAL_MACHINE, envvar, &dwType)))
234 /* Not found in the registry. */
235 return NULL;
236
237 if (dwType == REG_SZ)
238 /* Registry; no need to expand. */
239 return value;
240
241 if (dwType == REG_EXPAND_SZ)
242 {
243 DWORD size;
244
245 if (size = ExpandEnvironmentStrings (value, NULL, 0))
246 {
247 char *buffer = (char *) xmalloc (size);
248 if (ExpandEnvironmentStrings (value, buffer, size))
249 {
250 /* Found and expanded. */
251 free (value);
252 return buffer;
253 }
254
255 /* Error expanding. */
256 free (buffer);
257 }
258 }
259
260 /* Not the right type, or not correctly expanded. */
261 free (value);
262 return NULL;
263}
264
42073bfb 265int
f0384499 266w32_window_app ()
42073bfb
JB
267{
268 static int window_app = -1;
269 char szTitle[MAX_PATH];
270
271 if (window_app < 0)
dbf60b07
JR
272 {
273 /* Checking for STDOUT does not work; it's a valid handle also in
274 nonconsole apps. Testing for the console title seems to work. */
275 window_app = (GetConsoleTitleA (szTitle, MAX_PATH) == 0);
276 if (window_app)
277 InitCommonControls();
278 }
42073bfb
JB
279
280 return window_app;
281}
282#endif
283
284void
285message (int is_error, char *message, ...)
286{
c66648e0 287 char msg [2048];
42073bfb
JB
288 va_list args;
289
290 va_start (args, message);
42073bfb
JB
291 vsprintf (msg, message, args);
292 va_end (args);
293
294#ifdef WINDOWSNT
295 if (w32_window_app ())
296 {
297 if (is_error)
298 MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
299 else
300 MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
301 }
302 else
303#endif
9219db75
JB
304 {
305 FILE *f = is_error ? stderr : stdout;
306
307 fputs (msg, f);
308 fflush (f);
309 }
42073bfb
JB
310}
311
8f9aaa0a 312/* Decode the options from argv and argc.
5212210c 313 The global variable `optind' will say how many arguments we used up. */
8f9aaa0a 314
5212210c 315void
8f9aaa0a
RS
316decode_options (argc, argv)
317 int argc;
318 char **argv;
319{
70cd9104 320 alternate_editor = egetenv ("ALTERNATE_EDITOR");
b6b6d6d2 321
8f9aaa0a
RS
322 while (1)
323 {
324 int opt = getopt_long (argc, argv,
b03d27bd
JB
325#ifndef NO_SOCKETS_IN_FILE_SYSTEM
326 "VHnea:s:f:d:",
327#else
328 "VHnea:f:d:",
329#endif
330 longopts, 0);
8f9aaa0a
RS
331
332 if (opt == EOF)
333 break;
334
335 switch (opt)
336 {
337 case 0:
338 /* If getopt returns 0, then it has already processed a
339 long-named option. We should do nothing. */
340 break;
e69233c2 341
97e3214d
GM
342 case 'a':
343 alternate_editor = optarg;
344 break;
e69233c2 345
b03d27bd 346#ifndef NO_SOCKETS_IN_FILE_SYSTEM
254107e4
RS
347 case 's':
348 socket_name = optarg;
349 break;
b03d27bd 350#endif
254107e4 351
aa0b6932
JB
352 case 'f':
353 server_file = optarg;
354 break;
355
30be2360
SM
356 case 'd':
357 display = optarg;
358 break;
359
8f9aaa0a
RS
360 case 'n':
361 nowait = 1;
362 break;
363
30be2360
SM
364 case 'e':
365 eval = 1;
366 break;
367
8f9aaa0a 368 case 'V':
42073bfb 369 message (FALSE, "emacsclient %s\n", VERSION);
65396510 370 exit (EXIT_SUCCESS);
8f9aaa0a 371 break;
46cec291 372
8f9aaa0a 373 case 'H':
8f9aaa0a 374 print_help_and_exit ();
20c396e8
JB
375 break;
376
377 default:
42073bfb 378 message (TRUE, "Try `%s --help' for more information\n", progname);
65396510 379 exit (EXIT_FAILURE);
20c396e8 380 break;
8f9aaa0a
RS
381 }
382 }
8f9aaa0a
RS
383}
384
7f3bff3e 385void
8f9aaa0a
RS
386print_help_and_exit ()
387{
42073bfb 388 message (FALSE,
20c396e8 389 "Usage: %s [OPTIONS] FILE...\n\
30be2360
SM
390Tell the Emacs server to visit the specified files.\n\
391Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
20c396e8 392\n\
30be2360 393The following OPTIONS are accepted:\n\
30aa95ce
JB
394\n\
395-V, --version Just print version info and return\n\
396-H, --help Print this usage information message\n\
397-e, --eval Evaluate FILE arguments as Lisp expressions\n\
398-n, --no-wait Don't wait for the server to return\n\
399-d, --display=DISPLAY Visit the file in the given display\n"
aa0b6932
JB
400#ifndef NO_SOCKETS_IN_FILE_SYSTEM
401"-s, --socket-name=FILENAME\n\
30aa95ce 402 Set filename of the UNIX socket for communication\n"
aa0b6932
JB
403#endif
404"-f, --server-file=FILENAME\n\
30aa95ce 405 Set filename of the TCP authentication file\n\
30be2360 406-a, --alternate-editor=EDITOR\n\
30aa95ce 407 Editor to fallback to if server is not running\n\
20c396e8 408\n\
30be2360 409Report bugs to bug-gnu-emacs@gnu.org.\n", progname);
65396510 410 exit (EXIT_SUCCESS);
8f9aaa0a 411}
5212210c 412
aa0b6932 413\f
4472aef4
JB
414#ifdef WINDOWSNT
415
416/*
f0384499 417 execvp wrapper for Windows. Quotes arguments with embedded spaces.
4472aef4
JB
418
419 This is necessary due to the broken implementation of exec* routines in
420 the Microsoft libraries: they concatenate the arguments together without
421 quoting special characters, and pass the result to CreateProcess, with
422 predictably bad results. By contrast, Posix execvp passes the arguments
f0384499 423 directly into the argv array of the child process.
4472aef4
JB
424*/
425int
426w32_execvp (path, argv)
427 char *path;
428 char **argv;
429{
430 int i;
431
0d3d6719 432 /* Required to allow a .BAT script as alternate editor. */
4472aef4
JB
433 argv[0] = (char *) alternate_editor;
434
435 for (i = 0; argv[i]; i++)
436 if (strchr (argv[i], ' '))
437 {
438 char *quoted = alloca (strlen (argv[i]) + 3);
439 sprintf (quoted, "\"%s\"", argv[i]);
440 argv[i] = quoted;
441 }
442
443 return execvp (path, argv);
444}
445
446#undef execvp
447#define execvp w32_execvp
448
449#endif /* WINDOWSNT */
450
aa0b6932
JB
451/*
452 Try to run a different command, or --if no alternate editor is
453 defined-- exit with an errorcode.
454*/
455void
456fail (argc, argv)
457 int argc;
458 char **argv;
459{
460 if (alternate_editor)
461 {
462 int i = optind - 1;
4472aef4 463
aa0b6932 464 execvp (alternate_editor, argv + i);
42073bfb 465 message (TRUE, "%s: error executing alternate editor \"%s\"\n",
aa0b6932
JB
466 progname, alternate_editor);
467 }
aa0b6932
JB
468 exit (EXIT_FAILURE);
469}
470
471\f
1e7823d0 472#if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
aa0b6932
JB
473
474int
475main (argc, argv)
476 int argc;
477 char **argv;
478{
42073bfb 479 message (TRUE, "%s: Sorry, the Emacs server is supported only\non systems with Berkely sockets.\n",
aa0b6932 480 argv[0]);
aa0b6932
JB
481
482 fail (argc, argv);
483}
484
1e7823d0 485#else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
aa0b6932
JB
486
487#ifdef WINDOWSNT
488# include <winsock2.h>
489#else
490# include <sys/types.h>
491# include <sys/socket.h>
492# include <sys/un.h>
493# include <sys/stat.h>
494# include <errno.h>
495#endif
496
497#define AUTH_KEY_LENGTH 64
498#define SEND_BUFFER_SIZE 4096
499
500extern char *strerror ();
501extern int errno;
502
503/* Buffer to accumulate data to send in TCP connections. */
504char send_buffer[SEND_BUFFER_SIZE + 1];
505int sblen = 0; /* Fill pointer for the send buffer. */
506
d22b00e5
JR
507/* On Windows, the socket library was historically separate from the standard
508 C library, so errors are handled differently. */
509void
510sock_err_message (function_name)
511 char *function_name;
512{
513#ifdef WINDOWSNT
514 char* msg = NULL;
515
516 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
517 | FORMAT_MESSAGE_ALLOCATE_BUFFER
518 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
519 NULL, WSAGetLastError (), 0, (LPTSTR)&msg, 0, NULL);
520
521 message (TRUE, "%s: %s: %s\n", progname, function_name, msg);
522
523 LocalFree (msg);
524#else
525 message (TRUE, "%s: %s: %s\n", progname, function_name, strerror (errno));
526#endif
527}
528
529
aa0b6932
JB
530/* Let's send the data to Emacs when either
531 - the data ends in "\n", or
532 - the buffer is full (but this shouldn't happen)
533 Otherwise, we just accumulate it. */
b03d27bd
JB
534void
535send_to_emacs (s, data)
aa0b6932
JB
536 HSOCKET s;
537 char *data;
538{
539 while (data)
540 {
541 int dlen = strlen (data);
542 if (dlen + sblen >= SEND_BUFFER_SIZE)
543 {
544 int part = SEND_BUFFER_SIZE - sblen;
545 strncpy (&send_buffer[sblen], data, part);
546 data += part;
547 sblen = SEND_BUFFER_SIZE;
548 }
549 else if (dlen)
550 {
551 strcpy (&send_buffer[sblen], data);
552 data = NULL;
553 sblen += dlen;
554 }
555 else
556 break;
557
558 if (sblen == SEND_BUFFER_SIZE
559 || (sblen > 0 && send_buffer[sblen-1] == '\n'))
560 {
561 int sent = send (s, send_buffer, sblen, 0);
562 if (sent != sblen)
563 strcpy (send_buffer, &send_buffer[sent]);
564 sblen -= sent;
565 }
566 }
567}
568
a4cf2096
RS
569/* In NAME, insert a & before each &, each space, each newline, and
570 any initial -. Change spaces to underscores, too, so that the
5212210c 571 return value never contains a space. */
87209357 572void
aa0b6932
JB
573quote_file_name (s, name)
574 HSOCKET s;
5212210c
RS
575 char *name;
576{
70cd9104 577 char *copy = (char *) xmalloc (strlen (name) * 2 + 1);
5212210c
RS
578 char *p, *q;
579
580 p = name;
581 q = copy;
582 while (*p)
583 {
584 if (*p == ' ')
585 {
f1db6a73 586 *q++ = '&';
5212210c
RS
587 *q++ = '_';
588 p++;
589 }
3cf8c6aa
SM
590 else if (*p == '\n')
591 {
592 *q++ = '&';
593 *q++ = 'n';
594 p++;
595 }
5212210c
RS
596 else
597 {
f1db6a73
RS
598 if (*p == '&' || (*p == '-' && p == name))
599 *q++ = '&';
5212210c
RS
600 *q++ = *p++;
601 }
602 }
f1db6a73 603 *q++ = 0;
5212210c 604
aa0b6932 605 SEND_STRING (copy);
87209357
EZ
606
607 free (copy);
5212210c 608}
0c76956f 609
b03d27bd
JB
610int
611file_name_absolute_p (filename)
612 const unsigned char *filename;
613{
614 /* Sanity check, it shouldn't happen. */
615 if (! filename) return FALSE;
616
617 /* /xxx is always an absolute path. */
618 if (filename[0] == '/') return TRUE;
619
620 /* Empty filenames (which shouldn't happen) are relative. */
621 if (filename[0] == '\0') return FALSE;
622
623#ifdef WINDOWSNT
71b8f735 624 /* X:\xxx is always absolute. */
5f7a4874 625 if (isalpha (filename[0])
cb0297bb 626 && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
b03d27bd
JB
627 return TRUE;
628
629 /* Both \xxx and \\xxx\yyy are absolute. */
630 if (filename[0] == '\\') return TRUE;
71b8f735
JB
631
632 /*
633 FIXME: There's a corner case not dealt with, "x:y", where:
634
635 1) x is a valid drive designation (usually a letter in the A-Z range)
636 and y is a path, relative to the current directory on drive x. This
637 is absolute, *after* fixing the y part to include the current
638 directory in x.
639
640 2) x is a relative file name, and y is an NTFS stream name. This is a
641 correct relative path, but it is very unusual.
642
643 The trouble is that first case items are also valid examples of the
644 second case, i.e., "c:test" can be understood as drive:path or as
645 file:stream.
646
647 The "right" fix would involve checking whether
648 - the current drive/partition is NTFS,
649 - x is a valid (and accesible) drive designator,
650 - x:y already exists as a file:stream in the current directory,
651 - y already exists on the current directory of drive x,
652 - the auspices are favorable,
653 and then taking an "informed decision" based on the above.
654
655 Whatever the result, Emacs currently does a very bad job of dealing
656 with NTFS file:streams: it cannot visit them, and the only way to
657 create one is by setting `buffer-file-name' to point to it (either
658 manually or with emacsclient). So perhaps resorting to 1) and ignoring
659 2) for now is the right thing to do.
660
661 Anyway, something to decide After the Release.
662 */
b03d27bd
JB
663#endif
664
665 return FALSE;
666}
667
aa0b6932 668#ifdef WINDOWSNT
f0384499 669/* Wrapper to make WSACleanup a cdecl, as required by atexit. */
b03d27bd
JB
670void
671__cdecl close_winsock ()
aa0b6932
JB
672{
673 WSACleanup ();
674}
0c76956f 675
b03d27bd
JB
676/* Initialize the WinSock2 library. */
677void
678initialize_sockets ()
0c76956f 679{
aa0b6932
JB
680 WSADATA wsaData;
681
aa0b6932
JB
682 if (WSAStartup (MAKEWORD (2, 0), &wsaData))
683 {
42073bfb 684 message (TRUE, "%s: error initializing WinSock2", progname);
aa0b6932
JB
685 exit (EXIT_FAILURE);
686 }
687
688 atexit (close_winsock);
0c76956f 689}
e35fc962 690#endif /* WINDOWSNT */
8f9aaa0a 691\f
97e3214d 692/*
aa0b6932 693 * Read the information needed to set up a TCP comm channel with
434a6c5d 694 * the Emacs server: host, port, pid and authentication string.
0e0dced5 695 */
b03d27bd
JB
696int
697get_server_config (server, authentication)
aa0b6932
JB
698 struct sockaddr_in *server;
699 char *authentication;
97e3214d 700{
aa0b6932
JB
701 char dotted[32];
702 char *port;
434a6c5d 703 char *pid;
b03d27bd 704 FILE *config = NULL;
aa0b6932 705
b03d27bd
JB
706 if (file_name_absolute_p (server_file))
707 config = fopen (server_file, "rb");
708 else
97e3214d 709 {
70cd9104 710 char *home = egetenv ("HOME");
88b46d84 711
aa0b6932
JB
712 if (home)
713 {
714 char *path = alloca (32 + strlen (home) + strlen (server_file));
715 sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
716 config = fopen (path, "rb");
717 }
88b46d84 718#ifdef WINDOWSNT
70cd9104 719 if (!config && (home = egetenv ("APPDATA")))
88b46d84
JB
720 {
721 char *path = alloca (32 + strlen (home) + strlen (server_file));
722 sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
723 config = fopen (path, "rb");
724 }
725#endif
aa0b6932
JB
726 }
727
728 if (! config)
729 return FALSE;
730
731 if (fgets (dotted, sizeof dotted, config)
434a6c5d
JB
732 && (port = strchr (dotted, ':'))
733 && (pid = strchr (port, ' ')))
aa0b6932
JB
734 {
735 *port++ = '\0';
434a6c5d 736 *pid++ = '\0';
97e3214d
GM
737 }
738 else
739 {
42073bfb 740 message (TRUE, "%s: invalid configuration info", progname);
65396510 741 exit (EXIT_FAILURE);
97e3214d 742 }
97e3214d 743
aa0b6932
JB
744 server->sin_family = AF_INET;
745 server->sin_addr.s_addr = inet_addr (dotted);
746 server->sin_port = htons (atoi (port));
97e3214d 747
aa0b6932
JB
748 if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
749 {
42073bfb 750 message (TRUE, "%s: cannot read authentication info", progname);
aa0b6932
JB
751 exit (EXIT_FAILURE);
752 }
46cec291 753
aa0b6932 754 fclose (config);
97e3214d 755
c66648e0 756 emacs_pid = atoi (pid);
434a6c5d 757
aa0b6932 758 return TRUE;
46cec291
RS
759}
760
aa0b6932
JB
761HSOCKET
762set_tcp_socket ()
763{
764 HSOCKET s;
765 struct sockaddr_in server;
aa0b6932
JB
766 struct linger l_arg = {1, 1};
767 char auth_string[AUTH_KEY_LENGTH + 1];
46cec291 768
aa0b6932
JB
769 if (! get_server_config (&server, auth_string))
770 return INVALID_SOCKET;
771
b03d27bd 772 if (server.sin_addr.s_addr != inet_addr ("127.0.0.1"))
9219db75 773 message (FALSE, "%s: connected to remote socket at %s\n",
b03d27bd
JB
774 progname, inet_ntoa (server.sin_addr));
775
aa0b6932
JB
776 /*
777 * Open up an AF_INET socket
778 */
779 if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
780 {
d22b00e5 781 sock_err_message ("socket");
aa0b6932
JB
782 return INVALID_SOCKET;
783 }
784
785 /*
786 * Set up the socket
787 */
788 if (connect (s, (struct sockaddr *) &server, sizeof server) < 0)
789 {
d22b00e5 790 sock_err_message ("connect");
aa0b6932
JB
791 return INVALID_SOCKET;
792 }
793
aa0b6932
JB
794 setsockopt (s, SOL_SOCKET, SO_LINGER, (char *) &l_arg, sizeof l_arg);
795
796 /*
797 * Send the authentication
798 */
799 auth_string[AUTH_KEY_LENGTH] = '\0';
800
801 SEND_STRING ("-auth ");
802 SEND_STRING (auth_string);
803 SEND_STRING ("\n");
804
805 return s;
806}
807
808#if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
46cec291 809
9f637eea
GM
810/* Three possibilities:
811 2 - can't be `stat'ed (sets errno)
812 1 - isn't owned by us
813 0 - success: none of the above */
814
815static int
816socket_status (socket_name)
817 char *socket_name;
818{
819 struct stat statbfr;
820
821 if (stat (socket_name, &statbfr) == -1)
822 return 2;
823
824 if (statbfr.st_uid != geteuid ())
825 return 1;
826
827 return 0;
828}
829
aa0b6932
JB
830HSOCKET
831set_local_socket ()
46cec291 832{
aa0b6932 833 HSOCKET s;
46cec291 834 struct sockaddr_un server;
46cec291 835
e69233c2 836 /*
46cec291
RS
837 * Open up an AF_UNIX socket in this person's home directory
838 */
839
840 if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
841 {
42073bfb 842 message (TRUE, "%s: socket: %s\n", progname, strerror (errno));
aa0b6932 843 return INVALID_SOCKET;
46cec291 844 }
e69233c2 845
46cec291 846 server.sun_family = AF_UNIX;
c5fee545 847
c5fee545 848 {
9f637eea 849 int sock_status = 0;
5c9659d3 850 int default_sock = !socket_name;
152b6e83 851 int saved_errno;
0734b0d0
SM
852 char *server_name = "server";
853
854 if (socket_name && !index (socket_name, '/') && !index (socket_name, '\\'))
855 { /* socket_name is a file name component. */
856 server_name = socket_name;
857 socket_name = NULL;
858 default_sock = 1; /* Try both UIDs. */
859 }
efb859b4 860
5c9659d3 861 if (default_sock)
254107e4 862 {
0734b0d0
SM
863 socket_name = alloca (100 + strlen (server_name));
864 sprintf (socket_name, "/tmp/emacs%d/%s",
865 (int) geteuid (), server_name);
254107e4
RS
866 }
867
868 if (strlen (socket_name) < sizeof (server.sun_path))
869 strcpy (server.sun_path, socket_name);
870 else
5c9659d3 871 {
42073bfb 872 message (TRUE, "%s: socket-name %s too long",
aa0b6932 873 progname, socket_name);
65396510 874 exit (EXIT_FAILURE);
5c9659d3 875 }
efb859b4 876
9f637eea
GM
877 /* See if the socket exists, and if it's owned by us. */
878 sock_status = socket_status (server.sun_path);
152b6e83 879 saved_errno = errno;
5c9659d3 880 if (sock_status && default_sock)
efb859b4 881 {
9f637eea
GM
882 /* Failing that, see if LOGNAME or USER exist and differ from
883 our euid. If so, look for a socket based on the UID
884 associated with the name. This is reminiscent of the logic
885 that init_editfns uses to set the global Vuser_full_name. */
e69233c2 886
70cd9104 887 char *user_name = (char *) egetenv ("LOGNAME");
293f9f2a 888
9f637eea 889 if (!user_name)
70cd9104 890 user_name = (char *) egetenv ("USER");
e69233c2 891
9f637eea
GM
892 if (user_name)
893 {
894 struct passwd *pw = getpwnam (user_name);
293f9f2a 895
9f637eea
GM
896 if (pw && (pw->pw_uid != geteuid ()))
897 {
898 /* We're running under su, apparently. */
0734b0d0
SM
899 socket_name = alloca (100 + strlen (server_name));
900 sprintf (socket_name, "/tmp/emacs%d/%s",
901 (int) pw->pw_uid, server_name);
5c9659d3
SM
902
903 if (strlen (socket_name) < sizeof (server.sun_path))
904 strcpy (server.sun_path, socket_name);
905 else
906 {
42073bfb 907 message (TRUE, "%s: socket-name %s too long",
aa0b6932 908 progname, socket_name);
65396510 909 exit (EXIT_FAILURE);
5c9659d3
SM
910 }
911
9f637eea 912 sock_status = socket_status (server.sun_path);
152b6e83 913 saved_errno = errno;
9f637eea 914 }
293f9f2a
RS
915 else
916 errno = saved_errno;
9f637eea 917 }
efb859b4 918 }
e69233c2 919
aa0b6932
JB
920 switch (sock_status)
921 {
922 case 1:
923 /* There's a socket, but it isn't owned by us. This is OK if
924 we are root. */
925 if (0 != geteuid ())
926 {
42073bfb 927 message (TRUE, "%s: Invalid socket owner\n", progname);
aa0b6932
JB
928 return INVALID_SOCKET;
929 }
930 break;
931
932 case 2:
933 /* `stat' failed */
934 if (saved_errno == ENOENT)
42073bfb 935 message (TRUE,
aa0b6932 936 "%s: can't find socket; have you started the server?\n\
45adde32 937To start the server in Emacs, type \"M-x server-start\".\n",
aa0b6932
JB
938 progname);
939 else
42073bfb 940 message (TRUE, "%s: can't stat %s: %s\n",
aa0b6932 941 progname, server.sun_path, strerror (saved_errno));
b03d27bd 942 return INVALID_SOCKET;
aa0b6932 943 }
efb859b4 944 }
46cec291 945
4e23f2ba
JB
946 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
947 < 0)
46cec291 948 {
42073bfb 949 message (TRUE, "%s: connect: %s\n", progname, strerror (errno));
aa0b6932 950 return INVALID_SOCKET;
46cec291 951 }
23a7488d 952
aa0b6932
JB
953 return s;
954}
955#endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
956
957HSOCKET
958set_socket ()
959{
b03d27bd
JB
960 HSOCKET s;
961
962 INITIALIZE ();
963
aa0b6932 964#ifndef NO_SOCKETS_IN_FILE_SYSTEM
b03d27bd
JB
965 /* Explicit --socket-name argument. */
966 if (socket_name)
967 {
968 s = set_local_socket ();
969 if ((s != INVALID_SOCKET) || alternate_editor)
970 return s;
971
42073bfb 972 message (TRUE, "%s: error accessing socket \"%s\"",
b03d27bd
JB
973 progname, socket_name);
974 exit (EXIT_FAILURE);
975 }
976#endif
977
978 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
979 if (!server_file)
70cd9104 980 server_file = egetenv ("EMACS_SERVER_FILE");
b03d27bd
JB
981
982 if (server_file)
46cec291 983 {
b03d27bd
JB
984 s = set_tcp_socket ();
985 if ((s != INVALID_SOCKET) || alternate_editor)
986 return s;
987
42073bfb 988 message (TRUE, "%s: error accessing server file \"%s\"",
b03d27bd
JB
989 progname, server_file);
990 exit (EXIT_FAILURE);
46cec291 991 }
b03d27bd
JB
992
993#ifndef NO_SOCKETS_IN_FILE_SYSTEM
994 /* Implicit local socket. */
995 s = set_local_socket ();
996 if (s != INVALID_SOCKET)
997 return s;
998#endif
999
1000 /* Implicit server file. */
1001 server_file = "server";
1002 s = set_tcp_socket ();
1003 if ((s != INVALID_SOCKET) || alternate_editor)
1004 return s;
1005
1006 /* No implicit or explicit socket, and no alternate editor. */
42073bfb 1007 message (TRUE, "%s: No socket or alternate editor. Please use:\n\n"
b03d27bd
JB
1008#ifndef NO_SOCKETS_IN_FILE_SYSTEM
1009"\t--socket-name\n"
aa0b6932 1010#endif
b03d27bd
JB
1011"\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1012\t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1013 progname);
1014 exit (EXIT_FAILURE);
aa0b6932 1015}
46cec291 1016
0e0dced5
JB
1017#ifdef WINDOWSNT
1018FARPROC set_fg; /* Pointer to AllowSetForegroundWindow. */
1019FARPROC get_wc; /* Pointer to RealGetWindowClassA. */
1020
1021BOOL CALLBACK
1022w32_find_emacs_process (hWnd, lParam)
1023 HWND hWnd;
1024 LPARAM lParam;
1025{
1026 DWORD pid;
1027 char class[6];
1028
1029 /* Reject any window not of class "Emacs". */
1030 if (! get_wc (hWnd, class, sizeof (class))
1031 || strcmp (class, "Emacs"))
1032 return TRUE;
1033
1034 /* We only need the process id, not the thread id. */
1035 (void) GetWindowThreadProcessId (hWnd, &pid);
1036
1037 /* Not the one we're looking for. */
1038 if (pid != (DWORD) emacs_pid) return TRUE;
1039
1040 /* OK, let's raise it. */
1041 set_fg (emacs_pid);
1042
1043 /* Stop enumeration. */
1044 return FALSE;
1045}
1046
1047/*
1048 * Search for a window of class "Emacs" and owned by a process with
1049 * process id = emacs_pid. If found, allow it to grab the focus.
1050 */
1051void
1052w32_give_focus ()
1053{
1054 HMODULE hUser32;
1055
71b8f735 1056 /* It shouldn't happen when dealing with TCP sockets. */
0e0dced5
JB
1057 if (!emacs_pid) return;
1058
1059 if (!(hUser32 = LoadLibrary ("user32.dll"))) return;
1060
1061 /* Modern Windows restrict which processes can set the foreground window.
1062 emacsclient can allow Emacs to grab the focus by calling the function
1063 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1064 NT) lack this function, so we have to check its availability. */
1065 if ((set_fg = GetProcAddress (hUser32, "AllowSetForegroundWindow"))
1066 && (get_wc = GetProcAddress (hUser32, "RealGetWindowClassA")))
1067 EnumWindows (w32_find_emacs_process, (LPARAM) 0);
1068
1069 FreeLibrary (hUser32);
1070}
1071#endif
1072
aa0b6932
JB
1073int
1074main (argc, argv)
1075 int argc;
1076 char **argv;
1077{
1078 HSOCKET s;
1079 int i, rl, needlf = 0;
1080 char *cwd;
1081 char string[BUFSIZ+1];
1082
1083 progname = argv[0];
1084
1085 /* Process options. */
1086 decode_options (argc, argv);
1087
1088 if ((argc - optind < 1) && !eval)
23a7488d 1089 {
42073bfb
JB
1090 message (TRUE, "%s: file name or argument required\nTry `%s --help' for more information\n",
1091 progname, progname);
aa0b6932 1092 exit (EXIT_FAILURE);
23a7488d
RS
1093 }
1094
aa0b6932
JB
1095 if ((s = set_socket ()) == INVALID_SOCKET)
1096 fail (argc, argv);
1097
38732dba 1098#ifdef HAVE_GETCWD
ee6a193c 1099 cwd = getcwd (string, sizeof string);
38732dba
RS
1100#else
1101 cwd = getwd (string);
ee6a193c 1102#endif
46cec291
RS
1103 if (cwd == 0)
1104 {
1105 /* getwd puts message in STRING if it fails. */
42073bfb 1106 message (TRUE, "%s: %s (%s)\n", progname,
c66648e0
JB
1107#ifdef HAVE_GETCWD
1108 "Cannot get current working directory",
38732dba 1109#else
c66648e0 1110 string,
bd252662 1111#endif
c66648e0 1112 strerror (errno));
97e3214d 1113 fail (argc, argv);
46cec291
RS
1114 }
1115
c66648e0 1116#ifdef WINDOWSNT
0e0dced5 1117 w32_give_focus ();
c66648e0
JB
1118#endif
1119
5212210c 1120 if (nowait)
aa0b6932 1121 SEND_STRING ("-nowait ");
292d74a3 1122
30be2360 1123 if (eval)
aa0b6932 1124 SEND_STRING ("-eval ");
30be2360
SM
1125
1126 if (display)
87209357 1127 {
aa0b6932
JB
1128 SEND_STRING ("-display ");
1129 SEND_QUOTED (display);
1130 SEND_STRING (" ");
87209357 1131 }
30be2360 1132
87209357 1133 if ((argc - optind > 0))
5212210c 1134 {
87209357 1135 for (i = optind; i < argc; i++)
46cec291 1136 {
87209357
EZ
1137 if (eval)
1138 ; /* Don't prepend any cwd or anything like that. */
1139 else if (*argv[i] == '+')
1140 {
1141 char *p = argv[i] + 1;
1142 while (isdigit ((unsigned char) *p) || *p == ':') p++;
1143 if (*p != 0)
1144 {
aa0b6932
JB
1145 SEND_QUOTED (cwd);
1146 SEND_STRING ("/");
87209357
EZ
1147 }
1148 }
b03d27bd 1149 else if (! file_name_absolute_p (argv[i]))
87209357 1150 {
aa0b6932
JB
1151 SEND_QUOTED (cwd);
1152 SEND_STRING ("/");
87209357
EZ
1153 }
1154
aa0b6932
JB
1155 SEND_QUOTED (argv[i]);
1156 SEND_STRING (" ");
46cec291 1157 }
46cec291 1158 }
87209357
EZ
1159 else
1160 {
aa0b6932 1161 while (fgets (string, BUFSIZ, stdin))
87209357 1162 {
aa0b6932 1163 SEND_QUOTED (string);
87209357 1164 }
aa0b6932 1165 SEND_STRING (" ");
87209357 1166 }
65396510 1167
aa0b6932 1168 SEND_STRING ("\n");
46cec291 1169
292d74a3 1170 /* Maybe wait for an answer. */
aa0b6932 1171 if (!nowait)
30be2360 1172 {
aa0b6932
JB
1173 if (!eval)
1174 {
1175 printf ("Waiting for Emacs...");
1176 needlf = 2;
1177 }
1178 fflush (stdout);
1179
1180 /* Now, wait for an answer and print any messages. */
1181 while ((rl = recv (s, string, BUFSIZ, 0)) > 0)
1182 {
1183 string[rl] = '\0';
1184 if (needlf == 2)
1185 printf ("\n");
1186 printf ("%s", string);
1187 needlf = string[0] == '\0' ? needlf : string[strlen (string) - 1] != '\n';
1188 }
1189
1190 if (needlf)
1191 printf ("\n");
1192 fflush (stdout);
30be2360 1193 }
23a7488d 1194
aa0b6932 1195 CLOSE_SOCKET (s);
65396510 1196 return EXIT_SUCCESS;
46cec291
RS
1197}
1198
1e7823d0 1199#endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
aa0b6932 1200
27711600
RM
1201#ifndef HAVE_STRERROR
1202char *
1203strerror (errnum)
1204 int errnum;
1205{
1206 extern char *sys_errlist[];
1207 extern int sys_nerr;
1208
1209 if (errnum >= 0 && errnum < sys_nerr)
1210 return sys_errlist[errnum];
1211 return (char *) "Unknown error";
1212}
1213
1214#endif /* ! HAVE_STRERROR */
ab5796a9
MB
1215
1216/* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
1217 (do not change this comment) */
65396510
TTN
1218
1219/* emacsclient.c ends here */