]> code.delx.au - gnu-emacs/blob - lib-src/emacsclient.c
(Copyright): Update to 2008.
[gnu-emacs] / lib-src / emacsclient.c
1 /* Client process that communicates with GNU Emacs acting as server.
2 Copyright (C) 1986, 1987, 1994, 1999, 2000, 2001, 2002, 2003, 2004,
3 2005, 2006, 2007 Free Software Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA. */
21
22
23 #define NO_SHORTNAMES
24
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
28
29 #ifdef WINDOWSNT
30
31 /* config.h defines these, which disables sockets altogether! */
32 # undef _WINSOCKAPI_
33 # undef _WINSOCK_H
34
35 # include <malloc.h>
36 # include <stdlib.h>
37 # include <windows.h>
38 # include <commctrl.h>
39
40 # define NO_SOCKETS_IN_FILE_SYSTEM
41
42 # define HSOCKET SOCKET
43 # define CLOSE_SOCKET closesocket
44 # define INITIALIZE() (initialize_sockets ())
45
46 #else /* !WINDOWSNT */
47
48 # include <sys/types.h>
49
50 # ifdef HAVE_INET_SOCKETS
51 # include <netinet/in.h>
52 # endif
53
54 # define INVALID_SOCKET -1
55 # define HSOCKET int
56 # define CLOSE_SOCKET close
57 # define INITIALIZE()
58
59 #endif /* !WINDOWSNT */
60
61 #undef signal
62
63 #include <stdarg.h>
64 #include <ctype.h>
65 #include <stdio.h>
66 #include "getopt.h"
67 #ifdef HAVE_UNISTD_H
68 #include <unistd.h>
69 #endif
70
71 #ifdef VMS
72 # include "vms-pwd.h"
73 #else /* not VMS */
74 #ifdef WINDOWSNT
75 # include <io.h>
76 #else /* not WINDOWSNT */
77 # include <pwd.h>
78 #endif /* not WINDOWSNT */
79 #endif /* not VMS */
80
81 char *getenv (), *getwd ();
82 char *(getcwd) ();
83
84 #ifdef WINDOWSNT
85 char *w32_getenv ();
86 #define egetenv(VAR) w32_getenv(VAR)
87 #else
88 #define egetenv(VAR) getenv(VAR)
89 #endif
90
91 #ifndef VERSION
92 #define VERSION "unspecified"
93 #endif
94 \f
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
118 /* Name used to invoke this program. */
119 char *progname;
120
121 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
122 int nowait = 0;
123
124 /* Nonzero means args are expressions to be evaluated. --eval. */
125 int eval = 0;
126
127 /* The display on which Emacs should work. --display. */
128 char *display = NULL;
129
130 /* If non-NULL, the name of an editor to fallback to if the server
131 is not running. --alternate-editor. */
132 const char *alternate_editor = NULL;
133
134 /* If non-NULL, the filename of the UNIX socket. */
135 char *socket_name = NULL;
136
137 /* If non-NULL, the filename of the authentication file. */
138 char *server_file = NULL;
139
140 /* PID of the Emacs server process. */
141 int emacs_pid = 0;
142
143 void print_help_and_exit () NO_RETURN;
144
145 struct option longopts[] =
146 {
147 { "no-wait", no_argument, NULL, 'n' },
148 { "eval", no_argument, NULL, 'e' },
149 { "help", no_argument, NULL, 'H' },
150 { "version", no_argument, NULL, 'V' },
151 { "alternate-editor", required_argument, NULL, 'a' },
152 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
153 { "socket-name", required_argument, NULL, 's' },
154 #endif
155 { "server-file", required_argument, NULL, 'f' },
156 { "display", required_argument, NULL, 'd' },
157 { 0, 0, 0, 0 }
158 };
159
160 \f
161 /* Like malloc but get fatal error if memory is exhausted. */
162
163 long *
164 xmalloc (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
176 /* Message functions. */
177
178 #ifdef WINDOWSNT
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). */
185 char *
186 w32_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 */
221 char *
222 w32_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
265 int
266 w32_window_app ()
267 {
268 static int window_app = -1;
269 char szTitle[MAX_PATH];
270
271 if (window_app < 0)
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 }
279
280 return window_app;
281 }
282 #endif
283
284 void
285 message (int is_error, char *message, ...)
286 {
287 char msg [2048];
288 va_list args;
289
290 va_start (args, message);
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
304 {
305 FILE *f = is_error ? stderr : stdout;
306
307 fputs (msg, f);
308 fflush (f);
309 }
310 }
311
312 /* Decode the options from argv and argc.
313 The global variable `optind' will say how many arguments we used up. */
314
315 void
316 decode_options (argc, argv)
317 int argc;
318 char **argv;
319 {
320 alternate_editor = egetenv ("ALTERNATE_EDITOR");
321
322 while (1)
323 {
324 int opt = getopt_long (argc, argv,
325 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
326 "VHnea:s:f:d:",
327 #else
328 "VHnea:f:d:",
329 #endif
330 longopts, 0);
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;
341
342 case 'a':
343 alternate_editor = optarg;
344 break;
345
346 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
347 case 's':
348 socket_name = optarg;
349 break;
350 #endif
351
352 case 'f':
353 server_file = optarg;
354 break;
355
356 case 'd':
357 display = optarg;
358 break;
359
360 case 'n':
361 nowait = 1;
362 break;
363
364 case 'e':
365 eval = 1;
366 break;
367
368 case 'V':
369 message (FALSE, "emacsclient %s\n", VERSION);
370 exit (EXIT_SUCCESS);
371 break;
372
373 case 'H':
374 print_help_and_exit ();
375 break;
376
377 default:
378 message (TRUE, "Try `%s --help' for more information\n", progname);
379 exit (EXIT_FAILURE);
380 break;
381 }
382 }
383 }
384
385 void
386 print_help_and_exit ()
387 {
388 message (FALSE,
389 "Usage: %s [OPTIONS] FILE...\n\
390 Tell the Emacs server to visit the specified files.\n\
391 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
392 \n\
393 The following OPTIONS are accepted:\n\
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"
400 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
401 "-s, --socket-name=FILENAME\n\
402 Set filename of the UNIX socket for communication\n"
403 #endif
404 "-f, --server-file=FILENAME\n\
405 Set filename of the TCP authentication file\n\
406 -a, --alternate-editor=EDITOR\n\
407 Editor to fallback to if server is not running\n\
408 \n\
409 Report bugs to bug-gnu-emacs@gnu.org.\n", progname);
410 exit (EXIT_SUCCESS);
411 }
412
413 \f
414 #ifdef WINDOWSNT
415
416 /*
417 execvp wrapper for Windows. Quotes arguments with embedded spaces.
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
423 directly into the argv array of the child process.
424 */
425 int
426 w32_execvp (path, argv)
427 char *path;
428 char **argv;
429 {
430 int i;
431
432 /* Required to allow a .BAT script as alternate editor. */
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
451 /*
452 Try to run a different command, or --if no alternate editor is
453 defined-- exit with an errorcode.
454 */
455 void
456 fail (argc, argv)
457 int argc;
458 char **argv;
459 {
460 if (alternate_editor)
461 {
462 int i = optind - 1;
463
464 execvp (alternate_editor, argv + i);
465 message (TRUE, "%s: error executing alternate editor \"%s\"\n",
466 progname, alternate_editor);
467 }
468 exit (EXIT_FAILURE);
469 }
470
471 \f
472 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
473
474 int
475 main (argc, argv)
476 int argc;
477 char **argv;
478 {
479 message (TRUE, "%s: Sorry, the Emacs server is supported only\non systems with Berkely sockets.\n",
480 argv[0]);
481
482 fail (argc, argv);
483 }
484
485 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
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
500 extern char *strerror ();
501 extern int errno;
502
503 /* Buffer to accumulate data to send in TCP connections. */
504 char send_buffer[SEND_BUFFER_SIZE + 1];
505 int sblen = 0; /* Fill pointer for the send buffer. */
506
507 /* On Windows, the socket library was historically separate from the standard
508 C library, so errors are handled differently. */
509 void
510 sock_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
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. */
534 void
535 send_to_emacs (s, data)
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
569 /* In NAME, insert a & before each &, each space, each newline, and
570 any initial -. Change spaces to underscores, too, so that the
571 return value never contains a space. */
572 void
573 quote_file_name (s, name)
574 HSOCKET s;
575 char *name;
576 {
577 char *copy = (char *) xmalloc (strlen (name) * 2 + 1);
578 char *p, *q;
579
580 p = name;
581 q = copy;
582 while (*p)
583 {
584 if (*p == ' ')
585 {
586 *q++ = '&';
587 *q++ = '_';
588 p++;
589 }
590 else if (*p == '\n')
591 {
592 *q++ = '&';
593 *q++ = 'n';
594 p++;
595 }
596 else
597 {
598 if (*p == '&' || (*p == '-' && p == name))
599 *q++ = '&';
600 *q++ = *p++;
601 }
602 }
603 *q++ = 0;
604
605 SEND_STRING (copy);
606
607 free (copy);
608 }
609
610 int
611 file_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
624 /* X:\xxx is always absolute. */
625 if (isalpha (filename[0])
626 && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
627 return TRUE;
628
629 /* Both \xxx and \\xxx\yyy are absolute. */
630 if (filename[0] == '\\') return TRUE;
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 */
663 #endif
664
665 return FALSE;
666 }
667
668 #ifdef WINDOWSNT
669 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
670 void
671 __cdecl close_winsock ()
672 {
673 WSACleanup ();
674 }
675
676 /* Initialize the WinSock2 library. */
677 void
678 initialize_sockets ()
679 {
680 WSADATA wsaData;
681
682 if (WSAStartup (MAKEWORD (2, 0), &wsaData))
683 {
684 message (TRUE, "%s: error initializing WinSock2", progname);
685 exit (EXIT_FAILURE);
686 }
687
688 atexit (close_winsock);
689 }
690 #endif /* WINDOWSNT */
691 \f
692 /*
693 * Read the information needed to set up a TCP comm channel with
694 * the Emacs server: host, port, pid and authentication string.
695 */
696 int
697 get_server_config (server, authentication)
698 struct sockaddr_in *server;
699 char *authentication;
700 {
701 char dotted[32];
702 char *port;
703 char *pid;
704 FILE *config = NULL;
705
706 if (file_name_absolute_p (server_file))
707 config = fopen (server_file, "rb");
708 else
709 {
710 char *home = egetenv ("HOME");
711
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 }
718 #ifdef WINDOWSNT
719 if (!config && (home = egetenv ("APPDATA")))
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
726 }
727
728 if (! config)
729 return FALSE;
730
731 if (fgets (dotted, sizeof dotted, config)
732 && (port = strchr (dotted, ':'))
733 && (pid = strchr (port, ' ')))
734 {
735 *port++ = '\0';
736 *pid++ = '\0';
737 }
738 else
739 {
740 message (TRUE, "%s: invalid configuration info", progname);
741 exit (EXIT_FAILURE);
742 }
743
744 server->sin_family = AF_INET;
745 server->sin_addr.s_addr = inet_addr (dotted);
746 server->sin_port = htons (atoi (port));
747
748 if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
749 {
750 message (TRUE, "%s: cannot read authentication info", progname);
751 exit (EXIT_FAILURE);
752 }
753
754 fclose (config);
755
756 emacs_pid = atoi (pid);
757
758 return TRUE;
759 }
760
761 HSOCKET
762 set_tcp_socket ()
763 {
764 HSOCKET s;
765 struct sockaddr_in server;
766 struct linger l_arg = {1, 1};
767 char auth_string[AUTH_KEY_LENGTH + 1];
768
769 if (! get_server_config (&server, auth_string))
770 return INVALID_SOCKET;
771
772 if (server.sin_addr.s_addr != inet_addr ("127.0.0.1"))
773 message (FALSE, "%s: connected to remote socket at %s\n",
774 progname, inet_ntoa (server.sin_addr));
775
776 /*
777 * Open up an AF_INET socket
778 */
779 if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
780 {
781 sock_err_message ("socket");
782 return INVALID_SOCKET;
783 }
784
785 /*
786 * Set up the socket
787 */
788 if (connect (s, (struct sockaddr *) &server, sizeof server) < 0)
789 {
790 sock_err_message ("connect");
791 return INVALID_SOCKET;
792 }
793
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)
809
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
815 static int
816 socket_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
830 HSOCKET
831 set_local_socket ()
832 {
833 HSOCKET s;
834 struct sockaddr_un server;
835
836 /*
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 {
842 message (TRUE, "%s: socket: %s\n", progname, strerror (errno));
843 return INVALID_SOCKET;
844 }
845
846 server.sun_family = AF_UNIX;
847
848 {
849 int sock_status = 0;
850 int default_sock = !socket_name;
851 int saved_errno;
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 }
860
861 if (default_sock)
862 {
863 socket_name = alloca (100 + strlen (server_name));
864 sprintf (socket_name, "/tmp/emacs%d/%s",
865 (int) geteuid (), server_name);
866 }
867
868 if (strlen (socket_name) < sizeof (server.sun_path))
869 strcpy (server.sun_path, socket_name);
870 else
871 {
872 message (TRUE, "%s: socket-name %s too long",
873 progname, socket_name);
874 exit (EXIT_FAILURE);
875 }
876
877 /* See if the socket exists, and if it's owned by us. */
878 sock_status = socket_status (server.sun_path);
879 saved_errno = errno;
880 if (sock_status && default_sock)
881 {
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. */
886
887 char *user_name = (char *) egetenv ("LOGNAME");
888
889 if (!user_name)
890 user_name = (char *) egetenv ("USER");
891
892 if (user_name)
893 {
894 struct passwd *pw = getpwnam (user_name);
895
896 if (pw && (pw->pw_uid != geteuid ()))
897 {
898 /* We're running under su, apparently. */
899 socket_name = alloca (100 + strlen (server_name));
900 sprintf (socket_name, "/tmp/emacs%d/%s",
901 (int) pw->pw_uid, server_name);
902
903 if (strlen (socket_name) < sizeof (server.sun_path))
904 strcpy (server.sun_path, socket_name);
905 else
906 {
907 message (TRUE, "%s: socket-name %s too long",
908 progname, socket_name);
909 exit (EXIT_FAILURE);
910 }
911
912 sock_status = socket_status (server.sun_path);
913 saved_errno = errno;
914 }
915 else
916 errno = saved_errno;
917 }
918 }
919
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 {
927 message (TRUE, "%s: Invalid socket owner\n", progname);
928 return INVALID_SOCKET;
929 }
930 break;
931
932 case 2:
933 /* `stat' failed */
934 if (saved_errno == ENOENT)
935 message (TRUE,
936 "%s: can't find socket; have you started the server?\n\
937 To start the server in Emacs, type \"M-x server-start\".\n",
938 progname);
939 else
940 message (TRUE, "%s: can't stat %s: %s\n",
941 progname, server.sun_path, strerror (saved_errno));
942 return INVALID_SOCKET;
943 }
944 }
945
946 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
947 < 0)
948 {
949 message (TRUE, "%s: connect: %s\n", progname, strerror (errno));
950 return INVALID_SOCKET;
951 }
952
953 return s;
954 }
955 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
956
957 HSOCKET
958 set_socket ()
959 {
960 HSOCKET s;
961
962 INITIALIZE ();
963
964 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
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
972 message (TRUE, "%s: error accessing socket \"%s\"",
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)
980 server_file = egetenv ("EMACS_SERVER_FILE");
981
982 if (server_file)
983 {
984 s = set_tcp_socket ();
985 if ((s != INVALID_SOCKET) || alternate_editor)
986 return s;
987
988 message (TRUE, "%s: error accessing server file \"%s\"",
989 progname, server_file);
990 exit (EXIT_FAILURE);
991 }
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. */
1007 message (TRUE, "%s: No socket or alternate editor. Please use:\n\n"
1008 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1009 "\t--socket-name\n"
1010 #endif
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);
1015 }
1016
1017 #ifdef WINDOWSNT
1018 FARPROC set_fg; /* Pointer to AllowSetForegroundWindow. */
1019 FARPROC get_wc; /* Pointer to RealGetWindowClassA. */
1020
1021 BOOL CALLBACK
1022 w32_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 */
1051 void
1052 w32_give_focus ()
1053 {
1054 HMODULE hUser32;
1055
1056 /* It shouldn't happen when dealing with TCP sockets. */
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
1073 int
1074 main (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)
1089 {
1090 message (TRUE, "%s: file name or argument required\nTry `%s --help' for more information\n",
1091 progname, progname);
1092 exit (EXIT_FAILURE);
1093 }
1094
1095 if ((s = set_socket ()) == INVALID_SOCKET)
1096 fail (argc, argv);
1097
1098 #ifdef HAVE_GETCWD
1099 cwd = getcwd (string, sizeof string);
1100 #else
1101 cwd = getwd (string);
1102 #endif
1103 if (cwd == 0)
1104 {
1105 /* getwd puts message in STRING if it fails. */
1106 message (TRUE, "%s: %s (%s)\n", progname,
1107 #ifdef HAVE_GETCWD
1108 "Cannot get current working directory",
1109 #else
1110 string,
1111 #endif
1112 strerror (errno));
1113 fail (argc, argv);
1114 }
1115
1116 #ifdef WINDOWSNT
1117 w32_give_focus ();
1118 #endif
1119
1120 if (nowait)
1121 SEND_STRING ("-nowait ");
1122
1123 if (eval)
1124 SEND_STRING ("-eval ");
1125
1126 if (display)
1127 {
1128 SEND_STRING ("-display ");
1129 SEND_QUOTED (display);
1130 SEND_STRING (" ");
1131 }
1132
1133 if ((argc - optind > 0))
1134 {
1135 for (i = optind; i < argc; i++)
1136 {
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 {
1145 SEND_QUOTED (cwd);
1146 SEND_STRING ("/");
1147 }
1148 }
1149 else if (! file_name_absolute_p (argv[i]))
1150 {
1151 SEND_QUOTED (cwd);
1152 SEND_STRING ("/");
1153 }
1154
1155 SEND_QUOTED (argv[i]);
1156 SEND_STRING (" ");
1157 }
1158 }
1159 else
1160 {
1161 while (fgets (string, BUFSIZ, stdin))
1162 {
1163 SEND_QUOTED (string);
1164 }
1165 SEND_STRING (" ");
1166 }
1167
1168 SEND_STRING ("\n");
1169
1170 /* Maybe wait for an answer. */
1171 if (!nowait)
1172 {
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);
1193 }
1194
1195 CLOSE_SOCKET (s);
1196 return EXIT_SUCCESS;
1197 }
1198
1199 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
1200
1201 #ifndef HAVE_STRERROR
1202 char *
1203 strerror (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 */
1215
1216 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
1217 (do not change this comment) */
1218
1219 /* emacsclient.c ends here */