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 # include <darpa/inet.h>
52 # define INVALID_SOCKET -1
54 # define CLOSE_SOCKET close
57 #endif /* !WINDOWSNT */
71 #else /* not WINDOWSNT */
73 #endif /* not WINDOWSNT */
80 char *getenv (), *getwd ();
85 #define egetenv(VAR) w32_getenv(VAR)
87 #define egetenv(VAR) getenv(VAR)
91 #define VERSION "unspecified"
96 #define EXIT_SUCCESS 0
100 #define EXIT_FAILURE 1
115 /* Additional space when allocating buffers for filenames, etc. */
116 #define EXTRA_SPACE 100
119 /* Name used to invoke this program. */
122 /* The second argument to main. */
125 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
128 /* Nonzero means args are expressions to be evaluated. --eval. */
131 /* Nonzero means don't open a new frame. Inverse of --create-frame. */
132 int current_frame
= 1;
134 /* The display on which Emacs should work. --display. */
135 char *display
= NULL
;
137 /* Nonzero means open a new Emacs frame on the current terminal. */
140 /* If non-NULL, the name of an editor to fallback to if the server
141 is not running. --alternate-editor. */
142 const char *alternate_editor
= NULL
;
144 /* If non-NULL, the filename of the UNIX socket. */
145 char *socket_name
= NULL
;
147 /* If non-NULL, the filename of the authentication file. */
148 char *server_file
= NULL
;
150 /* PID of the Emacs server process. */
153 void print_help_and_exit () NO_RETURN
;
155 struct option longopts
[] =
157 { "no-wait", no_argument
, NULL
, 'n' },
158 { "eval", no_argument
, NULL
, 'e' },
159 { "help", no_argument
, NULL
, 'H' },
160 { "version", no_argument
, NULL
, 'V' },
161 { "tty", no_argument
, NULL
, 't' },
162 { "nw", no_argument
, NULL
, 't' },
163 { "create-frame", no_argument
, NULL
, 'c' },
164 { "alternate-editor", required_argument
, NULL
, 'a' },
165 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
166 { "socket-name", required_argument
, NULL
, 's' },
168 { "server-file", required_argument
, NULL
, 'f' },
170 { "display", required_argument
, NULL
, 'd' },
176 /* Like malloc but get fatal error if memory is exhausted. */
182 long *result
= (long *) malloc (size
);
191 /* Like strdup but get a fatal error if memory is exhausted. */
194 xstrdup (const char *s
)
196 char *result
= strdup (s
);
206 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
209 #ifndef DIRECTORY_SEP
210 #define DIRECTORY_SEP '/'
212 #ifndef IS_DIRECTORY_SEP
213 #define IS_DIRECTORY_SEP(_c_) ((_c_) == DIRECTORY_SEP)
215 #ifndef IS_DEVICE_SEP
217 #define IS_DEVICE_SEP(_c_) 0
219 #define IS_DEVICE_SEP(_c_) ((_c_) == DEVICE_SEP)
223 #define IS_ANY_SEP(_c_) (IS_DIRECTORY_SEP (_c_))
227 /* Return the current working directory. Returns NULL on errors.
228 Any other returned value must be freed with free. This is used
229 only when get_current_dir_name is not defined on the system. */
231 get_current_dir_name ()
235 struct stat dotstat
, pwdstat
;
236 /* If PWD is accurate, use it instead of calling getwd. PWD is
237 sometimes a nicer name, and using it may avoid a fatal error if a
238 parent directory is searchable but not readable. */
239 if ((pwd
= egetenv ("PWD")) != 0
240 && (IS_DIRECTORY_SEP (*pwd
) || (*pwd
&& IS_DEVICE_SEP (pwd
[1])))
241 && stat (pwd
, &pwdstat
) == 0
242 && stat (".", &dotstat
) == 0
243 && dotstat
.st_ino
== pwdstat
.st_ino
244 && dotstat
.st_dev
== pwdstat
.st_dev
246 && strlen (pwd
) < MAXPATHLEN
250 buf
= (char *) xmalloc (strlen (pwd
) + 1);
258 size_t buf_size
= 1024;
259 buf
= (char *) xmalloc (buf_size
);
264 if (getcwd (buf
, buf_size
) == buf
)
268 int tmp_errno
= errno
;
274 buf
= (char *) realloc (buf
, buf_size
);
282 /* We need MAXPATHLEN here. */
283 buf
= (char *) xmalloc (MAXPATHLEN
+ 1);
286 if (getwd (buf
) == NULL
)
288 int tmp_errno
= errno
;
301 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
303 /* Retrieve an environment variable from the Emacs subkeys of the registry.
304 Return NULL if the variable was not found, or it was empty.
305 This code is based on w32_get_resource (w32.c). */
307 w32_get_resource (predefined
, key
, type
)
312 HKEY hrootkey
= NULL
;
316 if (RegOpenKeyEx (predefined
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
318 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
)
320 result
= (char *) xmalloc (cbData
);
322 if ((RegQueryValueEx (hrootkey
, key
, NULL
, type
, result
, &cbData
) != ERROR_SUCCESS
)
330 RegCloseKey (hrootkey
);
337 getenv wrapper for Windows
339 This is needed to duplicate Emacs's behavior, which is to look for enviroment
340 variables in the registry if they don't appear in the environment.
349 if (value
= getenv (envvar
))
350 /* Found in the environment. */
353 if (! (value
= w32_get_resource (HKEY_CURRENT_USER
, envvar
, &dwType
)) &&
354 ! (value
= w32_get_resource (HKEY_LOCAL_MACHINE
, envvar
, &dwType
)))
356 /* "w32console" is what Emacs on Windows uses for tty-type under -nw. */
357 if (strcmp (envvar
, "TERM") == 0)
358 return xstrdup ("w32console");
359 /* Found neither in the environment nor in the registry. */
363 if (dwType
== REG_SZ
)
364 /* Registry; no need to expand. */
367 if (dwType
== REG_EXPAND_SZ
)
371 if (size
= ExpandEnvironmentStrings (value
, NULL
, 0))
373 char *buffer
= (char *) xmalloc (size
);
374 if (ExpandEnvironmentStrings (value
, buffer
, size
))
376 /* Found and expanded. */
381 /* Error expanding. */
386 /* Not the right type, or not correctly expanded. */
394 static int window_app
= -1;
395 char szTitle
[MAX_PATH
];
399 /* Checking for STDOUT does not work; it's a valid handle also in
400 nonconsole apps. Testing for the console title seems to work. */
401 window_app
= (GetConsoleTitleA (szTitle
, MAX_PATH
) == 0);
403 InitCommonControls();
410 execvp wrapper for Windows. Quotes arguments with embedded spaces.
412 This is necessary due to the broken implementation of exec* routines in
413 the Microsoft libraries: they concatenate the arguments together without
414 quoting special characters, and pass the result to CreateProcess, with
415 predictably bad results. By contrast, Posix execvp passes the arguments
416 directly into the argv array of the child process.
419 w32_execvp (path
, argv
)
425 /* Required to allow a .BAT script as alternate editor. */
426 argv
[0] = (char *) alternate_editor
;
428 for (i
= 0; argv
[i
]; i
++)
429 if (strchr (argv
[i
], ' '))
431 char *quoted
= alloca (strlen (argv
[i
]) + 3);
432 sprintf (quoted
, "\"%s\"", argv
[i
]);
436 return execvp (path
, argv
);
440 #define execvp w32_execvp
442 /* Emulation of ttyname for Windows. */
449 #endif /* WINDOWSNT */
451 /* Display a normal or error message.
452 On Windows, use a message box if compiled as a Windows app. */
454 message (int is_error
, char *message
, ...)
459 va_start (args
, message
);
460 vsprintf (msg
, message
, args
);
464 if (w32_window_app ())
467 MessageBox (NULL
, msg
, "Emacsclient ERROR", MB_ICONERROR
);
469 MessageBox (NULL
, msg
, "Emacsclient", MB_ICONINFORMATION
);
474 FILE *f
= is_error
? stderr
: stdout
;
481 /* Decode the options from argv and argc.
482 The global variable `optind' will say how many arguments we used up. */
485 decode_options (argc
, argv
)
489 alternate_editor
= egetenv ("ALTERNATE_EDITOR");
493 int opt
= getopt_long_only (argc
, argv
,
494 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
507 /* If getopt returns 0, then it has already processed a
508 long-named option. We should do nothing. */
512 alternate_editor
= optarg
;
515 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
517 socket_name
= optarg
;
522 server_file
= optarg
;
525 /* We used to disallow this argument in w32, but it seems better
526 to allow it, for the occasional case where the user is
527 connecting with a w32 client to a server compiled with X11
542 message (FALSE
, "emacsclient %s\n", VERSION
);
556 print_help_and_exit ();
560 message (TRUE
, "Try `%s --help' for more information\n", progname
);
566 /* If the -c option is used (without -t) and no --display argument
567 is provided, try $DISPLAY.
568 Without the -c option, we used to set `display' to $DISPLAY by
569 default, but this changed the default behavior and is sometimes
570 inconvenient. So we force users to use "--display $DISPLAY" if
571 they want Emacs to connect to their current display. */
572 if (!current_frame
&& !tty
&& !display
)
573 display
= egetenv ("DISPLAY");
575 /* A null-string display is invalid. */
576 if (display
&& strlen (display
) == 0)
579 /* If no display is available, new frames are tty frames. */
580 if (!current_frame
&& !display
)
583 /* --no-wait implies --current-frame on ttys when there are file
584 arguments or expressions given. */
585 if (nowait
&& tty
&& argc
- optind
> 0)
591 print_help_and_exit ()
593 /* Spaces and tabs are significant in this message; they're chosen so the
594 message aligns properly both in a tty and in a Windows message box.
595 Please try to preserve them; otherwise the output is very hard to read
596 when using emacsclientw. */
598 "Usage: %s [OPTIONS] FILE...\n\
599 Tell the Emacs server to visit the specified files.\n\
600 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
602 The following OPTIONS are accepted:\n\
603 -V, --version Just print version info and return\n\
604 -H, --help Print this usage information message\n\
605 -nw, -t, --tty Open a new Emacs frame on the current terminal\n\
606 -c, --create-frame Create a new frame instead of trying to\n\
607 use the current Emacs frame\n\
608 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
609 -n, --no-wait Don't wait for the server to return\n\
610 -d, --display=DISPLAY Visit the file in the given display\n"
611 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
612 "-s, --socket-name=FILENAME\n\
613 Set filename of the UNIX socket for communication\n"
615 "-f, --server-file=FILENAME\n\
616 Set filename of the TCP authentication file\n\
617 -a, --alternate-editor=EDITOR\n\
618 Editor to fallback to if the server is not running\n\
620 Report bugs to bug-gnu-emacs@gnu.org.\n", progname
);
625 Try to run a different command, or --if no alternate editor is
626 defined-- exit with an errorcode.
627 Uses argv, but gets it from the global variable main_argv.
632 if (alternate_editor
)
636 execvp (alternate_editor
, main_argv
+ i
);
637 message (TRUE
, "%s: error executing alternate editor \"%s\"\n",
638 progname
, alternate_editor
);
644 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
653 message (TRUE
, "%s: Sorry, the Emacs server is supported only\n"
654 "on systems with Berkeley sockets.\n",
659 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
662 # include <winsock2.h>
664 # include <sys/types.h>
665 # include <sys/socket.h>
669 #define AUTH_KEY_LENGTH 64
670 #define SEND_BUFFER_SIZE 4096
672 extern char *strerror ();
675 /* Buffer to accumulate data to send in TCP connections. */
676 char send_buffer
[SEND_BUFFER_SIZE
+ 1];
677 int sblen
= 0; /* Fill pointer for the send buffer. */
678 /* Socket used to communicate with the Emacs server process. */
679 HSOCKET emacs_socket
= 0;
681 /* On Windows, the socket library was historically separate from the standard
682 C library, so errors are handled differently. */
684 sock_err_message (function_name
)
690 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
691 | FORMAT_MESSAGE_ALLOCATE_BUFFER
692 | FORMAT_MESSAGE_ARGUMENT_ARRAY
,
693 NULL
, WSAGetLastError (), 0, (LPTSTR
)&msg
, 0, NULL
);
695 message (TRUE
, "%s: %s: %s\n", progname
, function_name
, msg
);
699 message (TRUE
, "%s: %s: %s\n", progname
, function_name
, strerror (errno
));
704 /* Let's send the data to Emacs when either
705 - the data ends in "\n", or
706 - the buffer is full (but this shouldn't happen)
707 Otherwise, we just accumulate it. */
709 send_to_emacs (s
, data
)
715 int dlen
= strlen (data
);
716 if (dlen
+ sblen
>= SEND_BUFFER_SIZE
)
718 int part
= SEND_BUFFER_SIZE
- sblen
;
719 strncpy (&send_buffer
[sblen
], data
, part
);
721 sblen
= SEND_BUFFER_SIZE
;
725 strcpy (&send_buffer
[sblen
], data
);
732 if (sblen
== SEND_BUFFER_SIZE
733 || (sblen
> 0 && send_buffer
[sblen
-1] == '\n'))
735 int sent
= send (s
, send_buffer
, sblen
, 0);
737 strcpy (send_buffer
, &send_buffer
[sent
]);
744 /* In STR, insert a & before each &, each space, each newline, and
745 any initial -. Change spaces to underscores, too, so that the
746 return value never contains a space.
748 Does not change the string. Outputs the result to STREAM. */
750 quote_argument (s
, str
)
754 char *copy
= (char *) xmalloc (strlen (str
) * 2 + 1);
775 if (*p
== '&' || (*p
== '-' && p
== str
))
782 send_to_emacs (s
, copy
);
788 /* The inverse of quote_argument. Removes quoting in string STR by
789 modifying the string in place. Returns STR. */
792 unquote_argument (str
)
824 file_name_absolute_p (filename
)
825 const unsigned char *filename
;
827 /* Sanity check, it shouldn't happen. */
828 if (! filename
) return FALSE
;
830 /* /xxx is always an absolute path. */
831 if (filename
[0] == '/') return TRUE
;
833 /* Empty filenames (which shouldn't happen) are relative. */
834 if (filename
[0] == '\0') return FALSE
;
837 /* X:\xxx is always absolute. */
838 if (isalpha (filename
[0])
839 && filename
[1] == ':' && (filename
[2] == '\\' || filename
[2] == '/'))
842 /* Both \xxx and \\xxx\yyy are absolute. */
843 if (filename
[0] == '\\') return TRUE
;
850 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
852 __cdecl
close_winsock ()
857 /* Initialize the WinSock2 library. */
859 initialize_sockets ()
863 if (WSAStartup (MAKEWORD (2, 0), &wsaData
))
865 message (TRUE
, "%s: error initializing WinSock2\n", progname
);
869 atexit (close_winsock
);
871 #endif /* WINDOWSNT */
875 * Read the information needed to set up a TCP comm channel with
876 * the Emacs server: host, port, pid and authentication string.
879 get_server_config (server
, authentication
)
880 struct sockaddr_in
*server
;
881 char *authentication
;
888 if (file_name_absolute_p (server_file
))
889 config
= fopen (server_file
, "rb");
892 char *home
= egetenv ("HOME");
896 char *path
= alloca (strlen (home
) + strlen (server_file
)
898 sprintf (path
, "%s/.emacs.d/server/%s", home
, server_file
);
899 config
= fopen (path
, "rb");
902 if (!config
&& (home
= egetenv ("APPDATA")))
904 char *path
= alloca (strlen (home
) + strlen (server_file
)
906 sprintf (path
, "%s/.emacs.d/server/%s", home
, server_file
);
907 config
= fopen (path
, "rb");
915 if (fgets (dotted
, sizeof dotted
, config
)
916 && (port
= strchr (dotted
, ':'))
917 && (pid
= strchr (port
, ' ')))
924 message (TRUE
, "%s: invalid configuration info\n", progname
);
928 server
->sin_family
= AF_INET
;
929 server
->sin_addr
.s_addr
= inet_addr (dotted
);
930 server
->sin_port
= htons (atoi (port
));
932 if (! fread (authentication
, AUTH_KEY_LENGTH
, 1, config
))
934 message (TRUE
, "%s: cannot read authentication info\n", progname
);
940 emacs_pid
= atoi (pid
);
949 struct sockaddr_in server
;
950 struct linger l_arg
= {1, 1};
951 char auth_string
[AUTH_KEY_LENGTH
+ 1];
953 if (! get_server_config (&server
, auth_string
))
954 return INVALID_SOCKET
;
956 if (server
.sin_addr
.s_addr
!= inet_addr ("127.0.0.1"))
957 message (FALSE
, "%s: connected to remote socket at %s\n",
958 progname
, inet_ntoa (server
.sin_addr
));
961 * Open up an AF_INET socket
963 if ((s
= socket (AF_INET
, SOCK_STREAM
, IPPROTO_TCP
)) < 0)
965 sock_err_message ("socket");
966 return INVALID_SOCKET
;
972 if (connect (s
, (struct sockaddr
*) &server
, sizeof server
) < 0)
974 sock_err_message ("connect");
975 return INVALID_SOCKET
;
978 setsockopt (s
, SOL_SOCKET
, SO_LINGER
, (char *) &l_arg
, sizeof l_arg
);
981 * Send the authentication
983 auth_string
[AUTH_KEY_LENGTH
] = '\0';
985 send_to_emacs (s
, "-auth ");
986 send_to_emacs (s
, auth_string
);
987 send_to_emacs (s
, " ");
993 /* Returns 1 if PREFIX is a prefix of STRING. */
995 strprefix (char *prefix
, char *string
)
997 return !strncmp (prefix
, string
, strlen (prefix
));
1000 /* Get tty name and type. If successful, return the type in TTY_TYPE
1001 and the name in TTY_NAME, and return 1. Otherwise, fail if NOABORT
1002 is zero, or return 0 if NOABORT is non-zero. */
1005 find_tty (char **tty_type
, char **tty_name
, int noabort
)
1007 char *type
= egetenv ("TERM");
1008 char *name
= ttyname (fileno (stdout
));
1016 message (TRUE
, "%s: could not get terminal name\n", progname
);
1027 message (TRUE
, "%s: please set the TERM variable to your terminal type\n",
1033 if (strcmp (type
, "eterm") == 0)
1039 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1040 message (TRUE
, "%s: opening a frame in an Emacs term buffer"
1041 " is not supported\n", progname
);
1052 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1054 /* Three possibilities:
1055 2 - can't be `stat'ed (sets errno)
1056 1 - isn't owned by us
1057 0 - success: none of the above */
1060 socket_status (socket_name
)
1063 struct stat statbfr
;
1065 if (stat (socket_name
, &statbfr
) == -1)
1068 if (statbfr
.st_uid
!= geteuid ())
1075 /* A signal handler that passes the signal to the Emacs process.
1076 Useful for SIGWINCH. */
1079 pass_signal_to_emacs (int signalnum
)
1081 int old_errno
= errno
;
1084 kill (emacs_pid
, signalnum
);
1086 signal (signalnum
, pass_signal_to_emacs
);
1090 /* Signal handler for SIGCONT; notify the Emacs process that it can
1091 now resume our tty frame. */
1094 handle_sigcont (int signalnum
)
1096 int old_errno
= errno
;
1098 if (tcgetpgrp (1) == getpgrp ())
1100 /* We are in the foreground. */
1101 send_to_emacs (emacs_socket
, "-resume \n");
1105 /* We are in the background; cancel the continue. */
1106 kill (getpid (), SIGSTOP
);
1109 signal (signalnum
, handle_sigcont
);
1113 /* Signal handler for SIGTSTP; notify the Emacs process that we are
1114 going to sleep. Normally the suspend is initiated by Emacs via
1115 server-handle-suspend-tty, but if the server gets out of sync with
1116 reality, we may get a SIGTSTP on C-z. Handling this signal and
1117 notifying Emacs about it should get things under control again. */
1120 handle_sigtstp (int signalnum
)
1122 int old_errno
= errno
;
1126 send_to_emacs (emacs_socket
, "-suspend \n");
1128 /* Unblock this signal and call the default handler by temporarily
1129 changing the handler and resignalling. */
1130 sigprocmask (SIG_BLOCK
, NULL
, &set
);
1131 sigdelset (&set
, signalnum
);
1132 signal (signalnum
, SIG_DFL
);
1133 kill (getpid (), signalnum
);
1134 sigprocmask (SIG_SETMASK
, &set
, NULL
); /* Let's the above signal through. */
1135 signal (signalnum
, handle_sigtstp
);
1141 /* Set up signal handlers before opening a frame on the current tty. */
1146 /* Set up signal handlers. */
1147 signal (SIGWINCH
, pass_signal_to_emacs
);
1149 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
1150 deciding which terminal the signal came from. C-g is now a
1151 normal input event on secondary terminals. */
1153 signal (SIGINT
, pass_signal_to_emacs
);
1154 signal (SIGQUIT
, pass_signal_to_emacs
);
1157 signal (SIGCONT
, handle_sigcont
);
1158 signal (SIGTSTP
, handle_sigtstp
);
1159 signal (SIGTTOU
, handle_sigtstp
);
1167 struct sockaddr_un server
;
1170 * Open up an AF_UNIX socket in this person's home directory
1173 if ((s
= socket (AF_UNIX
, SOCK_STREAM
, 0)) < 0)
1175 message (TRUE
, "%s: socket: %s\n", progname
, strerror (errno
));
1176 return INVALID_SOCKET
;
1179 server
.sun_family
= AF_UNIX
;
1182 int sock_status
= 0;
1183 int default_sock
= !socket_name
;
1184 int saved_errno
= 0;
1185 char *server_name
= "server";
1188 if (socket_name
&& !index (socket_name
, '/') && !index (socket_name
, '\\'))
1189 { /* socket_name is a file name component. */
1190 server_name
= socket_name
;
1192 default_sock
= 1; /* Try both UIDs. */
1197 tmpdir
= egetenv ("TMPDIR");
1200 socket_name
= alloca (strlen (tmpdir
) + strlen (server_name
)
1202 sprintf (socket_name
, "%s/emacs%d/%s",
1203 tmpdir
, (int) geteuid (), server_name
);
1206 if (strlen (socket_name
) < sizeof (server
.sun_path
))
1207 strcpy (server
.sun_path
, socket_name
);
1210 message (TRUE
, "%s: socket-name %s too long\n",
1211 progname
, socket_name
);
1215 /* See if the socket exists, and if it's owned by us. */
1216 sock_status
= socket_status (server
.sun_path
);
1217 saved_errno
= errno
;
1218 if (sock_status
&& default_sock
)
1220 /* Failing that, see if LOGNAME or USER exist and differ from
1221 our euid. If so, look for a socket based on the UID
1222 associated with the name. This is reminiscent of the logic
1223 that init_editfns uses to set the global Vuser_full_name. */
1225 char *user_name
= (char *) egetenv ("LOGNAME");
1228 user_name
= (char *) egetenv ("USER");
1232 struct passwd
*pw
= getpwnam (user_name
);
1234 if (pw
&& (pw
->pw_uid
!= geteuid ()))
1236 /* We're running under su, apparently. */
1237 socket_name
= alloca (strlen (tmpdir
) + strlen (server_name
)
1239 sprintf (socket_name
, "%s/emacs%d/%s",
1240 tmpdir
, (int) pw
->pw_uid
, server_name
);
1242 if (strlen (socket_name
) < sizeof (server
.sun_path
))
1243 strcpy (server
.sun_path
, socket_name
);
1246 message (TRUE
, "%s: socket-name %s too long\n",
1247 progname
, socket_name
);
1248 exit (EXIT_FAILURE
);
1251 sock_status
= socket_status (server
.sun_path
);
1252 saved_errno
= errno
;
1255 errno
= saved_errno
;
1259 switch (sock_status
)
1262 /* There's a socket, but it isn't owned by us. This is OK if
1264 if (0 != geteuid ())
1266 message (TRUE
, "%s: Invalid socket owner\n", progname
);
1267 return INVALID_SOCKET
;
1273 if (saved_errno
== ENOENT
)
1275 "%s: can't find socket; have you started the server?\n\
1276 To start the server in Emacs, type \"M-x server-start\".\n",
1279 message (TRUE
, "%s: can't stat %s: %s\n",
1280 progname
, server
.sun_path
, strerror (saved_errno
));
1281 return INVALID_SOCKET
;
1285 if (connect (s
, (struct sockaddr
*) &server
, strlen (server
.sun_path
) + 2)
1288 message (TRUE
, "%s: connect: %s\n", progname
, strerror (errno
));
1289 return INVALID_SOCKET
;
1294 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1303 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1304 /* Explicit --socket-name argument. */
1307 s
= set_local_socket ();
1308 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
1310 message (TRUE
, "%s: error accessing socket \"%s\"\n",
1311 progname
, socket_name
);
1312 exit (EXIT_FAILURE
);
1316 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1318 server_file
= egetenv ("EMACS_SERVER_FILE");
1322 s
= set_tcp_socket ();
1323 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
1326 message (TRUE
, "%s: error accessing server file \"%s\"\n",
1327 progname
, server_file
);
1328 exit (EXIT_FAILURE
);
1331 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1332 /* Implicit local socket. */
1333 s
= set_local_socket ();
1334 if (s
!= INVALID_SOCKET
)
1338 /* Implicit server file. */
1339 server_file
= "server";
1340 s
= set_tcp_socket ();
1341 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
1344 /* No implicit or explicit socket, and no alternate editor. */
1345 message (TRUE
, "%s: No socket or alternate editor. Please use:\n\n"
1346 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1349 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1350 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1352 exit (EXIT_FAILURE
);
1356 FARPROC set_fg
; /* Pointer to AllowSetForegroundWindow. */
1357 FARPROC get_wc
; /* Pointer to RealGetWindowClassA. */
1360 w32_find_emacs_process (hWnd
, lParam
)
1367 /* Reject any window not of class "Emacs". */
1368 if (! get_wc (hWnd
, class, sizeof (class))
1369 || strcmp (class, "Emacs"))
1372 /* We only need the process id, not the thread id. */
1373 (void) GetWindowThreadProcessId (hWnd
, &pid
);
1375 /* Not the one we're looking for. */
1376 if (pid
!= (DWORD
) emacs_pid
) return TRUE
;
1378 /* OK, let's raise it. */
1381 /* Stop enumeration. */
1386 * Search for a window of class "Emacs" and owned by a process with
1387 * process id = emacs_pid. If found, allow it to grab the focus.
1394 /* It shouldn't happen when dealing with TCP sockets. */
1395 if (!emacs_pid
) return;
1397 if (!(hUser32
= LoadLibrary ("user32.dll"))) return;
1399 /* Modern Windows restrict which processes can set the foreground window.
1400 emacsclient can allow Emacs to grab the focus by calling the function
1401 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1402 NT) lack this function, so we have to check its availability. */
1403 if ((set_fg
= GetProcAddress (hUser32
, "AllowSetForegroundWindow"))
1404 && (get_wc
= GetProcAddress (hUser32
, "RealGetWindowClassA")))
1405 EnumWindows (w32_find_emacs_process
, (LPARAM
) 0);
1407 FreeLibrary (hUser32
);
1416 int i
, rl
, needlf
= 0;
1418 char string
[BUFSIZ
+1];
1423 /* Process options. */
1424 decode_options (argc
, argv
);
1426 if ((argc
- optind
< 1) && !eval
&& current_frame
)
1428 message (TRUE
, "%s: file name or argument required\n"
1429 "Try `%s --help' for more information\n",
1430 progname
, progname
);
1431 exit (EXIT_FAILURE
);
1434 if ((emacs_socket
= set_socket ()) == INVALID_SOCKET
)
1438 cwd
= get_current_dir_name ();
1441 /* getwd puts message in STRING if it fails. */
1442 message (TRUE
, "%s: %s\n", progname
,
1443 "Cannot get current working directory");
1451 /* Send over our environment and current directory. */
1454 extern char **environ
;
1456 for (i
= 0; environ
[i
]; i
++)
1458 char *name
= xstrdup (environ
[i
]);
1459 char *value
= strchr (name
, '=');
1460 send_to_emacs (emacs_socket
, "-env ");
1461 quote_argument (emacs_socket
, environ
[i
]);
1462 send_to_emacs (emacs_socket
, " ");
1464 send_to_emacs (emacs_socket
, "-dir ");
1465 quote_argument (emacs_socket
, cwd
);
1466 send_to_emacs (emacs_socket
, "/");
1467 send_to_emacs (emacs_socket
, " ");
1472 send_to_emacs (emacs_socket
, "-nowait ");
1475 send_to_emacs (emacs_socket
, "-current-frame ");
1479 send_to_emacs (emacs_socket
, "-display ");
1480 quote_argument (emacs_socket
, display
);
1481 send_to_emacs (emacs_socket
, " ");
1484 /* If using the current frame, send tty information to Emacs anyway.
1485 In daemon mode, Emacs may need to occupy this tty if no other
1486 frame is available. */
1487 if (tty
|| (current_frame
&& !eval
))
1489 char *tty_type
, *tty_name
;
1491 if (find_tty (&tty_type
, &tty_name
, !tty
))
1493 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1496 send_to_emacs (emacs_socket
, "-tty ");
1497 quote_argument (emacs_socket
, tty_name
);
1498 send_to_emacs (emacs_socket
, " ");
1499 quote_argument (emacs_socket
, tty_type
);
1500 send_to_emacs (emacs_socket
, " ");
1504 if (!current_frame
&& !tty
)
1505 send_to_emacs (emacs_socket
, "-window-system ");
1507 if ((argc
- optind
> 0))
1509 for (i
= optind
; i
< argc
; i
++)
1515 /* Don't prepend cwd or anything like that. */
1516 send_to_emacs (emacs_socket
, "-eval ");
1517 quote_argument (emacs_socket
, argv
[i
]);
1518 send_to_emacs (emacs_socket
, " ");
1522 if (*argv
[i
] == '+')
1524 char *p
= argv
[i
] + 1;
1525 while (isdigit ((unsigned char) *p
) || *p
== ':') p
++;
1528 send_to_emacs (emacs_socket
, "-position ");
1529 quote_argument (emacs_socket
, argv
[i
]);
1530 send_to_emacs (emacs_socket
, " ");
1536 else if (! file_name_absolute_p (argv
[i
]))
1540 /* Call GetFullPathName so filenames of the form X:Y, where X is
1541 a valid drive designator, are interpreted as drive:path, not
1542 file:stream, and treated as absolute.
1543 The user can still pass a file:stream if desired (for example,
1544 .\X:Y), but it is not very useful, as Emacs currently does a
1545 very bad job of dealing with NTFS streams. */
1547 char *filename
= (char *) xmalloc (MAX_PATH
);
1550 size
= GetFullPathName (argv
[i
], MAX_PATH
, filename
, NULL
);
1551 if (size
> 0 && size
< MAX_PATH
)
1561 send_to_emacs (emacs_socket
, "-file ");
1564 quote_argument (emacs_socket
, cwd
);
1565 send_to_emacs (emacs_socket
, "/");
1567 quote_argument (emacs_socket
, argv
[i
]);
1568 send_to_emacs (emacs_socket
, " ");
1573 /* Read expressions interactively. */
1574 while ((str
= fgets (string
, BUFSIZ
, stdin
)))
1576 send_to_emacs (emacs_socket
, "-eval ");
1577 quote_argument (emacs_socket
, str
);
1579 send_to_emacs (emacs_socket
, " ");
1582 send_to_emacs (emacs_socket
, "\n");
1584 /* Wait for an answer. */
1585 if (!eval
&& !tty
&& !nowait
)
1587 printf ("Waiting for Emacs...");
1593 /* Now, wait for an answer and print any messages. */
1594 while ((rl
= recv (emacs_socket
, string
, BUFSIZ
, 0)) > 0)
1599 p
= string
+ strlen (string
) - 1;
1600 while (p
> string
&& *p
== '\n')
1603 if (strprefix ("-emacs-pid ", string
))
1605 /* -emacs-pid PID: The process id of the Emacs process. */
1606 emacs_pid
= strtol (string
+ strlen ("-emacs-pid"), NULL
, 10);
1608 else if (strprefix ("-window-system-unsupported ", string
))
1610 /* -window-system-unsupported: Emacs was compiled without X
1611 support. Try again on the terminal. */
1616 else if (strprefix ("-print ", string
))
1618 /* -print STRING: Print STRING on the terminal. */
1619 str
= unquote_argument (string
+ strlen ("-print "));
1623 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1625 else if (strprefix ("-error ", string
))
1627 /* -error DESCRIPTION: Signal an error on the terminal. */
1628 str
= unquote_argument (string
+ strlen ("-error "));
1631 fprintf (stderr
, "*ERROR*: %s", str
);
1632 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1635 else if (strprefix ("-suspend ", string
))
1637 /* -suspend: Suspend this terminal, i.e., stop the process. */
1646 /* Unknown command. */
1649 printf ("*ERROR*: Unknown message: %s", string
);
1650 needlf
= string
[0] == '\0' ? needlf
: string
[strlen (string
) - 1] != '\n';
1659 CLOSE_SOCKET (emacs_socket
);
1660 return EXIT_SUCCESS
;
1663 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
1666 #ifndef HAVE_STRERROR
1671 extern char *sys_errlist
[];
1672 extern int sys_nerr
;
1674 if (errnum
>= 0 && errnum
< sys_nerr
)
1675 return sys_errlist
[errnum
];
1676 return (char *) "Unknown error";
1679 #endif /* ! HAVE_STRERROR */
1681 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
1682 (do not change this comment) */
1684 /* emacsclient.c ends here */