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 args are expressions to be evaluated. --eval. */
135 /* Nonzero means don't open a new frame. Inverse of --create-frame. */
136 int current_frame
= 1;
138 /* The display on which Emacs should work. --display. */
139 const char *display
= NULL
;
141 /* The parent window ID, if we are opening a frame via XEmbed. */
142 char *parent_id
= NULL
;
144 /* Nonzero means open a new Emacs frame on the current terminal. */
147 /* If non-NULL, the name of an editor to fallback to if the server
148 is not running. --alternate-editor. */
149 const char *alternate_editor
= NULL
;
151 /* If non-NULL, the filename of the UNIX socket. */
152 char *socket_name
= NULL
;
154 /* If non-NULL, the filename of the authentication file. */
155 const char *server_file
= NULL
;
157 /* PID of the Emacs server process. */
160 static void print_help_and_exit (void) NO_RETURN
;
161 static void fail (void) NO_RETURN
;
164 struct option longopts
[] =
166 { "no-wait", no_argument
, NULL
, 'n' },
167 { "eval", no_argument
, NULL
, 'e' },
168 { "help", no_argument
, NULL
, 'H' },
169 { "version", no_argument
, NULL
, 'V' },
170 { "tty", no_argument
, NULL
, 't' },
171 { "nw", no_argument
, NULL
, 't' },
172 { "create-frame", no_argument
, NULL
, 'c' },
173 { "alternate-editor", required_argument
, NULL
, 'a' },
174 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
175 { "socket-name", required_argument
, NULL
, 's' },
177 { "server-file", required_argument
, NULL
, 'f' },
179 { "display", required_argument
, NULL
, 'd' },
181 { "parent-id", required_argument
, NULL
, 'p' },
186 /* Like malloc but get fatal error if memory is exhausted. */
189 xmalloc (unsigned int size
)
191 long *result
= (long *) malloc (size
);
201 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
204 #ifndef DIRECTORY_SEP
205 #define DIRECTORY_SEP '/'
207 #ifndef IS_DIRECTORY_SEP
208 #define IS_DIRECTORY_SEP(_c_) ((_c_) == DIRECTORY_SEP)
210 #ifndef IS_DEVICE_SEP
212 #define IS_DEVICE_SEP(_c_) 0
214 #define IS_DEVICE_SEP(_c_) ((_c_) == DEVICE_SEP)
218 #define IS_ANY_SEP(_c_) (IS_DIRECTORY_SEP (_c_))
222 /* Return the current working directory. Returns NULL on errors.
223 Any other returned value must be freed with free. This is used
224 only when get_current_dir_name is not defined on the system. */
226 get_current_dir_name (void)
230 struct stat dotstat
, pwdstat
;
231 /* If PWD is accurate, use it instead of calling getwd. PWD is
232 sometimes a nicer name, and using it may avoid a fatal error if a
233 parent directory is searchable but not readable. */
234 if ((pwd
= egetenv ("PWD")) != 0
235 && (IS_DIRECTORY_SEP (*pwd
) || (*pwd
&& IS_DEVICE_SEP (pwd
[1])))
236 && stat (pwd
, &pwdstat
) == 0
237 && stat (".", &dotstat
) == 0
238 && dotstat
.st_ino
== pwdstat
.st_ino
239 && dotstat
.st_dev
== pwdstat
.st_dev
241 && strlen (pwd
) < MAXPATHLEN
245 buf
= (char *) xmalloc (strlen (pwd
) + 1);
253 size_t buf_size
= 1024;
254 buf
= (char *) xmalloc (buf_size
);
259 if (getcwd (buf
, buf_size
) == buf
)
263 int tmp_errno
= errno
;
269 buf
= (char *) realloc (buf
, buf_size
);
277 /* We need MAXPATHLEN here. */
278 buf
= (char *) xmalloc (MAXPATHLEN
+ 1);
281 if (getwd (buf
) == NULL
)
283 int tmp_errno
= errno
;
296 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
298 /* Retrieve an environment variable from the Emacs subkeys of the registry.
299 Return NULL if the variable was not found, or it was empty.
300 This code is based on w32_get_resource (w32.c). */
302 w32_get_resource (HKEY predefined
, char *key
, LPDWORD type
)
304 HKEY hrootkey
= NULL
;
308 if (RegOpenKeyEx (predefined
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
310 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
)
312 result
= (char *) xmalloc (cbData
);
314 if ((RegQueryValueEx (hrootkey
, key
, NULL
, type
, result
, &cbData
) != ERROR_SUCCESS
)
322 RegCloseKey (hrootkey
);
329 getenv wrapper for Windows
331 This is needed to duplicate Emacs's behavior, which is to look for environment
332 variables in the registry if they don't appear in the environment.
335 w32_getenv (char *envvar
)
340 if (value
= getenv (envvar
))
341 /* Found in the environment. */
344 if (! (value
= w32_get_resource (HKEY_CURRENT_USER
, envvar
, &dwType
)) &&
345 ! (value
= w32_get_resource (HKEY_LOCAL_MACHINE
, envvar
, &dwType
)))
347 /* "w32console" is what Emacs on Windows uses for tty-type under -nw. */
348 if (strcmp (envvar
, "TERM") == 0)
350 /* Found neither in the environment nor in the registry. */
354 if (dwType
== REG_SZ
)
355 /* Registry; no need to expand. */
358 if (dwType
== REG_EXPAND_SZ
)
362 if (size
= ExpandEnvironmentStrings (value
, NULL
, 0))
364 char *buffer
= (char *) xmalloc (size
);
365 if (ExpandEnvironmentStrings (value
, buffer
, size
))
367 /* Found and expanded. */
372 /* Error expanding. */
377 /* Not the right type, or not correctly expanded. */
383 w32_set_user_model_id (void)
386 HRESULT (WINAPI
* set_user_model
) (wchar_t * id
);
388 /* On Windows 7 and later, we need to set the user model ID
389 to associate emacsclient launched files with Emacs frames
391 shell
= LoadLibrary ("shell32.dll");
395 = (void *) GetProcAddress (shell
,
396 "SetCurrentProcessExplicitAppUserModelID");
397 /* If the function is defined, then we are running on Windows 7
398 or newer, and the UI uses this to group related windows
399 together. Since emacs, runemacs, emacsclient are related, we
400 want them grouped even though the executables are different,
401 so we need to set a consistent ID between them. */
403 set_user_model (L
"GNU.Emacs");
410 w32_window_app (void)
412 static int window_app
= -1;
413 char szTitle
[MAX_PATH
];
417 /* Checking for STDOUT does not work; it's a valid handle also in
418 nonconsole apps. Testing for the console title seems to work. */
419 window_app
= (GetConsoleTitleA (szTitle
, MAX_PATH
) == 0);
421 InitCommonControls ();
428 execvp wrapper for Windows. Quotes arguments with embedded spaces.
430 This is necessary due to the broken implementation of exec* routines in
431 the Microsoft libraries: they concatenate the arguments together without
432 quoting special characters, and pass the result to CreateProcess, with
433 predictably bad results. By contrast, POSIX execvp passes the arguments
434 directly into the argv array of the child process.
437 w32_execvp (const char *path
, char **argv
)
441 /* Required to allow a .BAT script as alternate editor. */
442 argv
[0] = (char *) alternate_editor
;
444 for (i
= 0; argv
[i
]; i
++)
445 if (strchr (argv
[i
], ' '))
447 char *quoted
= alloca (strlen (argv
[i
]) + 3);
448 sprintf (quoted
, "\"%s\"", argv
[i
]);
452 return execvp (path
, argv
);
456 #define execvp w32_execvp
458 /* Emulation of ttyname for Windows. */
465 #endif /* WINDOWSNT */
467 /* Display a normal or error message.
468 On Windows, use a message box if compiled as a Windows app. */
470 message (int is_error
, const char *format
, ...)
475 va_start (args
, format
);
476 vsprintf (msg
, format
, args
);
480 if (w32_window_app ())
483 MessageBox (NULL
, msg
, "Emacsclient ERROR", MB_ICONERROR
);
485 MessageBox (NULL
, msg
, "Emacsclient", MB_ICONINFORMATION
);
490 FILE *f
= is_error
? stderr
: stdout
;
497 /* Decode the options from argv and argc.
498 The global variable `optind' will say how many arguments we used up. */
501 decode_options (int argc
, char **argv
)
503 alternate_editor
= egetenv ("ALTERNATE_EDITOR");
507 int opt
= getopt_long_only (argc
, argv
,
508 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
521 /* If getopt returns 0, then it has already processed a
522 long-named option. We should do nothing. */
526 alternate_editor
= optarg
;
529 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
531 socket_name
= optarg
;
536 server_file
= optarg
;
539 /* We used to disallow this argument in w32, but it seems better
540 to allow it, for the occasional case where the user is
541 connecting with a w32 client to a server compiled with X11
556 message (FALSE
, "emacsclient %s\n", VERSION
);
575 print_help_and_exit ();
579 message (TRUE
, "Try `%s --help' for more information\n", progname
);
585 /* If the -c option is used (without -t) and no --display argument
586 is provided, try $DISPLAY.
587 Without the -c option, we used to set `display' to $DISPLAY by
588 default, but this changed the default behavior and is sometimes
589 inconvenient. So we force users to use "--display $DISPLAY" if
590 they want Emacs to connect to their current display. */
591 if (!current_frame
&& !tty
&& !display
)
593 display
= egetenv ("DISPLAY");
595 /* Under Cocoa, we don't really use displays the same way as in X,
596 so provide a dummy. */
597 if (!display
|| strlen (display
) == 0)
602 /* A null-string display is invalid. */
603 if (display
&& strlen (display
) == 0)
606 /* If no display is available, new frames are tty frames. */
607 if (!current_frame
&& !display
)
610 /* --no-wait implies --current-frame on ttys when there are file
611 arguments or expressions given. */
612 if (nowait
&& tty
&& argc
- optind
> 0)
616 if (alternate_editor
&& alternate_editor
[0] == '\0')
618 message (TRUE
, "--alternate-editor argument or ALTERNATE_EDITOR variable cannot be\n\
622 #endif /* WINDOWSNT */
627 print_help_and_exit (void)
629 /* Spaces and tabs are significant in this message; they're chosen so the
630 message aligns properly both in a tty and in a Windows message box.
631 Please try to preserve them; otherwise the output is very hard to read
632 when using emacsclientw. */
634 "Usage: %s [OPTIONS] FILE...\n\
635 Tell the Emacs server to visit the specified files.\n\
636 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
638 The following OPTIONS are accepted:\n\
639 -V, --version Just print version info and return\n\
640 -H, --help Print this usage information message\n\
641 -nw, -t, --tty Open a new Emacs frame on the current terminal\n\
642 -c, --create-frame Create a new frame instead of trying to\n\
643 use the current Emacs frame\n\
644 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
645 -n, --no-wait Don't wait for the server to return\n\
646 -d DISPLAY, --display=DISPLAY\n\
647 Visit the file in the given display\n\
648 --parent-id=ID Open in parent window ID, via XEmbed\n"
649 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
650 "-s SOCKET, --socket-name=SOCKET\n\
651 Set filename of the UNIX socket for communication\n"
653 "-f SERVER, --server-file=SERVER\n\
654 Set filename of the TCP authentication file\n\
655 -a EDITOR, --alternate-editor=EDITOR\n\
656 Editor to fallback to if the server is not running\n"
658 " If EDITOR is the empty string, start Emacs in daemon\n\
659 mode and try connecting again\n"
660 #endif /* not WINDOWSNT */
662 Report bugs with M-x report-emacs-bug.\n", progname
);
667 Try to run a different command, or --if no alternate editor is
668 defined-- exit with an errorcode.
669 Uses argv, but gets it from the global variable main_argv.
674 if (alternate_editor
)
678 execvp (alternate_editor
, main_argv
+ i
);
679 message (TRUE
, "%s: error executing alternate editor \"%s\"\n",
680 progname
, alternate_editor
);
686 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
689 main (int argc
, char **argv
)
693 message (TRUE
, "%s: Sorry, the Emacs server is supported only\n"
694 "on systems with Berkeley sockets.\n",
699 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
701 #define AUTH_KEY_LENGTH 64
702 #define SEND_BUFFER_SIZE 4096
704 extern char *strerror (int);
706 /* Buffer to accumulate data to send in TCP connections. */
707 char send_buffer
[SEND_BUFFER_SIZE
+ 1];
708 int sblen
= 0; /* Fill pointer for the send buffer. */
709 /* Socket used to communicate with the Emacs server process. */
710 HSOCKET emacs_socket
= 0;
712 /* On Windows, the socket library was historically separate from the standard
713 C library, so errors are handled differently. */
715 sock_err_message (const char *function_name
)
720 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
721 | FORMAT_MESSAGE_ALLOCATE_BUFFER
722 | FORMAT_MESSAGE_ARGUMENT_ARRAY
,
723 NULL
, WSAGetLastError (), 0, (LPTSTR
)&msg
, 0, NULL
);
725 message (TRUE
, "%s: %s: %s\n", progname
, function_name
, msg
);
729 message (TRUE
, "%s: %s: %s\n", progname
, function_name
, strerror (errno
));
734 /* Let's send the data to Emacs when either
735 - the data ends in "\n", or
736 - the buffer is full (but this shouldn't happen)
737 Otherwise, we just accumulate it. */
739 send_to_emacs (HSOCKET s
, const char *data
)
743 size_t dlen
= strlen (data
);
744 if (dlen
+ sblen
>= SEND_BUFFER_SIZE
)
746 int part
= SEND_BUFFER_SIZE
- sblen
;
747 strncpy (&send_buffer
[sblen
], data
, part
);
749 sblen
= SEND_BUFFER_SIZE
;
753 strcpy (&send_buffer
[sblen
], data
);
760 if (sblen
== SEND_BUFFER_SIZE
761 || (sblen
> 0 && send_buffer
[sblen
-1] == '\n'))
763 int sent
= send (s
, send_buffer
, sblen
, 0);
765 strcpy (send_buffer
, &send_buffer
[sent
]);
772 /* In STR, insert a & before each &, each space, each newline, and
773 any initial -. Change spaces to underscores, too, so that the
774 return value never contains a space.
776 Does not change the string. Outputs the result to S. */
778 quote_argument (HSOCKET s
, const char *str
)
780 char *copy
= (char *) xmalloc (strlen (str
) * 2 + 1);
802 if (*p
== '&' || (*p
== '-' && p
== str
))
809 send_to_emacs (s
, copy
);
815 /* The inverse of quote_argument. Removes quoting in string STR by
816 modifying the string in place. Returns STR. */
819 unquote_argument (char *str
)
850 file_name_absolute_p (const char *filename
)
852 /* Sanity check, it shouldn't happen. */
853 if (! filename
) return FALSE
;
855 /* /xxx is always an absolute path. */
856 if (filename
[0] == '/') return TRUE
;
858 /* Empty filenames (which shouldn't happen) are relative. */
859 if (filename
[0] == '\0') return FALSE
;
862 /* X:\xxx is always absolute. */
863 if (isalpha ((unsigned char) filename
[0])
864 && filename
[1] == ':' && (filename
[2] == '\\' || filename
[2] == '/'))
867 /* Both \xxx and \\xxx\yyy are absolute. */
868 if (filename
[0] == '\\') return TRUE
;
875 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
882 /* Initialize the WinSock2 library. */
884 initialize_sockets (void)
888 if (WSAStartup (MAKEWORD (2, 0), &wsaData
))
890 message (TRUE
, "%s: error initializing WinSock2\n", progname
);
894 atexit (close_winsock
);
896 #endif /* WINDOWSNT */
900 * Read the information needed to set up a TCP comm channel with
901 * the Emacs server: host, port, and authentication string.
904 get_server_config (struct sockaddr_in
*server
, char *authentication
)
910 if (file_name_absolute_p (server_file
))
911 config
= fopen (server_file
, "rb");
914 const char *home
= egetenv ("HOME");
918 char *path
= alloca (strlen (home
) + strlen (server_file
)
920 sprintf (path
, "%s/.emacs.d/server/%s", home
, server_file
);
921 config
= fopen (path
, "rb");
924 if (!config
&& (home
= egetenv ("APPDATA")))
926 char *path
= alloca (strlen (home
) + strlen (server_file
)
928 sprintf (path
, "%s/.emacs.d/server/%s", home
, server_file
);
929 config
= fopen (path
, "rb");
937 if (fgets (dotted
, sizeof dotted
, config
)
938 && (port
= strchr (dotted
, ':')))
942 message (TRUE
, "%s: invalid configuration info\n", progname
);
946 server
->sin_family
= AF_INET
;
947 server
->sin_addr
.s_addr
= inet_addr (dotted
);
948 server
->sin_port
= htons (atoi (port
));
950 if (! fread (authentication
, AUTH_KEY_LENGTH
, 1, config
))
952 message (TRUE
, "%s: cannot read authentication info\n", progname
);
962 set_tcp_socket (void)
965 struct sockaddr_in server
;
966 struct linger l_arg
= {1, 1};
967 char auth_string
[AUTH_KEY_LENGTH
+ 1];
969 if (! get_server_config (&server
, auth_string
))
970 return INVALID_SOCKET
;
972 if (server
.sin_addr
.s_addr
!= inet_addr ("127.0.0.1"))
973 message (FALSE
, "%s: connected to remote socket at %s\n",
974 progname
, inet_ntoa (server
.sin_addr
));
977 * Open up an AF_INET socket
979 if ((s
= socket (AF_INET
, SOCK_STREAM
, IPPROTO_TCP
)) < 0)
981 sock_err_message ("socket");
982 return INVALID_SOCKET
;
988 if (connect (s
, (struct sockaddr
*) &server
, sizeof server
) < 0)
990 sock_err_message ("connect");
991 return INVALID_SOCKET
;
994 setsockopt (s
, SOL_SOCKET
, SO_LINGER
, (char *) &l_arg
, sizeof l_arg
);
997 * Send the authentication
999 auth_string
[AUTH_KEY_LENGTH
] = '\0';
1001 send_to_emacs (s
, "-auth ");
1002 send_to_emacs (s
, auth_string
);
1003 send_to_emacs (s
, " ");
1009 /* Returns 1 if PREFIX is a prefix of STRING. */
1011 strprefix (const char *prefix
, const char *string
)
1013 return !strncmp (prefix
, string
, strlen (prefix
));
1016 /* Get tty name and type. If successful, return the type in TTY_TYPE
1017 and the name in TTY_NAME, and return 1. Otherwise, fail if NOABORT
1018 is zero, or return 0 if NOABORT is non-zero. */
1021 find_tty (const char **tty_type
, const char **tty_name
, int noabort
)
1023 const char *type
= egetenv ("TERM");
1024 const char *name
= ttyname (fileno (stdout
));
1032 message (TRUE
, "%s: could not get terminal name\n", progname
);
1043 message (TRUE
, "%s: please set the TERM variable to your terminal type\n",
1049 if (strcmp (type
, "eterm") == 0)
1055 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1056 message (TRUE
, "%s: opening a frame in an Emacs term buffer"
1057 " is not supported\n", progname
);
1068 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1070 /* Three possibilities:
1071 2 - can't be `stat'ed (sets errno)
1072 1 - isn't owned by us
1073 0 - success: none of the above */
1076 socket_status (char *name
)
1078 struct stat statbfr
;
1080 if (stat (name
, &statbfr
) == -1)
1083 if (statbfr
.st_uid
!= geteuid ())
1090 /* A signal handler that passes the signal to the Emacs process.
1091 Useful for SIGWINCH. */
1094 pass_signal_to_emacs (int signalnum
)
1096 int old_errno
= errno
;
1099 kill (emacs_pid
, signalnum
);
1101 signal (signalnum
, pass_signal_to_emacs
);
1105 /* Signal handler for SIGCONT; notify the Emacs process that it can
1106 now resume our tty frame. */
1109 handle_sigcont (int signalnum
)
1111 int old_errno
= errno
;
1113 if (tcgetpgrp (1) == getpgrp ())
1115 /* We are in the foreground. */
1116 send_to_emacs (emacs_socket
, "-resume \n");
1120 /* We are in the background; cancel the continue. */
1121 kill (getpid (), SIGSTOP
);
1124 signal (signalnum
, handle_sigcont
);
1128 /* Signal handler for SIGTSTP; notify the Emacs process that we are
1129 going to sleep. Normally the suspend is initiated by Emacs via
1130 server-handle-suspend-tty, but if the server gets out of sync with
1131 reality, we may get a SIGTSTP on C-z. Handling this signal and
1132 notifying Emacs about it should get things under control again. */
1135 handle_sigtstp (int signalnum
)
1137 int old_errno
= errno
;
1141 send_to_emacs (emacs_socket
, "-suspend \n");
1143 /* Unblock this signal and call the default handler by temporarily
1144 changing the handler and resignalling. */
1145 sigprocmask (SIG_BLOCK
, NULL
, &set
);
1146 sigdelset (&set
, signalnum
);
1147 signal (signalnum
, SIG_DFL
);
1148 kill (getpid (), signalnum
);
1149 sigprocmask (SIG_SETMASK
, &set
, NULL
); /* Let's the above signal through. */
1150 signal (signalnum
, handle_sigtstp
);
1156 /* Set up signal handlers before opening a frame on the current tty. */
1161 /* Set up signal handlers. */
1162 signal (SIGWINCH
, pass_signal_to_emacs
);
1164 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
1165 deciding which terminal the signal came from. C-g is now a
1166 normal input event on secondary terminals. */
1168 signal (SIGINT
, pass_signal_to_emacs
);
1169 signal (SIGQUIT
, pass_signal_to_emacs
);
1172 signal (SIGCONT
, handle_sigcont
);
1173 signal (SIGTSTP
, handle_sigtstp
);
1174 signal (SIGTTOU
, handle_sigtstp
);
1179 set_local_socket (void)
1182 struct sockaddr_un server
;
1185 * Open up an AF_UNIX socket in this person's home directory
1188 if ((s
= socket (AF_UNIX
, SOCK_STREAM
, 0)) < 0)
1190 message (TRUE
, "%s: socket: %s\n", progname
, strerror (errno
));
1191 return INVALID_SOCKET
;
1194 server
.sun_family
= AF_UNIX
;
1197 int sock_status
= 0;
1198 int default_sock
= !socket_name
;
1199 int saved_errno
= 0;
1200 const char *server_name
= "server";
1201 const char *tmpdir
IF_LINT ( = NULL
);
1203 if (socket_name
&& !strchr (socket_name
, '/')
1204 && !strchr (socket_name
, '\\'))
1206 /* socket_name is a file name component. */
1207 server_name
= socket_name
;
1209 default_sock
= 1; /* Try both UIDs. */
1214 tmpdir
= egetenv ("TMPDIR");
1218 #ifndef _CS_DARWIN_USER_TEMP_DIR
1219 #define _CS_DARWIN_USER_TEMP_DIR 65537
1221 size_t n
= confstr (_CS_DARWIN_USER_TEMP_DIR
, NULL
, (size_t) 0);
1224 tmpdir
= alloca (n
);
1225 confstr (_CS_DARWIN_USER_TEMP_DIR
, tmpdir
, n
);
1231 socket_name
= alloca (strlen (tmpdir
) + strlen (server_name
)
1233 sprintf (socket_name
, "%s/emacs%d/%s",
1234 tmpdir
, (int) geteuid (), server_name
);
1237 if (strlen (socket_name
) < sizeof (server
.sun_path
))
1238 strcpy (server
.sun_path
, socket_name
);
1241 message (TRUE
, "%s: socket-name %s too long\n",
1242 progname
, socket_name
);
1246 /* See if the socket exists, and if it's owned by us. */
1247 sock_status
= socket_status (server
.sun_path
);
1248 saved_errno
= errno
;
1249 if (sock_status
&& default_sock
)
1251 /* Failing that, see if LOGNAME or USER exist and differ from
1252 our euid. If so, look for a socket based on the UID
1253 associated with the name. This is reminiscent of the logic
1254 that init_editfns uses to set the global Vuser_full_name. */
1256 const char *user_name
= egetenv ("LOGNAME");
1259 user_name
= egetenv ("USER");
1263 struct passwd
*pw
= getpwnam (user_name
);
1265 if (pw
&& (pw
->pw_uid
!= geteuid ()))
1267 /* We're running under su, apparently. */
1268 socket_name
= alloca (strlen (tmpdir
) + strlen (server_name
)
1270 sprintf (socket_name
, "%s/emacs%d/%s",
1271 tmpdir
, (int) pw
->pw_uid
, server_name
);
1273 if (strlen (socket_name
) < sizeof (server
.sun_path
))
1274 strcpy (server
.sun_path
, socket_name
);
1277 message (TRUE
, "%s: socket-name %s too long\n",
1278 progname
, socket_name
);
1279 exit (EXIT_FAILURE
);
1282 sock_status
= socket_status (server
.sun_path
);
1283 saved_errno
= errno
;
1286 errno
= saved_errno
;
1290 switch (sock_status
)
1293 /* There's a socket, but it isn't owned by us. This is OK if
1295 if (0 != geteuid ())
1297 message (TRUE
, "%s: Invalid socket owner\n", progname
);
1298 return INVALID_SOCKET
;
1304 if (saved_errno
== ENOENT
)
1306 "%s: can't find socket; have you started the server?\n\
1307 To start the server in Emacs, type \"M-x server-start\".\n",
1310 message (TRUE
, "%s: can't stat %s: %s\n",
1311 progname
, server
.sun_path
, strerror (saved_errno
));
1312 return INVALID_SOCKET
;
1316 if (connect (s
, (struct sockaddr
*) &server
, strlen (server
.sun_path
) + 2)
1319 message (TRUE
, "%s: connect: %s\n", progname
, strerror (errno
));
1320 return INVALID_SOCKET
;
1325 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1328 set_socket (int no_exit_if_error
)
1334 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1335 /* Explicit --socket-name argument. */
1338 s
= set_local_socket ();
1339 if ((s
!= INVALID_SOCKET
) || no_exit_if_error
)
1341 message (TRUE
, "%s: error accessing socket \"%s\"\n",
1342 progname
, socket_name
);
1343 exit (EXIT_FAILURE
);
1347 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1349 server_file
= egetenv ("EMACS_SERVER_FILE");
1353 s
= set_tcp_socket ();
1354 if ((s
!= INVALID_SOCKET
) || no_exit_if_error
)
1357 message (TRUE
, "%s: error accessing server file \"%s\"\n",
1358 progname
, server_file
);
1359 exit (EXIT_FAILURE
);
1362 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1363 /* Implicit local socket. */
1364 s
= set_local_socket ();
1365 if (s
!= INVALID_SOCKET
)
1369 /* Implicit server file. */
1370 server_file
= "server";
1371 s
= set_tcp_socket ();
1372 if ((s
!= INVALID_SOCKET
) || no_exit_if_error
)
1375 /* No implicit or explicit socket, and no alternate editor. */
1376 message (TRUE
, "%s: No socket or alternate editor. Please use:\n\n"
1377 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1380 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1381 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1383 exit (EXIT_FAILURE
);
1387 FARPROC set_fg
; /* Pointer to AllowSetForegroundWindow. */
1388 FARPROC get_wc
; /* Pointer to RealGetWindowClassA. */
1391 w32_find_emacs_process (HWND hWnd
, LPARAM lParam
)
1396 /* Reject any window not of class "Emacs". */
1397 if (! get_wc (hWnd
, class, sizeof (class))
1398 || strcmp (class, "Emacs"))
1401 /* We only need the process id, not the thread id. */
1402 (void) GetWindowThreadProcessId (hWnd
, &pid
);
1404 /* Not the one we're looking for. */
1405 if (pid
!= (DWORD
) emacs_pid
) return TRUE
;
1407 /* OK, let's raise it. */
1410 /* Stop enumeration. */
1415 * Search for a window of class "Emacs" and owned by a process with
1416 * process id = emacs_pid. If found, allow it to grab the focus.
1419 w32_give_focus (void)
1423 /* It shouldn't happen when dealing with TCP sockets. */
1424 if (!emacs_pid
) return;
1426 user32
= GetModuleHandle ("user32.dll");
1431 /* Modern Windows restrict which processes can set the foreground window.
1432 emacsclient can allow Emacs to grab the focus by calling the function
1433 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1434 NT) lack this function, so we have to check its availability. */
1435 if ((set_fg
= GetProcAddress (user32
, "AllowSetForegroundWindow"))
1436 && (get_wc
= GetProcAddress (user32
, "RealGetWindowClassA")))
1437 EnumWindows (w32_find_emacs_process
, (LPARAM
) 0);
1441 /* Start the emacs daemon and try to connect to it. */
1444 start_daemon_and_retry_set_socket (void)
1455 w
= waitpid (dpid
, &status
, WUNTRACED
| WCONTINUED
);
1457 if ((w
== -1) || !WIFEXITED (status
) || WEXITSTATUS (status
))
1459 message (TRUE
, "Error: Could not start the Emacs daemon\n");
1460 exit (EXIT_FAILURE
);
1463 /* Try connecting, the daemon should have started by now. */
1464 message (TRUE
, "Emacs daemon should have started, trying to connect again\n");
1465 if ((emacs_socket
= set_socket (1)) == INVALID_SOCKET
)
1467 message (TRUE
, "Error: Cannot connect even after starting the Emacs daemon\n");
1468 exit (EXIT_FAILURE
);
1473 fprintf (stderr
, "Error: Cannot fork!\n");
1474 exit (EXIT_FAILURE
);
1478 char emacs
[] = "emacs";
1479 char daemon_option
[] = "--daemon";
1480 char *d_argv
[] = {emacs
, daemon_option
, 0 };
1481 if (socket_name
!= NULL
)
1483 /* Pass --daemon=socket_name as argument. */
1484 const char *deq
= "--daemon=";
1485 char *daemon_arg
= alloca (strlen (deq
)
1486 + strlen (socket_name
) + 1);
1487 strcpy (daemon_arg
, deq
);
1488 strcat (daemon_arg
, socket_name
);
1489 d_argv
[1] = daemon_arg
;
1491 execvp ("emacs", d_argv
);
1492 message (TRUE
, "%s: error starting emacs daemon\n", progname
);
1494 #endif /* WINDOWSNT */
1498 main (int argc
, char **argv
)
1502 char string
[BUFSIZ
+1];
1503 int null_socket_name
IF_LINT ( = 0);
1504 int null_server_file
IF_LINT ( = 0);
1505 int start_daemon_if_needed
;
1506 int exit_status
= EXIT_SUCCESS
;
1512 /* On Windows 7 and later, we need to explicitly associate emacsclient
1513 with emacs so the UI behaves sensibly. */
1514 w32_set_user_model_id ();
1517 /* Process options. */
1518 decode_options (argc
, argv
);
1520 if ((argc
- optind
< 1) && !eval
&& current_frame
)
1522 message (TRUE
, "%s: file name or argument required\n"
1523 "Try `%s --help' for more information\n",
1524 progname
, progname
);
1525 exit (EXIT_FAILURE
);
1528 /* If alternate_editor is the empty string, start the emacs daemon
1529 in case of failure to connect. */
1530 start_daemon_if_needed
= (alternate_editor
1531 && (alternate_editor
[0] == '\0'));
1532 if (start_daemon_if_needed
)
1534 /* set_socket changes the values for socket_name and
1535 server_file, we need to reset them, if they were NULL before
1536 for the second call to set_socket. */
1537 null_socket_name
= (socket_name
== NULL
);
1538 null_server_file
= (server_file
== NULL
);
1541 emacs_socket
= set_socket (alternate_editor
|| start_daemon_if_needed
);
1542 if (emacs_socket
== INVALID_SOCKET
)
1544 if (! start_daemon_if_needed
)
1547 /* Reset socket_name and server_file if they were NULL
1548 before the set_socket call. */
1549 if (null_socket_name
)
1551 if (null_server_file
)
1554 start_daemon_and_retry_set_socket ();
1557 cwd
= get_current_dir_name ();
1560 /* getwd puts message in STRING if it fails. */
1561 message (TRUE
, "%s: %s\n", progname
,
1562 "Cannot get current working directory");
1570 /* Send over our environment and current directory. */
1573 extern char **environ
;
1575 for (i
= 0; environ
[i
]; i
++)
1577 send_to_emacs (emacs_socket
, "-env ");
1578 quote_argument (emacs_socket
, environ
[i
]);
1579 send_to_emacs (emacs_socket
, " ");
1582 send_to_emacs (emacs_socket
, "-dir ");
1583 quote_argument (emacs_socket
, cwd
);
1584 send_to_emacs (emacs_socket
, "/");
1585 send_to_emacs (emacs_socket
, " ");
1589 send_to_emacs (emacs_socket
, "-nowait ");
1592 send_to_emacs (emacs_socket
, "-current-frame ");
1596 send_to_emacs (emacs_socket
, "-display ");
1597 quote_argument (emacs_socket
, display
);
1598 send_to_emacs (emacs_socket
, " ");
1603 send_to_emacs (emacs_socket
, "-parent-id ");
1604 quote_argument (emacs_socket
, parent_id
);
1605 send_to_emacs (emacs_socket
, " ");
1608 /* If using the current frame, send tty information to Emacs anyway.
1609 In daemon mode, Emacs may need to occupy this tty if no other
1610 frame is available. */
1611 if (tty
|| (current_frame
&& !eval
))
1613 const char *tty_type
, *tty_name
;
1615 if (find_tty (&tty_type
, &tty_name
, !tty
))
1617 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1620 send_to_emacs (emacs_socket
, "-tty ");
1621 quote_argument (emacs_socket
, tty_name
);
1622 send_to_emacs (emacs_socket
, " ");
1623 quote_argument (emacs_socket
, tty_type
);
1624 send_to_emacs (emacs_socket
, " ");
1628 if (!current_frame
&& !tty
)
1629 send_to_emacs (emacs_socket
, "-window-system ");
1631 if ((argc
- optind
> 0))
1634 for (i
= optind
; i
< argc
; i
++)
1639 /* Don't prepend cwd or anything like that. */
1640 send_to_emacs (emacs_socket
, "-eval ");
1641 quote_argument (emacs_socket
, argv
[i
]);
1642 send_to_emacs (emacs_socket
, " ");
1646 if (*argv
[i
] == '+')
1648 char *p
= argv
[i
] + 1;
1649 while (isdigit ((unsigned char) *p
) || *p
== ':') p
++;
1652 send_to_emacs (emacs_socket
, "-position ");
1653 quote_argument (emacs_socket
, argv
[i
]);
1654 send_to_emacs (emacs_socket
, " ");
1659 else if (! file_name_absolute_p (argv
[i
])
1660 && (isalpha (argv
[i
][0]) && argv
[i
][1] == ':'))
1661 /* Windows can have a different default directory for each
1662 drive, so the cwd passed via "-dir" is not sufficient
1663 to account for that.
1664 If the user uses <drive>:<relpath>, we hence need to be
1665 careful to expand <relpath> with the default directory
1666 corresponding to <drive>. */
1668 char *filename
= (char *) xmalloc (MAX_PATH
);
1671 size
= GetFullPathName (argv
[i
], MAX_PATH
, filename
, NULL
);
1672 if (size
> 0 && size
< MAX_PATH
)
1679 send_to_emacs (emacs_socket
, "-file ");
1680 quote_argument (emacs_socket
, argv
[i
]);
1681 send_to_emacs (emacs_socket
, " ");
1686 /* Read expressions interactively. */
1687 while ((str
= fgets (string
, BUFSIZ
, stdin
)))
1689 send_to_emacs (emacs_socket
, "-eval ");
1690 quote_argument (emacs_socket
, str
);
1692 send_to_emacs (emacs_socket
, " ");
1695 send_to_emacs (emacs_socket
, "\n");
1697 /* Wait for an answer. */
1698 if (!eval
&& !tty
&& !nowait
)
1700 printf ("Waiting for Emacs...");
1706 /* Now, wait for an answer and print any messages. */
1707 while (exit_status
== EXIT_SUCCESS
)
1713 rl
= recv (emacs_socket
, string
, BUFSIZ
, 0);
1715 /* If we receive a signal (e.g. SIGWINCH, which we pass
1716 through to Emacs), on some OSes we get EINTR and must retry. */
1717 while (rl
< 0 && errno
== EINTR
);
1724 p
= string
+ strlen (string
) - 1;
1725 while (p
> string
&& *p
== '\n')
1728 if (strprefix ("-emacs-pid ", string
))
1730 /* -emacs-pid PID: The process id of the Emacs process. */
1731 emacs_pid
= strtol (string
+ strlen ("-emacs-pid"), NULL
, 10);
1733 else if (strprefix ("-window-system-unsupported ", string
))
1735 /* -window-system-unsupported: Emacs was compiled without X
1736 support. Try again on the terminal. */
1741 else if (strprefix ("-print ", string
))
1743 /* -print STRING: Print STRING on the terminal. */
1744 str
= unquote_argument (string
+ strlen ("-print "));
1748 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1750 else if (strprefix ("-error ", string
))
1752 /* -error DESCRIPTION: Signal an error on the terminal. */
1753 str
= unquote_argument (string
+ strlen ("-error "));
1756 fprintf (stderr
, "*ERROR*: %s", str
);
1757 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1758 exit_status
= EXIT_FAILURE
;
1761 else if (strprefix ("-suspend ", string
))
1763 /* -suspend: Suspend this terminal, i.e., stop the process. */
1772 /* Unknown command. */
1775 printf ("*ERROR*: Unknown message: %s", string
);
1777 == '\0' ? needlf
: string
[strlen (string
) - 1] != '\n';
1787 exit_status
= EXIT_FAILURE
;
1789 CLOSE_SOCKET (emacs_socket
);
1793 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
1796 #ifndef HAVE_STRERROR
1801 extern char *sys_errlist
[];
1802 extern int sys_nerr
;
1804 if (errnum
>= 0 && errnum
< sys_nerr
)
1805 return sys_errlist
[errnum
];
1806 return (char *) "Unknown error";
1809 #endif /* ! HAVE_STRERROR */
1812 /* emacsclient.c ends here */