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