(mac_cg_color_space_rgb) [USE_CG_DRAWING]:
[emacs.git] / lib-src / emacsclient.c
blobe2db67a4a84dcf271905f9d1868940f159f57bdd
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, 2008 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
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.
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.
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. */
23 #define NO_SHORTNAMES
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
29 #ifdef WINDOWSNT
31 /* config.h defines these, which disables sockets altogether! */
32 # undef _WINSOCKAPI_
33 # undef _WINSOCK_H
35 # include <malloc.h>
36 # include <stdlib.h>
37 # include <windows.h>
38 # include <commctrl.h>
40 # define NO_SOCKETS_IN_FILE_SYSTEM
42 # define HSOCKET SOCKET
43 # define CLOSE_SOCKET closesocket
44 # define INITIALIZE() (initialize_sockets ())
46 #else /* !WINDOWSNT */
48 # include <sys/types.h>
50 # ifdef HAVE_INET_SOCKETS
51 # include <netinet/in.h>
52 # endif
54 # define INVALID_SOCKET -1
55 # define HSOCKET int
56 # define CLOSE_SOCKET close
57 # define INITIALIZE()
59 #endif /* !WINDOWSNT */
61 #undef signal
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
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 */
81 char *getenv (), *getwd ();
82 char *(getcwd) ();
84 #ifdef WINDOWSNT
85 char *w32_getenv ();
86 #define egetenv(VAR) w32_getenv(VAR)
87 #else
88 #define egetenv(VAR) getenv(VAR)
89 #endif
91 #ifndef VERSION
92 #define VERSION "unspecified"
93 #endif
95 #define SEND_STRING(data) (send_to_emacs (s, (data)))
96 #define SEND_QUOTED(data) (quote_file_name (s, (data)))
98 #ifndef EXIT_SUCCESS
99 #define EXIT_SUCCESS 0
100 #endif
102 #ifndef EXIT_FAILURE
103 #define EXIT_FAILURE 1
104 #endif
106 #ifndef FALSE
107 #define FALSE 0
108 #endif
110 #ifndef TRUE
111 #define TRUE 1
112 #endif
114 #ifndef NO_RETURN
115 #define NO_RETURN
116 #endif
118 /* Name used to invoke this program. */
119 char *progname;
121 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
122 int nowait = 0;
124 /* Nonzero means args are expressions to be evaluated. --eval. */
125 int eval = 0;
127 /* The display on which Emacs should work. --display. */
128 char *display = NULL;
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;
134 /* If non-NULL, the filename of the UNIX socket. */
135 char *socket_name = NULL;
137 /* If non-NULL, the filename of the authentication file. */
138 char *server_file = NULL;
140 /* PID of the Emacs server process. */
141 int emacs_pid = 0;
143 void print_help_and_exit () NO_RETURN;
145 struct option longopts[] =
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 }
161 /* Like malloc but get fatal error if memory is exhausted. */
163 long *
164 xmalloc (size)
165 unsigned int size;
167 long *result = (long *) malloc (size);
168 if (result == NULL)
170 perror ("malloc");
171 exit (EXIT_FAILURE);
173 return result;
176 /* Message functions. */
178 #ifdef WINDOWSNT
180 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
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;
191 HKEY hrootkey = NULL;
192 char *result = NULL;
193 DWORD cbData;
195 if (RegOpenKeyEx (predefined, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
197 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS)
199 result = (char *) xmalloc (cbData);
201 if ((RegQueryValueEx (hrootkey, key, NULL, type, result, &cbData) != ERROR_SUCCESS) ||
202 (*result == 0))
204 free (result);
205 result = NULL;
209 RegCloseKey (hrootkey);
212 return result;
216 getenv wrapper for Windows
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.
221 char *
222 w32_getenv (envvar)
223 char *envvar;
225 char *value;
226 DWORD dwType;
228 if (value = getenv (envvar))
229 /* Found in the environment. */
230 return value;
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;
237 if (dwType == REG_SZ)
238 /* Registry; no need to expand. */
239 return value;
241 if (dwType == REG_EXPAND_SZ)
243 DWORD size;
245 if (size = ExpandEnvironmentStrings (value, NULL, 0))
247 char *buffer = (char *) xmalloc (size);
248 if (ExpandEnvironmentStrings (value, buffer, size))
250 /* Found and expanded. */
251 free (value);
252 return buffer;
255 /* Error expanding. */
256 free (buffer);
260 /* Not the right type, or not correctly expanded. */
261 free (value);
262 return NULL;
266 w32_window_app ()
268 static int window_app = -1;
269 char szTitle[MAX_PATH];
271 if (window_app < 0)
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();
280 return window_app;
282 #endif
284 void
285 message (int is_error, char *message, ...)
287 char msg [2048];
288 va_list args;
290 va_start (args, message);
291 vsprintf (msg, message, args);
292 va_end (args);
294 #ifdef WINDOWSNT
295 if (w32_window_app ())
297 if (is_error)
298 MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
299 else
300 MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
302 else
303 #endif
305 FILE *f = is_error ? stderr : stdout;
307 fputs (msg, f);
308 fflush (f);
312 /* Decode the options from argv and argc.
313 The global variable `optind' will say how many arguments we used up. */
315 void
316 decode_options (argc, argv)
317 int argc;
318 char **argv;
320 alternate_editor = egetenv ("ALTERNATE_EDITOR");
322 while (1)
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);
332 if (opt == EOF)
333 break;
335 switch (opt)
337 case 0:
338 /* If getopt returns 0, then it has already processed a
339 long-named option. We should do nothing. */
340 break;
342 case 'a':
343 alternate_editor = optarg;
344 break;
346 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
347 case 's':
348 socket_name = optarg;
349 break;
350 #endif
352 case 'f':
353 server_file = optarg;
354 break;
356 case 'd':
357 display = optarg;
358 break;
360 case 'n':
361 nowait = 1;
362 break;
364 case 'e':
365 eval = 1;
366 break;
368 case 'V':
369 message (FALSE, "emacsclient %s\n", VERSION);
370 exit (EXIT_SUCCESS);
371 break;
373 case 'H':
374 print_help_and_exit ();
375 break;
377 default:
378 message (TRUE, "Try `%s --help' for more information\n", progname);
379 exit (EXIT_FAILURE);
380 break;
385 void
386 print_help_and_exit ()
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\
393 The following OPTIONS are accepted:\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\
409 Report bugs to bug-gnu-emacs@gnu.org.\n", progname);
410 exit (EXIT_SUCCESS);
414 #ifdef WINDOWSNT
417 execvp wrapper for Windows. Quotes arguments with embedded spaces.
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.
426 w32_execvp (path, argv)
427 char *path;
428 char **argv;
430 int i;
432 /* Required to allow a .BAT script as alternate editor. */
433 argv[0] = (char *) alternate_editor;
435 for (i = 0; argv[i]; i++)
436 if (strchr (argv[i], ' '))
438 char *quoted = alloca (strlen (argv[i]) + 3);
439 sprintf (quoted, "\"%s\"", argv[i]);
440 argv[i] = quoted;
443 return execvp (path, argv);
446 #undef execvp
447 #define execvp w32_execvp
449 #endif /* WINDOWSNT */
452 Try to run a different command, or --if no alternate editor is
453 defined-- exit with an errorcode.
455 void
456 fail (argc, argv)
457 int argc;
458 char **argv;
460 if (alternate_editor)
462 int i = optind - 1;
464 execvp (alternate_editor, argv + i);
465 message (TRUE, "%s: error executing alternate editor \"%s\"\n",
466 progname, alternate_editor);
468 exit (EXIT_FAILURE);
472 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
475 main (argc, argv)
476 int argc;
477 char **argv;
479 message (TRUE, "%s: Sorry, the Emacs server is supported only\non systems with Berkely sockets.\n",
480 argv[0]);
482 fail (argc, argv);
485 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
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
497 #define AUTH_KEY_LENGTH 64
498 #define SEND_BUFFER_SIZE 4096
500 extern char *strerror ();
501 extern int errno;
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. */
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;
513 #ifdef WINDOWSNT
514 char* msg = NULL;
516 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
517 | FORMAT_MESSAGE_ALLOCATE_BUFFER
518 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
519 NULL, WSAGetLastError (), 0, (LPTSTR)&msg, 0, NULL);
521 message (TRUE, "%s: %s: %s\n", progname, function_name, msg);
523 LocalFree (msg);
524 #else
525 message (TRUE, "%s: %s: %s\n", progname, function_name, strerror (errno));
526 #endif
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;
539 while (data)
541 int dlen = strlen (data);
542 if (dlen + sblen >= SEND_BUFFER_SIZE)
544 int part = SEND_BUFFER_SIZE - sblen;
545 strncpy (&send_buffer[sblen], data, part);
546 data += part;
547 sblen = SEND_BUFFER_SIZE;
549 else if (dlen)
551 strcpy (&send_buffer[sblen], data);
552 data = NULL;
553 sblen += dlen;
555 else
556 break;
558 if (sblen == SEND_BUFFER_SIZE
559 || (sblen > 0 && send_buffer[sblen-1] == '\n'))
561 int sent = send (s, send_buffer, sblen, 0);
562 if (sent != sblen)
563 strcpy (send_buffer, &send_buffer[sent]);
564 sblen -= sent;
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;
577 char *copy = (char *) xmalloc (strlen (name) * 2 + 1);
578 char *p, *q;
580 p = name;
581 q = copy;
582 while (*p)
584 if (*p == ' ')
586 *q++ = '&';
587 *q++ = '_';
588 p++;
590 else if (*p == '\n')
592 *q++ = '&';
593 *q++ = 'n';
594 p++;
596 else
598 if (*p == '&' || (*p == '-' && p == name))
599 *q++ = '&';
600 *q++ = *p++;
603 *q++ = 0;
605 SEND_STRING (copy);
607 free (copy);
611 file_name_absolute_p (filename)
612 const unsigned char *filename;
614 /* Sanity check, it shouldn't happen. */
615 if (! filename) return FALSE;
617 /* /xxx is always an absolute path. */
618 if (filename[0] == '/') return TRUE;
620 /* Empty filenames (which shouldn't happen) are relative. */
621 if (filename[0] == '\0') return FALSE;
623 #ifdef WINDOWSNT
624 /* X:\xxx is always absolute. */
625 if (isalpha (filename[0])
626 && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
627 return TRUE;
629 /* Both \xxx and \\xxx\yyy are absolute. */
630 if (filename[0] == '\\') return TRUE;
633 FIXME: There's a corner case not dealt with, "x:y", where:
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.
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.
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.
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.
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.
661 Anyway, something to decide After the Release.
663 #endif
665 return FALSE;
668 #ifdef WINDOWSNT
669 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
670 void
671 __cdecl close_winsock ()
673 WSACleanup ();
676 /* Initialize the WinSock2 library. */
677 void
678 initialize_sockets ()
680 WSADATA wsaData;
682 if (WSAStartup (MAKEWORD (2, 0), &wsaData))
684 message (TRUE, "%s: error initializing WinSock2", progname);
685 exit (EXIT_FAILURE);
688 atexit (close_winsock);
690 #endif /* WINDOWSNT */
693 * Read the information needed to set up a TCP comm channel with
694 * the Emacs server: host, port, pid and authentication string.
697 get_server_config (server, authentication)
698 struct sockaddr_in *server;
699 char *authentication;
701 char dotted[32];
702 char *port;
703 char *pid;
704 FILE *config = NULL;
706 if (file_name_absolute_p (server_file))
707 config = fopen (server_file, "rb");
708 else
710 char *home = egetenv ("HOME");
712 if (home)
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");
718 #ifdef WINDOWSNT
719 if (!config && (home = egetenv ("APPDATA")))
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");
725 #endif
728 if (! config)
729 return FALSE;
731 if (fgets (dotted, sizeof dotted, config)
732 && (port = strchr (dotted, ':'))
733 && (pid = strchr (port, ' ')))
735 *port++ = '\0';
736 *pid++ = '\0';
738 else
740 message (TRUE, "%s: invalid configuration info", progname);
741 exit (EXIT_FAILURE);
744 server->sin_family = AF_INET;
745 server->sin_addr.s_addr = inet_addr (dotted);
746 server->sin_port = htons (atoi (port));
748 if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
750 message (TRUE, "%s: cannot read authentication info", progname);
751 exit (EXIT_FAILURE);
754 fclose (config);
756 emacs_pid = atoi (pid);
758 return TRUE;
761 HSOCKET
762 set_tcp_socket ()
764 HSOCKET s;
765 struct sockaddr_in server;
766 struct linger l_arg = {1, 1};
767 char auth_string[AUTH_KEY_LENGTH + 1];
769 if (! get_server_config (&server, auth_string))
770 return INVALID_SOCKET;
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));
777 * Open up an AF_INET socket
779 if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
781 sock_err_message ("socket");
782 return INVALID_SOCKET;
786 * Set up the socket
788 if (connect (s, (struct sockaddr *) &server, sizeof server) < 0)
790 sock_err_message ("connect");
791 return INVALID_SOCKET;
794 setsockopt (s, SOL_SOCKET, SO_LINGER, (char *) &l_arg, sizeof l_arg);
797 * Send the authentication
799 auth_string[AUTH_KEY_LENGTH] = '\0';
801 SEND_STRING ("-auth ");
802 SEND_STRING (auth_string);
803 SEND_STRING ("\n");
805 return s;
808 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
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 */
815 static int
816 socket_status (socket_name)
817 char *socket_name;
819 struct stat statbfr;
821 if (stat (socket_name, &statbfr) == -1)
822 return 2;
824 if (statbfr.st_uid != geteuid ())
825 return 1;
827 return 0;
830 HSOCKET
831 set_local_socket ()
833 HSOCKET s;
834 struct sockaddr_un server;
837 * Open up an AF_UNIX socket in this person's home directory
840 if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
842 message (TRUE, "%s: socket: %s\n", progname, strerror (errno));
843 return INVALID_SOCKET;
846 server.sun_family = AF_UNIX;
849 int sock_status = 0;
850 int default_sock = !socket_name;
851 int saved_errno;
852 char *server_name = "server";
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. */
861 if (default_sock)
863 socket_name = alloca (100 + strlen (server_name));
864 sprintf (socket_name, "/tmp/emacs%d/%s",
865 (int) geteuid (), server_name);
868 if (strlen (socket_name) < sizeof (server.sun_path))
869 strcpy (server.sun_path, socket_name);
870 else
872 message (TRUE, "%s: socket-name %s too long",
873 progname, socket_name);
874 exit (EXIT_FAILURE);
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)
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. */
887 char *user_name = (char *) egetenv ("LOGNAME");
889 if (!user_name)
890 user_name = (char *) egetenv ("USER");
892 if (user_name)
894 struct passwd *pw = getpwnam (user_name);
896 if (pw && (pw->pw_uid != geteuid ()))
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);
903 if (strlen (socket_name) < sizeof (server.sun_path))
904 strcpy (server.sun_path, socket_name);
905 else
907 message (TRUE, "%s: socket-name %s too long",
908 progname, socket_name);
909 exit (EXIT_FAILURE);
912 sock_status = socket_status (server.sun_path);
913 saved_errno = errno;
915 else
916 errno = saved_errno;
920 switch (sock_status)
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 ())
927 message (TRUE, "%s: Invalid socket owner\n", progname);
928 return INVALID_SOCKET;
930 break;
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;
946 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
947 < 0)
949 message (TRUE, "%s: connect: %s\n", progname, strerror (errno));
950 return INVALID_SOCKET;
953 return s;
955 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
957 HSOCKET
958 set_socket ()
960 HSOCKET s;
962 INITIALIZE ();
964 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
965 /* Explicit --socket-name argument. */
966 if (socket_name)
968 s = set_local_socket ();
969 if ((s != INVALID_SOCKET) || alternate_editor)
970 return s;
972 message (TRUE, "%s: error accessing socket \"%s\"",
973 progname, socket_name);
974 exit (EXIT_FAILURE);
976 #endif
978 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
979 if (!server_file)
980 server_file = egetenv ("EMACS_SERVER_FILE");
982 if (server_file)
984 s = set_tcp_socket ();
985 if ((s != INVALID_SOCKET) || alternate_editor)
986 return s;
988 message (TRUE, "%s: error accessing server file \"%s\"",
989 progname, server_file);
990 exit (EXIT_FAILURE);
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
1000 /* Implicit server file. */
1001 server_file = "server";
1002 s = set_tcp_socket ();
1003 if ((s != INVALID_SOCKET) || alternate_editor)
1004 return s;
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);
1017 #ifdef WINDOWSNT
1018 FARPROC set_fg; /* Pointer to AllowSetForegroundWindow. */
1019 FARPROC get_wc; /* Pointer to RealGetWindowClassA. */
1021 BOOL CALLBACK
1022 w32_find_emacs_process (hWnd, lParam)
1023 HWND hWnd;
1024 LPARAM lParam;
1026 DWORD pid;
1027 char class[6];
1029 /* Reject any window not of class "Emacs". */
1030 if (! get_wc (hWnd, class, sizeof (class))
1031 || strcmp (class, "Emacs"))
1032 return TRUE;
1034 /* We only need the process id, not the thread id. */
1035 (void) GetWindowThreadProcessId (hWnd, &pid);
1037 /* Not the one we're looking for. */
1038 if (pid != (DWORD) emacs_pid) return TRUE;
1040 /* OK, let's raise it. */
1041 set_fg (emacs_pid);
1043 /* Stop enumeration. */
1044 return FALSE;
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.
1051 void
1052 w32_give_focus ()
1054 HMODULE hUser32;
1056 /* It shouldn't happen when dealing with TCP sockets. */
1057 if (!emacs_pid) return;
1059 if (!(hUser32 = LoadLibrary ("user32.dll"))) return;
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);
1069 FreeLibrary (hUser32);
1071 #endif
1074 main (argc, argv)
1075 int argc;
1076 char **argv;
1078 HSOCKET s;
1079 int i, rl, needlf = 0;
1080 char *cwd;
1081 char string[BUFSIZ+1];
1083 progname = argv[0];
1085 /* Process options. */
1086 decode_options (argc, argv);
1088 if ((argc - optind < 1) && !eval)
1090 message (TRUE, "%s: file name or argument required\nTry `%s --help' for more information\n",
1091 progname, progname);
1092 exit (EXIT_FAILURE);
1095 if ((s = set_socket ()) == INVALID_SOCKET)
1096 fail (argc, argv);
1098 #ifdef HAVE_GETCWD
1099 cwd = getcwd (string, sizeof string);
1100 #else
1101 cwd = getwd (string);
1102 #endif
1103 if (cwd == 0)
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);
1116 #ifdef WINDOWSNT
1117 w32_give_focus ();
1118 #endif
1120 if (nowait)
1121 SEND_STRING ("-nowait ");
1123 if (eval)
1124 SEND_STRING ("-eval ");
1126 if (display)
1128 SEND_STRING ("-display ");
1129 SEND_QUOTED (display);
1130 SEND_STRING (" ");
1133 if ((argc - optind > 0))
1135 for (i = optind; i < argc; i++)
1137 if (eval)
1138 ; /* Don't prepend any cwd or anything like that. */
1139 else if (*argv[i] == '+')
1141 char *p = argv[i] + 1;
1142 while (isdigit ((unsigned char) *p) || *p == ':') p++;
1143 if (*p != 0)
1145 SEND_QUOTED (cwd);
1146 SEND_STRING ("/");
1149 else if (! file_name_absolute_p (argv[i]))
1151 SEND_QUOTED (cwd);
1152 SEND_STRING ("/");
1155 SEND_QUOTED (argv[i]);
1156 SEND_STRING (" ");
1159 else
1161 while (fgets (string, BUFSIZ, stdin))
1163 SEND_QUOTED (string);
1165 SEND_STRING (" ");
1168 SEND_STRING ("\n");
1170 /* Maybe wait for an answer. */
1171 if (!nowait)
1173 if (!eval)
1175 printf ("Waiting for Emacs...");
1176 needlf = 2;
1178 fflush (stdout);
1180 /* Now, wait for an answer and print any messages. */
1181 while ((rl = recv (s, string, BUFSIZ, 0)) > 0)
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';
1190 if (needlf)
1191 printf ("\n");
1192 fflush (stdout);
1195 CLOSE_SOCKET (s);
1196 return EXIT_SUCCESS;
1199 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
1201 #ifndef HAVE_STRERROR
1202 char *
1203 strerror (errnum)
1204 int errnum;
1206 extern char *sys_errlist[];
1207 extern int sys_nerr;
1209 if (errnum >= 0 && errnum < sys_nerr)
1210 return sys_errlist[errnum];
1211 return (char *) "Unknown error";
1214 #endif /* ! HAVE_STRERROR */
1216 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
1217 (do not change this comment) */
1219 /* emacsclient.c ends here */