1 /* Client process that communicates with GNU Emacs acting as server.
2 Copyright (C) 1986-1987, 1994, 1999-2011 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
24 /* config.h defines these, which disables sockets altogether! */
31 # include <commctrl.h>
33 # include <winsock2.h>
35 # define NO_SOCKETS_IN_FILE_SYSTEM
37 # define HSOCKET SOCKET
38 # define CLOSE_SOCKET closesocket
39 # define INITIALIZE() (initialize_sockets ())
41 char *w32_getenv (char *);
42 #define egetenv(VAR) w32_getenv(VAR)
44 #else /* !WINDOWSNT */
48 # ifdef HAVE_INET_SOCKETS
49 # include <netinet/in.h>
51 # include <sys/types.h>
52 # include <sys/socket.h>
54 # endif /* HAVE_SOCKETS */
56 # include <arpa/inet.h>
58 # define INVALID_SOCKET -1
60 # define CLOSE_SOCKET close
67 #define egetenv(VAR) getenv(VAR)
69 #endif /* !WINDOWSNT */
86 char *getenv (const char *), *getwd (char *);
88 char *(getcwd
) (char *, size_t);
92 #define VERSION "unspecified"
97 #define EXIT_SUCCESS 0
101 #define EXIT_FAILURE 1
112 /* Additional space when allocating buffers for filenames, etc. */
113 #define EXTRA_SPACE 100
115 /* Use this to suppress gcc's `...may be used before initialized' warnings. */
117 # define IF_LINT(Code) Code
119 # define IF_LINT(Code) /* empty */
123 /* Name used to invoke this program. */
124 const char *progname
;
126 /* The second argument to main. */
129 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
132 /* Nonzero means don't print messages for successful operations. --quiet. */
135 /* Nonzero means args are expressions to be evaluated. --eval. */
138 /* Nonzero means don't open a new frame. Inverse of --create-frame. */
139 int current_frame
= 1;
141 /* The display on which Emacs should work. --display. */
142 const char *display
= NULL
;
144 /* The parent window ID, if we are opening a frame via XEmbed. */
145 char *parent_id
= NULL
;
147 /* Nonzero means open a new Emacs frame on the current terminal. */
150 /* If non-NULL, the name of an editor to fallback to if the server
151 is not running. --alternate-editor. */
152 const char *alternate_editor
= NULL
;
154 /* If non-NULL, the filename of the UNIX socket. */
155 char *socket_name
= NULL
;
157 /* If non-NULL, the filename of the authentication file. */
158 const char *server_file
= NULL
;
160 /* PID of the Emacs server process. */
163 static void print_help_and_exit (void) NO_RETURN
;
164 static void fail (void) NO_RETURN
;
167 struct option longopts
[] =
169 { "no-wait", no_argument
, NULL
, 'n' },
170 { "quiet", no_argument
, NULL
, 'q' },
171 { "eval", no_argument
, NULL
, 'e' },
172 { "help", no_argument
, NULL
, 'H' },
173 { "version", no_argument
, NULL
, 'V' },
174 { "tty", no_argument
, NULL
, 't' },
175 { "nw", no_argument
, NULL
, 't' },
176 { "create-frame", no_argument
, NULL
, 'c' },
177 { "alternate-editor", required_argument
, NULL
, 'a' },
178 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
179 { "socket-name", required_argument
, NULL
, 's' },
181 { "server-file", required_argument
, NULL
, 'f' },
183 { "display", required_argument
, NULL
, 'd' },
185 { "parent-id", required_argument
, NULL
, 'p' },
190 /* Like malloc but get fatal error if memory is exhausted. */
193 xmalloc (unsigned int size
)
195 long *result
= (long *) malloc (size
);
205 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
208 #ifndef DIRECTORY_SEP
209 #define DIRECTORY_SEP '/'
211 #ifndef IS_DIRECTORY_SEP
212 #define IS_DIRECTORY_SEP(_c_) ((_c_) == DIRECTORY_SEP)
214 #ifndef IS_DEVICE_SEP
216 #define IS_DEVICE_SEP(_c_) 0
218 #define IS_DEVICE_SEP(_c_) ((_c_) == DEVICE_SEP)
222 char *get_current_dir_name (void);
224 /* Return the current working directory. Returns NULL on errors.
225 Any other returned value must be freed with free. This is used
226 only when get_current_dir_name is not defined on the system. */
228 get_current_dir_name (void)
232 struct stat dotstat
, pwdstat
;
233 /* If PWD is accurate, use it instead of calling getwd. PWD is
234 sometimes a nicer name, and using it may avoid a fatal error if a
235 parent directory is searchable but not readable. */
236 if ((pwd
= egetenv ("PWD")) != 0
237 && (IS_DIRECTORY_SEP (*pwd
) || (*pwd
&& IS_DEVICE_SEP (pwd
[1])))
238 && stat (pwd
, &pwdstat
) == 0
239 && stat (".", &dotstat
) == 0
240 && dotstat
.st_ino
== pwdstat
.st_ino
241 && dotstat
.st_dev
== pwdstat
.st_dev
243 && strlen (pwd
) < MAXPATHLEN
247 buf
= (char *) xmalloc (strlen (pwd
) + 1);
255 size_t buf_size
= 1024;
256 buf
= (char *) xmalloc (buf_size
);
261 if (getcwd (buf
, buf_size
) == buf
)
265 int tmp_errno
= errno
;
271 buf
= (char *) realloc (buf
, buf_size
);
279 /* We need MAXPATHLEN here. */
280 buf
= (char *) xmalloc (MAXPATHLEN
+ 1);
283 if (getwd (buf
) == NULL
)
285 int tmp_errno
= errno
;
298 /* Like strdup but get a fatal error if memory is exhausted. */
301 xstrdup (const char *s
)
303 char *result
= strdup (s
);
312 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
314 /* Retrieve an environment variable from the Emacs subkeys of the registry.
315 Return NULL if the variable was not found, or it was empty.
316 This code is based on w32_get_resource (w32.c). */
318 w32_get_resource (HKEY predefined
, char *key
, LPDWORD type
)
320 HKEY hrootkey
= NULL
;
324 if (RegOpenKeyEx (predefined
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
326 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
)
328 result
= (char *) xmalloc (cbData
);
330 if ((RegQueryValueEx (hrootkey
, key
, NULL
, type
, result
, &cbData
) != ERROR_SUCCESS
)
338 RegCloseKey (hrootkey
);
345 getenv wrapper for Windows
347 Value is allocated on the heap, and can be free'd.
349 This is needed to duplicate Emacs's behavior, which is to look for
350 environment variables in the registry if they don't appear in the
353 w32_getenv (char *envvar
)
358 if (value
= getenv (envvar
))
359 /* Found in the environment. strdup it, because values returned
360 by getenv cannot be free'd. */
361 return xstrdup (value
);
363 if (! (value
= w32_get_resource (HKEY_CURRENT_USER
, envvar
, &dwType
)) &&
364 ! (value
= w32_get_resource (HKEY_LOCAL_MACHINE
, envvar
, &dwType
)))
366 /* "w32console" is what Emacs on Windows uses for tty-type under -nw. */
367 if (strcmp (envvar
, "TERM") == 0)
368 return xstrdup ("w32console");
369 /* Found neither in the environment nor in the registry. */
373 if (dwType
== REG_SZ
)
374 /* Registry; no need to expand. */
377 if (dwType
== REG_EXPAND_SZ
)
381 if (size
= ExpandEnvironmentStrings (value
, NULL
, 0))
383 char *buffer
= (char *) xmalloc (size
);
384 if (ExpandEnvironmentStrings (value
, buffer
, size
))
386 /* Found and expanded. */
391 /* Error expanding. */
396 /* Not the right type, or not correctly expanded. */
402 w32_set_user_model_id (void)
405 HRESULT (WINAPI
* set_user_model
) (wchar_t * id
);
407 /* On Windows 7 and later, we need to set the user model ID
408 to associate emacsclient launched files with Emacs frames
410 shell
= LoadLibrary ("shell32.dll");
414 = (void *) GetProcAddress (shell
,
415 "SetCurrentProcessExplicitAppUserModelID");
416 /* If the function is defined, then we are running on Windows 7
417 or newer, and the UI uses this to group related windows
418 together. Since emacs, runemacs, emacsclient are related, we
419 want them grouped even though the executables are different,
420 so we need to set a consistent ID between them. */
422 set_user_model (L
"GNU.Emacs");
429 w32_window_app (void)
431 static int window_app
= -1;
432 char szTitle
[MAX_PATH
];
436 /* Checking for STDOUT does not work; it's a valid handle also in
437 nonconsole apps. Testing for the console title seems to work. */
438 window_app
= (GetConsoleTitleA (szTitle
, MAX_PATH
) == 0);
440 InitCommonControls ();
447 execvp wrapper for Windows. Quotes arguments with embedded spaces.
449 This is necessary due to the broken implementation of exec* routines in
450 the Microsoft libraries: they concatenate the arguments together without
451 quoting special characters, and pass the result to CreateProcess, with
452 predictably bad results. By contrast, POSIX execvp passes the arguments
453 directly into the argv array of the child process.
456 w32_execvp (const char *path
, char **argv
)
460 /* Required to allow a .BAT script as alternate editor. */
461 argv
[0] = (char *) alternate_editor
;
463 for (i
= 0; argv
[i
]; i
++)
464 if (strchr (argv
[i
], ' '))
466 char *quoted
= alloca (strlen (argv
[i
]) + 3);
467 sprintf (quoted
, "\"%s\"", argv
[i
]);
471 return execvp (path
, argv
);
475 #define execvp w32_execvp
477 /* Emulation of ttyname for Windows. */
484 #endif /* WINDOWSNT */
486 /* Display a normal or error message.
487 On Windows, use a message box if compiled as a Windows app. */
488 static void message (int, const char *, ...) ATTRIBUTE_FORMAT_PRINTF (2, 3);
490 message (int is_error
, const char *format
, ...)
495 va_start (args
, format
);
496 vsprintf (msg
, format
, args
);
500 if (w32_window_app ())
503 MessageBox (NULL
, msg
, "Emacsclient ERROR", MB_ICONERROR
);
505 MessageBox (NULL
, msg
, "Emacsclient", MB_ICONINFORMATION
);
510 FILE *f
= is_error
? stderr
: stdout
;
517 /* Decode the options from argv and argc.
518 The global variable `optind' will say how many arguments we used up. */
521 decode_options (int argc
, char **argv
)
523 alternate_editor
= egetenv ("ALTERNATE_EDITOR");
527 int opt
= getopt_long_only (argc
, argv
,
528 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
541 /* If getopt returns 0, then it has already processed a
542 long-named option. We should do nothing. */
546 alternate_editor
= optarg
;
549 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
551 socket_name
= optarg
;
556 server_file
= optarg
;
559 /* We used to disallow this argument in w32, but it seems better
560 to allow it, for the occasional case where the user is
561 connecting with a w32 client to a server compiled with X11
580 message (FALSE
, "emacsclient %s\n", VERSION
);
599 print_help_and_exit ();
603 message (TRUE
, "Try `%s --help' for more information\n", progname
);
609 /* If the -c option is used (without -t) and no --display argument
610 is provided, try $DISPLAY.
611 Without the -c option, we used to set `display' to $DISPLAY by
612 default, but this changed the default behavior and is sometimes
613 inconvenient. So we force users to use "--display $DISPLAY" if
614 they want Emacs to connect to their current display. */
615 if (!current_frame
&& !tty
&& !display
)
617 display
= egetenv ("DISPLAY");
619 /* Under Cocoa, we don't really use displays the same way as in X,
620 so provide a dummy. */
621 if (!display
|| strlen (display
) == 0)
626 /* A null-string display is invalid. */
627 if (display
&& strlen (display
) == 0)
630 /* If no display is available, new frames are tty frames. */
631 if (!current_frame
&& !display
)
634 /* --no-wait implies --current-frame on ttys when there are file
635 arguments or expressions given. */
636 if (nowait
&& tty
&& argc
- optind
> 0)
640 if (alternate_editor
&& alternate_editor
[0] == '\0')
642 message (TRUE
, "--alternate-editor argument or ALTERNATE_EDITOR variable cannot be\n\
646 #endif /* WINDOWSNT */
651 print_help_and_exit (void)
653 /* Spaces and tabs are significant in this message; they're chosen so the
654 message aligns properly both in a tty and in a Windows message box.
655 Please try to preserve them; otherwise the output is very hard to read
656 when using emacsclientw. */
658 "Usage: %s [OPTIONS] FILE...\n\
659 Tell the Emacs server to visit the specified files.\n\
660 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
662 The following OPTIONS are accepted:\n\
663 -V, --version Just print version info and return\n\
664 -H, --help Print this usage information message\n\
665 -nw, -t, --tty Open a new Emacs frame on the current terminal\n\
666 -c, --create-frame Create a new frame instead of trying to\n\
667 use the current Emacs frame\n\
668 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
669 -n, --no-wait Don't wait for the server to return\n\
670 -q, --quiet Don't display messages on success\n\
671 -d DISPLAY, --display=DISPLAY\n\
672 Visit the file in the given display\n\
673 --parent-id=ID Open in parent window ID, via XEmbed\n"
674 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
675 "-s SOCKET, --socket-name=SOCKET\n\
676 Set filename of the UNIX socket for communication\n"
678 "-f SERVER, --server-file=SERVER\n\
679 Set filename of the TCP authentication file\n\
680 -a EDITOR, --alternate-editor=EDITOR\n\
681 Editor to fallback to if the server is not running\n"
683 " If EDITOR is the empty string, start Emacs in daemon\n\
684 mode and try connecting again\n"
685 #endif /* not WINDOWSNT */
687 Report bugs with M-x report-emacs-bug.\n", progname
);
692 Try to run a different command, or --if no alternate editor is
693 defined-- exit with an errorcode.
694 Uses argv, but gets it from the global variable main_argv.
699 if (alternate_editor
)
703 execvp (alternate_editor
, main_argv
+ i
);
704 message (TRUE
, "%s: error executing alternate editor \"%s\"\n",
705 progname
, alternate_editor
);
711 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
714 main (int argc
, char **argv
)
718 message (TRUE
, "%s: Sorry, the Emacs server is supported only\n"
719 "on systems with Berkeley sockets.\n",
724 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
726 #define AUTH_KEY_LENGTH 64
727 #define SEND_BUFFER_SIZE 4096
729 extern char *strerror (int);
731 /* Buffer to accumulate data to send in TCP connections. */
732 char send_buffer
[SEND_BUFFER_SIZE
+ 1];
733 int sblen
= 0; /* Fill pointer for the send buffer. */
734 /* Socket used to communicate with the Emacs server process. */
735 HSOCKET emacs_socket
= 0;
737 /* On Windows, the socket library was historically separate from the standard
738 C library, so errors are handled differently. */
740 sock_err_message (const char *function_name
)
745 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
746 | FORMAT_MESSAGE_ALLOCATE_BUFFER
747 | FORMAT_MESSAGE_ARGUMENT_ARRAY
,
748 NULL
, WSAGetLastError (), 0, (LPTSTR
)&msg
, 0, NULL
);
750 message (TRUE
, "%s: %s: %s\n", progname
, function_name
, msg
);
754 message (TRUE
, "%s: %s: %s\n", progname
, function_name
, strerror (errno
));
759 /* Let's send the data to Emacs when either
760 - the data ends in "\n", or
761 - the buffer is full (but this shouldn't happen)
762 Otherwise, we just accumulate it. */
764 send_to_emacs (HSOCKET s
, const char *data
)
768 size_t dlen
= strlen (data
);
769 if (dlen
+ sblen
>= SEND_BUFFER_SIZE
)
771 int part
= SEND_BUFFER_SIZE
- sblen
;
772 strncpy (&send_buffer
[sblen
], data
, part
);
774 sblen
= SEND_BUFFER_SIZE
;
778 strcpy (&send_buffer
[sblen
], data
);
785 if (sblen
== SEND_BUFFER_SIZE
786 || (sblen
> 0 && send_buffer
[sblen
-1] == '\n'))
788 int sent
= send (s
, send_buffer
, sblen
, 0);
790 strcpy (send_buffer
, &send_buffer
[sent
]);
797 /* In STR, insert a & before each &, each space, each newline, and
798 any initial -. Change spaces to underscores, too, so that the
799 return value never contains a space.
801 Does not change the string. Outputs the result to S. */
803 quote_argument (HSOCKET s
, const char *str
)
805 char *copy
= (char *) xmalloc (strlen (str
) * 2 + 1);
827 if (*p
== '&' || (*p
== '-' && p
== str
))
834 send_to_emacs (s
, copy
);
840 /* The inverse of quote_argument. Removes quoting in string STR by
841 modifying the string in place. Returns STR. */
844 unquote_argument (char *str
)
875 file_name_absolute_p (const char *filename
)
877 /* Sanity check, it shouldn't happen. */
878 if (! filename
) return FALSE
;
880 /* /xxx is always an absolute path. */
881 if (filename
[0] == '/') return TRUE
;
883 /* Empty filenames (which shouldn't happen) are relative. */
884 if (filename
[0] == '\0') return FALSE
;
887 /* X:\xxx is always absolute. */
888 if (isalpha ((unsigned char) filename
[0])
889 && filename
[1] == ':' && (filename
[2] == '\\' || filename
[2] == '/'))
892 /* Both \xxx and \\xxx\yyy are absolute. */
893 if (filename
[0] == '\\') return TRUE
;
900 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
907 /* Initialize the WinSock2 library. */
909 initialize_sockets (void)
913 if (WSAStartup (MAKEWORD (2, 0), &wsaData
))
915 message (TRUE
, "%s: error initializing WinSock2\n", progname
);
919 atexit (close_winsock
);
921 #endif /* WINDOWSNT */
925 * Read the information needed to set up a TCP comm channel with
926 * the Emacs server: host, port, and authentication string.
929 get_server_config (struct sockaddr_in
*server
, char *authentication
)
935 if (file_name_absolute_p (server_file
))
936 config
= fopen (server_file
, "rb");
939 const char *home
= egetenv ("HOME");
943 char *path
= alloca (strlen (home
) + strlen (server_file
)
945 sprintf (path
, "%s/.emacs.d/server/%s", home
, server_file
);
946 config
= fopen (path
, "rb");
949 if (!config
&& (home
= egetenv ("APPDATA")))
951 char *path
= alloca (strlen (home
) + strlen (server_file
)
953 sprintf (path
, "%s/.emacs.d/server/%s", home
, server_file
);
954 config
= fopen (path
, "rb");
962 if (fgets (dotted
, sizeof dotted
, config
)
963 && (port
= strchr (dotted
, ':')))
967 message (TRUE
, "%s: invalid configuration info\n", progname
);
971 server
->sin_family
= AF_INET
;
972 server
->sin_addr
.s_addr
= inet_addr (dotted
);
973 server
->sin_port
= htons (atoi (port
));
975 if (! fread (authentication
, AUTH_KEY_LENGTH
, 1, config
))
977 message (TRUE
, "%s: cannot read authentication info\n", progname
);
987 set_tcp_socket (void)
990 struct sockaddr_in server
;
991 struct linger l_arg
= {1, 1};
992 char auth_string
[AUTH_KEY_LENGTH
+ 1];
994 if (! get_server_config (&server
, auth_string
))
995 return INVALID_SOCKET
;
997 if (server
.sin_addr
.s_addr
!= inet_addr ("127.0.0.1") && !quiet
)
998 message (FALSE
, "%s: connected to remote socket at %s\n",
999 progname
, inet_ntoa (server
.sin_addr
));
1002 * Open up an AF_INET socket
1004 if ((s
= socket (AF_INET
, SOCK_STREAM
, IPPROTO_TCP
)) < 0)
1006 sock_err_message ("socket");
1007 return INVALID_SOCKET
;
1013 if (connect (s
, (struct sockaddr
*) &server
, sizeof server
) < 0)
1015 sock_err_message ("connect");
1016 return INVALID_SOCKET
;
1019 setsockopt (s
, SOL_SOCKET
, SO_LINGER
, (char *) &l_arg
, sizeof l_arg
);
1022 * Send the authentication
1024 auth_string
[AUTH_KEY_LENGTH
] = '\0';
1026 send_to_emacs (s
, "-auth ");
1027 send_to_emacs (s
, auth_string
);
1028 send_to_emacs (s
, " ");
1034 /* Returns 1 if PREFIX is a prefix of STRING. */
1036 strprefix (const char *prefix
, const char *string
)
1038 return !strncmp (prefix
, string
, strlen (prefix
));
1041 /* Get tty name and type. If successful, return the type in TTY_TYPE
1042 and the name in TTY_NAME, and return 1. Otherwise, fail if NOABORT
1043 is zero, or return 0 if NOABORT is non-zero. */
1046 find_tty (const char **tty_type
, const char **tty_name
, int noabort
)
1048 const char *type
= egetenv ("TERM");
1049 const char *name
= ttyname (fileno (stdout
));
1057 message (TRUE
, "%s: could not get terminal name\n", progname
);
1068 message (TRUE
, "%s: please set the TERM variable to your terminal type\n",
1074 if (strcmp (type
, "eterm") == 0)
1080 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1081 message (TRUE
, "%s: opening a frame in an Emacs term buffer"
1082 " is not supported\n", progname
);
1093 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1095 /* Three possibilities:
1096 2 - can't be `stat'ed (sets errno)
1097 1 - isn't owned by us
1098 0 - success: none of the above */
1101 socket_status (const char *name
)
1103 struct stat statbfr
;
1105 if (stat (name
, &statbfr
) == -1)
1108 if (statbfr
.st_uid
!= geteuid ())
1115 /* A signal handler that passes the signal to the Emacs process.
1116 Useful for SIGWINCH. */
1119 pass_signal_to_emacs (int signalnum
)
1121 int old_errno
= errno
;
1124 kill (emacs_pid
, signalnum
);
1126 signal (signalnum
, pass_signal_to_emacs
);
1130 /* Signal handler for SIGCONT; notify the Emacs process that it can
1131 now resume our tty frame. */
1134 handle_sigcont (int signalnum
)
1136 int old_errno
= errno
;
1138 if (tcgetpgrp (1) == getpgrp ())
1140 /* We are in the foreground. */
1141 send_to_emacs (emacs_socket
, "-resume \n");
1145 /* We are in the background; cancel the continue. */
1146 kill (getpid (), SIGSTOP
);
1149 signal (signalnum
, handle_sigcont
);
1153 /* Signal handler for SIGTSTP; notify the Emacs process that we are
1154 going to sleep. Normally the suspend is initiated by Emacs via
1155 server-handle-suspend-tty, but if the server gets out of sync with
1156 reality, we may get a SIGTSTP on C-z. Handling this signal and
1157 notifying Emacs about it should get things under control again. */
1160 handle_sigtstp (int signalnum
)
1162 int old_errno
= errno
;
1166 send_to_emacs (emacs_socket
, "-suspend \n");
1168 /* Unblock this signal and call the default handler by temporarily
1169 changing the handler and resignalling. */
1170 sigprocmask (SIG_BLOCK
, NULL
, &set
);
1171 sigdelset (&set
, signalnum
);
1172 signal (signalnum
, SIG_DFL
);
1173 kill (getpid (), signalnum
);
1174 sigprocmask (SIG_SETMASK
, &set
, NULL
); /* Let's the above signal through. */
1175 signal (signalnum
, handle_sigtstp
);
1181 /* Set up signal handlers before opening a frame on the current tty. */
1186 /* Set up signal handlers. */
1187 signal (SIGWINCH
, pass_signal_to_emacs
);
1189 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
1190 deciding which terminal the signal came from. C-g is now a
1191 normal input event on secondary terminals. */
1193 signal (SIGINT
, pass_signal_to_emacs
);
1194 signal (SIGQUIT
, pass_signal_to_emacs
);
1197 signal (SIGCONT
, handle_sigcont
);
1198 signal (SIGTSTP
, handle_sigtstp
);
1199 signal (SIGTTOU
, handle_sigtstp
);
1204 set_local_socket (void)
1207 struct sockaddr_un server
;
1210 * Open up an AF_UNIX socket in this person's home directory
1213 if ((s
= socket (AF_UNIX
, SOCK_STREAM
, 0)) < 0)
1215 message (TRUE
, "%s: socket: %s\n", progname
, strerror (errno
));
1216 return INVALID_SOCKET
;
1219 server
.sun_family
= AF_UNIX
;
1222 int sock_status
= 0;
1223 int default_sock
= !socket_name
;
1224 int saved_errno
= 0;
1225 const char *server_name
= "server";
1226 const char *tmpdir
IF_LINT ( = NULL
);
1228 if (socket_name
&& !strchr (socket_name
, '/')
1229 && !strchr (socket_name
, '\\'))
1231 /* socket_name is a file name component. */
1232 server_name
= socket_name
;
1234 default_sock
= 1; /* Try both UIDs. */
1239 tmpdir
= egetenv ("TMPDIR");
1243 #ifndef _CS_DARWIN_USER_TEMP_DIR
1244 #define _CS_DARWIN_USER_TEMP_DIR 65537
1246 size_t n
= confstr (_CS_DARWIN_USER_TEMP_DIR
, NULL
, (size_t) 0);
1249 tmpdir
= alloca (n
);
1250 confstr (_CS_DARWIN_USER_TEMP_DIR
, tmpdir
, n
);
1256 socket_name
= alloca (strlen (tmpdir
) + strlen (server_name
)
1258 sprintf (socket_name
, "%s/emacs%d/%s",
1259 tmpdir
, (int) geteuid (), server_name
);
1262 if (strlen (socket_name
) < sizeof (server
.sun_path
))
1263 strcpy (server
.sun_path
, socket_name
);
1266 message (TRUE
, "%s: socket-name %s too long\n",
1267 progname
, socket_name
);
1271 /* See if the socket exists, and if it's owned by us. */
1272 sock_status
= socket_status (server
.sun_path
);
1273 saved_errno
= errno
;
1274 if (sock_status
&& default_sock
)
1276 /* Failing that, see if LOGNAME or USER exist and differ from
1277 our euid. If so, look for a socket based on the UID
1278 associated with the name. This is reminiscent of the logic
1279 that init_editfns uses to set the global Vuser_full_name. */
1281 const char *user_name
= egetenv ("LOGNAME");
1284 user_name
= egetenv ("USER");
1288 struct passwd
*pw
= getpwnam (user_name
);
1290 if (pw
&& (pw
->pw_uid
!= geteuid ()))
1292 /* We're running under su, apparently. */
1293 socket_name
= alloca (strlen (tmpdir
) + strlen (server_name
)
1295 sprintf (socket_name
, "%s/emacs%d/%s",
1296 tmpdir
, (int) pw
->pw_uid
, server_name
);
1298 if (strlen (socket_name
) < sizeof (server
.sun_path
))
1299 strcpy (server
.sun_path
, socket_name
);
1302 message (TRUE
, "%s: socket-name %s too long\n",
1303 progname
, socket_name
);
1304 exit (EXIT_FAILURE
);
1307 sock_status
= socket_status (server
.sun_path
);
1308 saved_errno
= errno
;
1311 errno
= saved_errno
;
1315 switch (sock_status
)
1318 /* There's a socket, but it isn't owned by us. This is OK if
1320 if (0 != geteuid ())
1322 message (TRUE
, "%s: Invalid socket owner\n", progname
);
1323 return INVALID_SOCKET
;
1329 if (saved_errno
== ENOENT
)
1331 "%s: can't find socket; have you started the server?\n\
1332 To start the server in Emacs, type \"M-x server-start\".\n",
1335 message (TRUE
, "%s: can't stat %s: %s\n",
1336 progname
, server
.sun_path
, strerror (saved_errno
));
1337 return INVALID_SOCKET
;
1341 if (connect (s
, (struct sockaddr
*) &server
, strlen (server
.sun_path
) + 2)
1344 message (TRUE
, "%s: connect: %s\n", progname
, strerror (errno
));
1345 return INVALID_SOCKET
;
1350 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1353 set_socket (int no_exit_if_error
)
1359 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1360 /* Explicit --socket-name argument. */
1363 s
= set_local_socket ();
1364 if ((s
!= INVALID_SOCKET
) || no_exit_if_error
)
1366 message (TRUE
, "%s: error accessing socket \"%s\"\n",
1367 progname
, socket_name
);
1368 exit (EXIT_FAILURE
);
1372 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1374 server_file
= egetenv ("EMACS_SERVER_FILE");
1378 s
= set_tcp_socket ();
1379 if ((s
!= INVALID_SOCKET
) || no_exit_if_error
)
1382 message (TRUE
, "%s: error accessing server file \"%s\"\n",
1383 progname
, server_file
);
1384 exit (EXIT_FAILURE
);
1387 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1388 /* Implicit local socket. */
1389 s
= set_local_socket ();
1390 if (s
!= INVALID_SOCKET
)
1394 /* Implicit server file. */
1395 server_file
= "server";
1396 s
= set_tcp_socket ();
1397 if ((s
!= INVALID_SOCKET
) || no_exit_if_error
)
1400 /* No implicit or explicit socket, and no alternate editor. */
1401 message (TRUE
, "%s: No socket or alternate editor. Please use:\n\n"
1402 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1405 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1406 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1408 exit (EXIT_FAILURE
);
1412 FARPROC set_fg
; /* Pointer to AllowSetForegroundWindow. */
1413 FARPROC get_wc
; /* Pointer to RealGetWindowClassA. */
1416 w32_find_emacs_process (HWND hWnd
, LPARAM lParam
)
1421 /* Reject any window not of class "Emacs". */
1422 if (! get_wc (hWnd
, class, sizeof (class))
1423 || strcmp (class, "Emacs"))
1426 /* We only need the process id, not the thread id. */
1427 (void) GetWindowThreadProcessId (hWnd
, &pid
);
1429 /* Not the one we're looking for. */
1430 if (pid
!= (DWORD
) emacs_pid
) return TRUE
;
1432 /* OK, let's raise it. */
1435 /* Stop enumeration. */
1440 * Search for a window of class "Emacs" and owned by a process with
1441 * process id = emacs_pid. If found, allow it to grab the focus.
1444 w32_give_focus (void)
1448 /* It shouldn't happen when dealing with TCP sockets. */
1449 if (!emacs_pid
) return;
1451 user32
= GetModuleHandle ("user32.dll");
1456 /* Modern Windows restrict which processes can set the foreground window.
1457 emacsclient can allow Emacs to grab the focus by calling the function
1458 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1459 NT) lack this function, so we have to check its availability. */
1460 if ((set_fg
= GetProcAddress (user32
, "AllowSetForegroundWindow"))
1461 && (get_wc
= GetProcAddress (user32
, "RealGetWindowClassA")))
1462 EnumWindows (w32_find_emacs_process
, (LPARAM
) 0);
1466 /* Start the emacs daemon and try to connect to it. */
1469 start_daemon_and_retry_set_socket (void)
1480 w
= waitpid (dpid
, &status
, WUNTRACED
| WCONTINUED
);
1482 if ((w
== -1) || !WIFEXITED (status
) || WEXITSTATUS (status
))
1484 message (TRUE
, "Error: Could not start the Emacs daemon\n");
1485 exit (EXIT_FAILURE
);
1488 /* Try connecting, the daemon should have started by now. */
1489 message (TRUE
, "Emacs daemon should have started, trying to connect again\n");
1490 if ((emacs_socket
= set_socket (1)) == INVALID_SOCKET
)
1492 message (TRUE
, "Error: Cannot connect even after starting the Emacs daemon\n");
1493 exit (EXIT_FAILURE
);
1498 fprintf (stderr
, "Error: Cannot fork!\n");
1499 exit (EXIT_FAILURE
);
1503 char emacs
[] = "emacs";
1504 char daemon_option
[] = "--daemon";
1505 char *d_argv
[] = {emacs
, daemon_option
, 0 };
1506 if (socket_name
!= NULL
)
1508 /* Pass --daemon=socket_name as argument. */
1509 const char *deq
= "--daemon=";
1510 char *daemon_arg
= alloca (strlen (deq
)
1511 + strlen (socket_name
) + 1);
1512 strcpy (daemon_arg
, deq
);
1513 strcat (daemon_arg
, socket_name
);
1514 d_argv
[1] = daemon_arg
;
1516 execvp ("emacs", d_argv
);
1517 message (TRUE
, "%s: error starting emacs daemon\n", progname
);
1519 #endif /* WINDOWSNT */
1523 main (int argc
, char **argv
)
1525 int rl
= 0, needlf
= 0;
1527 char string
[BUFSIZ
+1];
1528 int null_socket_name
IF_LINT ( = 0);
1529 int null_server_file
IF_LINT ( = 0);
1530 int start_daemon_if_needed
;
1531 int exit_status
= EXIT_SUCCESS
;
1537 /* On Windows 7 and later, we need to explicitly associate emacsclient
1538 with emacs so the UI behaves sensibly. */
1539 w32_set_user_model_id ();
1542 /* Process options. */
1543 decode_options (argc
, argv
);
1545 if ((argc
- optind
< 1) && !eval
&& current_frame
)
1547 message (TRUE
, "%s: file name or argument required\n"
1548 "Try `%s --help' for more information\n",
1549 progname
, progname
);
1550 exit (EXIT_FAILURE
);
1553 /* If alternate_editor is the empty string, start the emacs daemon
1554 in case of failure to connect. */
1555 start_daemon_if_needed
= (alternate_editor
1556 && (alternate_editor
[0] == '\0'));
1557 if (start_daemon_if_needed
)
1559 /* set_socket changes the values for socket_name and
1560 server_file, we need to reset them, if they were NULL before
1561 for the second call to set_socket. */
1562 null_socket_name
= (socket_name
== NULL
);
1563 null_server_file
= (server_file
== NULL
);
1566 emacs_socket
= set_socket (alternate_editor
|| start_daemon_if_needed
);
1567 if (emacs_socket
== INVALID_SOCKET
)
1569 if (! start_daemon_if_needed
)
1572 /* Reset socket_name and server_file if they were NULL
1573 before the set_socket call. */
1574 if (null_socket_name
)
1576 if (null_server_file
)
1579 start_daemon_and_retry_set_socket ();
1582 cwd
= get_current_dir_name ();
1585 /* getwd puts message in STRING if it fails. */
1586 message (TRUE
, "%s: %s\n", progname
,
1587 "Cannot get current working directory");
1595 /* Send over our environment and current directory. */
1598 extern char **environ
;
1600 for (i
= 0; environ
[i
]; i
++)
1602 send_to_emacs (emacs_socket
, "-env ");
1603 quote_argument (emacs_socket
, environ
[i
]);
1604 send_to_emacs (emacs_socket
, " ");
1607 send_to_emacs (emacs_socket
, "-dir ");
1608 quote_argument (emacs_socket
, cwd
);
1609 send_to_emacs (emacs_socket
, "/");
1610 send_to_emacs (emacs_socket
, " ");
1614 send_to_emacs (emacs_socket
, "-nowait ");
1617 send_to_emacs (emacs_socket
, "-current-frame ");
1621 send_to_emacs (emacs_socket
, "-display ");
1622 quote_argument (emacs_socket
, display
);
1623 send_to_emacs (emacs_socket
, " ");
1628 send_to_emacs (emacs_socket
, "-parent-id ");
1629 quote_argument (emacs_socket
, parent_id
);
1630 send_to_emacs (emacs_socket
, " ");
1633 /* If using the current frame, send tty information to Emacs anyway.
1634 In daemon mode, Emacs may need to occupy this tty if no other
1635 frame is available. */
1636 if (tty
|| (current_frame
&& !eval
))
1638 const char *tty_type
, *tty_name
;
1640 if (find_tty (&tty_type
, &tty_name
, !tty
))
1642 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1645 send_to_emacs (emacs_socket
, "-tty ");
1646 quote_argument (emacs_socket
, tty_name
);
1647 send_to_emacs (emacs_socket
, " ");
1648 quote_argument (emacs_socket
, tty_type
);
1649 send_to_emacs (emacs_socket
, " ");
1653 if (!current_frame
&& !tty
)
1654 send_to_emacs (emacs_socket
, "-window-system ");
1656 if ((argc
- optind
> 0))
1659 for (i
= optind
; i
< argc
; i
++)
1664 /* Don't prepend cwd or anything like that. */
1665 send_to_emacs (emacs_socket
, "-eval ");
1666 quote_argument (emacs_socket
, argv
[i
]);
1667 send_to_emacs (emacs_socket
, " ");
1671 if (*argv
[i
] == '+')
1673 char *p
= argv
[i
] + 1;
1674 while (isdigit ((unsigned char) *p
) || *p
== ':') p
++;
1677 send_to_emacs (emacs_socket
, "-position ");
1678 quote_argument (emacs_socket
, argv
[i
]);
1679 send_to_emacs (emacs_socket
, " ");
1684 else if (! file_name_absolute_p (argv
[i
])
1685 && (isalpha (argv
[i
][0]) && argv
[i
][1] == ':'))
1686 /* Windows can have a different default directory for each
1687 drive, so the cwd passed via "-dir" is not sufficient
1688 to account for that.
1689 If the user uses <drive>:<relpath>, we hence need to be
1690 careful to expand <relpath> with the default directory
1691 corresponding to <drive>. */
1693 char *filename
= (char *) xmalloc (MAX_PATH
);
1696 size
= GetFullPathName (argv
[i
], MAX_PATH
, filename
, NULL
);
1697 if (size
> 0 && size
< MAX_PATH
)
1704 send_to_emacs (emacs_socket
, "-file ");
1705 quote_argument (emacs_socket
, argv
[i
]);
1706 send_to_emacs (emacs_socket
, " ");
1711 /* Read expressions interactively. */
1712 while ((str
= fgets (string
, BUFSIZ
, stdin
)))
1714 send_to_emacs (emacs_socket
, "-eval ");
1715 quote_argument (emacs_socket
, str
);
1717 send_to_emacs (emacs_socket
, " ");
1720 send_to_emacs (emacs_socket
, "\n");
1722 /* Wait for an answer. */
1723 if (!eval
&& !tty
&& !nowait
&& !quiet
)
1725 printf ("Waiting for Emacs...");
1731 /* Now, wait for an answer and print any messages. */
1732 while (exit_status
== EXIT_SUCCESS
)
1738 rl
= recv (emacs_socket
, string
, BUFSIZ
, 0);
1740 /* If we receive a signal (e.g. SIGWINCH, which we pass
1741 through to Emacs), on some OSes we get EINTR and must retry. */
1742 while (rl
< 0 && errno
== EINTR
);
1749 p
= string
+ strlen (string
) - 1;
1750 while (p
> string
&& *p
== '\n')
1753 if (strprefix ("-emacs-pid ", string
))
1755 /* -emacs-pid PID: The process id of the Emacs process. */
1756 emacs_pid
= strtol (string
+ strlen ("-emacs-pid"), NULL
, 10);
1758 else if (strprefix ("-window-system-unsupported ", string
))
1760 /* -window-system-unsupported: Emacs was compiled without X
1761 support. Try again on the terminal. */
1766 else if (strprefix ("-print ", string
))
1768 /* -print STRING: Print STRING on the terminal. */
1769 str
= unquote_argument (string
+ strlen ("-print "));
1773 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1775 else if (strprefix ("-error ", string
))
1777 /* -error DESCRIPTION: Signal an error on the terminal. */
1778 str
= unquote_argument (string
+ strlen ("-error "));
1781 fprintf (stderr
, "*ERROR*: %s", str
);
1782 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1783 exit_status
= EXIT_FAILURE
;
1786 else if (strprefix ("-suspend ", string
))
1788 /* -suspend: Suspend this terminal, i.e., stop the process. */
1797 /* Unknown command. */
1800 printf ("*ERROR*: Unknown message: %s", string
);
1802 == '\0' ? needlf
: string
[strlen (string
) - 1] != '\n';
1812 exit_status
= EXIT_FAILURE
;
1814 CLOSE_SOCKET (emacs_socket
);
1818 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
1821 #ifndef HAVE_STRERROR
1826 extern char *sys_errlist
[];
1827 extern int sys_nerr
;
1829 if (errnum
>= 0 && errnum
< sys_nerr
)
1830 return sys_errlist
[errnum
];
1831 return (char *) "Unknown error";
1834 #endif /* ! HAVE_STRERROR */
1837 /* emacsclient.c ends here */