1 /* Client process that communicates with GNU Emacs acting as server.
3 Copyright (C) 1986-1987, 1994, 1999-2017 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 of the License, or (at
10 your option) 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. If not, see <http://www.gnu.org/licenses/>. */
25 /* ms-w32.h defines these, which disables sockets altogether! */
32 # include <commctrl.h>
34 # include <winsock2.h>
36 # define NO_SOCKETS_IN_FILE_SYSTEM
38 # define HSOCKET SOCKET
39 # define CLOSE_SOCKET closesocket
40 # define INITIALIZE() (initialize_sockets ())
42 char *w32_getenv (const char *);
43 #define egetenv(VAR) w32_getenv(VAR)
45 #else /* !WINDOWSNT */
49 # endif /* HAVE_NTGUI */
53 # ifdef HAVE_INET_SOCKETS
54 # include <netinet/in.h>
56 # include <sys/types.h>
57 # include <sys/socket.h>
59 # endif /* HAVE_SOCKETS */
61 # include <arpa/inet.h>
63 # define INVALID_SOCKET -1
65 # define CLOSE_SOCKET close
68 #define egetenv(VAR) getenv(VAR)
70 #endif /* !WINDOWSNT */
88 #define VERSION "unspecified"
93 #define EXIT_SUCCESS 0
97 #define EXIT_FAILURE 1
100 /* Additional space when allocating buffers for filenames, etc. */
101 #define EXTRA_SPACE 100
106 #define min(x, y) (((x) < (y)) ? (x) : (y))
109 /* Name used to invoke this program. */
110 const char *progname
;
112 /* The second argument to main. */
115 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
118 /* Nonzero means don't print messages for successful operations. --quiet. */
121 /* Nonzero means don't print values returned from emacs. --suppress-output. */
122 int suppress_output
= 0;
124 /* Nonzero means args are expressions to be evaluated. --eval. */
127 /* Nonzero means don't open a new frame. Inverse of --create-frame. */
128 int current_frame
= 1;
130 /* The display on which Emacs should work. --display. */
131 const char *display
= NULL
;
133 /* The alternate display we should try if Emacs does not support display. */
134 const char *alt_display
= NULL
;
136 /* The parent window ID, if we are opening a frame via XEmbed. */
137 char *parent_id
= NULL
;
139 /* Nonzero means open a new Emacs frame on the current terminal. */
142 /* If non-NULL, the name of an editor to fallback to if the server
143 is not running. --alternate-editor. */
144 const char *alternate_editor
= NULL
;
146 /* If non-NULL, the filename of the UNIX socket. */
147 const char *socket_name
= NULL
;
149 /* If non-NULL, the filename of the authentication file. */
150 const char *server_file
= NULL
;
152 /* PID of the Emacs server process. */
155 /* If non-NULL, a string that should form a frame parameter alist to
156 be used for the new frame. */
157 const char *frame_parameters
= NULL
;
159 static _Noreturn
void print_help_and_exit (void);
162 struct option longopts
[] =
164 { "no-wait", no_argument
, NULL
, 'n' },
165 { "quiet", no_argument
, NULL
, 'q' },
166 { "suppress-output", no_argument
, NULL
, 'u' },
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 { "frame-parameters", required_argument
, NULL
, 'F' },
175 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
176 { "socket-name", required_argument
, NULL
, 's' },
178 { "server-file", required_argument
, NULL
, 'f' },
179 { "display", required_argument
, NULL
, 'd' },
180 { "parent-id", required_argument
, NULL
, 'p' },
185 /* Like malloc but get fatal error if memory is exhausted. */
188 xmalloc (size_t size
)
190 void *result
= malloc (size
);
200 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
202 char *get_current_dir_name (void);
204 /* Return the current working directory. Returns NULL on errors.
205 Any other returned value must be freed with free. This is used
206 only when get_current_dir_name is not defined on the system. */
208 get_current_dir_name (void)
212 struct stat dotstat
, pwdstat
;
213 /* If PWD is accurate, use it instead of calling getcwd. PWD is
214 sometimes a nicer name, and using it may avoid a fatal error if a
215 parent directory is searchable but not readable. */
216 if ((pwd
= egetenv ("PWD")) != 0
217 && (IS_DIRECTORY_SEP (*pwd
) || (*pwd
&& IS_DEVICE_SEP (pwd
[1])))
218 && stat (pwd
, &pwdstat
) == 0
219 && stat (".", &dotstat
) == 0
220 && dotstat
.st_ino
== pwdstat
.st_ino
221 && dotstat
.st_dev
== pwdstat
.st_dev
223 && strlen (pwd
) < MAXPATHLEN
227 buf
= (char *) xmalloc (strlen (pwd
) + 1);
232 size_t buf_size
= 1024;
236 buf
= malloc (buf_size
);
239 if (getcwd (buf
, buf_size
) == buf
)
243 if (tmp_errno
!= ERANGE
)
262 /* Like strdup but get a fatal error if memory is exhausted. */
263 char *xstrdup (const char *);
266 xstrdup (const char *s
)
268 char *result
= strdup (s
);
277 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
279 char *w32_get_resource (HKEY
, const char *, LPDWORD
);
281 /* Retrieve an environment variable from the Emacs subkeys of the registry.
282 Return NULL if the variable was not found, or it was empty.
283 This code is based on w32_get_resource (w32.c). */
285 w32_get_resource (HKEY predefined
, const char *key
, LPDWORD type
)
287 HKEY hrootkey
= NULL
;
291 if (RegOpenKeyEx (predefined
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
293 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
)
295 result
= (char *) xmalloc (cbData
);
297 if ((RegQueryValueEx (hrootkey
, key
, NULL
, type
, (LPBYTE
)result
, &cbData
) != ERROR_SUCCESS
)
305 RegCloseKey (hrootkey
);
312 getenv wrapper for Windows
314 Value is allocated on the heap, and can be free'd.
316 This is needed to duplicate Emacs's behavior, which is to look for
317 environment variables in the registry if they don't appear in the
320 w32_getenv (const char *envvar
)
325 if ((value
= getenv (envvar
)))
326 /* Found in the environment. strdup it, because values returned
327 by getenv cannot be free'd. */
328 return xstrdup (value
);
330 if (! (value
= w32_get_resource (HKEY_CURRENT_USER
, envvar
, &dwType
)) &&
331 ! (value
= w32_get_resource (HKEY_LOCAL_MACHINE
, envvar
, &dwType
)))
333 /* "w32console" is what Emacs on Windows uses for tty-type under -nw. */
334 if (strcmp (envvar
, "TERM") == 0)
335 return xstrdup ("w32console");
336 /* Found neither in the environment nor in the registry. */
340 if (dwType
== REG_SZ
)
341 /* Registry; no need to expand. */
344 if (dwType
== REG_EXPAND_SZ
)
348 if ((size
= ExpandEnvironmentStrings (value
, NULL
, 0)))
350 char *buffer
= (char *) xmalloc (size
);
351 if (ExpandEnvironmentStrings (value
, buffer
, size
))
353 /* Found and expanded. */
358 /* Error expanding. */
363 /* Not the right type, or not correctly expanded. */
368 int w32_window_app (void);
371 w32_window_app (void)
373 static int window_app
= -1;
374 char szTitle
[MAX_PATH
];
378 /* Checking for STDOUT does not work; it's a valid handle also in
379 nonconsole apps. Testing for the console title seems to work. */
380 window_app
= (GetConsoleTitleA (szTitle
, MAX_PATH
) == 0);
382 InitCommonControls ();
388 /* execvp wrapper for Windows. Quotes arguments with embedded spaces.
390 This is necessary due to the broken implementation of exec* routines in
391 the Microsoft libraries: they concatenate the arguments together without
392 quoting special characters, and pass the result to CreateProcess, with
393 predictably bad results. By contrast, POSIX execvp passes the arguments
394 directly into the argv array of the child process. */
396 int w32_execvp (const char *, char **);
399 w32_execvp (const char *path
, char **argv
)
403 /* Required to allow a .BAT script as alternate editor. */
404 argv
[0] = (char *) alternate_editor
;
406 for (i
= 0; argv
[i
]; i
++)
407 if (strchr (argv
[i
], ' '))
409 char *quoted
= alloca (strlen (argv
[i
]) + 3);
410 sprintf (quoted
, "\"%s\"", argv
[i
]);
414 return execvp (path
, argv
);
418 #define execvp w32_execvp
420 /* Emulation of ttyname for Windows. */
421 const char *ttyname (int);
428 #endif /* WINDOWSNT */
430 /* Display a normal or error message.
431 On Windows, use a message box if compiled as a Windows app. */
432 static void message (bool, const char *, ...) ATTRIBUTE_FORMAT_PRINTF (2, 3);
434 message (bool is_error
, const char *format
, ...)
438 va_start (args
, format
);
441 if (w32_window_app ())
444 vsnprintf (msg
, sizeof msg
, format
, args
);
445 msg
[sizeof msg
- 1] = '\0';
448 MessageBox (NULL
, msg
, "Emacsclient ERROR", MB_ICONERROR
);
450 MessageBox (NULL
, msg
, "Emacsclient", MB_ICONINFORMATION
);
455 FILE *f
= is_error
? stderr
: stdout
;
457 vfprintf (f
, format
, args
);
464 /* Decode the options from argv and argc.
465 The global variable `optind' will say how many arguments we used up. */
468 decode_options (int argc
, char **argv
)
470 alternate_editor
= egetenv ("ALTERNATE_EDITOR");
474 int opt
= getopt_long_only (argc
, argv
,
475 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
476 "VHnequa:s:f:d:F:tc",
488 /* If getopt returns 0, then it has already processed a
489 long-named option. We should do nothing. */
493 alternate_editor
= optarg
;
496 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
498 socket_name
= optarg
;
503 server_file
= optarg
;
506 /* We used to disallow this argument in w32, but it seems better
507 to allow it, for the occasional case where the user is
508 connecting with a w32 client to a server compiled with X11
531 message (false, "emacsclient %s\n", VERSION
);
550 print_help_and_exit ();
554 frame_parameters
= optarg
;
558 message (true, "Try '%s --help' for more information\n", progname
);
564 /* If the -c option is used (without -t) and no --display argument
565 is provided, try $DISPLAY.
566 Without the -c option, we used to set `display' to $DISPLAY by
567 default, but this changed the default behavior and is sometimes
568 inconvenient. So we force users to use "--display $DISPLAY" if
569 they want Emacs to connect to their current display.
571 Some window systems have a notion of default display not
572 reflected in the DISPLAY variable. If the user didn't give us an
573 explicit display, try this platform-specific after trying the
574 display in DISPLAY (if any). */
575 if (!current_frame
&& !tty
&& !display
)
577 /* Set these here so we use a default_display only when the user
578 didn't give us an explicit display. */
579 #if defined (NS_IMPL_COCOA)
581 #elif defined (HAVE_NTGUI)
585 display
= egetenv ("DISPLAY");
590 display
= alt_display
;
594 /* A null-string display is invalid. */
595 if (display
&& strlen (display
) == 0)
598 /* If no display is available, new frames are tty frames. */
599 if (!current_frame
&& !display
)
603 /* Emacs on Windows does not support graphical and text terminal
604 frames in the same instance. So, treat the -t and -c options as
605 equivalent, and open a new frame on the server's terminal.
606 Ideally, we would only set tty = 1 when the serve is running in a
607 console, but alas we don't know that. As a workaround, always
608 ask for a tty frame, and let server.el figure it out. */
614 #endif /* WINDOWSNT */
618 static _Noreturn
void
619 print_help_and_exit (void)
621 /* Spaces and tabs are significant in this message; they're chosen so the
622 message aligns properly both in a tty and in a Windows message box.
623 Please try to preserve them; otherwise the output is very hard to read
624 when using emacsclientw. */
626 "Usage: %s [OPTIONS] FILE...\n%s%s%s", progname
, "\
627 Tell the Emacs server to visit the specified files.\n\
628 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
630 The following OPTIONS are accepted:\n\
631 -V, --version Just print version info and return\n\
632 -H, --help Print this usage information message\n\
633 -nw, -t, --tty Open a new Emacs frame on the current terminal\n\
634 -c, --create-frame Create a new frame instead of trying to\n\
635 use the current Emacs frame\n\
637 -F ALIST, --frame-parameters=ALIST\n\
638 Set the parameters of a new frame\n\
639 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
640 -n, --no-wait Don't wait for the server to return\n\
641 -q, --quiet Don't display messages on success\n\
642 -u, --suppress-output Don't display return values from the server\n\
643 -d DISPLAY, --display=DISPLAY\n\
644 Visit the file in the given display\n\
646 --parent-id=ID Open in parent window ID, via XEmbed\n"
647 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
648 "-s SOCKET, --socket-name=SOCKET\n\
649 Set filename of the UNIX socket for communication\n"
651 "-f SERVER, --server-file=SERVER\n\
652 Set filename of the TCP authentication file\n\
653 -a EDITOR, --alternate-editor=EDITOR\n\
654 Editor to fallback to if the server is not running\n"
655 " If EDITOR is the empty string, start Emacs in daemon\n\
656 mode and try connecting again\n"
658 Report bugs with M-x report-emacs-bug.\n");
662 /* Try to run a different command, or --if no alternate editor is
663 defined-- exit with an errorcode.
664 Uses argv, but gets it from the global variable main_argv. */
666 static _Noreturn
void
669 if (alternate_editor
)
673 execvp (alternate_editor
, main_argv
+ i
);
674 message (true, "%s: error executing alternate editor \"%s\"\n",
675 progname
, alternate_editor
);
681 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
684 main (int argc
, char **argv
)
688 message (true, "%s: Sorry, the Emacs server is supported only\n"
689 "on systems with Berkeley sockets.\n",
694 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
696 #define AUTH_KEY_LENGTH 64
697 #define SEND_BUFFER_SIZE 4096
699 /* Buffer to accumulate data to send in TCP connections. */
700 char send_buffer
[SEND_BUFFER_SIZE
+ 1];
701 int sblen
= 0; /* Fill pointer for the send buffer. */
702 /* Socket used to communicate with the Emacs server process. */
703 HSOCKET emacs_socket
= 0;
705 /* On Windows, the socket library was historically separate from the
706 standard C library, so errors are handled differently. */
709 sock_err_message (const char *function_name
)
714 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
715 | FORMAT_MESSAGE_ALLOCATE_BUFFER
716 | FORMAT_MESSAGE_ARGUMENT_ARRAY
,
717 NULL
, WSAGetLastError (), 0, (LPTSTR
)&msg
, 0, NULL
);
719 message (true, "%s: %s: %s\n", progname
, function_name
, msg
);
723 message (true, "%s: %s: %s\n", progname
, function_name
, strerror (errno
));
728 /* Let's send the data to Emacs when either
729 - the data ends in "\n", or
730 - the buffer is full (but this shouldn't happen)
731 Otherwise, we just accumulate it. */
733 send_to_emacs (HSOCKET s
, const char *data
)
740 dlen
= strlen (data
);
743 size_t part
= min (dlen
, SEND_BUFFER_SIZE
- sblen
);
744 memcpy (&send_buffer
[sblen
], data
, part
);
748 if (sblen
== SEND_BUFFER_SIZE
749 || (sblen
> 0 && send_buffer
[sblen
-1] == '\n'))
751 int sent
= send (s
, send_buffer
, sblen
, 0);
754 message (true, "%s: failed to send %d bytes to socket: %s\n",
755 progname
, sblen
, strerror (errno
));
759 memmove (send_buffer
, &send_buffer
[sent
], sblen
- sent
);
768 /* In STR, insert a & before each &, each space, each newline, and
769 any initial -. Change spaces to underscores, too, so that the
770 return value never contains a space.
772 Does not change the string. Outputs the result to S. */
774 quote_argument (HSOCKET s
, const char *str
)
776 char *copy
= (char *) xmalloc (strlen (str
) * 2 + 1);
798 if (*p
== '&' || (*p
== '-' && p
== str
))
805 send_to_emacs (s
, copy
);
811 /* The inverse of quote_argument. Removes quoting in string STR by
812 modifying the string in place. Returns STR. */
815 unquote_argument (char *str
)
846 file_name_absolute_p (const char *filename
)
848 /* Sanity check, it shouldn't happen. */
849 if (! filename
) return false;
851 /* /xxx is always an absolute path. */
852 if (filename
[0] == '/') return true;
854 /* Empty filenames (which shouldn't happen) are relative. */
855 if (filename
[0] == '\0') return false;
858 /* X:\xxx is always absolute. */
859 if (isalpha ((unsigned char) filename
[0])
860 && filename
[1] == ':' && (filename
[2] == '\\' || filename
[2] == '/'))
863 /* Both \xxx and \\xxx\yyy are absolute. */
864 if (filename
[0] == '\\') return true;
871 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
872 void __cdecl
close_winsock (void);
879 /* Initialize the WinSock2 library. */
880 void initialize_sockets (void);
882 initialize_sockets (void)
886 if (WSAStartup (MAKEWORD (2, 0), &wsaData
))
888 message (true, "%s: error initializing WinSock2\n", progname
);
892 atexit (close_winsock
);
894 #endif /* WINDOWSNT */
897 /* Read the information needed to set up a TCP comm channel with
898 the Emacs server: host, port, and authentication string. */
901 get_server_config (const char *config_file
, struct sockaddr_in
*server
,
902 char *authentication
)
908 if (file_name_absolute_p (config_file
))
909 config
= fopen (config_file
, "rb");
912 const char *home
= egetenv ("HOME");
916 char *path
= xmalloc (strlen (home
) + strlen (config_file
)
918 char *z
= stpcpy (path
, home
);
919 z
= stpcpy (z
, "/.emacs.d/server/");
920 strcpy (z
, config_file
);
921 config
= fopen (path
, "rb");
925 if (!config
&& (home
= egetenv ("APPDATA")))
927 char *path
= xmalloc (strlen (home
) + strlen (config_file
)
929 char *z
= stpcpy (path
, home
);
930 z
= stpcpy (z
, "/.emacs.d/server/");
931 strcpy (z
, config_file
);
932 config
= fopen (path
, "rb");
941 if (fgets (dotted
, sizeof dotted
, config
)
942 && (port
= strchr (dotted
, ':')))
946 message (true, "%s: invalid configuration info\n", progname
);
950 server
->sin_family
= AF_INET
;
951 server
->sin_addr
.s_addr
= inet_addr (dotted
);
952 server
->sin_port
= htons (atoi (port
));
954 if (! fread (authentication
, AUTH_KEY_LENGTH
, 1, config
))
956 message (true, "%s: cannot read authentication info\n", progname
);
966 set_tcp_socket (const char *local_server_file
)
969 struct sockaddr_in server
;
970 struct linger l_arg
= {1, 1};
971 char auth_string
[AUTH_KEY_LENGTH
+ 1];
973 if (! get_server_config (local_server_file
, &server
, auth_string
))
974 return INVALID_SOCKET
;
976 if (server
.sin_addr
.s_addr
!= inet_addr ("127.0.0.1") && !quiet
)
977 message (false, "%s: connected to remote socket at %s\n",
978 progname
, inet_ntoa (server
.sin_addr
));
980 /* Open up an AF_INET socket. */
981 if ((s
= socket (AF_INET
, SOCK_STREAM
, IPPROTO_TCP
)) < 0)
983 /* Since we have an alternate to try out, this is not an error
984 yet; popping out a modal dialog at this stage would make -a
985 option totally useless for emacsclientw -- the user will
986 still get an error message if the alternate editor fails. */
988 if(!(w32_window_app () && alternate_editor
))
990 sock_err_message ("socket");
991 return INVALID_SOCKET
;
994 /* Set up the socket. */
995 if (connect (s
, (struct sockaddr
*) &server
, sizeof server
) < 0)
998 if(!(w32_window_app () && alternate_editor
))
1000 sock_err_message ("connect");
1001 return INVALID_SOCKET
;
1004 setsockopt (s
, SOL_SOCKET
, SO_LINGER
, (char *) &l_arg
, sizeof l_arg
);
1006 /* Send the authentication. */
1007 auth_string
[AUTH_KEY_LENGTH
] = '\0';
1009 send_to_emacs (s
, "-auth ");
1010 send_to_emacs (s
, auth_string
);
1011 send_to_emacs (s
, " ");
1017 /* Returns 1 if PREFIX is a prefix of STRING. */
1019 strprefix (const char *prefix
, const char *string
)
1021 return !strncmp (prefix
, string
, strlen (prefix
));
1024 /* Get tty name and type. If successful, return the type in TTY_TYPE
1025 and the name in TTY_NAME, and return 1. Otherwise, fail if NOABORT
1026 is zero, or return 0 if NOABORT is non-zero. */
1029 find_tty (const char **tty_type
, const char **tty_name
, int noabort
)
1031 const char *type
= egetenv ("TERM");
1032 const char *name
= ttyname (fileno (stdout
));
1040 message (true, "%s: could not get terminal name\n", progname
);
1051 message (true, "%s: please set the TERM variable to your terminal type\n",
1057 if (strcmp (type
, "eterm") == 0)
1063 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1064 message (true, "%s: opening a frame in an Emacs term buffer"
1065 " is not supported\n", progname
);
1076 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1078 /* Three possibilities:
1079 2 - can't be `stat'ed (sets errno)
1080 1 - isn't owned by us
1081 0 - success: none of the above */
1084 socket_status (const char *name
)
1086 struct stat statbfr
;
1088 if (stat (name
, &statbfr
) == -1)
1091 if (statbfr
.st_uid
!= geteuid ())
1098 /* A signal handler that passes the signal to the Emacs process.
1099 Useful for SIGWINCH. */
1102 pass_signal_to_emacs (int signalnum
)
1104 int old_errno
= errno
;
1107 kill (emacs_pid
, signalnum
);
1109 signal (signalnum
, pass_signal_to_emacs
);
1113 /* Signal handler for SIGCONT; notify the Emacs process that it can
1114 now resume our tty frame. */
1117 handle_sigcont (int signalnum
)
1119 int old_errno
= errno
;
1120 pid_t pgrp
= getpgrp ();
1121 pid_t tcpgrp
= tcgetpgrp (1);
1125 /* We are in the foreground. */
1126 send_to_emacs (emacs_socket
, "-resume \n");
1128 else if (0 <= tcpgrp
&& tty
)
1130 /* We are in the background; cancel the continue. */
1131 kill (-pgrp
, SIGTTIN
);
1134 signal (signalnum
, handle_sigcont
);
1138 /* Signal handler for SIGTSTP; notify the Emacs process that we are
1139 going to sleep. Normally the suspend is initiated by Emacs via
1140 server-handle-suspend-tty, but if the server gets out of sync with
1141 reality, we may get a SIGTSTP on C-z. Handling this signal and
1142 notifying Emacs about it should get things under control again. */
1145 handle_sigtstp (int signalnum
)
1147 int old_errno
= errno
;
1151 send_to_emacs (emacs_socket
, "-suspend \n");
1153 /* Unblock this signal and call the default handler by temporarily
1154 changing the handler and resignaling. */
1155 sigprocmask (SIG_BLOCK
, NULL
, &set
);
1156 sigdelset (&set
, signalnum
);
1157 signal (signalnum
, SIG_DFL
);
1159 sigprocmask (SIG_SETMASK
, &set
, NULL
); /* Let's the above signal through. */
1160 signal (signalnum
, handle_sigtstp
);
1166 /* Set up signal handlers before opening a frame on the current tty. */
1171 /* Set up signal handlers. */
1172 signal (SIGWINCH
, pass_signal_to_emacs
);
1174 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
1175 deciding which terminal the signal came from. C-g is now a
1176 normal input event on secondary terminals. */
1178 signal (SIGINT
, pass_signal_to_emacs
);
1179 signal (SIGQUIT
, pass_signal_to_emacs
);
1182 signal (SIGCONT
, handle_sigcont
);
1183 signal (SIGTSTP
, handle_sigtstp
);
1184 signal (SIGTTOU
, handle_sigtstp
);
1189 set_local_socket (const char *local_socket_name
)
1192 struct sockaddr_un server
;
1194 /* Open up an AF_UNIX socket in this person's home directory. */
1195 if ((s
= socket (AF_UNIX
, SOCK_STREAM
, 0)) < 0)
1197 message (true, "%s: socket: %s\n", progname
, strerror (errno
));
1198 return INVALID_SOCKET
;
1201 server
.sun_family
= AF_UNIX
;
1206 const char *server_name
= local_socket_name
;
1207 const char *tmpdir
= NULL
;
1208 char *tmpdir_storage
= NULL
;
1209 char *socket_name_storage
= NULL
;
1211 if (!strchr (local_socket_name
, '/') && !strchr (local_socket_name
, '\\'))
1213 /* socket_name is a file name component. */
1214 long uid
= geteuid ();
1215 tmpdir
= egetenv ("TMPDIR");
1219 #ifndef _CS_DARWIN_USER_TEMP_DIR
1220 #define _CS_DARWIN_USER_TEMP_DIR 65537
1222 size_t n
= confstr (_CS_DARWIN_USER_TEMP_DIR
, NULL
, (size_t) 0);
1225 tmpdir
= tmpdir_storage
= xmalloc (n
);
1226 confstr (_CS_DARWIN_USER_TEMP_DIR
, tmpdir_storage
, n
);
1232 socket_name_storage
=
1233 xmalloc (strlen (tmpdir
) + strlen (server_name
) + EXTRA_SPACE
);
1234 char *z
= stpcpy (socket_name_storage
, tmpdir
);
1235 z
+= sprintf (z
, "/emacs%ld/", uid
);
1236 strcpy (z
, server_name
);
1237 local_socket_name
= socket_name_storage
;
1240 if (strlen (local_socket_name
) < sizeof (server
.sun_path
))
1241 strcpy (server
.sun_path
, local_socket_name
);
1244 message (true, "%s: socket-name %s too long\n",
1245 progname
, local_socket_name
);
1249 /* See if the socket exists, and if it's owned by us. */
1250 sock_status
= socket_status (server
.sun_path
);
1251 saved_errno
= errno
;
1252 if (sock_status
&& tmpdir
)
1254 /* Failing that, see if LOGNAME or USER exist and differ from
1255 our euid. If so, look for a socket based on the UID
1256 associated with the name. This is reminiscent of the logic
1257 that init_editfns uses to set the global Vuser_full_name. */
1259 const char *user_name
= egetenv ("LOGNAME");
1262 user_name
= egetenv ("USER");
1266 struct passwd
*pw
= getpwnam (user_name
);
1268 if (pw
&& (pw
->pw_uid
!= geteuid ()))
1270 /* We're running under su, apparently. */
1271 long uid
= pw
->pw_uid
;
1272 char *user_socket_name
1273 = xmalloc (strlen (tmpdir
) + strlen (server_name
)
1275 char *z
= stpcpy (user_socket_name
, tmpdir
);
1276 z
+= sprintf (z
, "/emacs%ld/", uid
);
1277 strcpy (z
, server_name
);
1279 if (strlen (user_socket_name
) < sizeof (server
.sun_path
))
1280 strcpy (server
.sun_path
, user_socket_name
);
1283 message (true, "%s: socket-name %s too long\n",
1284 progname
, user_socket_name
);
1285 exit (EXIT_FAILURE
);
1287 free (user_socket_name
);
1289 sock_status
= socket_status (server
.sun_path
);
1290 saved_errno
= errno
;
1293 errno
= saved_errno
;
1297 free (socket_name_storage
);
1298 free (tmpdir_storage
);
1300 switch (sock_status
)
1303 /* There's a socket, but it isn't owned by us. This is OK if
1305 if (0 != geteuid ())
1307 message (true, "%s: Invalid socket owner\n", progname
);
1308 return INVALID_SOCKET
;
1314 if (saved_errno
== ENOENT
)
1316 "%s: can't find socket; have you started the server?\n\
1317 To start the server in Emacs, type \"M-x server-start\".\n",
1320 message (true, "%s: can't stat %s: %s\n",
1321 progname
, server
.sun_path
, strerror (saved_errno
));
1322 return INVALID_SOCKET
;
1326 if (connect (s
, (struct sockaddr
*) &server
, strlen (server
.sun_path
) + 2)
1329 message (true, "%s: connect: %s\n", progname
, strerror (errno
));
1330 return INVALID_SOCKET
;
1335 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1338 set_socket (int no_exit_if_error
)
1341 const char *local_server_file
= server_file
;
1345 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1346 /* Explicit --socket-name argument. */
1349 s
= set_local_socket (socket_name
);
1350 if ((s
!= INVALID_SOCKET
) || no_exit_if_error
)
1352 message (true, "%s: error accessing socket \"%s\"\n",
1353 progname
, socket_name
);
1354 exit (EXIT_FAILURE
);
1358 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1359 if (!local_server_file
)
1360 local_server_file
= egetenv ("EMACS_SERVER_FILE");
1362 if (local_server_file
)
1364 s
= set_tcp_socket (local_server_file
);
1365 if ((s
!= INVALID_SOCKET
) || no_exit_if_error
)
1368 message (true, "%s: error accessing server file \"%s\"\n",
1369 progname
, local_server_file
);
1370 exit (EXIT_FAILURE
);
1373 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1374 /* Implicit local socket. */
1375 s
= set_local_socket ("server");
1376 if (s
!= INVALID_SOCKET
)
1380 /* Implicit server file. */
1381 s
= set_tcp_socket ("server");
1382 if ((s
!= INVALID_SOCKET
) || no_exit_if_error
)
1385 /* No implicit or explicit socket, and no alternate editor. */
1386 message (true, "%s: No socket or alternate editor. Please use:\n\n"
1387 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1390 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1391 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1393 exit (EXIT_FAILURE
);
1397 FARPROC set_fg
; /* Pointer to AllowSetForegroundWindow. */
1398 FARPROC get_wc
; /* Pointer to RealGetWindowClassA. */
1400 void w32_set_user_model_id (void);
1403 w32_set_user_model_id (void)
1406 HRESULT (WINAPI
* set_user_model
) (const wchar_t * id
);
1408 /* On Windows 7 and later, we need to set the user model ID
1409 to associate emacsclient launched files with Emacs frames
1411 shell
= LoadLibrary ("shell32.dll");
1415 = (void *) GetProcAddress (shell
,
1416 "SetCurrentProcessExplicitAppUserModelID");
1417 /* If the function is defined, then we are running on Windows 7
1418 or newer, and the UI uses this to group related windows
1419 together. Since emacs, runemacs, emacsclient are related, we
1420 want them grouped even though the executables are different,
1421 so we need to set a consistent ID between them. */
1423 set_user_model (L
"GNU.Emacs");
1425 FreeLibrary (shell
);
1429 BOOL CALLBACK
w32_find_emacs_process (HWND
, LPARAM
);
1432 w32_find_emacs_process (HWND hWnd
, LPARAM lParam
)
1437 /* Reject any window not of class "Emacs". */
1438 if (! get_wc (hWnd
, class, sizeof (class))
1439 || strcmp (class, "Emacs"))
1442 /* We only need the process id, not the thread id. */
1443 (void) GetWindowThreadProcessId (hWnd
, &pid
);
1445 /* Not the one we're looking for. */
1446 if (pid
!= (DWORD
) emacs_pid
) return TRUE
;
1448 /* OK, let's raise it. */
1451 /* Stop enumeration. */
1455 /* Search for a window of class "Emacs" and owned by a process with
1456 process id = emacs_pid. If found, allow it to grab the focus. */
1457 void w32_give_focus (void);
1460 w32_give_focus (void)
1464 /* It shouldn't happen when dealing with TCP sockets. */
1465 if (!emacs_pid
) return;
1467 user32
= GetModuleHandle ("user32.dll");
1472 /* Modern Windows restrict which processes can set the foreground window.
1473 emacsclient can allow Emacs to grab the focus by calling the function
1474 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1475 NT) lack this function, so we have to check its availability. */
1476 if ((set_fg
= GetProcAddress (user32
, "AllowSetForegroundWindow"))
1477 && (get_wc
= GetProcAddress (user32
, "RealGetWindowClassA")))
1478 EnumWindows (w32_find_emacs_process
, (LPARAM
) 0);
1480 #endif /* HAVE_NTGUI */
1482 /* Start the emacs daemon and try to connect to it. */
1485 start_daemon_and_retry_set_socket (void)
1496 w
= waitpid (dpid
, &status
, WUNTRACED
| WCONTINUED
);
1498 if ((w
== -1) || !WIFEXITED (status
) || WEXITSTATUS (status
))
1500 message (true, "Error: Could not start the Emacs daemon\n");
1501 exit (EXIT_FAILURE
);
1504 /* Try connecting, the daemon should have started by now. */
1505 message (true, "Emacs daemon should have started, trying to connect again\n");
1506 if ((emacs_socket
= set_socket (1)) == INVALID_SOCKET
)
1508 message (true, "Error: Cannot connect even after starting the Emacs daemon\n");
1509 exit (EXIT_FAILURE
);
1514 fprintf (stderr
, "Error: Cannot fork!\n");
1515 exit (EXIT_FAILURE
);
1519 char emacs
[] = "emacs";
1520 char daemon_option
[] = "--daemon";
1523 d_argv
[1] = daemon_option
;
1525 if (socket_name
!= NULL
)
1527 /* Pass --daemon=socket_name as argument. */
1528 const char *deq
= "--daemon=";
1529 char *daemon_arg
= xmalloc (strlen (deq
)
1530 + strlen (socket_name
) + 1);
1531 strcpy (stpcpy (daemon_arg
, deq
), socket_name
);
1532 d_argv
[1] = daemon_arg
;
1534 execvp ("emacs", d_argv
);
1535 message (true, "%s: error starting emacs daemon\n", progname
);
1537 #else /* WINDOWSNT */
1539 HANDLE w32_daemon_event
;
1541 PROCESS_INFORMATION pi
;
1543 ZeroMemory (&si
, sizeof si
);
1545 ZeroMemory (&pi
, sizeof pi
);
1547 /* We start Emacs in daemon mode, and then wait for it to signal us
1548 it is ready to accept client connections, by asserting an event
1549 whose name is known to the daemon (defined by nt/inc/ms-w32.h). */
1551 if (!CreateProcess (NULL
, (LPSTR
)"emacs --daemon", NULL
, NULL
, FALSE
,
1552 CREATE_NO_WINDOW
, NULL
, NULL
, &si
, &pi
))
1556 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
1557 | FORMAT_MESSAGE_ALLOCATE_BUFFER
1558 | FORMAT_MESSAGE_ARGUMENT_ARRAY
,
1559 NULL
, GetLastError (), 0, (LPTSTR
)&msg
, 0, NULL
);
1560 message (true, "%s: error starting emacs daemon (%s)\n", progname
, msg
);
1561 exit (EXIT_FAILURE
);
1564 w32_daemon_event
= CreateEvent (NULL
, TRUE
, FALSE
, W32_DAEMON_EVENT
);
1565 if (w32_daemon_event
== NULL
)
1567 message (true, "Couldn't create Windows daemon event");
1568 exit (EXIT_FAILURE
);
1570 if ((wait_result
= WaitForSingleObject (w32_daemon_event
, INFINITE
))
1573 const char *msg
= NULL
;
1575 switch (wait_result
)
1577 case WAIT_ABANDONED
:
1578 msg
= "The daemon exited unexpectedly";
1581 /* Can't happen due to INFINITE. */
1584 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
1585 | FORMAT_MESSAGE_ALLOCATE_BUFFER
1586 | FORMAT_MESSAGE_ARGUMENT_ARRAY
,
1587 NULL
, GetLastError (), 0, (LPTSTR
)&msg
, 0, NULL
);
1590 message (true, "Error: Could not start the Emacs daemon: %s\n", msg
);
1591 exit (EXIT_FAILURE
);
1593 CloseHandle (w32_daemon_event
);
1595 /* Try connecting, the daemon should have started by now. */
1596 /* It's just a progress message, so don't pop a dialog if this is
1598 if (!w32_window_app ())
1600 "Emacs daemon should have started, trying to connect again\n");
1601 if ((emacs_socket
= set_socket (1)) == INVALID_SOCKET
)
1604 "Error: Cannot connect even after starting the Emacs daemon\n");
1605 exit (EXIT_FAILURE
);
1607 #endif /* WINDOWSNT */
1611 main (int argc
, char **argv
)
1613 int rl
= 0, needlf
= 0;
1615 char string
[BUFSIZ
+1];
1616 int start_daemon_if_needed
;
1617 int exit_status
= EXIT_SUCCESS
;
1623 /* On Windows 7 and later, we need to explicitly associate
1624 emacsclient with emacs so the UI behaves sensibly. This
1625 association does no harm if we're not actually connecting to an
1626 Emacs using a window display. */
1627 w32_set_user_model_id ();
1628 #endif /* HAVE_NTGUI */
1630 /* Process options. */
1631 decode_options (argc
, argv
);
1633 if ((argc
- optind
< 1) && !eval
&& current_frame
)
1635 message (true, "%s: file name or argument required\n"
1636 "Try '%s --help' for more information\n",
1637 progname
, progname
);
1638 exit (EXIT_FAILURE
);
1644 pid_t pgrp
= getpgrp ();
1645 pid_t tcpgrp
= tcgetpgrp (1);
1646 if (0 <= tcpgrp
&& tcpgrp
!= pgrp
)
1647 kill (-pgrp
, SIGTTIN
);
1649 #endif /* !WINDOWSNT */
1651 /* If alternate_editor is the empty string, start the emacs daemon
1652 in case of failure to connect. */
1653 start_daemon_if_needed
= (alternate_editor
1654 && (alternate_editor
[0] == '\0'));
1656 emacs_socket
= set_socket (alternate_editor
|| start_daemon_if_needed
);
1657 if (emacs_socket
== INVALID_SOCKET
)
1659 if (! start_daemon_if_needed
)
1662 start_daemon_and_retry_set_socket ();
1665 cwd
= get_current_dir_name ();
1668 message (true, "%s: %s\n", progname
,
1669 "Cannot get current working directory");
1674 if (display
&& !strcmp (display
, "w32"))
1676 #endif /* HAVE_NTGUI */
1678 /* Send over our environment and current directory. */
1682 for (i
= 0; environ
[i
]; i
++)
1684 send_to_emacs (emacs_socket
, "-env ");
1685 quote_argument (emacs_socket
, environ
[i
]);
1686 send_to_emacs (emacs_socket
, " ");
1689 send_to_emacs (emacs_socket
, "-dir ");
1690 quote_argument (emacs_socket
, cwd
);
1691 send_to_emacs (emacs_socket
, "/");
1692 send_to_emacs (emacs_socket
, " ");
1696 send_to_emacs (emacs_socket
, "-nowait ");
1699 send_to_emacs (emacs_socket
, "-current-frame ");
1703 send_to_emacs (emacs_socket
, "-display ");
1704 quote_argument (emacs_socket
, display
);
1705 send_to_emacs (emacs_socket
, " ");
1710 send_to_emacs (emacs_socket
, "-parent-id ");
1711 quote_argument (emacs_socket
, parent_id
);
1712 send_to_emacs (emacs_socket
, " ");
1715 if (frame_parameters
&& !current_frame
)
1717 send_to_emacs (emacs_socket
, "-frame-parameters ");
1718 quote_argument (emacs_socket
, frame_parameters
);
1719 send_to_emacs (emacs_socket
, " ");
1722 /* Unless we are certain we don't want to occupy the tty, send our
1723 tty information to Emacs. For example, in daemon mode Emacs may
1724 need to occupy this tty if no other frame is available. */
1725 if (!current_frame
|| !eval
)
1727 const char *tty_type
, *tty_name
;
1729 if (find_tty (&tty_type
, &tty_name
, !tty
))
1731 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1734 send_to_emacs (emacs_socket
, "-tty ");
1735 quote_argument (emacs_socket
, tty_name
);
1736 send_to_emacs (emacs_socket
, " ");
1737 quote_argument (emacs_socket
, tty_type
);
1738 send_to_emacs (emacs_socket
, " ");
1742 if (!current_frame
&& !tty
)
1743 send_to_emacs (emacs_socket
, "-window-system ");
1745 if ((argc
- optind
> 0))
1748 for (i
= optind
; i
< argc
; i
++)
1753 /* Don't prepend cwd or anything like that. */
1754 send_to_emacs (emacs_socket
, "-eval ");
1755 quote_argument (emacs_socket
, argv
[i
]);
1756 send_to_emacs (emacs_socket
, " ");
1760 if (*argv
[i
] == '+')
1762 char *p
= argv
[i
] + 1;
1763 while (isdigit ((unsigned char) *p
) || *p
== ':') p
++;
1766 send_to_emacs (emacs_socket
, "-position ");
1767 quote_argument (emacs_socket
, argv
[i
]);
1768 send_to_emacs (emacs_socket
, " ");
1773 else if (! file_name_absolute_p (argv
[i
])
1774 && (isalpha (argv
[i
][0]) && argv
[i
][1] == ':'))
1775 /* Windows can have a different default directory for each
1776 drive, so the cwd passed via "-dir" is not sufficient
1777 to account for that.
1778 If the user uses <drive>:<relpath>, we hence need to be
1779 careful to expand <relpath> with the default directory
1780 corresponding to <drive>. */
1782 char *filename
= (char *) xmalloc (MAX_PATH
);
1785 size
= GetFullPathName (argv
[i
], MAX_PATH
, filename
, NULL
);
1786 if (size
> 0 && size
< MAX_PATH
)
1793 send_to_emacs (emacs_socket
, "-file ");
1794 quote_argument (emacs_socket
, argv
[i
]);
1795 send_to_emacs (emacs_socket
, " ");
1800 /* Read expressions interactively. */
1801 while ((str
= fgets (string
, BUFSIZ
, stdin
)))
1803 send_to_emacs (emacs_socket
, "-eval ");
1804 quote_argument (emacs_socket
, str
);
1806 send_to_emacs (emacs_socket
, " ");
1809 send_to_emacs (emacs_socket
, "\n");
1811 /* Wait for an answer. */
1812 if (!eval
&& !tty
&& !nowait
&& !quiet
)
1814 printf ("Waiting for Emacs...");
1818 while (fdatasync (1) != 0 && errno
== EINTR
)
1821 /* Now, wait for an answer and print any messages. */
1822 while (exit_status
== EXIT_SUCCESS
)
1828 rl
= recv (emacs_socket
, string
, BUFSIZ
, 0);
1830 /* If we receive a signal (e.g. SIGWINCH, which we pass
1831 through to Emacs), on some OSes we get EINTR and must retry. */
1832 while (rl
< 0 && errno
== EINTR
);
1839 /* Loop over all NL-terminated messages. */
1840 for (end_p
= p
= string
; end_p
!= NULL
&& *end_p
!= '\0'; p
= end_p
)
1842 end_p
= strchr (p
, '\n');
1846 if (strprefix ("-emacs-pid ", p
))
1848 /* -emacs-pid PID: The process id of the Emacs process. */
1849 emacs_pid
= strtol (p
+ strlen ("-emacs-pid"), NULL
, 10);
1851 else if (strprefix ("-window-system-unsupported ", p
))
1853 /* -window-system-unsupported: Emacs was compiled without support
1854 for whatever window system we tried. Try the alternate
1855 display, or, failing that, try the terminal. */
1858 display
= alt_display
;
1869 else if (strprefix ("-print ", p
))
1871 /* -print STRING: Print STRING on the terminal. */
1872 if (!suppress_output
)
1874 str
= unquote_argument (p
+ strlen ("-print "));
1878 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1881 else if (strprefix ("-print-nonl ", p
))
1883 /* -print-nonl STRING: Print STRING on the terminal.
1884 Used to continue a preceding -print command. */
1885 if (!suppress_output
)
1887 str
= unquote_argument (p
+ strlen ("-print-nonl "));
1889 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1892 else if (strprefix ("-error ", p
))
1894 /* -error DESCRIPTION: Signal an error on the terminal. */
1895 str
= unquote_argument (p
+ strlen ("-error "));
1898 fprintf (stderr
, "*ERROR*: %s", str
);
1899 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1900 exit_status
= EXIT_FAILURE
;
1903 else if (strprefix ("-suspend ", p
))
1905 /* -suspend: Suspend this terminal, i.e., stop the process. */
1914 /* Unknown command. */
1918 printf ("*ERROR*: Unknown message: %s\n", p
);
1926 while (fdatasync (1) != 0 && errno
== EINTR
)
1930 exit_status
= EXIT_FAILURE
;
1932 CLOSE_SOCKET (emacs_socket
);
1936 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */