* mule.texi (Coding Systems): Put a few more of the coding systems into the index.
[bpt/emacs.git] / lib-src / emacsclient.c
1 /* Client process that communicates with GNU Emacs acting as server.
2 Copyright (C) 1986-1987, 1994, 1999-2011 Free Software Foundation, Inc.
3
4 This file is part of GNU Emacs.
5
6 GNU Emacs is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
18
19
20 #include <config.h>
21
22 #ifdef WINDOWSNT
23
24 /* config.h defines these, which disables sockets altogether! */
25 # undef _WINSOCKAPI_
26 # undef _WINSOCK_H
27
28 # include <malloc.h>
29 # include <stdlib.h>
30 # include <windows.h>
31 # include <commctrl.h>
32 # include <io.h>
33 # include <winsock2.h>
34
35 # define NO_SOCKETS_IN_FILE_SYSTEM
36
37 # define HSOCKET SOCKET
38 # define CLOSE_SOCKET closesocket
39 # define INITIALIZE() (initialize_sockets ())
40
41 char *w32_getenv (char *);
42 #define egetenv(VAR) w32_getenv(VAR)
43
44 #else /* !WINDOWSNT */
45
46 # include "syswait.h"
47
48 # ifdef HAVE_INET_SOCKETS
49 # include <netinet/in.h>
50 # ifdef HAVE_SOCKETS
51 # include <sys/types.h>
52 # include <sys/socket.h>
53 # include <sys/un.h>
54 # endif /* HAVE_SOCKETS */
55 # endif
56 # include <arpa/inet.h>
57
58 # define INVALID_SOCKET -1
59 # define HSOCKET int
60 # define CLOSE_SOCKET close
61 # define INITIALIZE()
62
63 # ifndef WCONTINUED
64 # define WCONTINUED 8
65 # endif
66
67 #define egetenv(VAR) getenv(VAR)
68
69 #endif /* !WINDOWSNT */
70
71 #undef signal
72
73 #include <stdarg.h>
74 #include <ctype.h>
75 #include <stdio.h>
76 #include <getopt.h>
77 #include <unistd.h>
78
79 #include <pwd.h>
80 #include <sys/stat.h>
81 #include <signal.h>
82 #include <errno.h>
83
84
85 \f
86 char *getenv (const char *), *getwd (char *);
87 #ifdef HAVE_GETCWD
88 char *(getcwd) (char *, size_t);
89 #endif
90
91 #ifndef VERSION
92 #define VERSION "unspecified"
93 #endif
94 \f
95
96 #ifndef EXIT_SUCCESS
97 #define EXIT_SUCCESS 0
98 #endif
99
100 #ifndef EXIT_FAILURE
101 #define EXIT_FAILURE 1
102 #endif
103
104 #ifndef FALSE
105 #define FALSE 0
106 #endif
107
108 #ifndef TRUE
109 #define TRUE 1
110 #endif
111
112 /* Additional space when allocating buffers for filenames, etc. */
113 #define EXTRA_SPACE 100
114
115 /* Use this to suppress gcc's `...may be used before initialized' warnings. */
116 #ifdef lint
117 # define IF_LINT(Code) Code
118 #else
119 # define IF_LINT(Code) /* empty */
120 #endif
121
122 \f
123 /* Name used to invoke this program. */
124 const char *progname;
125
126 /* The second argument to main. */
127 char **main_argv;
128
129 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
130 int nowait = 0;
131
132 /* Nonzero means don't print messages for successful operations. --quiet. */
133 int quiet = 0;
134
135 /* Nonzero means args are expressions to be evaluated. --eval. */
136 int eval = 0;
137
138 /* Nonzero means don't open a new frame. Inverse of --create-frame. */
139 int current_frame = 1;
140
141 /* The display on which Emacs should work. --display. */
142 const char *display = NULL;
143
144 /* The parent window ID, if we are opening a frame via XEmbed. */
145 char *parent_id = NULL;
146
147 /* Nonzero means open a new Emacs frame on the current terminal. */
148 int tty = 0;
149
150 /* If non-NULL, the name of an editor to fallback to if the server
151 is not running. --alternate-editor. */
152 const char *alternate_editor = NULL;
153
154 /* If non-NULL, the filename of the UNIX socket. */
155 char *socket_name = NULL;
156
157 /* If non-NULL, the filename of the authentication file. */
158 const char *server_file = NULL;
159
160 /* PID of the Emacs server process. */
161 int emacs_pid = 0;
162
163 /* If non-NULL, a string that should form a frame parameter alist to
164 be used for the new frame */
165 const char *frame_parameters = NULL;
166
167 static void print_help_and_exit (void) NO_RETURN;
168 static void fail (void) NO_RETURN;
169
170
171 struct option longopts[] =
172 {
173 { "no-wait", no_argument, NULL, 'n' },
174 { "quiet", no_argument, NULL, 'q' },
175 { "eval", no_argument, NULL, 'e' },
176 { "help", no_argument, NULL, 'H' },
177 { "version", no_argument, NULL, 'V' },
178 { "tty", no_argument, NULL, 't' },
179 { "nw", no_argument, NULL, 't' },
180 { "create-frame", no_argument, NULL, 'c' },
181 { "alternate-editor", required_argument, NULL, 'a' },
182 { "frame-parameters", required_argument, NULL, 'F' },
183 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
184 { "socket-name", required_argument, NULL, 's' },
185 #endif
186 { "server-file", required_argument, NULL, 'f' },
187 #ifndef WINDOWSNT
188 { "display", required_argument, NULL, 'd' },
189 #endif
190 { "parent-id", required_argument, NULL, 'p' },
191 { 0, 0, 0, 0 }
192 };
193
194 \f
195 /* Like malloc but get fatal error if memory is exhausted. */
196
197 static long *
198 xmalloc (unsigned int size)
199 {
200 long *result = (long *) malloc (size);
201 if (result == NULL)
202 {
203 perror ("malloc");
204 exit (EXIT_FAILURE);
205 }
206 return result;
207 }
208
209 /* From sysdep.c */
210 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
211
212 /* From lisp.h */
213 #ifndef DIRECTORY_SEP
214 #define DIRECTORY_SEP '/'
215 #endif
216 #ifndef IS_DIRECTORY_SEP
217 #define IS_DIRECTORY_SEP(_c_) ((_c_) == DIRECTORY_SEP)
218 #endif
219 #ifndef IS_DEVICE_SEP
220 #ifndef DEVICE_SEP
221 #define IS_DEVICE_SEP(_c_) 0
222 #else
223 #define IS_DEVICE_SEP(_c_) ((_c_) == DEVICE_SEP)
224 #endif
225 #endif
226
227 char *get_current_dir_name (void);
228
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. */
232 char*
233 get_current_dir_name (void)
234 {
235 char *buf;
236 const char *pwd;
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
247 #ifdef MAXPATHLEN
248 && strlen (pwd) < MAXPATHLEN
249 #endif
250 )
251 {
252 buf = (char *) xmalloc (strlen (pwd) + 1);
253 if (!buf)
254 return NULL;
255 strcpy (buf, pwd);
256 }
257 #ifdef HAVE_GETCWD
258 else
259 {
260 size_t buf_size = 1024;
261 buf = (char *) xmalloc (buf_size);
262 if (!buf)
263 return NULL;
264 for (;;)
265 {
266 if (getcwd (buf, buf_size) == buf)
267 break;
268 if (errno != ERANGE)
269 {
270 int tmp_errno = errno;
271 free (buf);
272 errno = tmp_errno;
273 return NULL;
274 }
275 buf_size *= 2;
276 buf = (char *) realloc (buf, buf_size);
277 if (!buf)
278 return NULL;
279 }
280 }
281 #else
282 else
283 {
284 /* We need MAXPATHLEN here. */
285 buf = (char *) xmalloc (MAXPATHLEN + 1);
286 if (!buf)
287 return NULL;
288 if (getwd (buf) == NULL)
289 {
290 int tmp_errno = errno;
291 free (buf);
292 errno = tmp_errno;
293 return NULL;
294 }
295 }
296 #endif
297 return buf;
298 }
299 #endif
300
301 #ifdef WINDOWSNT
302
303 /* Like strdup but get a fatal error if memory is exhausted. */
304
305 char *
306 xstrdup (const char *s)
307 {
308 char *result = strdup (s);
309 if (result == NULL)
310 {
311 perror ("strdup");
312 exit (EXIT_FAILURE);
313 }
314 return result;
315 }
316
317 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
318
319 /* Retrieve an environment variable from the Emacs subkeys of the registry.
320 Return NULL if the variable was not found, or it was empty.
321 This code is based on w32_get_resource (w32.c). */
322 char *
323 w32_get_resource (HKEY predefined, char *key, LPDWORD type)
324 {
325 HKEY hrootkey = NULL;
326 char *result = NULL;
327 DWORD cbData;
328
329 if (RegOpenKeyEx (predefined, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
330 {
331 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS)
332 {
333 result = (char *) xmalloc (cbData);
334
335 if ((RegQueryValueEx (hrootkey, key, NULL, type, result, &cbData) != ERROR_SUCCESS)
336 || (*result == 0))
337 {
338 free (result);
339 result = NULL;
340 }
341 }
342
343 RegCloseKey (hrootkey);
344 }
345
346 return result;
347 }
348
349 /*
350 getenv wrapper for Windows
351
352 Value is allocated on the heap, and can be free'd.
353
354 This is needed to duplicate Emacs's behavior, which is to look for
355 environment variables in the registry if they don't appear in the
356 environment. */
357 char *
358 w32_getenv (char *envvar)
359 {
360 char *value;
361 DWORD dwType;
362
363 if (value = getenv (envvar))
364 /* Found in the environment. strdup it, because values returned
365 by getenv cannot be free'd. */
366 return xstrdup (value);
367
368 if (! (value = w32_get_resource (HKEY_CURRENT_USER, envvar, &dwType)) &&
369 ! (value = w32_get_resource (HKEY_LOCAL_MACHINE, envvar, &dwType)))
370 {
371 /* "w32console" is what Emacs on Windows uses for tty-type under -nw. */
372 if (strcmp (envvar, "TERM") == 0)
373 return xstrdup ("w32console");
374 /* Found neither in the environment nor in the registry. */
375 return NULL;
376 }
377
378 if (dwType == REG_SZ)
379 /* Registry; no need to expand. */
380 return value;
381
382 if (dwType == REG_EXPAND_SZ)
383 {
384 DWORD size;
385
386 if (size = ExpandEnvironmentStrings (value, NULL, 0))
387 {
388 char *buffer = (char *) xmalloc (size);
389 if (ExpandEnvironmentStrings (value, buffer, size))
390 {
391 /* Found and expanded. */
392 free (value);
393 return buffer;
394 }
395
396 /* Error expanding. */
397 free (buffer);
398 }
399 }
400
401 /* Not the right type, or not correctly expanded. */
402 free (value);
403 return NULL;
404 }
405
406 void
407 w32_set_user_model_id (void)
408 {
409 HMODULE shell;
410 HRESULT (WINAPI * set_user_model) (wchar_t * id);
411
412 /* On Windows 7 and later, we need to set the user model ID
413 to associate emacsclient launched files with Emacs frames
414 in the UI. */
415 shell = LoadLibrary ("shell32.dll");
416 if (shell)
417 {
418 set_user_model
419 = (void *) GetProcAddress (shell,
420 "SetCurrentProcessExplicitAppUserModelID");
421 /* If the function is defined, then we are running on Windows 7
422 or newer, and the UI uses this to group related windows
423 together. Since emacs, runemacs, emacsclient are related, we
424 want them grouped even though the executables are different,
425 so we need to set a consistent ID between them. */
426 if (set_user_model)
427 set_user_model (L"GNU.Emacs");
428
429 FreeLibrary (shell);
430 }
431 }
432
433 int
434 w32_window_app (void)
435 {
436 static int window_app = -1;
437 char szTitle[MAX_PATH];
438
439 if (window_app < 0)
440 {
441 /* Checking for STDOUT does not work; it's a valid handle also in
442 nonconsole apps. Testing for the console title seems to work. */
443 window_app = (GetConsoleTitleA (szTitle, MAX_PATH) == 0);
444 if (window_app)
445 InitCommonControls ();
446 }
447
448 return window_app;
449 }
450
451 /*
452 execvp wrapper for Windows. Quotes arguments with embedded spaces.
453
454 This is necessary due to the broken implementation of exec* routines in
455 the Microsoft libraries: they concatenate the arguments together without
456 quoting special characters, and pass the result to CreateProcess, with
457 predictably bad results. By contrast, POSIX execvp passes the arguments
458 directly into the argv array of the child process.
459 */
460 int
461 w32_execvp (const char *path, char **argv)
462 {
463 int i;
464
465 /* Required to allow a .BAT script as alternate editor. */
466 argv[0] = (char *) alternate_editor;
467
468 for (i = 0; argv[i]; i++)
469 if (strchr (argv[i], ' '))
470 {
471 char *quoted = alloca (strlen (argv[i]) + 3);
472 sprintf (quoted, "\"%s\"", argv[i]);
473 argv[i] = quoted;
474 }
475
476 return execvp (path, argv);
477 }
478
479 #undef execvp
480 #define execvp w32_execvp
481
482 /* Emulation of ttyname for Windows. */
483 char *
484 ttyname (int fd)
485 {
486 return "CONOUT$";
487 }
488
489 #endif /* WINDOWSNT */
490
491 /* Display a normal or error message.
492 On Windows, use a message box if compiled as a Windows app. */
493 static void message (int, const char *, ...) ATTRIBUTE_FORMAT_PRINTF (2, 3);
494 static void
495 message (int is_error, const char *format, ...)
496 {
497 char msg[2048];
498 va_list args;
499
500 va_start (args, format);
501 vsprintf (msg, format, args);
502 va_end (args);
503
504 #ifdef WINDOWSNT
505 if (w32_window_app ())
506 {
507 if (is_error)
508 MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
509 else
510 MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
511 }
512 else
513 #endif
514 {
515 FILE *f = is_error ? stderr : stdout;
516
517 fputs (msg, f);
518 fflush (f);
519 }
520 }
521
522 /* Decode the options from argv and argc.
523 The global variable `optind' will say how many arguments we used up. */
524
525 static void
526 decode_options (int argc, char **argv)
527 {
528 alternate_editor = egetenv ("ALTERNATE_EDITOR");
529
530 while (1)
531 {
532 int opt = getopt_long_only (argc, argv,
533 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
534 "VHneqa:s:f:d:F:tc",
535 #else
536 "VHneqa:f:d:F:tc",
537 #endif
538 longopts, 0);
539
540 if (opt == EOF)
541 break;
542
543 switch (opt)
544 {
545 case 0:
546 /* If getopt returns 0, then it has already processed a
547 long-named option. We should do nothing. */
548 break;
549
550 case 'a':
551 alternate_editor = optarg;
552 break;
553
554 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
555 case 's':
556 socket_name = optarg;
557 break;
558 #endif
559
560 case 'f':
561 server_file = optarg;
562 break;
563
564 /* We used to disallow this argument in w32, but it seems better
565 to allow it, for the occasional case where the user is
566 connecting with a w32 client to a server compiled with X11
567 support. */
568 case 'd':
569 display = optarg;
570 break;
571
572 case 'n':
573 nowait = 1;
574 break;
575
576 case 'e':
577 eval = 1;
578 break;
579
580 case 'q':
581 quiet = 1;
582 break;
583
584 case 'V':
585 message (FALSE, "emacsclient %s\n", VERSION);
586 exit (EXIT_SUCCESS);
587 break;
588
589 case 't':
590 tty = 1;
591 current_frame = 0;
592 break;
593
594 case 'c':
595 current_frame = 0;
596 break;
597
598 case 'p':
599 parent_id = optarg;
600 current_frame = 0;
601 break;
602
603 case 'H':
604 print_help_and_exit ();
605 break;
606
607 case 'F':
608 frame_parameters = optarg;
609 break;
610
611 default:
612 message (TRUE, "Try `%s --help' for more information\n", progname);
613 exit (EXIT_FAILURE);
614 break;
615 }
616 }
617
618 /* If the -c option is used (without -t) and no --display argument
619 is provided, try $DISPLAY.
620 Without the -c option, we used to set `display' to $DISPLAY by
621 default, but this changed the default behavior and is sometimes
622 inconvenient. So we force users to use "--display $DISPLAY" if
623 they want Emacs to connect to their current display. */
624 if (!current_frame && !tty && !display)
625 {
626 display = egetenv ("DISPLAY");
627 #ifdef NS_IMPL_COCOA
628 /* Under Cocoa, we don't really use displays the same way as in X,
629 so provide a dummy. */
630 if (!display || strlen (display) == 0)
631 display = "ns";
632 #endif
633 }
634
635 /* A null-string display is invalid. */
636 if (display && strlen (display) == 0)
637 display = NULL;
638
639 /* If no display is available, new frames are tty frames. */
640 if (!current_frame && !display)
641 tty = 1;
642
643 /* --no-wait implies --current-frame on ttys when there are file
644 arguments or expressions given. */
645 if (nowait && tty && argc - optind > 0)
646 current_frame = 1;
647
648 #ifdef WINDOWSNT
649 if (alternate_editor && alternate_editor[0] == '\0')
650 {
651 message (TRUE, "--alternate-editor argument or ALTERNATE_EDITOR variable cannot be\n\
652 an empty string");
653 exit (EXIT_FAILURE);
654 }
655 #endif /* WINDOWSNT */
656 }
657
658 \f
659 static void
660 print_help_and_exit (void)
661 {
662 /* Spaces and tabs are significant in this message; they're chosen so the
663 message aligns properly both in a tty and in a Windows message box.
664 Please try to preserve them; otherwise the output is very hard to read
665 when using emacsclientw. */
666 message (FALSE,
667 "Usage: %s [OPTIONS] FILE...\n\
668 Tell the Emacs server to visit the specified files.\n\
669 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
670 \n\
671 The following OPTIONS are accepted:\n\
672 -V, --version Just print version info and return\n\
673 -H, --help Print this usage information message\n\
674 -nw, -t, --tty Open a new Emacs frame on the current terminal\n\
675 -c, --create-frame Create a new frame instead of trying to\n\
676 use the current Emacs frame\n\
677 -F ALIST, --frame-parameters=ALIST\n\
678 Set the parameters of a new frame\n\
679 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
680 -n, --no-wait Don't wait for the server to return\n\
681 -q, --quiet Don't display messages on success\n\
682 -d DISPLAY, --display=DISPLAY\n\
683 Visit the file in the given display\n\
684 --parent-id=ID Open in parent window ID, via XEmbed\n"
685 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
686 "-s SOCKET, --socket-name=SOCKET\n\
687 Set filename of the UNIX socket for communication\n"
688 #endif
689 "-f SERVER, --server-file=SERVER\n\
690 Set filename of the TCP authentication file\n\
691 -a EDITOR, --alternate-editor=EDITOR\n\
692 Editor to fallback to if the server is not running\n"
693 #ifndef WINDOWSNT
694 " If EDITOR is the empty string, start Emacs in daemon\n\
695 mode and try connecting again\n"
696 #endif /* not WINDOWSNT */
697 "\n\
698 Report bugs with M-x report-emacs-bug.\n", progname);
699 exit (EXIT_SUCCESS);
700 }
701
702 /*
703 Try to run a different command, or --if no alternate editor is
704 defined-- exit with an errorcode.
705 Uses argv, but gets it from the global variable main_argv.
706 */
707 static void
708 fail (void)
709 {
710 if (alternate_editor)
711 {
712 int i = optind - 1;
713
714 execvp (alternate_editor, main_argv + i);
715 message (TRUE, "%s: error executing alternate editor \"%s\"\n",
716 progname, alternate_editor);
717 }
718 exit (EXIT_FAILURE);
719 }
720
721 \f
722 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
723
724 int
725 main (int argc, char **argv)
726 {
727 main_argv = argv;
728 progname = argv[0];
729 message (TRUE, "%s: Sorry, the Emacs server is supported only\n"
730 "on systems with Berkeley sockets.\n",
731 argv[0]);
732 fail ();
733 }
734
735 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
736
737 #define AUTH_KEY_LENGTH 64
738 #define SEND_BUFFER_SIZE 4096
739
740 extern char *strerror (int);
741
742 /* Buffer to accumulate data to send in TCP connections. */
743 char send_buffer[SEND_BUFFER_SIZE + 1];
744 int sblen = 0; /* Fill pointer for the send buffer. */
745 /* Socket used to communicate with the Emacs server process. */
746 HSOCKET emacs_socket = 0;
747
748 /* On Windows, the socket library was historically separate from the standard
749 C library, so errors are handled differently. */
750 static void
751 sock_err_message (const char *function_name)
752 {
753 #ifdef WINDOWSNT
754 char* msg = NULL;
755
756 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
757 | FORMAT_MESSAGE_ALLOCATE_BUFFER
758 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
759 NULL, WSAGetLastError (), 0, (LPTSTR)&msg, 0, NULL);
760
761 message (TRUE, "%s: %s: %s\n", progname, function_name, msg);
762
763 LocalFree (msg);
764 #else
765 message (TRUE, "%s: %s: %s\n", progname, function_name, strerror (errno));
766 #endif
767 }
768
769
770 /* Let's send the data to Emacs when either
771 - the data ends in "\n", or
772 - the buffer is full (but this shouldn't happen)
773 Otherwise, we just accumulate it. */
774 static void
775 send_to_emacs (HSOCKET s, const char *data)
776 {
777 while (data)
778 {
779 size_t dlen = strlen (data);
780 if (dlen + sblen >= SEND_BUFFER_SIZE)
781 {
782 int part = SEND_BUFFER_SIZE - sblen;
783 strncpy (&send_buffer[sblen], data, part);
784 data += part;
785 sblen = SEND_BUFFER_SIZE;
786 }
787 else if (dlen)
788 {
789 strcpy (&send_buffer[sblen], data);
790 data = NULL;
791 sblen += dlen;
792 }
793 else
794 break;
795
796 if (sblen == SEND_BUFFER_SIZE
797 || (sblen > 0 && send_buffer[sblen-1] == '\n'))
798 {
799 int sent = send (s, send_buffer, sblen, 0);
800 if (sent != sblen)
801 strcpy (send_buffer, &send_buffer[sent]);
802 sblen -= sent;
803 }
804 }
805 }
806
807 \f
808 /* In STR, insert a & before each &, each space, each newline, and
809 any initial -. Change spaces to underscores, too, so that the
810 return value never contains a space.
811
812 Does not change the string. Outputs the result to S. */
813 static void
814 quote_argument (HSOCKET s, const char *str)
815 {
816 char *copy = (char *) xmalloc (strlen (str) * 2 + 1);
817 const char *p;
818 char *q;
819
820 p = str;
821 q = copy;
822 while (*p)
823 {
824 if (*p == ' ')
825 {
826 *q++ = '&';
827 *q++ = '_';
828 p++;
829 }
830 else if (*p == '\n')
831 {
832 *q++ = '&';
833 *q++ = 'n';
834 p++;
835 }
836 else
837 {
838 if (*p == '&' || (*p == '-' && p == str))
839 *q++ = '&';
840 *q++ = *p++;
841 }
842 }
843 *q++ = 0;
844
845 send_to_emacs (s, copy);
846
847 free (copy);
848 }
849
850
851 /* The inverse of quote_argument. Removes quoting in string STR by
852 modifying the string in place. Returns STR. */
853
854 static char *
855 unquote_argument (char *str)
856 {
857 char *p, *q;
858
859 if (! str)
860 return str;
861
862 p = str;
863 q = str;
864 while (*p)
865 {
866 if (*p == '&')
867 {
868 p++;
869 if (*p == '&')
870 *p = '&';
871 else if (*p == '_')
872 *p = ' ';
873 else if (*p == 'n')
874 *p = '\n';
875 else if (*p == '-')
876 *p = '-';
877 }
878 *q++ = *p++;
879 }
880 *q = 0;
881 return str;
882 }
883
884 \f
885 static int
886 file_name_absolute_p (const char *filename)
887 {
888 /* Sanity check, it shouldn't happen. */
889 if (! filename) return FALSE;
890
891 /* /xxx is always an absolute path. */
892 if (filename[0] == '/') return TRUE;
893
894 /* Empty filenames (which shouldn't happen) are relative. */
895 if (filename[0] == '\0') return FALSE;
896
897 #ifdef WINDOWSNT
898 /* X:\xxx is always absolute. */
899 if (isalpha ((unsigned char) filename[0])
900 && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
901 return TRUE;
902
903 /* Both \xxx and \\xxx\yyy are absolute. */
904 if (filename[0] == '\\') return TRUE;
905 #endif
906
907 return FALSE;
908 }
909
910 #ifdef WINDOWSNT
911 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
912 void __cdecl
913 close_winsock (void)
914 {
915 WSACleanup ();
916 }
917
918 /* Initialize the WinSock2 library. */
919 void
920 initialize_sockets (void)
921 {
922 WSADATA wsaData;
923
924 if (WSAStartup (MAKEWORD (2, 0), &wsaData))
925 {
926 message (TRUE, "%s: error initializing WinSock2\n", progname);
927 exit (EXIT_FAILURE);
928 }
929
930 atexit (close_winsock);
931 }
932 #endif /* WINDOWSNT */
933
934 \f
935 /*
936 * Read the information needed to set up a TCP comm channel with
937 * the Emacs server: host, port, and authentication string.
938 */
939 static int
940 get_server_config (struct sockaddr_in *server, char *authentication)
941 {
942 char dotted[32];
943 char *port;
944 FILE *config = NULL;
945
946 if (file_name_absolute_p (server_file))
947 config = fopen (server_file, "rb");
948 else
949 {
950 const char *home = egetenv ("HOME");
951
952 if (home)
953 {
954 char *path = alloca (strlen (home) + strlen (server_file)
955 + EXTRA_SPACE);
956 sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
957 config = fopen (path, "rb");
958 }
959 #ifdef WINDOWSNT
960 if (!config && (home = egetenv ("APPDATA")))
961 {
962 char *path = alloca (strlen (home) + strlen (server_file)
963 + EXTRA_SPACE);
964 sprintf (path, "%s/.emacs.d/server/%s", home, server_file);
965 config = fopen (path, "rb");
966 }
967 #endif
968 }
969
970 if (! config)
971 return FALSE;
972
973 if (fgets (dotted, sizeof dotted, config)
974 && (port = strchr (dotted, ':')))
975 *port++ = '\0';
976 else
977 {
978 message (TRUE, "%s: invalid configuration info\n", progname);
979 exit (EXIT_FAILURE);
980 }
981
982 server->sin_family = AF_INET;
983 server->sin_addr.s_addr = inet_addr (dotted);
984 server->sin_port = htons (atoi (port));
985
986 if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
987 {
988 message (TRUE, "%s: cannot read authentication info\n", progname);
989 exit (EXIT_FAILURE);
990 }
991
992 fclose (config);
993
994 return TRUE;
995 }
996
997 static HSOCKET
998 set_tcp_socket (void)
999 {
1000 HSOCKET s;
1001 struct sockaddr_in server;
1002 struct linger l_arg = {1, 1};
1003 char auth_string[AUTH_KEY_LENGTH + 1];
1004
1005 if (! get_server_config (&server, auth_string))
1006 return INVALID_SOCKET;
1007
1008 if (server.sin_addr.s_addr != inet_addr ("127.0.0.1") && !quiet)
1009 message (FALSE, "%s: connected to remote socket at %s\n",
1010 progname, inet_ntoa (server.sin_addr));
1011
1012 /*
1013 * Open up an AF_INET socket
1014 */
1015 if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
1016 {
1017 sock_err_message ("socket");
1018 return INVALID_SOCKET;
1019 }
1020
1021 /*
1022 * Set up the socket
1023 */
1024 if (connect (s, (struct sockaddr *) &server, sizeof server) < 0)
1025 {
1026 sock_err_message ("connect");
1027 return INVALID_SOCKET;
1028 }
1029
1030 setsockopt (s, SOL_SOCKET, SO_LINGER, (char *) &l_arg, sizeof l_arg);
1031
1032 /*
1033 * Send the authentication
1034 */
1035 auth_string[AUTH_KEY_LENGTH] = '\0';
1036
1037 send_to_emacs (s, "-auth ");
1038 send_to_emacs (s, auth_string);
1039 send_to_emacs (s, " ");
1040
1041 return s;
1042 }
1043
1044
1045 /* Returns 1 if PREFIX is a prefix of STRING. */
1046 static int
1047 strprefix (const char *prefix, const char *string)
1048 {
1049 return !strncmp (prefix, string, strlen (prefix));
1050 }
1051
1052 /* Get tty name and type. If successful, return the type in TTY_TYPE
1053 and the name in TTY_NAME, and return 1. Otherwise, fail if NOABORT
1054 is zero, or return 0 if NOABORT is non-zero. */
1055
1056 static int
1057 find_tty (const char **tty_type, const char **tty_name, int noabort)
1058 {
1059 const char *type = egetenv ("TERM");
1060 const char *name = ttyname (fileno (stdout));
1061
1062 if (!name)
1063 {
1064 if (noabort)
1065 return 0;
1066 else
1067 {
1068 message (TRUE, "%s: could not get terminal name\n", progname);
1069 fail ();
1070 }
1071 }
1072
1073 if (!type)
1074 {
1075 if (noabort)
1076 return 0;
1077 else
1078 {
1079 message (TRUE, "%s: please set the TERM variable to your terminal type\n",
1080 progname);
1081 fail ();
1082 }
1083 }
1084
1085 if (strcmp (type, "eterm") == 0)
1086 {
1087 if (noabort)
1088 return 0;
1089 else
1090 {
1091 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1092 message (TRUE, "%s: opening a frame in an Emacs term buffer"
1093 " is not supported\n", progname);
1094 fail ();
1095 }
1096 }
1097
1098 *tty_name = name;
1099 *tty_type = type;
1100 return 1;
1101 }
1102
1103
1104 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1105
1106 /* Three possibilities:
1107 2 - can't be `stat'ed (sets errno)
1108 1 - isn't owned by us
1109 0 - success: none of the above */
1110
1111 static int
1112 socket_status (const char *name)
1113 {
1114 struct stat statbfr;
1115
1116 if (stat (name, &statbfr) == -1)
1117 return 2;
1118
1119 if (statbfr.st_uid != geteuid ())
1120 return 1;
1121
1122 return 0;
1123 }
1124
1125 \f
1126 /* A signal handler that passes the signal to the Emacs process.
1127 Useful for SIGWINCH. */
1128
1129 static void
1130 pass_signal_to_emacs (int signalnum)
1131 {
1132 int old_errno = errno;
1133
1134 if (emacs_pid)
1135 kill (emacs_pid, signalnum);
1136
1137 signal (signalnum, pass_signal_to_emacs);
1138 errno = old_errno;
1139 }
1140
1141 /* Signal handler for SIGCONT; notify the Emacs process that it can
1142 now resume our tty frame. */
1143
1144 static void
1145 handle_sigcont (int signalnum)
1146 {
1147 int old_errno = errno;
1148
1149 if (tcgetpgrp (1) == getpgrp ())
1150 {
1151 /* We are in the foreground. */
1152 send_to_emacs (emacs_socket, "-resume \n");
1153 }
1154 else
1155 {
1156 /* We are in the background; cancel the continue. */
1157 kill (getpid (), SIGSTOP);
1158 }
1159
1160 signal (signalnum, handle_sigcont);
1161 errno = old_errno;
1162 }
1163
1164 /* Signal handler for SIGTSTP; notify the Emacs process that we are
1165 going to sleep. Normally the suspend is initiated by Emacs via
1166 server-handle-suspend-tty, but if the server gets out of sync with
1167 reality, we may get a SIGTSTP on C-z. Handling this signal and
1168 notifying Emacs about it should get things under control again. */
1169
1170 static void
1171 handle_sigtstp (int signalnum)
1172 {
1173 int old_errno = errno;
1174 sigset_t set;
1175
1176 if (emacs_socket)
1177 send_to_emacs (emacs_socket, "-suspend \n");
1178
1179 /* Unblock this signal and call the default handler by temporarily
1180 changing the handler and resignalling. */
1181 sigprocmask (SIG_BLOCK, NULL, &set);
1182 sigdelset (&set, signalnum);
1183 signal (signalnum, SIG_DFL);
1184 kill (getpid (), signalnum);
1185 sigprocmask (SIG_SETMASK, &set, NULL); /* Let's the above signal through. */
1186 signal (signalnum, handle_sigtstp);
1187
1188 errno = old_errno;
1189 }
1190
1191
1192 /* Set up signal handlers before opening a frame on the current tty. */
1193
1194 static void
1195 init_signals (void)
1196 {
1197 /* Set up signal handlers. */
1198 signal (SIGWINCH, pass_signal_to_emacs);
1199
1200 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
1201 deciding which terminal the signal came from. C-g is now a
1202 normal input event on secondary terminals. */
1203 #if 0
1204 signal (SIGINT, pass_signal_to_emacs);
1205 signal (SIGQUIT, pass_signal_to_emacs);
1206 #endif
1207
1208 signal (SIGCONT, handle_sigcont);
1209 signal (SIGTSTP, handle_sigtstp);
1210 signal (SIGTTOU, handle_sigtstp);
1211 }
1212
1213
1214 static HSOCKET
1215 set_local_socket (void)
1216 {
1217 HSOCKET s;
1218 struct sockaddr_un server;
1219
1220 /*
1221 * Open up an AF_UNIX socket in this person's home directory
1222 */
1223
1224 if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
1225 {
1226 message (TRUE, "%s: socket: %s\n", progname, strerror (errno));
1227 return INVALID_SOCKET;
1228 }
1229
1230 server.sun_family = AF_UNIX;
1231
1232 {
1233 int sock_status = 0;
1234 int default_sock = !socket_name;
1235 int saved_errno = 0;
1236 const char *server_name = "server";
1237 const char *tmpdir IF_LINT ( = NULL);
1238
1239 if (socket_name && !strchr (socket_name, '/')
1240 && !strchr (socket_name, '\\'))
1241 {
1242 /* socket_name is a file name component. */
1243 server_name = socket_name;
1244 socket_name = NULL;
1245 default_sock = 1; /* Try both UIDs. */
1246 }
1247
1248 if (default_sock)
1249 {
1250 tmpdir = egetenv ("TMPDIR");
1251 if (!tmpdir)
1252 {
1253 #ifdef DARWIN_OS
1254 #ifndef _CS_DARWIN_USER_TEMP_DIR
1255 #define _CS_DARWIN_USER_TEMP_DIR 65537
1256 #endif
1257 size_t n = confstr (_CS_DARWIN_USER_TEMP_DIR, NULL, (size_t) 0);
1258 if (n > 0)
1259 {
1260 tmpdir = alloca (n);
1261 confstr (_CS_DARWIN_USER_TEMP_DIR, tmpdir, n);
1262 }
1263 else
1264 #endif
1265 tmpdir = "/tmp";
1266 }
1267 socket_name = alloca (strlen (tmpdir) + strlen (server_name)
1268 + EXTRA_SPACE);
1269 sprintf (socket_name, "%s/emacs%d/%s",
1270 tmpdir, (int) geteuid (), server_name);
1271 }
1272
1273 if (strlen (socket_name) < sizeof (server.sun_path))
1274 strcpy (server.sun_path, socket_name);
1275 else
1276 {
1277 message (TRUE, "%s: socket-name %s too long\n",
1278 progname, socket_name);
1279 fail ();
1280 }
1281
1282 /* See if the socket exists, and if it's owned by us. */
1283 sock_status = socket_status (server.sun_path);
1284 saved_errno = errno;
1285 if (sock_status && default_sock)
1286 {
1287 /* Failing that, see if LOGNAME or USER exist and differ from
1288 our euid. If so, look for a socket based on the UID
1289 associated with the name. This is reminiscent of the logic
1290 that init_editfns uses to set the global Vuser_full_name. */
1291
1292 const char *user_name = egetenv ("LOGNAME");
1293
1294 if (!user_name)
1295 user_name = egetenv ("USER");
1296
1297 if (user_name)
1298 {
1299 struct passwd *pw = getpwnam (user_name);
1300
1301 if (pw && (pw->pw_uid != geteuid ()))
1302 {
1303 /* We're running under su, apparently. */
1304 socket_name = alloca (strlen (tmpdir) + strlen (server_name)
1305 + EXTRA_SPACE);
1306 sprintf (socket_name, "%s/emacs%d/%s",
1307 tmpdir, (int) pw->pw_uid, server_name);
1308
1309 if (strlen (socket_name) < sizeof (server.sun_path))
1310 strcpy (server.sun_path, socket_name);
1311 else
1312 {
1313 message (TRUE, "%s: socket-name %s too long\n",
1314 progname, socket_name);
1315 exit (EXIT_FAILURE);
1316 }
1317
1318 sock_status = socket_status (server.sun_path);
1319 saved_errno = errno;
1320 }
1321 else
1322 errno = saved_errno;
1323 }
1324 }
1325
1326 switch (sock_status)
1327 {
1328 case 1:
1329 /* There's a socket, but it isn't owned by us. This is OK if
1330 we are root. */
1331 if (0 != geteuid ())
1332 {
1333 message (TRUE, "%s: Invalid socket owner\n", progname);
1334 return INVALID_SOCKET;
1335 }
1336 break;
1337
1338 case 2:
1339 /* `stat' failed */
1340 if (saved_errno == ENOENT)
1341 message (TRUE,
1342 "%s: can't find socket; have you started the server?\n\
1343 To start the server in Emacs, type \"M-x server-start\".\n",
1344 progname);
1345 else
1346 message (TRUE, "%s: can't stat %s: %s\n",
1347 progname, server.sun_path, strerror (saved_errno));
1348 return INVALID_SOCKET;
1349 }
1350 }
1351
1352 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
1353 < 0)
1354 {
1355 message (TRUE, "%s: connect: %s\n", progname, strerror (errno));
1356 return INVALID_SOCKET;
1357 }
1358
1359 return s;
1360 }
1361 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1362
1363 static HSOCKET
1364 set_socket (int no_exit_if_error)
1365 {
1366 HSOCKET s;
1367
1368 INITIALIZE ();
1369
1370 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1371 /* Explicit --socket-name argument. */
1372 if (socket_name)
1373 {
1374 s = set_local_socket ();
1375 if ((s != INVALID_SOCKET) || no_exit_if_error)
1376 return s;
1377 message (TRUE, "%s: error accessing socket \"%s\"\n",
1378 progname, socket_name);
1379 exit (EXIT_FAILURE);
1380 }
1381 #endif
1382
1383 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1384 if (!server_file)
1385 server_file = egetenv ("EMACS_SERVER_FILE");
1386
1387 if (server_file)
1388 {
1389 s = set_tcp_socket ();
1390 if ((s != INVALID_SOCKET) || no_exit_if_error)
1391 return s;
1392
1393 message (TRUE, "%s: error accessing server file \"%s\"\n",
1394 progname, server_file);
1395 exit (EXIT_FAILURE);
1396 }
1397
1398 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1399 /* Implicit local socket. */
1400 s = set_local_socket ();
1401 if (s != INVALID_SOCKET)
1402 return s;
1403 #endif
1404
1405 /* Implicit server file. */
1406 server_file = "server";
1407 s = set_tcp_socket ();
1408 if ((s != INVALID_SOCKET) || no_exit_if_error)
1409 return s;
1410
1411 /* No implicit or explicit socket, and no alternate editor. */
1412 message (TRUE, "%s: No socket or alternate editor. Please use:\n\n"
1413 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1414 "\t--socket-name\n"
1415 #endif
1416 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1417 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1418 progname);
1419 exit (EXIT_FAILURE);
1420 }
1421
1422 #ifdef WINDOWSNT
1423 FARPROC set_fg; /* Pointer to AllowSetForegroundWindow. */
1424 FARPROC get_wc; /* Pointer to RealGetWindowClassA. */
1425
1426 BOOL CALLBACK
1427 w32_find_emacs_process (HWND hWnd, LPARAM lParam)
1428 {
1429 DWORD pid;
1430 char class[6];
1431
1432 /* Reject any window not of class "Emacs". */
1433 if (! get_wc (hWnd, class, sizeof (class))
1434 || strcmp (class, "Emacs"))
1435 return TRUE;
1436
1437 /* We only need the process id, not the thread id. */
1438 (void) GetWindowThreadProcessId (hWnd, &pid);
1439
1440 /* Not the one we're looking for. */
1441 if (pid != (DWORD) emacs_pid) return TRUE;
1442
1443 /* OK, let's raise it. */
1444 set_fg (emacs_pid);
1445
1446 /* Stop enumeration. */
1447 return FALSE;
1448 }
1449
1450 /*
1451 * Search for a window of class "Emacs" and owned by a process with
1452 * process id = emacs_pid. If found, allow it to grab the focus.
1453 */
1454 void
1455 w32_give_focus (void)
1456 {
1457 HANDLE user32;
1458
1459 /* It shouldn't happen when dealing with TCP sockets. */
1460 if (!emacs_pid) return;
1461
1462 user32 = GetModuleHandle ("user32.dll");
1463
1464 if (!user32)
1465 return;
1466
1467 /* Modern Windows restrict which processes can set the foreground window.
1468 emacsclient can allow Emacs to grab the focus by calling the function
1469 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1470 NT) lack this function, so we have to check its availability. */
1471 if ((set_fg = GetProcAddress (user32, "AllowSetForegroundWindow"))
1472 && (get_wc = GetProcAddress (user32, "RealGetWindowClassA")))
1473 EnumWindows (w32_find_emacs_process, (LPARAM) 0);
1474 }
1475 #endif
1476
1477 /* Start the emacs daemon and try to connect to it. */
1478
1479 static void
1480 start_daemon_and_retry_set_socket (void)
1481 {
1482 #ifndef WINDOWSNT
1483 pid_t dpid;
1484 int status;
1485
1486 dpid = fork ();
1487
1488 if (dpid > 0)
1489 {
1490 pid_t w;
1491 w = waitpid (dpid, &status, WUNTRACED | WCONTINUED);
1492
1493 if ((w == -1) || !WIFEXITED (status) || WEXITSTATUS (status))
1494 {
1495 message (TRUE, "Error: Could not start the Emacs daemon\n");
1496 exit (EXIT_FAILURE);
1497 }
1498
1499 /* Try connecting, the daemon should have started by now. */
1500 message (TRUE, "Emacs daemon should have started, trying to connect again\n");
1501 if ((emacs_socket = set_socket (1)) == INVALID_SOCKET)
1502 {
1503 message (TRUE, "Error: Cannot connect even after starting the Emacs daemon\n");
1504 exit (EXIT_FAILURE);
1505 }
1506 }
1507 else if (dpid < 0)
1508 {
1509 fprintf (stderr, "Error: Cannot fork!\n");
1510 exit (EXIT_FAILURE);
1511 }
1512 else
1513 {
1514 char emacs[] = "emacs";
1515 char daemon_option[] = "--daemon";
1516 char *d_argv[] = {emacs, daemon_option, 0 };
1517 if (socket_name != NULL)
1518 {
1519 /* Pass --daemon=socket_name as argument. */
1520 const char *deq = "--daemon=";
1521 char *daemon_arg = alloca (strlen (deq)
1522 + strlen (socket_name) + 1);
1523 strcpy (daemon_arg, deq);
1524 strcat (daemon_arg, socket_name);
1525 d_argv[1] = daemon_arg;
1526 }
1527 execvp ("emacs", d_argv);
1528 message (TRUE, "%s: error starting emacs daemon\n", progname);
1529 }
1530 #endif /* WINDOWSNT */
1531 }
1532
1533 int
1534 main (int argc, char **argv)
1535 {
1536 int rl = 0, needlf = 0;
1537 char *cwd, *str;
1538 char string[BUFSIZ+1];
1539 int null_socket_name IF_LINT ( = 0);
1540 int null_server_file IF_LINT ( = 0);
1541 int start_daemon_if_needed;
1542 int exit_status = EXIT_SUCCESS;
1543
1544 main_argv = argv;
1545 progname = argv[0];
1546
1547 #ifdef WINDOWSNT
1548 /* On Windows 7 and later, we need to explicitly associate emacsclient
1549 with emacs so the UI behaves sensibly. */
1550 w32_set_user_model_id ();
1551 #endif
1552
1553 /* Process options. */
1554 decode_options (argc, argv);
1555
1556 if ((argc - optind < 1) && !eval && current_frame)
1557 {
1558 message (TRUE, "%s: file name or argument required\n"
1559 "Try `%s --help' for more information\n",
1560 progname, progname);
1561 exit (EXIT_FAILURE);
1562 }
1563
1564 /* If alternate_editor is the empty string, start the emacs daemon
1565 in case of failure to connect. */
1566 start_daemon_if_needed = (alternate_editor
1567 && (alternate_editor[0] == '\0'));
1568 if (start_daemon_if_needed)
1569 {
1570 /* set_socket changes the values for socket_name and
1571 server_file, we need to reset them, if they were NULL before
1572 for the second call to set_socket. */
1573 null_socket_name = (socket_name == NULL);
1574 null_server_file = (server_file == NULL);
1575 }
1576
1577 emacs_socket = set_socket (alternate_editor || start_daemon_if_needed);
1578 if (emacs_socket == INVALID_SOCKET)
1579 {
1580 if (! start_daemon_if_needed)
1581 fail ();
1582
1583 /* Reset socket_name and server_file if they were NULL
1584 before the set_socket call. */
1585 if (null_socket_name)
1586 socket_name = NULL;
1587 if (null_server_file)
1588 server_file = NULL;
1589
1590 start_daemon_and_retry_set_socket ();
1591 }
1592
1593 cwd = get_current_dir_name ();
1594 if (cwd == 0)
1595 {
1596 /* getwd puts message in STRING if it fails. */
1597 message (TRUE, "%s: %s\n", progname,
1598 "Cannot get current working directory");
1599 fail ();
1600 }
1601
1602 #ifdef WINDOWSNT
1603 w32_give_focus ();
1604 #endif
1605
1606 /* Send over our environment and current directory. */
1607 if (!current_frame)
1608 {
1609 extern char **environ;
1610 int i;
1611 for (i = 0; environ[i]; i++)
1612 {
1613 send_to_emacs (emacs_socket, "-env ");
1614 quote_argument (emacs_socket, environ[i]);
1615 send_to_emacs (emacs_socket, " ");
1616 }
1617 }
1618 send_to_emacs (emacs_socket, "-dir ");
1619 quote_argument (emacs_socket, cwd);
1620 send_to_emacs (emacs_socket, "/");
1621 send_to_emacs (emacs_socket, " ");
1622
1623 retry:
1624 if (nowait)
1625 send_to_emacs (emacs_socket, "-nowait ");
1626
1627 if (current_frame)
1628 send_to_emacs (emacs_socket, "-current-frame ");
1629
1630 if (display)
1631 {
1632 send_to_emacs (emacs_socket, "-display ");
1633 quote_argument (emacs_socket, display);
1634 send_to_emacs (emacs_socket, " ");
1635 }
1636
1637 if (parent_id)
1638 {
1639 send_to_emacs (emacs_socket, "-parent-id ");
1640 quote_argument (emacs_socket, parent_id);
1641 send_to_emacs (emacs_socket, " ");
1642 }
1643
1644 if (frame_parameters && !current_frame)
1645 {
1646 send_to_emacs (emacs_socket, "-frame-parameters ");
1647 quote_argument (emacs_socket, frame_parameters);
1648 send_to_emacs (emacs_socket, " ");
1649 }
1650
1651 /* If using the current frame, send tty information to Emacs anyway.
1652 In daemon mode, Emacs may need to occupy this tty if no other
1653 frame is available. */
1654 if (tty || (current_frame && !eval))
1655 {
1656 const char *tty_type, *tty_name;
1657
1658 if (find_tty (&tty_type, &tty_name, !tty))
1659 {
1660 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1661 init_signals ();
1662 #endif
1663 send_to_emacs (emacs_socket, "-tty ");
1664 quote_argument (emacs_socket, tty_name);
1665 send_to_emacs (emacs_socket, " ");
1666 quote_argument (emacs_socket, tty_type);
1667 send_to_emacs (emacs_socket, " ");
1668 }
1669 }
1670
1671 if (!current_frame && !tty)
1672 send_to_emacs (emacs_socket, "-window-system ");
1673
1674 if ((argc - optind > 0))
1675 {
1676 int i;
1677 for (i = optind; i < argc; i++)
1678 {
1679
1680 if (eval)
1681 {
1682 /* Don't prepend cwd or anything like that. */
1683 send_to_emacs (emacs_socket, "-eval ");
1684 quote_argument (emacs_socket, argv[i]);
1685 send_to_emacs (emacs_socket, " ");
1686 continue;
1687 }
1688
1689 if (*argv[i] == '+')
1690 {
1691 char *p = argv[i] + 1;
1692 while (isdigit ((unsigned char) *p) || *p == ':') p++;
1693 if (*p == 0)
1694 {
1695 send_to_emacs (emacs_socket, "-position ");
1696 quote_argument (emacs_socket, argv[i]);
1697 send_to_emacs (emacs_socket, " ");
1698 continue;
1699 }
1700 }
1701 #ifdef WINDOWSNT
1702 else if (! file_name_absolute_p (argv[i])
1703 && (isalpha (argv[i][0]) && argv[i][1] == ':'))
1704 /* Windows can have a different default directory for each
1705 drive, so the cwd passed via "-dir" is not sufficient
1706 to account for that.
1707 If the user uses <drive>:<relpath>, we hence need to be
1708 careful to expand <relpath> with the default directory
1709 corresponding to <drive>. */
1710 {
1711 char *filename = (char *) xmalloc (MAX_PATH);
1712 DWORD size;
1713
1714 size = GetFullPathName (argv[i], MAX_PATH, filename, NULL);
1715 if (size > 0 && size < MAX_PATH)
1716 argv[i] = filename;
1717 else
1718 free (filename);
1719 }
1720 #endif
1721
1722 send_to_emacs (emacs_socket, "-file ");
1723 quote_argument (emacs_socket, argv[i]);
1724 send_to_emacs (emacs_socket, " ");
1725 }
1726 }
1727 else if (eval)
1728 {
1729 /* Read expressions interactively. */
1730 while ((str = fgets (string, BUFSIZ, stdin)))
1731 {
1732 send_to_emacs (emacs_socket, "-eval ");
1733 quote_argument (emacs_socket, str);
1734 }
1735 send_to_emacs (emacs_socket, " ");
1736 }
1737
1738 send_to_emacs (emacs_socket, "\n");
1739
1740 /* Wait for an answer. */
1741 if (!eval && !tty && !nowait && !quiet)
1742 {
1743 printf ("Waiting for Emacs...");
1744 needlf = 2;
1745 }
1746 fflush (stdout);
1747 fsync (1);
1748
1749 /* Now, wait for an answer and print any messages. */
1750 while (exit_status == EXIT_SUCCESS)
1751 {
1752 char *p;
1753 do
1754 {
1755 errno = 0;
1756 rl = recv (emacs_socket, string, BUFSIZ, 0);
1757 }
1758 /* If we receive a signal (e.g. SIGWINCH, which we pass
1759 through to Emacs), on some OSes we get EINTR and must retry. */
1760 while (rl < 0 && errno == EINTR);
1761
1762 if (rl <= 0)
1763 break;
1764
1765 string[rl] = '\0';
1766
1767 p = string + strlen (string) - 1;
1768 while (p > string && *p == '\n')
1769 *p-- = 0;
1770
1771 if (strprefix ("-emacs-pid ", string))
1772 {
1773 /* -emacs-pid PID: The process id of the Emacs process. */
1774 emacs_pid = strtol (string + strlen ("-emacs-pid"), NULL, 10);
1775 }
1776 else if (strprefix ("-window-system-unsupported ", string))
1777 {
1778 /* -window-system-unsupported: Emacs was compiled without X
1779 support. Try again on the terminal. */
1780 nowait = 0;
1781 tty = 1;
1782 goto retry;
1783 }
1784 else if (strprefix ("-print ", string))
1785 {
1786 /* -print STRING: Print STRING on the terminal. */
1787 str = unquote_argument (string + strlen ("-print "));
1788 if (needlf)
1789 printf ("\n");
1790 printf ("%s", str);
1791 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1792 }
1793 else if (strprefix ("-error ", string))
1794 {
1795 /* -error DESCRIPTION: Signal an error on the terminal. */
1796 str = unquote_argument (string + strlen ("-error "));
1797 if (needlf)
1798 printf ("\n");
1799 fprintf (stderr, "*ERROR*: %s", str);
1800 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1801 exit_status = EXIT_FAILURE;
1802 }
1803 #ifdef SIGSTOP
1804 else if (strprefix ("-suspend ", string))
1805 {
1806 /* -suspend: Suspend this terminal, i.e., stop the process. */
1807 if (needlf)
1808 printf ("\n");
1809 needlf = 0;
1810 kill (0, SIGSTOP);
1811 }
1812 #endif
1813 else
1814 {
1815 /* Unknown command. */
1816 if (needlf)
1817 printf ("\n");
1818 printf ("*ERROR*: Unknown message: %s", string);
1819 needlf = string[0]
1820 == '\0' ? needlf : string[strlen (string) - 1] != '\n';
1821 }
1822 }
1823
1824 if (needlf)
1825 printf ("\n");
1826 fflush (stdout);
1827 fsync (1);
1828
1829 if (rl < 0)
1830 exit_status = EXIT_FAILURE;
1831
1832 CLOSE_SOCKET (emacs_socket);
1833 return exit_status;
1834 }
1835
1836 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
1837
1838 \f
1839 #ifndef HAVE_STRERROR
1840 char *
1841 strerror (errnum)
1842 int errnum;
1843 {
1844 extern char *sys_errlist[];
1845 extern int sys_nerr;
1846
1847 if (errnum >= 0 && errnum < sys_nerr)
1848 return sys_errlist[errnum];
1849 return (char *) "Unknown error";
1850 }
1851
1852 #endif /* ! HAVE_STRERROR */
1853
1854
1855 /* emacsclient.c ends here */