root/trunk/lib-src/emacsclient.c

Revision 4220, 27.0 kB (checked in by miyoshi, 8 months ago)

Sync up with Emacs22.2.

  • Property svn:eol-style set to native
Line 
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.
4
5 This file is part of GNU Emacs.
6
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)
10 any later version.
11
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.
16
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.  */
21
22
23 #define NO_SHORTNAMES
24
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
28
29 #ifdef WINDOWSNT
30
31 /* config.h defines these, which disables sockets altogether! */
32 # undef _WINSOCKAPI_
33 # undef _WINSOCK_H
34
35 # include <malloc.h>
36 # include <stdlib.h>
37 # include <windows.h>
38 # include <commctrl.h>
39
40 # define NO_SOCKETS_IN_FILE_SYSTEM
41
42 # define HSOCKET SOCKET
43 # define CLOSE_SOCKET closesocket
44 # define INITIALIZE() (initialize_sockets ())
45
46 #else /* !WINDOWSNT */
47
48 # include <sys/types.h>
49
50 # ifdef HAVE_INET_SOCKETS
51 #  include <netinet/in.h>
52 # endif
53
54 # define INVALID_SOCKET -1
55 # define HSOCKET int
56 # define CLOSE_SOCKET close
57 # define INITIALIZE()
58
59 #endif /* !WINDOWSNT */
60
61 #undef signal
62
63 #include <stdarg.h>
64 #include <ctype.h>
65 #include <stdio.h>
66 #include "getopt.h"
67 #ifdef HAVE_UNISTD_H
68 #include <unistd.h>
69 #endif
70
71 #ifdef VMS
72 # include "vms-pwd.h"
73 #else /* not VMS */
74 #ifdef WINDOWSNT
75 # include <io.h>
76 #else /* not WINDOWSNT */
77 # include <pwd.h>
78 #endif /* not WINDOWSNT */
79 #endif /* not VMS */
80
81 char *getenv (), *getwd ();
82 char *(getcwd) ();
83
84 #ifdef WINDOWSNT
85 char *w32_getenv ();
86 #define egetenv(VAR) w32_getenv(VAR)
87 #else
88 #define egetenv(VAR) getenv(VAR)
89 #endif
90
91 #ifndef VERSION
92 #define VERSION "unspecified"
93 #endif
94
95 #define SEND_STRING(data) (send_to_emacs (s, (data)))
96 #define SEND_QUOTED(data) (quote_file_name (s, (data)))
97
98 #ifndef EXIT_SUCCESS
99 #define EXIT_SUCCESS 0
100 #endif
101
102 #ifndef EXIT_FAILURE
103 #define EXIT_FAILURE 1
104 #endif
105
106 #ifndef FALSE
107 #define FALSE 0
108 #endif
109
110 #ifndef TRUE
111 #define TRUE 1
112 #endif
113
114 #ifndef NO_RETURN
115 #define NO_RETURN
116 #endif
117
118 /* Name used to invoke this program.  */
119 char *progname;
120
121 /* Nonzero means don't wait for a response from Emacs.  --no-wait.  */
122 int nowait = 0;
123
124 /* Nonzero means args are expressions to be evaluated.  --eval.  */
125 int eval = 0;
126
127 /* The display on which Emacs should work.  --display.  */
128 char *display = NULL;
129
130 /* If non-NULL, the name of an editor to fallback to if the server
131    is not running.  --alternate-editor.   */
132 const char *alternate_editor = NULL;
133
134 /* If non-NULL, the filename of the UNIX socket.  */
135 char *socket_name = NULL;
136
137 /* If non-NULL, the filename of the authentication file.  */
138 char *server_file = NULL;
139
140 /* PID of the Emacs server process.  */
141 int emacs_pid = 0;
142
143 void print_help_and_exit () NO_RETURN;
144
145 struct option longopts[] =
146 {
147   { "no-wait",  no_argument,       NULL, 'n' },
148   { "eval",     no_argument,       NULL, 'e' },
149   { "help",     no_argument,       NULL, 'H' },
150   { "version",  no_argument,       NULL, 'V' },
151   { "alternate-editor", required_argument, NULL, 'a' },
152 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
153   { "socket-name",      required_argument, NULL, 's' },
154 #endif
155   { "server-file",      required_argument, NULL, 'f' },
156   { "display",  required_argument, NULL, 'd' },
157   { 0, 0, 0, 0 }
158 };
159
160
161 /* Like malloc but get fatal error if memory is exhausted.  */
162
163 long *
164 xmalloc (size)
165      unsigned int size;
166 {
167   long *result = (long *) malloc (size);
168   if (result == NULL)
169     {
170       perror ("malloc");
171       exit (EXIT_FAILURE);
172     }
173   return result;
174 }
175
176 /* Message functions. */
177
178 #ifdef WINDOWSNT
179
180 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
181
182 /* Retrieve an environment variable from the Emacs subkeys of the registry.
183    Return NULL if the variable was not found, or it was empty.
184    This code is based on w32_get_resource (w32.c).  */
185 char *
186 w32_get_resource (predefined, key, type)
187      HKEY predefined;
188      char *key;
189      LPDWORD type;
190 {
191   HKEY hrootkey = NULL;
192   char *result = NULL;
193   DWORD cbData;
194
195   if (RegOpenKeyEx (predefined, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
196     {
197       if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS)
198         {
199           result = (char *) xmalloc (cbData);
200
201           if ((RegQueryValueEx (hrootkey, key, NULL, type, result, &cbData) != ERROR_SUCCESS) ||
202               (*result == 0))
203             {
204               free (result);
205               result = NULL;
206             }
207         }
208
209       RegCloseKey (hrootkey);
210     }
211
212   return result;
213 }
214
215 /*
216   getenv wrapper for Windows
217
218   This is needed to duplicate Emacs's behavior, which is to look for enviroment
219   variables in the registry if they don't appear in the environment.
220 */
221 char *
222 w32_getenv (envvar)
223      char *envvar;
224 {
225   char *value;
226   DWORD dwType;
227
228   if (value = getenv (envvar))
229     /* Found in the environment.  */
230     return value;
231
232   if (! (value = w32_get_resource (HKEY_CURRENT_USER, envvar, &dwType)) &&
233       ! (value = w32_get_resource (HKEY_LOCAL_MACHINE, envvar, &dwType)))
234     /* Not found in the registry.  */
235     return NULL;
236
237   if (dwType == REG_SZ)
238     /* Registry; no need to expand.  */
239     return value;
240
241   if (dwType == REG_EXPAND_SZ)
242     {
243       DWORD size;
244
245       if (size = ExpandEnvironmentStrings (value, NULL, 0))
246         {
247           char *buffer = (char *) xmalloc (size);
248           if (ExpandEnvironmentStrings (value, buffer, size))
249             {
250               /* Found and expanded.  */
251               free (value);
252               return buffer;
253             }
254
255           /* Error expanding.  */
256           free (buffer);
257         }
258     }
259
260   /* Not the right type, or not correctly expanded.  */
261   free (value);
262   return NULL;
263 }
264
265 int
266 w32_window_app ()
267 {
268   static int window_app = -1;
269   char szTitle[MAX_PATH];
270
271   if (window_app < 0)
272     {
273       /* Checking for STDOUT does not work; it's a valid handle also in
274          nonconsole apps.  Testing for the console title seems to work. */
275       window_app = (GetConsoleTitleA (szTitle, MAX_PATH) == 0);
276       if (window_app)
277         InitCommonControls();
278     }
279
280   return window_app;
281 }
282 #endif
283
284 void
285 message (int is_error, char *message, ...)
286 {
287   char msg [2048];
288   va_list args;
289
290   va_start (args, message);
291   vsprintf (msg, message, args);
292   va_end (args);
293
294 #ifdef WINDOWSNT
295   if (w32_window_app ())
296     {
297       if (is_error)
298         MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
299       else
300         MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
301     }
302   else
303 #endif
304     {
305       FILE *f = is_error ? stderr : stdout;
306
307       fputs (msg, f);
308       fflush (f);
309     }
310 }
311
312 /* Decode the options from argv and argc.
313    The global variable `optind' will say how many arguments we used up.  */
314
315 void
316 decode_options (argc, argv)
317      int argc;
318      char **argv;
319 {
320   alternate_editor = egetenv ("ALTERNATE_EDITOR");
321
322   while (1)
323     {
324       int opt = getopt_long (argc, argv,
325 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
326                              "VHnea:s:f:d:",
327 #else
328                              "VHnea:f:d:",
329 #endif
330                              longopts, 0);
331
332       if (opt == EOF)
333         break;
334
335       switch (opt)
336         {
337         case 0:
338           /* If getopt returns 0, then it has already processed a
339              long-named option.  We should do nothing.  */
340           break;
341
342         case 'a':
343           alternate_editor = optarg;
344           break;
345
346 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
347         case 's':
348           socket_name = optarg;
349           break;
350 #endif
351
352         case 'f':
353           server_file = optarg;
354           break;
355
356         case 'd':
357           display = optarg;
358           break;
359
360         case 'n':
361           nowait = 1;
362           break;
363
364         case 'e':
365           eval = 1;
366           break;
367
368         case 'V':
369           message (FALSE, "emacsclient %s\n", VERSION);
370           exit (EXIT_SUCCESS);
371           break;
372
373         case 'H':
374           print_help_and_exit ();
375           break;
376
377         default:
378           message (TRUE, "Try `%s --help' for more information\n", progname);
379           exit (EXIT_FAILURE);
380           break;
381         }
382     }
383 }
384
385 void
386 print_help_and_exit ()
387 {
388   message (FALSE,
389           "Usage: %s [OPTIONS] FILE...\n\
390 Tell the Emacs server to visit the specified files.\n\
391 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
392 \n\
393 The following OPTIONS are accepted:\n\
394 \n\
395 -V, --version           Just print version info and return\n\
396 -H, --help              Print this usage information message\n\
397 -e, --eval              Evaluate FILE arguments as Lisp expressions\n\
398 -n, --no-wait           Don't wait for the server to return\n\
399 -d, --display=DISPLAY   Visit the file in the given display\n"
400 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
401 "-s, --socket-name=FILENAME\n\
402                         Set filename of the UNIX socket for communication\n"
403 #endif
404 "-f, --server-file=FILENAME\n\
405                         Set filename of the TCP authentication file\n\
406 -a, --alternate-editor=EDITOR\n\
407                         Editor to fallback to if server is not running\n\
408 \n\
409 Report bugs to bug-gnu-emacs@gnu.org.\n", progname);
410   exit (EXIT_SUCCESS);
411 }
412
413
414 #ifdef WINDOWSNT
415
416 /*
417   execvp wrapper for Windows. Quotes arguments with embedded spaces.
418
419   This is necessary due to the broken implementation of exec* routines in
420   the Microsoft libraries: they concatenate the arguments together without
421   quoting special characters, and pass the result to CreateProcess, with
422   predictably bad results.  By contrast, Posix execvp passes the arguments
423   directly into the argv array of the child process.
424 */
425 int
426 w32_execvp (path, argv)
427      char *path;
428      char **argv;
429 {
430   int i;
431
432   /* Required to allow a .BAT script as alternate editor.  */
433   argv[0] = (char *) alternate_editor;
434
435   for (i = 0; argv[i]; i++)
436     if (strchr (argv[i], ' '))
437       {
438         char *quoted = alloca (strlen (argv[i]) + 3);
439         sprintf (quoted, "\"%s\"", argv[i]);
440         argv[i] = quoted;
441       }
442
443   return execvp (path, argv);
444 }
445
446 #undef execvp
447 #define execvp w32_execvp
448
449 #endif /* WINDOWSNT */
450
451 /*
452   Try to run a different command, or --if no alternate editor is
453   defined-- exit with an errorcode.
454 */
455 void
456 fail (argc, argv)
457      int argc;
458      char **argv;
459 {
460   if (alternate_editor)
461     {
462       int i = optind - 1;
463
464       execvp (alternate_editor, argv + i);
465       message (TRUE, "%s: error executing alternate editor \"%s\"\n",
466                progname, alternate_editor);
467     }
468   exit (EXIT_FAILURE);
469 }
470
471
472 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
473
474 int
475 main (argc, argv)
476      int argc;
477      char **argv;
478 {
479   message (TRUE, "%s: Sorry, the Emacs server is supported only\non systems with Berkely sockets.\n",
480            argv[0]);
481
482   fail (argc, argv);
483 }
484
485 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
486
487 #ifdef WINDOWSNT
488 # include <winsock2.h>
489 #else
490 # include <sys/types.h>
491 # include <sys/socket.h>
492 # include <sys/un.h>
493 # include <sys/stat.h>
494 # include <errno.h>
495 #endif
496
497 #define AUTH_KEY_LENGTH      64
498 #define SEND_BUFFER_SIZE   4096
499
500 extern char *strerror ();
501 extern int errno;
502
503 /* Buffer to accumulate data to send in TCP connections.  */
504 char send_buffer[SEND_BUFFER_SIZE + 1];
505 int sblen = 0;  /* Fill pointer for the send buffer.  */
506
507 /* On Windows, the socket library was historically separate from the standard
508    C library, so errors are handled differently.  */
509 void
510 sock_err_message (function_name)
511      char *function_name;
512 {
513 #ifdef WINDOWSNT
514   char* msg = NULL;
515
516   FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
517                  | FORMAT_MESSAGE_ALLOCATE_BUFFER
518                  | FORMAT_MESSAGE_ARGUMENT_ARRAY,
519                  NULL, WSAGetLastError (), 0, (LPTSTR)&msg, 0, NULL);
520
521   message (TRUE, "%s: %s: %s\n", progname, function_name, msg);
522
523   LocalFree (msg);
524 #else
525   message (TRUE, "%s: %s: %s\n", progname, function_name, strerror (errno));
526 #endif
527 }
528
529
530 /* Let's send the data to Emacs when either
531    - the data ends in "\n", or
532    - the buffer is full (but this shouldn't happen)
533    Otherwise, we just accumulate it.  */
534 void
535 send_to_emacs (s, data)
536      HSOCKET s;
537      char *data;
538 {
539   while (data)
540     {
541       int dlen = strlen (data);
542       if (dlen + sblen >= SEND_BUFFER_SIZE)
543         {
544           int part = SEND_BUFFER_SIZE - sblen;
545           strncpy (&send_buffer[sblen], data, part);
546           data += part;
547           sblen = SEND_BUFFER_SIZE;
548         }
549       else if (dlen)
550         {
551           strcpy (&send_buffer[sblen], data);
552           data = NULL;
553           sblen += dlen;
554         }
555       else
556         break;
557
558       if (sblen == SEND_BUFFER_SIZE
559           || (sblen > 0 && send_buffer[sblen-1] == '\n'))
560         {
561           int sent = send (s, send_buffer, sblen, 0);
562           if (sent != sblen)
563             strcpy (send_buffer, &send_buffer[sent]);
564           sblen -= sent;
565         }
566     }
567 }
568
569 /* In NAME, insert a & before each &, each space, each newline, and
570    any initial -.  Change spaces to underscores, too, so that the
571    return value never contains a space.  */
572 void
573 quote_file_name (s, name)
574      HSOCKET s;
575      char *name;
576 {
577   char *copy = (char *) xmalloc (strlen (name) * 2 + 1);
578   char *p, *q;
579
580   p = name;
581   q = copy;
582   while (*p)
583     {
584       if (*p == ' ')
585         {
586           *q++ = '&';
587           *q++ = '_';
588           p++;
589         }
590       else if (*p == '\n')
591         {
592           *q++ = '&';
593           *q++ = 'n';
594           p++;
595         }
596       else
597         {
598           if (*p == '&' || (*p == '-' && p == name))
599             *q++ = '&';
600           *q++ = *p++;
601         }
602     }
603   *q++ = 0;
604
605   SEND_STRING (copy);
606
607   free (copy);
608 }
609
610 int
611 file_name_absolute_p (filename)
612      const unsigned char *filename;
613 {
614   /* Sanity check, it shouldn't happen.  */
615   if (! filename) return FALSE;
616
617   /* /xxx is always an absolute path.  */
618   if (filename[0] == '/') return TRUE;
619
620   /* Empty filenames (which shouldn't happen) are relative.  */
621   if (filename[0] == '\0') return FALSE;
622
623 #ifdef WINDOWSNT
624   /* X:\xxx is always absolute.  */
625   if (isalpha (filename[0])
626       && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
627     return TRUE;
628
629   /* Both \xxx and \\xxx\yyy are absolute.  */
630   if (filename[0] == '\\') return TRUE;
631
632   /*
633     FIXME:  There's a corner case not dealt with, "x:y", where:
634
635     1) x is a valid drive designation (usually a letter in the A-Z range)
636        and y is a path, relative to the current directory on drive x.  This
637        is absolute, *after* fixing the y part to include the current
638        directory in x.
639
640     2) x is a relative file name, and y is an NTFS stream name.  This is a
641        correct relative path, but it is very unusual.
642
643     The trouble is that first case items are also valid examples of the
644     second case, i.e., "c:test" can be understood as drive:path or as
645     file:stream.
646
647     The "right" fix would involve checking whether
648     - the current drive/partition is NTFS,
649     - x is a valid (and accesible) drive designator,
650     - x:y already exists as a file:stream in the current directory,
651     - y already exists on the current directory of drive x,
652     - the auspices are favorable,
653     and then taking an "informed decision" based on the above.
654
655     Whatever the result, Emacs currently does a very bad job of dealing
656     with NTFS file:streams: it cannot visit them, and the only way to
657     create one is by setting `buffer-file-name' to point to it (either
658     manually or with emacsclient). So perhaps resorting to 1) and ignoring
659     2) for now is the right thing to do.
660
661     Anyway, something to decide After the Release.
662   */
663 #endif
664
665   return FALSE;
666 }
667
668 #ifdef WINDOWSNT
669 /* Wrapper to make WSACleanup a cdecl, as required by atexit.  */
670 void
671 __cdecl close_winsock ()
672 {
673   WSACleanup ();
674 }
675
676 /* Initialize the WinSock2 library.  */
677 void
678 initialize_sockets ()
679 {
680   WSADATA wsaData;
681
682   if (WSAStartup (MAKEWORD (2, 0), &wsaData))
683     {
684       message (TRUE, "%s: error initializing WinSock2", progname);
685       exit (EXIT_FAILURE);
686     }
687
688   atexit (close_winsock);
689 }
690 #endif /* WINDOWSNT */
691
692 /*
693  * Read the information needed to set up a TCP comm channel with
694  * the Emacs server: host, port, pid and authentication string.
695  */
696 int
697 get_server_config (server, authentication)
698      struct sockaddr_in *server;
699      char *authentication;
700 {
701   char dotted[32];
702   char *port;
703   char *pid;
704   FILE *config = NULL;
705
706   if (file_name_absolute_p (server_file))
707     config = fopen (server_file, "rb");
708   else
709     {
710       char *home = egetenv ("HOME");
711
712       if (home)
713         {
714           char *path = alloca (32 + strlen (home