1 /* Client process that communicates with GNU Emacs acting as server.
2 Copyright (C) 1986, 1987, 1994, 1999, 2000, 2001, 2002, 2003, 2004,
3 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at 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/>. */
27 /* config.h defines these, which disables sockets altogether! */
34 # include <commctrl.h>
36 # define NO_SOCKETS_IN_FILE_SYSTEM
38 # define HSOCKET SOCKET
39 # define CLOSE_SOCKET closesocket
40 # define INITIALIZE() (initialize_sockets ())
42 #else /* !WINDOWSNT */
44 # include <sys/types.h>
46 # ifdef HAVE_INET_SOCKETS
47 # include <netinet/in.h>
50 # define INVALID_SOCKET -1
52 # define CLOSE_SOCKET close
55 #endif /* !WINDOWSNT */
69 #else /* not WINDOWSNT */
71 #endif /* not WINDOWSNT */
78 char *getenv (), *getwd ();
83 #define egetenv(VAR) w32_getenv(VAR)
85 #define egetenv(VAR) getenv(VAR)
89 #define VERSION "unspecified"
94 #define EXIT_SUCCESS 0
98 #define EXIT_FAILURE 1
113 /* Additional space when allocating buffers for filenames, etc. */
114 #define EXTRA_SPACE 100
117 /* Name used to invoke this program. */
120 /* The second argument to main. */
123 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
126 /* Nonzero means args are expressions to be evaluated. --eval. */
129 /* Nonzero means don't open a new frame. Inverse of --create-frame. */
130 int current_frame
= 1;
132 /* Nonzero means open a new graphical frame. */
133 int window_system
= 0;
135 /* The display on which Emacs should work. --display. */
136 char *display
= NULL
;
138 /* Nonzero means open a new Emacs frame on the current terminal. */
141 /* If non-NULL, the name of an editor to fallback to if the server
142 is not running. --alternate-editor. */
143 const char *alternate_editor
= NULL
;
145 /* If non-NULL, the filename of the UNIX socket. */
146 char *socket_name
= NULL
;
148 /* If non-NULL, the filename of the authentication file. */
149 char *server_file
= NULL
;
151 /* PID of the Emacs server process. */
154 void print_help_and_exit () NO_RETURN
;
156 struct option longopts
[] =
158 { "no-wait", no_argument
, NULL
, 'n' },
159 { "eval", no_argument
, NULL
, 'e' },
160 { "help", no_argument
, NULL
, 'H' },
161 { "version", no_argument
, NULL
, 'V' },
162 { "tty", no_argument
, NULL
, 't' },
163 { "nw", no_argument
, NULL
, 't' },
164 { "create-frame", no_argument
, NULL
, 'c' },
165 { "alternate-editor", required_argument
, NULL
, 'a' },
166 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
167 { "socket-name", required_argument
, NULL
, 's' },
169 { "server-file", required_argument
, NULL
, 'f' },
171 { "display", required_argument
, NULL
, 'd' },
177 /* Like malloc but get fatal error if memory is exhausted. */
183 long *result
= (long *) malloc (size
);
192 /* Like strdup but get a fatal error if memory is exhausted. */
195 xstrdup (const char *s
)
197 char *result
= strdup (s
);
207 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
210 #ifndef DIRECTORY_SEP
211 #define DIRECTORY_SEP '/'
213 #ifndef IS_DIRECTORY_SEP
214 #define IS_DIRECTORY_SEP(_c_) ((_c_) == DIRECTORY_SEP)
216 #ifndef IS_DEVICE_SEP
218 #define IS_DEVICE_SEP(_c_) 0
220 #define IS_DEVICE_SEP(_c_) ((_c_) == DEVICE_SEP)
224 #define IS_ANY_SEP(_c_) (IS_DIRECTORY_SEP (_c_))
228 /* Return the current working directory. Returns NULL on errors.
229 Any other returned value must be freed with free. This is used
230 only when get_current_dir_name is not defined on the system. */
232 get_current_dir_name ()
236 struct stat dotstat
, pwdstat
;
237 /* If PWD is accurate, use it instead of calling getwd. PWD is
238 sometimes a nicer name, and using it may avoid a fatal error if a
239 parent directory is searchable but not readable. */
240 if ((pwd
= egetenv ("PWD")) != 0
241 && (IS_DIRECTORY_SEP (*pwd
) || (*pwd
&& IS_DEVICE_SEP (pwd
[1])))
242 && stat (pwd
, &pwdstat
) == 0
243 && stat (".", &dotstat
) == 0
244 && dotstat
.st_ino
== pwdstat
.st_ino
245 && dotstat
.st_dev
== pwdstat
.st_dev
247 && strlen (pwd
) < MAXPATHLEN
251 buf
= (char *) xmalloc (strlen (pwd
) + 1);
259 size_t buf_size
= 1024;
260 buf
= (char *) xmalloc (buf_size
);
265 if (getcwd (buf
, buf_size
) == buf
)
269 int tmp_errno
= errno
;
275 buf
= (char *) realloc (buf
, buf_size
);
283 /* We need MAXPATHLEN here. */
284 buf
= (char *) xmalloc (MAXPATHLEN
+ 1);
287 if (getwd (buf
) == NULL
)
289 int tmp_errno
= errno
;
302 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
304 /* Retrieve an environment variable from the Emacs subkeys of the registry.
305 Return NULL if the variable was not found, or it was empty.
306 This code is based on w32_get_resource (w32.c). */
308 w32_get_resource (predefined
, key
, type
)
313 HKEY hrootkey
= NULL
;
317 if (RegOpenKeyEx (predefined
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
319 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
)
321 result
= (char *) xmalloc (cbData
);
323 if ((RegQueryValueEx (hrootkey
, key
, NULL
, type
, result
, &cbData
) != ERROR_SUCCESS
)
331 RegCloseKey (hrootkey
);
338 getenv wrapper for Windows
340 This is needed to duplicate Emacs's behavior, which is to look for enviroment
341 variables in the registry if they don't appear in the environment.
350 if (value
= getenv (envvar
))
351 /* Found in the environment. */
354 if (! (value
= w32_get_resource (HKEY_CURRENT_USER
, envvar
, &dwType
)) &&
355 ! (value
= w32_get_resource (HKEY_LOCAL_MACHINE
, envvar
, &dwType
)))
357 /* "w32console" is what Emacs on Windows uses for tty-type under -nw. */
358 if (strcmp (envvar
, "TERM") == 0)
359 return xstrdup ("w32console");
360 /* Found neither in the environment nor in the registry. */
364 if (dwType
== REG_SZ
)
365 /* Registry; no need to expand. */
368 if (dwType
== REG_EXPAND_SZ
)
372 if (size
= ExpandEnvironmentStrings (value
, NULL
, 0))
374 char *buffer
= (char *) xmalloc (size
);
375 if (ExpandEnvironmentStrings (value
, buffer
, size
))
377 /* Found and expanded. */
382 /* Error expanding. */
387 /* Not the right type, or not correctly expanded. */
395 static int window_app
= -1;
396 char szTitle
[MAX_PATH
];
400 /* Checking for STDOUT does not work; it's a valid handle also in
401 nonconsole apps. Testing for the console title seems to work. */
402 window_app
= (GetConsoleTitleA (szTitle
, MAX_PATH
) == 0);
404 InitCommonControls();
411 execvp wrapper for Windows. Quotes arguments with embedded spaces.
413 This is necessary due to the broken implementation of exec* routines in
414 the Microsoft libraries: they concatenate the arguments together without
415 quoting special characters, and pass the result to CreateProcess, with
416 predictably bad results. By contrast, Posix execvp passes the arguments
417 directly into the argv array of the child process.
420 w32_execvp (path
, argv
)
426 /* Required to allow a .BAT script as alternate editor. */
427 argv
[0] = (char *) alternate_editor
;
429 for (i
= 0; argv
[i
]; i
++)
430 if (strchr (argv
[i
], ' '))
432 char *quoted
= alloca (strlen (argv
[i
]) + 3);
433 sprintf (quoted
, "\"%s\"", argv
[i
]);
437 return execvp (path
, argv
);
441 #define execvp w32_execvp
443 /* Emulation of ttyname for Windows. */
450 #endif /* WINDOWSNT */
452 /* Display a normal or error message.
453 On Windows, use a message box if compiled as a Windows app. */
455 message (int is_error
, char *message
, ...)
460 va_start (args
, message
);
461 vsprintf (msg
, message
, args
);
465 if (w32_window_app ())
468 MessageBox (NULL
, msg
, "Emacsclient ERROR", MB_ICONERROR
);
470 MessageBox (NULL
, msg
, "Emacsclient", MB_ICONINFORMATION
);
475 FILE *f
= is_error
? stderr
: stdout
;
482 /* Decode the options from argv and argc.
483 The global variable `optind' will say how many arguments we used up. */
486 decode_options (argc
, argv
)
490 alternate_editor
= egetenv ("ALTERNATE_EDITOR");
494 int opt
= getopt_long_only (argc
, argv
,
495 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
508 /* If getopt returns 0, then it has already processed a
509 long-named option. We should do nothing. */
513 alternate_editor
= optarg
;
516 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
518 socket_name
= optarg
;
523 server_file
= optarg
;
526 /* We used to disallow this argument in w32, but it seems better
527 to allow it, for the occasional case where the user is
528 connecting with a w32 client to a server compiled with X11
530 #if 1 /* !defined WINDOWS */
545 message (FALSE
, "emacsclient %s\n", VERSION
);
559 print_help_and_exit ();
563 message (TRUE
, "Try `%s --help' for more information\n", progname
);
569 /* We used to set `display' to $DISPLAY by default, but this changed the
570 default behavior and is sometimes inconvenient. So instead of forcing
571 users to say "--display ''" when they want to use Emacs's existing tty
572 or display connection, we force them to use "--display $DISPLAY" if
573 they want Emacs to connect to their current display.
574 -c still implicitly passes --display $DISPLAY unless -t was specified
575 so as to try and mimick the behavior of `emacs' which either uses
576 the current tty or the current $DISPLAY. */
577 if (!current_frame
&& !tty
&& !display
)
578 display
= egetenv ("DISPLAY");
580 if (display
&& strlen (display
) == 0)
585 else if (!current_frame
)
588 /* --no-wait implies --current-frame on ttys when there are file
589 arguments or expressions given. */
590 if (nowait
&& tty
&& argc
- optind
> 0)
605 print_help_and_exit ()
607 /* Spaces and tabs are significant in this message; they're chosen so the
608 message aligns properly both in a tty and in a Windows message box.
609 Please try to preserve them; otherwise the output is very hard to read
610 when using emacsclientw. */
612 "Usage: %s [OPTIONS] FILE...\n\
613 Tell the Emacs server to visit the specified files.\n\
614 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
616 The following OPTIONS are accepted:\n\
617 -V, --version Just print version info and return\n\
618 -H, --help Print this usage information message\n\
619 -nw, -t, --tty Open a new Emacs frame on the current terminal\n\
620 -c, --create-frame Create a new frame instead of trying to\n\
621 use the current Emacs frame\n\
622 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
623 -n, --no-wait Don't wait for the server to return\n\
624 -d, --display=DISPLAY Visit the file in the given display\n"
625 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
626 "-s, --socket-name=FILENAME\n\
627 Set filename of the UNIX socket for communication\n"
629 "-f, --server-file=FILENAME\n\
630 Set filename of the TCP authentication file\n\
631 -a, --alternate-editor=EDITOR\n\
632 Editor to fallback to if the server is not running\n\
634 Report bugs to bug-gnu-emacs@gnu.org.\n", progname
);
639 Try to run a different command, or --if no alternate editor is
640 defined-- exit with an errorcode.
641 Uses argv, but gets it from the global variable main_argv.
646 if (alternate_editor
)
650 execvp (alternate_editor
, main_argv
+ i
);
651 message (TRUE
, "%s: error executing alternate editor \"%s\"\n",
652 progname
, alternate_editor
);
658 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
667 message (TRUE
, "%s: Sorry, the Emacs server is supported only\n"
668 "on systems with Berkeley sockets.\n",
673 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
676 # include <winsock2.h>
678 # include <sys/types.h>
679 # include <sys/socket.h>
683 #define AUTH_KEY_LENGTH 64
684 #define SEND_BUFFER_SIZE 4096
686 extern char *strerror ();
689 /* Buffer to accumulate data to send in TCP connections. */
690 char send_buffer
[SEND_BUFFER_SIZE
+ 1];
691 int sblen
= 0; /* Fill pointer for the send buffer. */
692 /* Socket used to communicate with the Emacs server process. */
693 HSOCKET emacs_socket
= 0;
695 /* On Windows, the socket library was historically separate from the standard
696 C library, so errors are handled differently. */
698 sock_err_message (function_name
)
704 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
705 | FORMAT_MESSAGE_ALLOCATE_BUFFER
706 | FORMAT_MESSAGE_ARGUMENT_ARRAY
,
707 NULL
, WSAGetLastError (), 0, (LPTSTR
)&msg
, 0, NULL
);
709 message (TRUE
, "%s: %s: %s\n", progname
, function_name
, msg
);
713 message (TRUE
, "%s: %s: %s\n", progname
, function_name
, strerror (errno
));
718 /* Let's send the data to Emacs when either
719 - the data ends in "\n", or
720 - the buffer is full (but this shouldn't happen)
721 Otherwise, we just accumulate it. */
723 send_to_emacs (s
, data
)
729 int dlen
= strlen (data
);
730 if (dlen
+ sblen
>= SEND_BUFFER_SIZE
)
732 int part
= SEND_BUFFER_SIZE
- sblen
;
733 strncpy (&send_buffer
[sblen
], data
, part
);
735 sblen
= SEND_BUFFER_SIZE
;
739 strcpy (&send_buffer
[sblen
], data
);
746 if (sblen
== SEND_BUFFER_SIZE
747 || (sblen
> 0 && send_buffer
[sblen
-1] == '\n'))
749 int sent
= send (s
, send_buffer
, sblen
, 0);
751 strcpy (send_buffer
, &send_buffer
[sent
]);
758 /* In STR, insert a & before each &, each space, each newline, and
759 any initial -. Change spaces to underscores, too, so that the
760 return value never contains a space.
762 Does not change the string. Outputs the result to STREAM. */
764 quote_argument (s
, str
)
768 char *copy
= (char *) xmalloc (strlen (str
) * 2 + 1);
789 if (*p
== '&' || (*p
== '-' && p
== str
))
796 send_to_emacs (s
, copy
);
802 /* The inverse of quote_argument. Removes quoting in string STR by
803 modifying the string in place. Returns STR. */
806 unquote_argument (str
)
838 file_name_absolute_p (filename
)
839 const unsigned char *filename
;
841 /* Sanity check, it shouldn't happen. */
842 if (! filename
) return FALSE
;
844 /* /xxx is always an absolute path. */
845 if (filename
[0] == '/') return TRUE
;
847 /* Empty filenames (which shouldn't happen) are relative. */
848 if (filename
[0] == '\0') return FALSE
;
851 /* X:\xxx is always absolute. */
852 if (isalpha (filename
[0])
853 && filename
[1] == ':' && (filename
[2] == '\\' || filename
[2] == '/'))
856 /* Both \xxx and \\xxx\yyy are absolute. */
857 if (filename
[0] == '\\') return TRUE
;
864 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
866 __cdecl
close_winsock ()
871 /* Initialize the WinSock2 library. */
873 initialize_sockets ()
877 if (WSAStartup (MAKEWORD (2, 0), &wsaData
))
879 message (TRUE
, "%s: error initializing WinSock2\n", progname
);
883 atexit (close_winsock
);
885 #endif /* WINDOWSNT */
889 * Read the information needed to set up a TCP comm channel with
890 * the Emacs server: host, port, pid and authentication string.
893 get_server_config (server
, authentication
)
894 struct sockaddr_in
*server
;
895 char *authentication
;
902 if (file_name_absolute_p (server_file
))
903 config
= fopen (server_file
, "rb");
906 char *home
= egetenv ("HOME");
910 char *path
= alloca (strlen (home
) + strlen (server_file
)
912 sprintf (path
, "%s/.emacs.d/server/%s", home
, server_file
);
913 config
= fopen (path
, "rb");
916 if (!config
&& (home
= egetenv ("APPDATA")))
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");
929 if (fgets (dotted
, sizeof dotted
, config
)
930 && (port
= strchr (dotted
, ':'))
931 && (pid
= strchr (port
, ' ')))
938 message (TRUE
, "%s: invalid configuration info\n", progname
);
942 server
->sin_family
= AF_INET
;
943 server
->sin_addr
.s_addr
= inet_addr (dotted
);
944 server
->sin_port
= htons (atoi (port
));
946 if (! fread (authentication
, AUTH_KEY_LENGTH
, 1, config
))
948 message (TRUE
, "%s: cannot read authentication info\n", progname
);
954 emacs_pid
= atoi (pid
);
963 struct sockaddr_in server
;
964 struct linger l_arg
= {1, 1};
965 char auth_string
[AUTH_KEY_LENGTH
+ 1];
967 if (! get_server_config (&server
, auth_string
))
968 return INVALID_SOCKET
;
970 if (server
.sin_addr
.s_addr
!= inet_addr ("127.0.0.1"))
971 message (FALSE
, "%s: connected to remote socket at %s\n",
972 progname
, inet_ntoa (server
.sin_addr
));
975 * Open up an AF_INET socket
977 if ((s
= socket (AF_INET
, SOCK_STREAM
, IPPROTO_TCP
)) < 0)
979 sock_err_message ("socket");
980 return INVALID_SOCKET
;
986 if (connect (s
, (struct sockaddr
*) &server
, sizeof server
) < 0)
988 sock_err_message ("connect");
989 return INVALID_SOCKET
;
992 setsockopt (s
, SOL_SOCKET
, SO_LINGER
, (char *) &l_arg
, sizeof l_arg
);
995 * Send the authentication
997 auth_string
[AUTH_KEY_LENGTH
] = '\0';
999 send_to_emacs (s
, "-auth ");
1000 send_to_emacs (s
, auth_string
);
1001 send_to_emacs (s
, " ");
1007 /* Returns 1 if PREFIX is a prefix of STRING. */
1009 strprefix (char *prefix
, char *string
)
1011 return !strncmp (prefix
, string
, strlen (prefix
));
1015 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1017 /* Three possibilities:
1018 2 - can't be `stat'ed (sets errno)
1019 1 - isn't owned by us
1020 0 - success: none of the above */
1023 socket_status (socket_name
)
1026 struct stat statbfr
;
1028 if (stat (socket_name
, &statbfr
) == -1)
1031 if (statbfr
.st_uid
!= geteuid ())
1038 /* A signal handler that passes the signal to the Emacs process.
1039 Useful for SIGWINCH. */
1042 pass_signal_to_emacs (int signalnum
)
1044 int old_errno
= errno
;
1047 kill (emacs_pid
, signalnum
);
1049 signal (signalnum
, pass_signal_to_emacs
);
1053 /* Signal handler for SIGCONT; notify the Emacs process that it can
1054 now resume our tty frame. */
1057 handle_sigcont (int signalnum
)
1059 int old_errno
= errno
;
1061 if (tcgetpgrp (1) == getpgrp ())
1063 /* We are in the foreground. */
1064 send_to_emacs (emacs_socket
, "-resume \n");
1068 /* We are in the background; cancel the continue. */
1069 kill (getpid (), SIGSTOP
);
1072 signal (signalnum
, handle_sigcont
);
1076 /* Signal handler for SIGTSTP; notify the Emacs process that we are
1077 going to sleep. Normally the suspend is initiated by Emacs via
1078 server-handle-suspend-tty, but if the server gets out of sync with
1079 reality, we may get a SIGTSTP on C-z. Handling this signal and
1080 notifying Emacs about it should get things under control again. */
1083 handle_sigtstp (int signalnum
)
1085 int old_errno
= errno
;
1089 send_to_emacs (emacs_socket
, "-suspend \n");
1091 /* Unblock this signal and call the default handler by temporarily
1092 changing the handler and resignalling. */
1093 sigprocmask (SIG_BLOCK
, NULL
, &set
);
1094 sigdelset (&set
, signalnum
);
1095 signal (signalnum
, SIG_DFL
);
1096 kill (getpid (), signalnum
);
1097 sigprocmask (SIG_SETMASK
, &set
, NULL
); /* Let's the above signal through. */
1098 signal (signalnum
, handle_sigtstp
);
1102 /* Set up signal handlers before opening a frame on the current tty. */
1107 /* Set up signal handlers. */
1108 signal (SIGWINCH
, pass_signal_to_emacs
);
1110 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
1111 deciding which terminal the signal came from. C-g is now a
1112 normal input event on secondary terminals. */
1114 signal (SIGINT
, pass_signal_to_emacs
);
1115 signal (SIGQUIT
, pass_signal_to_emacs
);
1118 signal (SIGCONT
, handle_sigcont
);
1119 signal (SIGTSTP
, handle_sigtstp
);
1120 signal (SIGTTOU
, handle_sigtstp
);
1128 struct sockaddr_un server
;
1131 * Open up an AF_UNIX socket in this person's home directory
1134 if ((s
= socket (AF_UNIX
, SOCK_STREAM
, 0)) < 0)
1136 message (TRUE
, "%s: socket: %s\n", progname
, strerror (errno
));
1137 return INVALID_SOCKET
;
1140 server
.sun_family
= AF_UNIX
;
1143 int sock_status
= 0;
1144 int default_sock
= !socket_name
;
1145 int saved_errno
= 0;
1146 char *server_name
= "server";
1149 if (socket_name
&& !index (socket_name
, '/') && !index (socket_name
, '\\'))
1150 { /* socket_name is a file name component. */
1151 server_name
= socket_name
;
1153 default_sock
= 1; /* Try both UIDs. */
1158 tmpdir
= egetenv ("TMPDIR");
1161 socket_name
= alloca (strlen (tmpdir
) + strlen (server_name
)
1163 sprintf (socket_name
, "%s/emacs%d/%s",
1164 tmpdir
, (int) geteuid (), server_name
);
1167 if (strlen (socket_name
) < sizeof (server
.sun_path
))
1168 strcpy (server
.sun_path
, socket_name
);
1171 message (TRUE
, "%s: socket-name %s too long\n",
1172 progname
, socket_name
);
1176 /* See if the socket exists, and if it's owned by us. */
1177 sock_status
= socket_status (server
.sun_path
);
1178 saved_errno
= errno
;
1179 if (sock_status
&& default_sock
)
1181 /* Failing that, see if LOGNAME or USER exist and differ from
1182 our euid. If so, look for a socket based on the UID
1183 associated with the name. This is reminiscent of the logic
1184 that init_editfns uses to set the global Vuser_full_name. */
1186 char *user_name
= (char *) egetenv ("LOGNAME");
1189 user_name
= (char *) egetenv ("USER");
1193 struct passwd
*pw
= getpwnam (user_name
);
1195 if (pw
&& (pw
->pw_uid
!= geteuid ()))
1197 /* We're running under su, apparently. */
1198 socket_name
= alloca (strlen (tmpdir
) + strlen (server_name
)
1200 sprintf (socket_name
, "%s/emacs%d/%s",
1201 tmpdir
, (int) pw
->pw_uid
, server_name
);
1203 if (strlen (socket_name
) < sizeof (server
.sun_path
))
1204 strcpy (server
.sun_path
, socket_name
);
1207 message (TRUE
, "%s: socket-name %s too long\n",
1208 progname
, socket_name
);
1209 exit (EXIT_FAILURE
);
1212 sock_status
= socket_status (server
.sun_path
);
1213 saved_errno
= errno
;
1216 errno
= saved_errno
;
1220 switch (sock_status
)
1223 /* There's a socket, but it isn't owned by us. This is OK if
1225 if (0 != geteuid ())
1227 message (TRUE
, "%s: Invalid socket owner\n", progname
);
1228 return INVALID_SOCKET
;
1234 if (saved_errno
== ENOENT
)
1236 "%s: can't find socket; have you started the server?\n\
1237 To start the server in Emacs, type \"M-x server-start\".\n",
1240 message (TRUE
, "%s: can't stat %s: %s\n",
1241 progname
, server
.sun_path
, strerror (saved_errno
));
1242 return INVALID_SOCKET
;
1246 if (connect (s
, (struct sockaddr
*) &server
, strlen (server
.sun_path
) + 2)
1249 message (TRUE
, "%s: connect: %s\n", progname
, strerror (errno
));
1250 return INVALID_SOCKET
;
1255 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1264 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1265 /* Explicit --socket-name argument. */
1268 s
= set_local_socket ();
1269 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
1271 message (TRUE
, "%s: error accessing socket \"%s\"\n",
1272 progname
, socket_name
);
1273 exit (EXIT_FAILURE
);
1277 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1279 server_file
= egetenv ("EMACS_SERVER_FILE");
1283 s
= set_tcp_socket ();
1284 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
1287 message (TRUE
, "%s: error accessing server file \"%s\"\n",
1288 progname
, server_file
);
1289 exit (EXIT_FAILURE
);
1292 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1293 /* Implicit local socket. */
1294 s
= set_local_socket ();
1295 if (s
!= INVALID_SOCKET
)
1299 /* Implicit server file. */
1300 server_file
= "server";
1301 s
= set_tcp_socket ();
1302 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
1305 /* No implicit or explicit socket, and no alternate editor. */
1306 message (TRUE
, "%s: No socket or alternate editor. Please use:\n\n"
1307 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1310 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1311 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1313 exit (EXIT_FAILURE
);
1317 FARPROC set_fg
; /* Pointer to AllowSetForegroundWindow. */
1318 FARPROC get_wc
; /* Pointer to RealGetWindowClassA. */
1321 w32_find_emacs_process (hWnd
, lParam
)
1328 /* Reject any window not of class "Emacs". */
1329 if (! get_wc (hWnd
, class, sizeof (class))
1330 || strcmp (class, "Emacs"))
1333 /* We only need the process id, not the thread id. */
1334 (void) GetWindowThreadProcessId (hWnd
, &pid
);
1336 /* Not the one we're looking for. */
1337 if (pid
!= (DWORD
) emacs_pid
) return TRUE
;
1339 /* OK, let's raise it. */
1342 /* Stop enumeration. */
1347 * Search for a window of class "Emacs" and owned by a process with
1348 * process id = emacs_pid. If found, allow it to grab the focus.
1355 /* It shouldn't happen when dealing with TCP sockets. */
1356 if (!emacs_pid
) return;
1358 if (!(hUser32
= LoadLibrary ("user32.dll"))) return;
1360 /* Modern Windows restrict which processes can set the foreground window.
1361 emacsclient can allow Emacs to grab the focus by calling the function
1362 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1363 NT) lack this function, so we have to check its availability. */
1364 if ((set_fg
= GetProcAddress (hUser32
, "AllowSetForegroundWindow"))
1365 && (get_wc
= GetProcAddress (hUser32
, "RealGetWindowClassA")))
1366 EnumWindows (w32_find_emacs_process
, (LPARAM
) 0);
1368 FreeLibrary (hUser32
);
1377 int i
, rl
, needlf
= 0;
1379 char string
[BUFSIZ
+1];
1384 /* Process options. */
1385 decode_options (argc
, argv
);
1387 if ((argc
- optind
< 1) && !eval
&& !tty
&& !window_system
)
1389 message (TRUE
, "%s: file name or argument required\n"
1390 "Try `%s --help' for more information\n",
1391 progname
, progname
);
1392 exit (EXIT_FAILURE
);
1395 if ((emacs_socket
= set_socket ()) == INVALID_SOCKET
)
1399 cwd
= get_current_dir_name ();
1402 /* getwd puts message in STRING if it fails. */
1403 message (TRUE
, "%s: %s\n", progname
,
1404 "Cannot get current working directory");
1412 /* Send over our environment. */
1415 extern char **environ
;
1417 for (i
= 0; environ
[i
]; i
++)
1419 char *name
= xstrdup (environ
[i
]);
1420 char *value
= strchr (name
, '=');
1421 send_to_emacs (emacs_socket
, "-env ");
1422 quote_argument (emacs_socket
, environ
[i
]);
1423 send_to_emacs (emacs_socket
, " ");
1427 /* Send over our current directory. */
1430 send_to_emacs (emacs_socket
, "-dir ");
1431 quote_argument (emacs_socket
, cwd
);
1432 send_to_emacs (emacs_socket
, "/");
1433 send_to_emacs (emacs_socket
, " ");
1438 send_to_emacs (emacs_socket
, "-nowait ");
1441 send_to_emacs (emacs_socket
, "-current-frame ");
1445 send_to_emacs (emacs_socket
, "-display ");
1446 quote_argument (emacs_socket
, display
);
1447 send_to_emacs (emacs_socket
, " ");
1450 /* If using the current frame, send tty information to Emacs anyway.
1451 In daemon mode, Emacs may need to occupy this tty if no other
1452 frame is available. */
1453 if (tty
|| (current_frame
&& !eval
))
1455 char *type
= egetenv ("TERM");
1456 char *tty_name
= NULL
;
1458 tty_name
= ttyname (fileno (stdout
));
1462 message (TRUE
, "%s: could not get terminal name\n", progname
);
1468 message (TRUE
, "%s: please set the TERM variable to your terminal type\n",
1473 if (! strcmp (type
, "eterm"))
1475 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1476 message (TRUE
, "%s: opening a frame in an Emacs term buffer"
1477 " is not supported\n", progname
);
1480 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1484 send_to_emacs (emacs_socket
, "-tty ");
1485 quote_argument (emacs_socket
, tty_name
);
1486 send_to_emacs (emacs_socket
, " ");
1487 quote_argument (emacs_socket
, type
);
1488 send_to_emacs (emacs_socket
, " ");
1492 send_to_emacs (emacs_socket
, "-window-system ");
1494 if ((argc
- optind
> 0))
1496 for (i
= optind
; i
< argc
; i
++)
1502 /* Don't prepend cwd or anything like that. */
1503 send_to_emacs (emacs_socket
, "-eval ");
1504 quote_argument (emacs_socket
, argv
[i
]);
1505 send_to_emacs (emacs_socket
, " ");
1509 if (*argv
[i
] == '+')
1511 char *p
= argv
[i
] + 1;
1512 while (isdigit ((unsigned char) *p
) || *p
== ':') p
++;
1515 send_to_emacs (emacs_socket
, "-position ");
1516 quote_argument (emacs_socket
, argv
[i
]);
1517 send_to_emacs (emacs_socket
, " ");
1523 else if (! file_name_absolute_p (argv
[i
]))
1527 /* Call GetFullPathName so filenames of the form X:Y, where X is
1528 a valid drive designator, are interpreted as drive:path, not
1529 file:stream, and treated as absolute.
1530 The user can still pass a file:stream if desired (for example,
1531 .\X:Y), but it is not very useful, as Emacs currently does a
1532 very bad job of dealing with NTFS streams. */
1534 char *filename
= (char *) xmalloc (MAX_PATH
);
1537 size
= GetFullPathName (argv
[i
], MAX_PATH
, filename
, NULL
);
1538 if (size
> 0 && size
< MAX_PATH
)
1548 send_to_emacs (emacs_socket
, "-file ");
1551 quote_argument (emacs_socket
, cwd
);
1552 send_to_emacs (emacs_socket
, "/");
1554 quote_argument (emacs_socket
, argv
[i
]);
1555 send_to_emacs (emacs_socket
, " ");
1560 if (!tty
&& !window_system
)
1562 while ((str
= fgets (string
, BUFSIZ
, stdin
)))
1565 send_to_emacs (emacs_socket
, "-eval ");
1567 send_to_emacs (emacs_socket
, "-file ");
1568 quote_argument (emacs_socket
, str
);
1570 send_to_emacs (emacs_socket
, " ");
1574 send_to_emacs (emacs_socket
, "\n");
1576 /* Wait for an answer. */
1577 if (!eval
&& !tty
&& !nowait
)
1579 printf ("Waiting for Emacs...");
1585 /* Now, wait for an answer and print any messages. */
1586 while ((rl
= recv (emacs_socket
, string
, BUFSIZ
, 0)) > 0)
1591 p
= string
+ strlen (string
) - 1;
1592 while (p
> string
&& *p
== '\n')
1595 if (strprefix ("-emacs-pid ", string
))
1597 /* -emacs-pid PID: The process id of the Emacs process. */
1598 emacs_pid
= strtol (string
+ strlen ("-emacs-pid"), NULL
, 10);
1600 else if (strprefix ("-window-system-unsupported ", string
))
1602 /* -window-system-unsupported: Emacs was compiled without X
1603 support. Try again on the terminal. */
1609 else if (strprefix ("-print ", string
))
1611 /* -print STRING: Print STRING on the terminal. */
1612 str
= unquote_argument (string
+ strlen ("-print "));
1616 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1618 else if (strprefix ("-error ", string
))
1620 /* -error DESCRIPTION: Signal an error on the terminal. */
1621 str
= unquote_argument (string
+ strlen ("-error "));
1624 fprintf (stderr
, "*ERROR*: %s", str
);
1625 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1628 else if (strprefix ("-suspend ", string
))
1630 /* -suspend: Suspend this terminal, i.e., stop the process. */
1639 /* Unknown command. */
1642 printf ("*ERROR*: Unknown message: %s", string
);
1643 needlf
= string
[0] == '\0' ? needlf
: string
[strlen (string
) - 1] != '\n';
1652 CLOSE_SOCKET (emacs_socket
);
1653 return EXIT_SUCCESS
;
1656 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
1659 #ifndef HAVE_STRERROR
1664 extern char *sys_errlist
[];
1665 extern int sys_nerr
;
1667 if (errnum
>= 0 && errnum
< sys_nerr
)
1668 return sys_errlist
[errnum
];
1669 return (char *) "Unknown error";
1672 #endif /* ! HAVE_STRERROR */
1674 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
1675 (do not change this comment) */
1677 /* emacsclient.c ends here */