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