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