1 /* Client process that communicates with GNU Emacs acting as server.
2 Copyright (C) 1986, 1987, 1994, 1999, 2000, 2001, 2002, 2003, 2004,
3 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA. */
31 /* config.h defines these, which disables sockets altogether! */
38 # include <commctrl.h>
40 # define NO_SOCKETS_IN_FILE_SYSTEM
42 # define HSOCKET SOCKET
43 # define CLOSE_SOCKET closesocket
44 # define INITIALIZE() (initialize_sockets ())
46 #else /* !WINDOWSNT */
48 # include <sys/types.h>
50 # ifdef HAVE_INET_SOCKETS
51 # include <netinet/in.h>
54 # define INVALID_SOCKET -1
56 # define CLOSE_SOCKET close
59 #endif /* !WINDOWSNT */
76 #else /* not WINDOWSNT */
78 #endif /* not WINDOWSNT */
86 char *getenv (), *getwd ();
91 #define egetenv(VAR) w32_getenv(VAR)
93 #define egetenv(VAR) getenv(VAR)
97 #define VERSION "unspecified"
102 #define EXIT_SUCCESS 0
106 #define EXIT_FAILURE 1
121 /* Name used to invoke this program. */
124 /* The second argument to main. */
127 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
130 /* Nonzero means args are expressions to be evaluated. --eval. */
133 /* Nonzero means don't open a new frame. Inverse of --create-frame. */
134 int current_frame
= 1;
136 /* Nonzero means open a new graphical frame. */
137 int window_system
= 0;
139 /* The display on which Emacs should work. --display. */
140 char *display
= NULL
;
142 /* Nonzero means open a new Emacs frame on the current terminal. */
145 /* If non-NULL, the name of an editor to fallback to if the server
146 is not running. --alternate-editor. */
147 const char *alternate_editor
= NULL
;
149 /* If non-NULL, the filename of the UNIX socket. */
150 char *socket_name
= NULL
;
152 /* If non-NULL, the filename of the authentication file. */
153 char *server_file
= NULL
;
155 /* PID of the Emacs server process. */
158 void print_help_and_exit () NO_RETURN
;
160 struct option longopts
[] =
162 { "no-wait", no_argument
, NULL
, 'n' },
163 { "eval", no_argument
, NULL
, 'e' },
164 { "help", no_argument
, NULL
, 'H' },
165 { "version", no_argument
, NULL
, 'V' },
166 { "tty", no_argument
, NULL
, 't' },
167 { "create-frame", no_argument
, NULL
, 'c' },
168 { "alternate-editor", required_argument
, NULL
, 'a' },
169 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
170 { "socket-name", required_argument
, NULL
, 's' },
172 { "server-file", required_argument
, NULL
, 'f' },
173 { "display", required_argument
, NULL
, 'd' },
178 /* Like malloc but get fatal error if memory is exhausted. */
184 long *result
= (long *) malloc (size
);
193 /* Like strdup but get a fatal error if memory is exhausted. */
196 xstrdup (const char *s
)
198 char *result
= strdup (s
);
208 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
211 #ifndef DIRECTORY_SEP
212 #define DIRECTORY_SEP '/'
214 #ifndef IS_DIRECTORY_SEP
215 #define IS_DIRECTORY_SEP(_c_) ((_c_) == DIRECTORY_SEP)
217 #ifndef IS_DEVICE_SEP
219 #define IS_DEVICE_SEP(_c_) 0
221 #define IS_DEVICE_SEP(_c_) ((_c_) == DEVICE_SEP)
225 #define IS_ANY_SEP(_c_) (IS_DIRECTORY_SEP (_c_))
229 /* Return the current working directory. Returns NULL on errors.
230 Any other returned value must be freed with free. This is used
231 only when get_current_dir_name is not defined on the system. */
233 get_current_dir_name ()
237 struct stat dotstat
, pwdstat
;
238 /* If PWD is accurate, use it instead of calling getwd. PWD is
239 sometimes a nicer name, and using it may avoid a fatal error if a
240 parent directory is searchable but not readable. */
241 if ((pwd
= egetenv ("PWD")) != 0
242 && (IS_DIRECTORY_SEP (*pwd
) || (*pwd
&& IS_DEVICE_SEP (pwd
[1])))
243 && stat (pwd
, &pwdstat
) == 0
244 && stat (".", &dotstat
) == 0
245 && dotstat
.st_ino
== pwdstat
.st_ino
246 && dotstat
.st_dev
== pwdstat
.st_dev
248 && strlen (pwd
) < MAXPATHLEN
252 buf
= (char *) xmalloc (strlen (pwd
) + 1);
260 size_t buf_size
= 1024;
261 buf
= (char *) xmalloc (buf_size
);
266 if (getcwd (buf
, buf_size
) == buf
)
270 int tmp_errno
= errno
;
276 buf
= (char *) realloc (buf
, buf_size
);
284 /* We need MAXPATHLEN here. */
285 buf
= (char *) xmalloc (MAXPATHLEN
+ 1);
288 if (getwd (buf
) == NULL
)
290 int tmp_errno
= errno
;
303 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
305 /* Retrieve an environment variable from the Emacs subkeys of the registry.
306 Return NULL if the variable was not found, or it was empty.
307 This code is based on w32_get_resource (w32.c). */
309 w32_get_resource (predefined
, key
, type
)
314 HKEY hrootkey
= NULL
;
318 if (RegOpenKeyEx (predefined
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
320 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
)
322 result
= (char *) xmalloc (cbData
);
324 if ((RegQueryValueEx (hrootkey
, key
, NULL
, type
, result
, &cbData
) != ERROR_SUCCESS
) ||
332 RegCloseKey (hrootkey
);
339 getenv wrapper for Windows
341 This is needed to duplicate Emacs's behavior, which is to look for enviroment
342 variables in the registry if they don't appear in the environment.
351 if (value
= getenv (envvar
))
352 /* Found in the environment. */
355 if (! (value
= w32_get_resource (HKEY_CURRENT_USER
, envvar
, &dwType
)) &&
356 ! (value
= w32_get_resource (HKEY_LOCAL_MACHINE
, envvar
, &dwType
)))
357 /* Not found in the registry. */
360 if (dwType
== REG_SZ
)
361 /* Registry; no need to expand. */
364 if (dwType
== REG_EXPAND_SZ
)
368 if (size
= ExpandEnvironmentStrings (value
, NULL
, 0))
370 char *buffer
= (char *) xmalloc (size
);
371 if (ExpandEnvironmentStrings (value
, buffer
, size
))
373 /* Found and expanded. */
378 /* Error expanding. */
383 /* Not the right type, or not correctly expanded. */
391 static int window_app
= -1;
392 char szTitle
[MAX_PATH
];
396 /* Checking for STDOUT does not work; it's a valid handle also in
397 nonconsole apps. Testing for the console title seems to work. */
398 window_app
= (GetConsoleTitleA (szTitle
, MAX_PATH
) == 0);
400 InitCommonControls();
407 execvp wrapper for Windows. Quotes arguments with embedded spaces.
409 This is necessary due to the broken implementation of exec* routines in
410 the Microsoft libraries: they concatenate the arguments together without
411 quoting special characters, and pass the result to CreateProcess, with
412 predictably bad results. By contrast, Posix execvp passes the arguments
413 directly into the argv array of the child process.
416 w32_execvp (path
, argv
)
422 /* Required to allow a .BAT script as alternate editor. */
423 argv
[0] = (char *) alternate_editor
;
425 for (i
= 0; argv
[i
]; i
++)
426 if (strchr (argv
[i
], ' '))
428 char *quoted
= alloca (strlen (argv
[i
]) + 3);
429 sprintf (quoted
, "\"%s\"", argv
[i
]);
433 return execvp (path
, argv
);
437 #define execvp w32_execvp
439 #endif /* WINDOWSNT */
441 /* Display a normal or error message.
442 On Windows, use a message box if compiled as a Windows app. */
444 message (int is_error
, char *message
, ...)
449 va_start (args
, message
);
450 vsprintf (msg
, message
, args
);
454 if (w32_window_app ())
457 MessageBox (NULL
, msg
, "Emacsclient ERROR", MB_ICONERROR
);
459 MessageBox (NULL
, msg
, "Emacsclient", MB_ICONINFORMATION
);
464 FILE *f
= is_error
? stderr
: stdout
;
471 /* Decode the options from argv and argc.
472 The global variable `optind' will say how many arguments we used up. */
475 decode_options (argc
, argv
)
479 alternate_editor
= egetenv ("ALTERNATE_EDITOR");
480 display
= egetenv ("DISPLAY");
481 if (display
&& strlen (display
) == 0)
486 int opt
= getopt_long (argc
, argv
,
487 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
500 /* If getopt returns 0, then it has already processed a
501 long-named option. We should do nothing. */
505 alternate_editor
= optarg
;
508 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
510 socket_name
= optarg
;
515 server_file
= optarg
;
531 message (FALSE
, "emacsclient %s\n", VERSION
);
545 print_help_and_exit ();
549 message (TRUE
, "Try `%s --help' for more information\n", progname
);
557 #if !defined (WINDOWSNT) && !defined (HAVE_CARBON)
562 /* --no-wait implies --current-frame on ttys when there are file
563 arguments or expressions given. */
564 if (nowait
&& tty
&& argc
- optind
> 0)
579 print_help_and_exit ()
581 /* Spaces and tabs are significant in this message; they're chosen so the
582 message aligns properly both in a tty and in a Windows message box.
583 Please try to preserve them; otherwise the output is very hard to read
584 when using emacsclientw. */
586 "Usage: %s [OPTIONS] FILE...\n\
587 Tell the Emacs server to visit the specified files.\n\
588 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
590 The following OPTIONS are accepted:\n\
591 -V, --version Just print version info and return\n\
592 -H, --help Print this usage information message\n\
593 -t, --tty Open a new Emacs frame on the current terminal\n\
594 -c, --create-frame Create a new frame instead of trying to\n\
595 use the current Emacs frame\n\
596 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
597 -n, --no-wait Don't wait for the server to return\n\
598 -d, --display=DISPLAY Visit the file in the given display\n"
599 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
600 "-s, --socket-name=FILENAME\n\
601 Set filename of the UNIX socket for communication\n"
603 "-f, --server-file=FILENAME\n\
604 Set filename of the TCP authentication file\n\
605 -a, --alternate-editor=EDITOR\n\
606 Editor to fallback to if the server is not running\n\
608 Report bugs to bug-gnu-emacs@gnu.org.\n", progname
);
613 Try to run a different command, or --if no alternate editor is
614 defined-- exit with an errorcode.
615 Uses argv, but gets it from the global variable main_argv.
620 if (alternate_editor
)
624 execvp (alternate_editor
, main_argv
+ i
);
625 message (TRUE
, "%s: error executing alternate editor \"%s\"\n",
626 progname
, alternate_editor
);
632 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
641 message (TRUE
, "%s: Sorry, the Emacs server is supported only\n"
642 "on systems with Berkeley sockets.\n",
647 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
650 # include <winsock2.h>
652 # include <sys/types.h>
653 # include <sys/socket.h>
657 #define AUTH_KEY_LENGTH 64
658 #define SEND_BUFFER_SIZE 4096
660 extern char *strerror ();
663 /* Buffer to accumulate data to send in TCP connections. */
664 char send_buffer
[SEND_BUFFER_SIZE
+ 1];
665 int sblen
= 0; /* Fill pointer for the send buffer. */
666 /* Socket used to communicate with the Emacs server process. */
667 HSOCKET emacs_socket
= 0;
669 /* On Windows, the socket library was historically separate from the standard
670 C library, so errors are handled differently. */
672 sock_err_message (function_name
)
678 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
679 | FORMAT_MESSAGE_ALLOCATE_BUFFER
680 | FORMAT_MESSAGE_ARGUMENT_ARRAY
,
681 NULL
, WSAGetLastError (), 0, (LPTSTR
)&msg
, 0, NULL
);
683 message (TRUE
, "%s: %s: %s\n", progname
, function_name
, msg
);
687 message (TRUE
, "%s: %s: %s\n", progname
, function_name
, strerror (errno
));
692 /* Let's send the data to Emacs when either
693 - the data ends in "\n", or
694 - the buffer is full (but this shouldn't happen)
695 Otherwise, we just accumulate it. */
697 send_to_emacs (s
, data
)
703 int dlen
= strlen (data
);
704 if (dlen
+ sblen
>= SEND_BUFFER_SIZE
)
706 int part
= SEND_BUFFER_SIZE
- sblen
;
707 strncpy (&send_buffer
[sblen
], data
, part
);
709 sblen
= SEND_BUFFER_SIZE
;
713 strcpy (&send_buffer
[sblen
], data
);
720 if (sblen
== SEND_BUFFER_SIZE
721 || (sblen
> 0 && send_buffer
[sblen
-1] == '\n'))
723 int sent
= send (s
, send_buffer
, sblen
, 0);
725 strcpy (send_buffer
, &send_buffer
[sent
]);
732 /* In STR, insert a & before each &, each space, each newline, and
733 any initial -. Change spaces to underscores, too, so that the
734 return value never contains a space.
736 Does not change the string. Outputs the result to STREAM. */
738 quote_argument (s
, str
)
742 char *copy
= (char *) xmalloc (strlen (str
) * 2 + 1);
763 if (*p
== '&' || (*p
== '-' && p
== str
))
770 send_to_emacs (s
, copy
);
776 /* The inverse of quote_argument. Removes quoting in string STR by
777 modifying the string in place. Returns STR. */
780 unquote_argument (str
)
812 file_name_absolute_p (filename
)
813 const unsigned char *filename
;
815 /* Sanity check, it shouldn't happen. */
816 if (! filename
) return FALSE
;
818 /* /xxx is always an absolute path. */
819 if (filename
[0] == '/') return TRUE
;
821 /* Empty filenames (which shouldn't happen) are relative. */
822 if (filename
[0] == '\0') return FALSE
;
825 /* X:\xxx is always absolute. */
826 if (isalpha (filename
[0])
827 && filename
[1] == ':' && (filename
[2] == '\\' || filename
[2] == '/'))
830 /* Both \xxx and \\xxx\yyy are absolute. */
831 if (filename
[0] == '\\') return TRUE
;
834 FIXME: There's a corner case not dealt with, "x:y", where:
836 1) x is a valid drive designation (usually a letter in the A-Z range)
837 and y is a path, relative to the current directory on drive x. This
838 is absolute, *after* fixing the y part to include the current
841 2) x is a relative file name, and y is an NTFS stream name. This is a
842 correct relative path, but it is very unusual.
844 The trouble is that first case items are also valid examples of the
845 second case, i.e., "c:test" can be understood as drive:path or as
848 The "right" fix would involve checking whether
849 - the current drive/partition is NTFS,
850 - x is a valid (and accesible) drive designator,
851 - x:y already exists as a file:stream in the current directory,
852 - y already exists on the current directory of drive x,
853 - the auspices are favorable,
854 and then taking an "informed decision" based on the above.
856 Whatever the result, Emacs currently does a very bad job of dealing
857 with NTFS file:streams: it cannot visit them, and the only way to
858 create one is by setting `buffer-file-name' to point to it (either
859 manually or with emacsclient). So perhaps resorting to 1) and ignoring
860 2) for now is the right thing to do.
862 Anyway, something to decide After the Release.
870 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
872 __cdecl
close_winsock ()
877 /* Initialize the WinSock2 library. */
879 initialize_sockets ()
883 if (WSAStartup (MAKEWORD (2, 0), &wsaData
))
885 message (TRUE
, "%s: error initializing WinSock2", progname
);
889 atexit (close_winsock
);
891 #endif /* WINDOWSNT */
895 * Read the information needed to set up a TCP comm channel with
896 * the Emacs server: host, port, pid and authentication string.
899 get_server_config (server
, authentication
)
900 struct sockaddr_in
*server
;
901 char *authentication
;
908 if (file_name_absolute_p (server_file
))
909 config
= fopen (server_file
, "rb");
912 char *home
= egetenv ("HOME");
916 char *path
= alloca (32 + strlen (home
) + strlen (server_file
));
917 sprintf (path
, "%s/.emacs.d/server/%s", home
, server_file
);
918 config
= fopen (path
, "rb");
921 if (!config
&& (home
= egetenv ("APPDATA")))
923 char *path
= alloca (32 + strlen (home
) + strlen (server_file
));
924 sprintf (path
, "%s/.emacs.d/server/%s", home
, server_file
);
925 config
= fopen (path
, "rb");
933 if (fgets (dotted
, sizeof dotted
, config
)
934 && (port
= strchr (dotted
, ':'))
935 && (pid
= strchr (port
, ' ')))
942 message (TRUE
, "%s: invalid configuration info", 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", progname
);
958 emacs_pid
= atoi (pid
);
967 struct sockaddr_in server
;
968 struct linger l_arg
= {1, 1};
969 char auth_string
[AUTH_KEY_LENGTH
+ 1];
971 if (! get_server_config (&server
, auth_string
))
972 return INVALID_SOCKET
;
974 if (server
.sin_addr
.s_addr
!= inet_addr ("127.0.0.1"))
975 message (FALSE
, "%s: connected to remote socket at %s\n",
976 progname
, inet_ntoa (server
.sin_addr
));
979 * Open up an AF_INET socket
981 if ((s
= socket (AF_INET
, SOCK_STREAM
, IPPROTO_TCP
)) < 0)
983 sock_err_message ("socket");
984 return INVALID_SOCKET
;
990 if (connect (s
, (struct sockaddr
*) &server
, sizeof server
) < 0)
992 sock_err_message ("connect");
993 return INVALID_SOCKET
;
996 setsockopt (s
, SOL_SOCKET
, SO_LINGER
, (char *) &l_arg
, sizeof l_arg
);
999 * Send the authentication
1001 auth_string
[AUTH_KEY_LENGTH
] = '\0';
1003 send_to_emacs (s
, "-auth ");
1004 send_to_emacs (s
, auth_string
);
1005 send_to_emacs (s
, "\n");
1011 /* Returns 1 if PREFIX is a prefix of STRING. */
1013 strprefix (char *prefix
, char *string
)
1015 return !strncmp (prefix
, string
, strlen (prefix
));
1019 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1021 /* Three possibilities:
1022 2 - can't be `stat'ed (sets errno)
1023 1 - isn't owned by us
1024 0 - success: none of the above */
1027 socket_status (socket_name
)
1030 struct stat statbfr
;
1032 if (stat (socket_name
, &statbfr
) == -1)
1035 if (statbfr
.st_uid
!= geteuid ())
1042 /* A signal handler that passes the signal to the Emacs process.
1043 Useful for SIGWINCH. */
1046 pass_signal_to_emacs (int signalnum
)
1048 int old_errno
= errno
;
1051 kill (emacs_pid
, signalnum
);
1053 signal (signalnum
, pass_signal_to_emacs
);
1057 /* Signal handler for SIGCONT; notify the Emacs process that it can
1058 now resume our tty frame. */
1061 handle_sigcont (int signalnum
)
1063 int old_errno
= errno
;
1065 if (tcgetpgrp (1) == getpgrp ())
1067 /* We are in the foreground. */
1068 send_to_emacs (emacs_socket
, "-resume \n");
1072 /* We are in the background; cancel the continue. */
1073 kill (getpid (), SIGSTOP
);
1076 signal (signalnum
, handle_sigcont
);
1080 /* Signal handler for SIGTSTP; notify the Emacs process that we are
1081 going to sleep. Normally the suspend is initiated by Emacs via
1082 server-handle-suspend-tty, but if the server gets out of sync with
1083 reality, we may get a SIGTSTP on C-z. Handling this signal and
1084 notifying Emacs about it should get things under control again. */
1087 handle_sigtstp (int signalnum
)
1089 int old_errno
= errno
;
1093 send_to_emacs (emacs_socket
, "-suspend \n");
1095 /* Unblock this signal and call the default handler by temprarily
1096 changing the handler and resignalling. */
1097 sigprocmask (SIG_BLOCK
, NULL
, &set
);
1098 sigdelset (&set
, signalnum
);
1099 signal (signalnum
, SIG_DFL
);
1100 kill (getpid (), signalnum
);
1101 sigprocmask (SIG_SETMASK
, &set
, NULL
); /* Let's the above signal through. */
1102 signal (signalnum
, handle_sigtstp
);
1106 /* Set up signal handlers before opening a frame on the current tty. */
1111 /* Set up signal handlers. */
1112 signal (SIGWINCH
, pass_signal_to_emacs
);
1114 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
1115 deciding which terminal the signal came from. C-g is now a
1116 normal input event on secondary terminals. */
1118 signal (SIGINT
, pass_signal_to_emacs
);
1119 signal (SIGQUIT
, pass_signal_to_emacs
);
1122 signal (SIGCONT
, handle_sigcont
);
1123 signal (SIGTSTP
, handle_sigtstp
);
1124 signal (SIGTTOU
, handle_sigtstp
);
1132 struct sockaddr_un server
;
1135 * Open up an AF_UNIX socket in this person's home directory
1138 if ((s
= socket (AF_UNIX
, SOCK_STREAM
, 0)) < 0)
1140 message (TRUE
, "%s: socket: %s\n", progname
, strerror (errno
));
1141 return INVALID_SOCKET
;
1144 server
.sun_family
= AF_UNIX
;
1147 int sock_status
= 0;
1148 int default_sock
= !socket_name
;
1149 int saved_errno
= 0;
1150 char *server_name
= "server";
1152 if (socket_name
&& !index (socket_name
, '/') && !index (socket_name
, '\\'))
1153 { /* socket_name is a file name component. */
1154 server_name
= socket_name
;
1156 default_sock
= 1; /* Try both UIDs. */
1161 socket_name
= alloca (100 + strlen (server_name
));
1162 sprintf (socket_name
, "/tmp/emacs%d/%s",
1163 (int) geteuid (), server_name
);
1166 if (strlen (socket_name
) < sizeof (server
.sun_path
))
1167 strcpy (server
.sun_path
, socket_name
);
1170 message (TRUE
, "%s: socket-name %s too long",
1171 progname
, socket_name
);
1175 /* See if the socket exists, and if it's owned by us. */
1176 sock_status
= socket_status (server
.sun_path
);
1177 saved_errno
= errno
;
1178 if (sock_status
&& default_sock
)
1180 /* Failing that, see if LOGNAME or USER exist and differ from
1181 our euid. If so, look for a socket based on the UID
1182 associated with the name. This is reminiscent of the logic
1183 that init_editfns uses to set the global Vuser_full_name. */
1185 char *user_name
= (char *) egetenv ("LOGNAME");
1188 user_name
= (char *) egetenv ("USER");
1192 struct passwd
*pw
= getpwnam (user_name
);
1194 if (pw
&& (pw
->pw_uid
!= geteuid ()))
1196 /* We're running under su, apparently. */
1197 socket_name
= alloca (100 + strlen (server_name
));
1198 sprintf (socket_name
, "/tmp/emacs%d/%s",
1199 (int) pw
->pw_uid
, server_name
);
1201 if (strlen (socket_name
) < sizeof (server
.sun_path
))
1202 strcpy (server
.sun_path
, socket_name
);
1205 message (TRUE
, "%s: socket-name %s too long",
1206 progname
, socket_name
);
1207 exit (EXIT_FAILURE
);
1210 sock_status
= socket_status (server
.sun_path
);
1211 saved_errno
= errno
;
1214 errno
= saved_errno
;
1218 switch (sock_status
)
1221 /* There's a socket, but it isn't owned by us. This is OK if
1223 if (0 != geteuid ())
1225 message (TRUE
, "%s: Invalid socket owner\n", progname
);
1226 return INVALID_SOCKET
;
1232 if (saved_errno
== ENOENT
)
1234 "%s: can't find socket; have you started the server?\n\
1235 To start the server in Emacs, type \"M-x server-start\".\n",
1238 message (TRUE
, "%s: can't stat %s: %s\n",
1239 progname
, server
.sun_path
, strerror (saved_errno
));
1240 return INVALID_SOCKET
;
1244 if (connect (s
, (struct sockaddr
*) &server
, strlen (server
.sun_path
) + 2)
1247 message (TRUE
, "%s: connect: %s\n", progname
, strerror (errno
));
1248 return INVALID_SOCKET
;
1253 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1262 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1263 /* Explicit --socket-name argument. */
1266 s
= set_local_socket ();
1267 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
1269 message (TRUE
, "%s: error accessing socket \"%s\"",
1270 progname
, socket_name
);
1271 exit (EXIT_FAILURE
);
1275 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1277 server_file
= egetenv ("EMACS_SERVER_FILE");
1281 s
= set_tcp_socket ();
1282 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
1285 message (TRUE
, "%s: error accessing server file \"%s\"",
1286 progname
, server_file
);
1287 exit (EXIT_FAILURE
);
1290 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1291 /* Implicit local socket. */
1292 s
= set_local_socket ();
1293 if (s
!= INVALID_SOCKET
)
1297 /* Implicit server file. */
1298 server_file
= "server";
1299 s
= set_tcp_socket ();
1300 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
1303 /* No implicit or explicit socket, and no alternate editor. */
1304 message (TRUE
, "%s: No socket or alternate editor. Please use:\n\n"
1305 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1308 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1309 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1311 exit (EXIT_FAILURE
);
1315 FARPROC set_fg
; /* Pointer to AllowSetForegroundWindow. */
1316 FARPROC get_wc
; /* Pointer to RealGetWindowClassA. */
1319 w32_find_emacs_process (hWnd
, lParam
)
1326 /* Reject any window not of class "Emacs". */
1327 if (! get_wc (hWnd
, class, sizeof (class))
1328 || strcmp (class, "Emacs"))
1331 /* We only need the process id, not the thread id. */
1332 (void) GetWindowThreadProcessId (hWnd
, &pid
);
1334 /* Not the one we're looking for. */
1335 if (pid
!= (DWORD
) emacs_pid
) return TRUE
;
1337 /* OK, let's raise it. */
1340 /* Stop enumeration. */
1345 * Search for a window of class "Emacs" and owned by a process with
1346 * process id = emacs_pid. If found, allow it to grab the focus.
1353 /* It shouldn't happen when dealing with TCP sockets. */
1354 if (!emacs_pid
) return;
1356 if (!(hUser32
= LoadLibrary ("user32.dll"))) return;
1358 /* Modern Windows restrict which processes can set the foreground window.
1359 emacsclient can allow Emacs to grab the focus by calling the function
1360 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1361 NT) lack this function, so we have to check its availability. */
1362 if ((set_fg
= GetProcAddress (hUser32
, "AllowSetForegroundWindow"))
1363 && (get_wc
= GetProcAddress (hUser32
, "RealGetWindowClassA")))
1364 EnumWindows (w32_find_emacs_process
, (LPARAM
) 0);
1366 FreeLibrary (hUser32
);
1375 int i
, rl
, needlf
= 0;
1377 char string
[BUFSIZ
+1];
1382 /* Process options. */
1383 decode_options (argc
, argv
);
1385 if ((argc
- optind
< 1) && !eval
&& !tty
&& !window_system
)
1387 message (TRUE
, "%s: file name or argument required\n"
1388 "Try `%s --help' for more information\n",
1389 progname
, progname
);
1390 exit (EXIT_FAILURE
);
1393 if ((emacs_socket
= set_socket ()) == INVALID_SOCKET
)
1397 cwd
= get_current_dir_name ();
1400 /* getwd puts message in STRING if it fails. */
1401 message (TRUE
, "%s: %s\n", progname
,
1402 "Cannot get current working directory");
1410 /* Send over our environment. */
1413 extern char **environ
;
1415 for (i
= 0; environ
[i
]; i
++)
1417 char *name
= xstrdup (environ
[i
]);
1418 char *value
= strchr (name
, '=');
1419 send_to_emacs (emacs_socket
, "-env ");
1420 quote_argument (emacs_socket
, environ
[i
]);
1421 send_to_emacs (emacs_socket
, " ");
1425 /* Send over our current directory. */
1428 send_to_emacs (emacs_socket
, "-dir ");
1429 quote_argument (emacs_socket
, cwd
);
1430 send_to_emacs (emacs_socket
, "/");
1431 send_to_emacs (emacs_socket
, " ");
1436 send_to_emacs (emacs_socket
, "-nowait ");
1439 send_to_emacs (emacs_socket
, "-current-frame ");
1443 send_to_emacs (emacs_socket
, "-display ");
1444 quote_argument (emacs_socket
, display
);
1445 send_to_emacs (emacs_socket
, " ");
1450 char *type
= egetenv ("TERM");
1451 char *tty_name
= NULL
;
1453 tty_name
= ttyname (fileno (stdin
));
1458 message (TRUE
, "%s: could not get terminal name\n", progname
);
1464 message (TRUE
, "%s: please set the TERM variable to your terminal type\n",
1469 if (! strcmp (type
, "eterm"))
1471 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1472 message (TRUE
, "%s: opening a frame in an Emacs term buffer"
1473 " is not supported\n", progname
);
1476 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1480 send_to_emacs (emacs_socket
, "-tty ");
1481 quote_argument (emacs_socket
, tty_name
);
1482 send_to_emacs (emacs_socket
, " ");
1483 quote_argument (emacs_socket
, type
);
1484 send_to_emacs (emacs_socket
, " ");
1488 send_to_emacs (emacs_socket
, "-window-system ");
1490 if ((argc
- optind
> 0))
1492 for (i
= optind
; i
< argc
; i
++)
1498 /* Don't prepend cwd or anything like that. */
1499 send_to_emacs (emacs_socket
, "-eval ");
1500 quote_argument (emacs_socket
, argv
[i
]);
1501 send_to_emacs (emacs_socket
, " ");
1505 if (*argv
[i
] == '+')
1507 char *p
= argv
[i
] + 1;
1508 while (isdigit ((unsigned char) *p
) || *p
== ':') p
++;
1511 send_to_emacs (emacs_socket
, "-position ");
1512 quote_argument (emacs_socket
, argv
[i
]);
1513 send_to_emacs (emacs_socket
, " ");
1519 else if (! file_name_absolute_p (argv
[i
]))
1522 send_to_emacs (emacs_socket
, "-file ");
1525 quote_argument (emacs_socket
, cwd
);
1526 send_to_emacs (emacs_socket
, "/");
1528 quote_argument (emacs_socket
, argv
[i
]);
1529 send_to_emacs (emacs_socket
, " ");
1534 if (!tty
&& !window_system
)
1536 while ((str
= fgets (string
, BUFSIZ
, stdin
)))
1539 send_to_emacs (emacs_socket
, "-eval ");
1541 send_to_emacs (emacs_socket
, "-file ");
1542 quote_argument (emacs_socket
, str
);
1544 send_to_emacs (emacs_socket
, " ");
1548 send_to_emacs (emacs_socket
, "\n");
1550 /* Wait for an answer. */
1551 if (!eval
&& !tty
&& !nowait
)
1553 printf ("Waiting for Emacs...");
1559 /* Now, wait for an answer and print any messages. */
1560 while ((rl
= recv (emacs_socket
, string
, BUFSIZ
, 0)) > 0)
1565 p
= string
+ strlen (string
) - 1;
1566 while (p
> string
&& *p
== '\n')
1569 if (strprefix ("-emacs-pid ", string
))
1571 /* -emacs-pid PID: The process id of the Emacs process. */
1572 emacs_pid
= strtol (string
+ strlen ("-emacs-pid"), NULL
, 10);
1574 else if (strprefix ("-window-system-unsupported ", string
))
1576 /* -window-system-unsupported: Emacs was compiled without X
1577 support. Try again on the terminal. */
1583 else if (strprefix ("-print ", string
))
1585 /* -print STRING: Print STRING on the terminal. */
1586 str
= unquote_argument (string
+ strlen ("-print "));
1590 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1592 else if (strprefix ("-error ", string
))
1594 /* -error DESCRIPTION: Signal an error on the terminal. */
1595 str
= unquote_argument (string
+ strlen ("-error "));
1598 fprintf (stderr
, "*ERROR*: %s", str
);
1599 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1602 else if (strprefix ("-suspend ", string
))
1604 /* -suspend: Suspend this terminal, i.e., stop the process. */
1613 /* Unknown command. */
1616 printf ("*ERROR*: Unknown message: %s", string
);
1617 needlf
= string
[0] == '\0' ? needlf
: string
[strlen (string
) - 1] != '\n';
1626 CLOSE_SOCKET (emacs_socket
);
1627 return EXIT_SUCCESS
;
1630 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
1633 #ifndef HAVE_STRERROR
1638 extern char *sys_errlist
[];
1639 extern int sys_nerr
;
1641 if (errnum
>= 0 && errnum
< sys_nerr
)
1642 return sys_errlist
[errnum
];
1643 return (char *) "Unknown error";
1646 #endif /* ! HAVE_STRERROR */
1648 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
1649 (do not change this comment) */
1651 /* emacsclient.c ends here */