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 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 */
81 char *getenv (), *getwd ();
85 #define VERSION "unspecified"
88 #define SEND_STRING(data) (send_to_emacs (s, (data)))
89 #define SEND_QUOTED(data) (quote_file_name (s, (data)))
92 #define EXIT_SUCCESS 0
96 #define EXIT_FAILURE 1
111 /* Name used to invoke this program. */
114 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
117 /* Nonzero means args are expressions to be evaluated. --eval. */
120 /* The display on which Emacs should work. --display. */
121 char *display
= NULL
;
123 /* If non-NULL, the name of an editor to fallback to if the server
124 is not running. --alternate-editor. */
125 const char *alternate_editor
= NULL
;
127 /* If non-NULL, the filename of the UNIX socket. */
128 char *socket_name
= NULL
;
130 /* If non-NULL, the filename of the authentication file. */
131 char *server_file
= NULL
;
133 /* PID of the Emacs server process. */
136 void print_help_and_exit () NO_RETURN
;
138 struct option longopts
[] =
140 { "no-wait", no_argument
, NULL
, 'n' },
141 { "eval", no_argument
, NULL
, 'e' },
142 { "help", no_argument
, NULL
, 'H' },
143 { "version", no_argument
, NULL
, 'V' },
144 { "alternate-editor", required_argument
, NULL
, 'a' },
145 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
146 { "socket-name", required_argument
, NULL
, 's' },
148 { "server-file", required_argument
, NULL
, 'f' },
149 { "display", required_argument
, NULL
, 'd' },
153 /* Message functions. */
159 static int window_app
= -1;
160 char szTitle
[MAX_PATH
];
164 /* Checking for STDOUT does not work; it's a valid handle also in
165 nonconsole apps. Testing for the console title seems to work. */
166 window_app
= (GetConsoleTitleA (szTitle
, MAX_PATH
) == 0);
168 InitCommonControls();
176 message (int is_error
, char *message
, ...)
181 va_start (args
, message
);
182 vsprintf (msg
, message
, args
);
186 if (w32_window_app ())
189 MessageBox (NULL
, msg
, "Emacsclient ERROR", MB_ICONERROR
);
191 MessageBox (NULL
, msg
, "Emacsclient", MB_ICONINFORMATION
);
196 FILE *f
= is_error
? stderr
: stdout
;
203 /* Decode the options from argv and argc.
204 The global variable `optind' will say how many arguments we used up. */
207 decode_options (argc
, argv
)
211 alternate_editor
= getenv ("ALTERNATE_EDITOR");
215 int opt
= getopt_long (argc
, argv
,
216 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
229 /* If getopt returns 0, then it has already processed a
230 long-named option. We should do nothing. */
234 alternate_editor
= optarg
;
237 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
239 socket_name
= optarg
;
244 server_file
= optarg
;
260 message (FALSE
, "emacsclient %s\n", VERSION
);
265 print_help_and_exit ();
269 message (TRUE
, "Try `%s --help' for more information\n", progname
);
277 print_help_and_exit ()
280 "Usage: %s [OPTIONS] FILE...\n\
281 Tell the Emacs server to visit the specified files.\n\
282 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
284 The following OPTIONS are accepted:\n\
286 -V, --version Just print version info and return\n\
287 -H, --help Print this usage information message\n\
288 -e, --eval Evaluate FILE arguments as Lisp expressions\n\
289 -n, --no-wait Don't wait for the server to return\n\
290 -d, --display=DISPLAY Visit the file in the given display\n"
291 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
292 "-s, --socket-name=FILENAME\n\
293 Set filename of the UNIX socket for communication\n"
295 "-f, --server-file=FILENAME\n\
296 Set filename of the TCP authentication file\n\
297 -a, --alternate-editor=EDITOR\n\
298 Editor to fallback to if server is not running\n\
300 Report bugs to bug-gnu-emacs@gnu.org.\n", progname
);
308 execvp wrapper for Windows. Quotes arguments with embedded spaces.
310 This is necessary due to the broken implementation of exec* routines in
311 the Microsoft libraries: they concatenate the arguments together without
312 quoting special characters, and pass the result to CreateProcess, with
313 predictably bad results. By contrast, Posix execvp passes the arguments
314 directly into the argv array of the child process.
317 w32_execvp (path
, argv
)
323 /* Required to allow a .BAT script as alternate editor. */
324 argv
[0] = (char *) alternate_editor
;
326 for (i
= 0; argv
[i
]; i
++)
327 if (strchr (argv
[i
], ' '))
329 char *quoted
= alloca (strlen (argv
[i
]) + 3);
330 sprintf (quoted
, "\"%s\"", argv
[i
]);
334 return execvp (path
, argv
);
338 #define execvp w32_execvp
340 #endif /* WINDOWSNT */
343 Try to run a different command, or --if no alternate editor is
344 defined-- exit with an errorcode.
351 if (alternate_editor
)
355 execvp (alternate_editor
, argv
+ i
);
356 message (TRUE
, "%s: error executing alternate editor \"%s\"\n",
357 progname
, alternate_editor
);
363 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
370 message (TRUE
, "%s: Sorry, the Emacs server is supported only\non systems with Berkely sockets.\n",
376 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
379 # include <winsock2.h>
381 # include <sys/types.h>
382 # include <sys/socket.h>
384 # include <sys/stat.h>
388 #define AUTH_KEY_LENGTH 64
389 #define SEND_BUFFER_SIZE 4096
391 extern char *strerror ();
394 /* Buffer to accumulate data to send in TCP connections. */
395 char send_buffer
[SEND_BUFFER_SIZE
+ 1];
396 int sblen
= 0; /* Fill pointer for the send buffer. */
398 /* Let's send the data to Emacs when either
399 - the data ends in "\n", or
400 - the buffer is full (but this shouldn't happen)
401 Otherwise, we just accumulate it. */
403 send_to_emacs (s
, data
)
409 int dlen
= strlen (data
);
410 if (dlen
+ sblen
>= SEND_BUFFER_SIZE
)
412 int part
= SEND_BUFFER_SIZE
- sblen
;
413 strncpy (&send_buffer
[sblen
], data
, part
);
415 sblen
= SEND_BUFFER_SIZE
;
419 strcpy (&send_buffer
[sblen
], data
);
426 if (sblen
== SEND_BUFFER_SIZE
427 || (sblen
> 0 && send_buffer
[sblen
-1] == '\n'))
429 int sent
= send (s
, send_buffer
, sblen
, 0);
431 strcpy (send_buffer
, &send_buffer
[sent
]);
437 /* In NAME, insert a & before each &, each space, each newline, and
438 any initial -. Change spaces to underscores, too, so that the
439 return value never contains a space. */
441 quote_file_name (s
, name
)
445 char *copy
= (char *) malloc (strlen (name
) * 2 + 1);
466 if (*p
== '&' || (*p
== '-' && p
== name
))
479 file_name_absolute_p (filename
)
480 const unsigned char *filename
;
482 /* Sanity check, it shouldn't happen. */
483 if (! filename
) return FALSE
;
485 /* /xxx is always an absolute path. */
486 if (filename
[0] == '/') return TRUE
;
488 /* Empty filenames (which shouldn't happen) are relative. */
489 if (filename
[0] == '\0') return FALSE
;
492 /* X:\xxx is always absolute. */
493 if (isalpha (filename
[0])
494 && filename
[1] == ':' && (filename
[2] == '\\' || filename
[2] == '/'))
497 /* Both \xxx and \\xxx\yyy are absolute. */
498 if (filename
[0] == '\\') return TRUE
;
501 FIXME: There's a corner case not dealt with, "x:y", where:
503 1) x is a valid drive designation (usually a letter in the A-Z range)
504 and y is a path, relative to the current directory on drive x. This
505 is absolute, *after* fixing the y part to include the current
508 2) x is a relative file name, and y is an NTFS stream name. This is a
509 correct relative path, but it is very unusual.
511 The trouble is that first case items are also valid examples of the
512 second case, i.e., "c:test" can be understood as drive:path or as
515 The "right" fix would involve checking whether
516 - the current drive/partition is NTFS,
517 - x is a valid (and accesible) drive designator,
518 - x:y already exists as a file:stream in the current directory,
519 - y already exists on the current directory of drive x,
520 - the auspices are favorable,
521 and then taking an "informed decision" based on the above.
523 Whatever the result, Emacs currently does a very bad job of dealing
524 with NTFS file:streams: it cannot visit them, and the only way to
525 create one is by setting `buffer-file-name' to point to it (either
526 manually or with emacsclient). So perhaps resorting to 1) and ignoring
527 2) for now is the right thing to do.
529 Anyway, something to decide After the Release.
537 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
539 __cdecl
close_winsock ()
544 /* Initialize the WinSock2 library. */
546 initialize_sockets ()
550 if (WSAStartup (MAKEWORD (2, 0), &wsaData
))
552 message (TRUE
, "%s: error initializing WinSock2", progname
);
556 atexit (close_winsock
);
558 #endif /* WINDOWSNT */
561 * Read the information needed to set up a TCP comm channel with
562 * the Emacs server: host, port, pid and authentication string.
565 get_server_config (server
, authentication
)
566 struct sockaddr_in
*server
;
567 char *authentication
;
574 if (file_name_absolute_p (server_file
))
575 config
= fopen (server_file
, "rb");
578 char *home
= getenv ("HOME");
582 char *path
= alloca (32 + strlen (home
) + strlen (server_file
));
583 sprintf (path
, "%s/.emacs.d/server/%s", home
, server_file
);
584 config
= fopen (path
, "rb");
587 if (!config
&& (home
= getenv ("APPDATA")))
589 char *path
= alloca (32 + strlen (home
) + strlen (server_file
));
590 sprintf (path
, "%s/.emacs.d/server/%s", home
, server_file
);
591 config
= fopen (path
, "rb");
599 if (fgets (dotted
, sizeof dotted
, config
)
600 && (port
= strchr (dotted
, ':'))
601 && (pid
= strchr (port
, ' ')))
608 message (TRUE
, "%s: invalid configuration info", progname
);
612 server
->sin_family
= AF_INET
;
613 server
->sin_addr
.s_addr
= inet_addr (dotted
);
614 server
->sin_port
= htons (atoi (port
));
616 if (! fread (authentication
, AUTH_KEY_LENGTH
, 1, config
))
618 message (TRUE
, "%s: cannot read authentication info", progname
);
624 emacs_pid
= atoi (pid
);
633 struct sockaddr_in server
;
634 struct linger l_arg
= {1, 1};
635 char auth_string
[AUTH_KEY_LENGTH
+ 1];
637 if (! get_server_config (&server
, auth_string
))
638 return INVALID_SOCKET
;
640 if (server
.sin_addr
.s_addr
!= inet_addr ("127.0.0.1"))
641 message (FALSE
, "%s: connected to remote socket at %s\n",
642 progname
, inet_ntoa (server
.sin_addr
));
645 * Open up an AF_INET socket
647 if ((s
= socket (AF_INET
, SOCK_STREAM
, IPPROTO_TCP
)) < 0)
649 message (TRUE
, "%s: socket: %s\n", progname
, strerror (errno
));
650 return INVALID_SOCKET
;
656 if (connect (s
, (struct sockaddr
*) &server
, sizeof server
) < 0)
658 message (TRUE
, "%s: connect: %s\n", progname
, strerror (errno
));
659 return INVALID_SOCKET
;
662 setsockopt (s
, SOL_SOCKET
, SO_LINGER
, (char *) &l_arg
, sizeof l_arg
);
665 * Send the authentication
667 auth_string
[AUTH_KEY_LENGTH
] = '\0';
669 SEND_STRING ("-auth ");
670 SEND_STRING (auth_string
);
676 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
678 /* Three possibilities:
679 2 - can't be `stat'ed (sets errno)
680 1 - isn't owned by us
681 0 - success: none of the above */
684 socket_status (socket_name
)
689 if (stat (socket_name
, &statbfr
) == -1)
692 if (statbfr
.st_uid
!= geteuid ())
702 struct sockaddr_un server
;
705 * Open up an AF_UNIX socket in this person's home directory
708 if ((s
= socket (AF_UNIX
, SOCK_STREAM
, 0)) < 0)
710 message (TRUE
, "%s: socket: %s\n", progname
, strerror (errno
));
711 return INVALID_SOCKET
;
714 server
.sun_family
= AF_UNIX
;
718 int default_sock
= !socket_name
;
720 char *server_name
= "server";
722 if (socket_name
&& !index (socket_name
, '/') && !index (socket_name
, '\\'))
723 { /* socket_name is a file name component. */
724 server_name
= socket_name
;
726 default_sock
= 1; /* Try both UIDs. */
731 socket_name
= alloca (100 + strlen (server_name
));
732 sprintf (socket_name
, "/tmp/emacs%d/%s",
733 (int) geteuid (), server_name
);
736 if (strlen (socket_name
) < sizeof (server
.sun_path
))
737 strcpy (server
.sun_path
, socket_name
);
740 message (TRUE
, "%s: socket-name %s too long",
741 progname
, socket_name
);
745 /* See if the socket exists, and if it's owned by us. */
746 sock_status
= socket_status (server
.sun_path
);
748 if (sock_status
&& default_sock
)
750 /* Failing that, see if LOGNAME or USER exist and differ from
751 our euid. If so, look for a socket based on the UID
752 associated with the name. This is reminiscent of the logic
753 that init_editfns uses to set the global Vuser_full_name. */
755 char *user_name
= (char *) getenv ("LOGNAME");
758 user_name
= (char *) getenv ("USER");
762 struct passwd
*pw
= getpwnam (user_name
);
764 if (pw
&& (pw
->pw_uid
!= geteuid ()))
766 /* We're running under su, apparently. */
767 socket_name
= alloca (100 + strlen (server_name
));
768 sprintf (socket_name
, "/tmp/emacs%d/%s",
769 (int) pw
->pw_uid
, server_name
);
771 if (strlen (socket_name
) < sizeof (server
.sun_path
))
772 strcpy (server
.sun_path
, socket_name
);
775 message (TRUE
, "%s: socket-name %s too long",
776 progname
, socket_name
);
780 sock_status
= socket_status (server
.sun_path
);
791 /* There's a socket, but it isn't owned by us. This is OK if
795 message (TRUE
, "%s: Invalid socket owner\n", progname
);
796 return INVALID_SOCKET
;
802 if (saved_errno
== ENOENT
)
804 "%s: can't find socket; have you started the server?\n\
805 To start the server in Emacs, type \"M-x server-start\".\n",
808 message (TRUE
, "%s: can't stat %s: %s\n",
809 progname
, server
.sun_path
, strerror (saved_errno
));
810 return INVALID_SOCKET
;
814 if (connect (s
, (struct sockaddr
*) &server
, strlen (server
.sun_path
) + 2)
817 message (TRUE
, "%s: connect: %s\n", progname
, strerror (errno
));
818 return INVALID_SOCKET
;
823 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
832 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
833 /* Explicit --socket-name argument. */
836 s
= set_local_socket ();
837 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
840 message (TRUE
, "%s: error accessing socket \"%s\"",
841 progname
, socket_name
);
846 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
848 server_file
= getenv ("EMACS_SERVER_FILE");
852 s
= set_tcp_socket ();
853 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
856 message (TRUE
, "%s: error accessing server file \"%s\"",
857 progname
, server_file
);
861 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
862 /* Implicit local socket. */
863 s
= set_local_socket ();
864 if (s
!= INVALID_SOCKET
)
868 /* Implicit server file. */
869 server_file
= "server";
870 s
= set_tcp_socket ();
871 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
874 /* No implicit or explicit socket, and no alternate editor. */
875 message (TRUE
, "%s: No socket or alternate editor. Please use:\n\n"
876 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
879 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
880 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
886 FARPROC set_fg
; /* Pointer to AllowSetForegroundWindow. */
887 FARPROC get_wc
; /* Pointer to RealGetWindowClassA. */
890 w32_find_emacs_process (hWnd
, lParam
)
897 /* Reject any window not of class "Emacs". */
898 if (! get_wc (hWnd
, class, sizeof (class))
899 || strcmp (class, "Emacs"))
902 /* We only need the process id, not the thread id. */
903 (void) GetWindowThreadProcessId (hWnd
, &pid
);
905 /* Not the one we're looking for. */
906 if (pid
!= (DWORD
) emacs_pid
) return TRUE
;
908 /* OK, let's raise it. */
911 /* Stop enumeration. */
916 * Search for a window of class "Emacs" and owned by a process with
917 * process id = emacs_pid. If found, allow it to grab the focus.
924 /* It shouldn't happen when dealing with TCP sockets. */
925 if (!emacs_pid
) return;
927 if (!(hUser32
= LoadLibrary ("user32.dll"))) return;
929 /* Modern Windows restrict which processes can set the foreground window.
930 emacsclient can allow Emacs to grab the focus by calling the function
931 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
932 NT) lack this function, so we have to check its availability. */
933 if ((set_fg
= GetProcAddress (hUser32
, "AllowSetForegroundWindow"))
934 && (get_wc
= GetProcAddress (hUser32
, "RealGetWindowClassA")))
935 EnumWindows (w32_find_emacs_process
, (LPARAM
) 0);
937 FreeLibrary (hUser32
);
947 int i
, rl
, needlf
= 0;
949 char string
[BUFSIZ
+1];
953 /* Process options. */
954 decode_options (argc
, argv
);
956 if ((argc
- optind
< 1) && !eval
)
958 message (TRUE
, "%s: file name or argument required\nTry `%s --help' for more information\n",
963 if ((s
= set_socket ()) == INVALID_SOCKET
)
967 cwd
= getcwd (string
, sizeof string
);
969 cwd
= getwd (string
);
973 /* getwd puts message in STRING if it fails. */
974 message (TRUE
, "%s: %s (%s)\n", progname
,
976 "Cannot get current working directory",
989 SEND_STRING ("-nowait ");
992 SEND_STRING ("-eval ");
996 SEND_STRING ("-display ");
997 SEND_QUOTED (display
);
1001 if ((argc
- optind
> 0))
1003 for (i
= optind
; i
< argc
; i
++)
1006 ; /* Don't prepend any cwd or anything like that. */
1007 else if (*argv
[i
] == '+')
1009 char *p
= argv
[i
] + 1;
1010 while (isdigit ((unsigned char) *p
) || *p
== ':') p
++;
1017 else if (! file_name_absolute_p (argv
[i
]))
1023 SEND_QUOTED (argv
[i
]);
1029 while (fgets (string
, BUFSIZ
, stdin
))
1031 SEND_QUOTED (string
);
1038 /* Maybe wait for an answer. */
1043 printf ("Waiting for Emacs...");
1048 /* Now, wait for an answer and print any messages. */
1049 while ((rl
= recv (s
, string
, BUFSIZ
, 0)) > 0)
1054 printf ("%s", string
);
1055 needlf
= string
[0] == '\0' ? needlf
: string
[strlen (string
) - 1] != '\n';
1064 return EXIT_SUCCESS
;
1067 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
1069 #ifndef HAVE_STRERROR
1074 extern char *sys_errlist
[];
1075 extern int sys_nerr
;
1077 if (errnum
>= 0 && errnum
< sys_nerr
)
1078 return sys_errlist
[errnum
];
1079 return (char *) "Unknown error";
1082 #endif /* ! HAVE_STRERROR */
1084 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
1085 (do not change this comment) */
1087 /* emacsclient.c ends here */