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