This source file includes following definitions.
- xmalloc
- xrealloc
- xstrdup
- get_current_dir_name
- w32_get_resource
- w32_getenv
- w32_window_app
- w32_execvp
- ttyname
- message
- decode_options
- print_help_and_exit
- fail
- act_on_signals
- init_signals
- sock_err_message
- send_to_emacs
- quote_argument
- unquote_argument
- close_winsock
- initialize_sockets
- open_config
- get_server_config
- cloexec_socket
- set_tcp_socket
- strprefix
- find_tty
- process_grouping
- connect_socket
- reinstall_handler_if_needed
- handle_sigcont
- handle_sigtstp
- handle_sigttou
- handle_sigwinch
- install_handler
- init_signals
- act_on_tty_signal
- act_on_signals
- local_sockname
- set_local_socket
- set_socket
- w32_set_user_model_id
- w32_find_emacs_process
- w32_give_focus
- start_daemon_and_retry_set_socket
- set_socket_timeout
- check_socket_timeout
- main
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 #include <config.h>
22
23 #ifdef WINDOWSNT
24
25
26 # undef _WINSOCKAPI_
27 # undef _WINSOCK_H
28
29 # include <malloc.h>
30 # include <windows.h>
31 # include <commctrl.h>
32 # include <io.h>
33 # include <winsock2.h>
34
35 # define HSOCKET SOCKET
36 # define CLOSE_SOCKET closesocket
37 # define INITIALIZE() initialize_sockets ()
38
39 char *w32_getenv (const char *);
40 # define egetenv(VAR) w32_getenv (VAR)
41
42 # undef signal
43
44 #else
45
46 # ifdef HAVE_NTGUI
47 # include <windows.h>
48 # endif
49
50 # include "syswait.h"
51
52 # include <arpa/inet.h>
53 # include <fcntl.h>
54 # include <netinet/in.h>
55 # include <sys/socket.h>
56 # include <sys/un.h>
57
58 # define SOCKETS_IN_FILE_SYSTEM
59
60 # define INVALID_SOCKET (-1)
61 # define HSOCKET int
62 # define CLOSE_SOCKET close
63 # define INITIALIZE()
64
65 # define egetenv(VAR) getenv (VAR)
66
67 #endif
68
69 #define DEFAULT_TIMEOUT (30)
70
71 #include <ctype.h>
72 #include <errno.h>
73 #include <getopt.h>
74 #include <inttypes.h>
75 #include <pwd.h>
76 #include <signal.h>
77 #include <stdarg.h>
78 #include <stddef.h>
79 #include <stdint.h>
80 #include <stdlib.h>
81 #include <string.h>
82 #include <sys/stat.h>
83 #include <unistd.h>
84
85 #include <attribute.h>
86 #include <filename.h>
87 #include <intprops.h>
88 #include <min-max.h>
89 #include <pathmax.h>
90 #include <unlocked-io.h>
91
92
93 #if GNUC_PREREQ (7, 0, 0)
94 # pragma GCC diagnostic ignored "-Wformat-truncation=2"
95 #endif
96
97
98
99 static char const *progname;
100
101
102 static int main_argc;
103
104
105 static char *const *main_argv;
106
107
108 static bool nowait;
109
110
111 static bool quiet;
112
113
114 static bool suppress_output;
115
116
117 static bool eval;
118
119
120 static bool create_frame;
121
122
123 static bool reuse_frame;
124
125
126 static char const *display;
127
128
129 static char const *alt_display;
130
131
132 static char *parent_id;
133
134
135 static bool tty;
136
137
138
139 static char *alternate_editor;
140
141 #ifdef SOCKETS_IN_FILE_SYSTEM
142
143 static char const *socket_name;
144 #endif
145
146
147 static char const *server_file;
148
149
150 static uintmax_t timeout;
151
152
153 static char const *tramp_prefix;
154
155
156 static pid_t emacs_pid;
157
158
159
160 static char const *frame_parameters;
161
162 static _Noreturn void print_help_and_exit (void);
163
164
165
166 static struct option const longopts[] =
167 {
168 { "no-wait", no_argument, NULL, 'n' },
169 { "quiet", no_argument, NULL, 'q' },
170 { "suppress-output", no_argument, NULL, 'u' },
171 { "eval", no_argument, NULL, 'e' },
172 { "help", no_argument, NULL, 'H' },
173 { "version", no_argument, NULL, 'V' },
174 { "tty", no_argument, NULL, 't' },
175 { "nw", no_argument, NULL, 't' },
176 { "create-frame", no_argument, NULL, 'c' },
177 { "reuse-frame", no_argument, NULL, 'r' },
178 { "alternate-editor", required_argument, NULL, 'a' },
179 { "frame-parameters", required_argument, NULL, 'F' },
180 #ifdef SOCKETS_IN_FILE_SYSTEM
181 { "socket-name", required_argument, NULL, 's' },
182 #endif
183 { "server-file", required_argument, NULL, 'f' },
184 { "display", required_argument, NULL, 'd' },
185 { "parent-id", required_argument, NULL, 'p' },
186 { "timeout", required_argument, NULL, 'w' },
187 { "tramp", required_argument, NULL, 'T' },
188 { 0, 0, 0, 0 }
189 };
190
191
192
193 static char const shortopts[] =
194 "nqueHVtca:F:w:"
195 #ifdef SOCKETS_IN_FILE_SYSTEM
196 "s:"
197 #endif
198 "f:d:T:";
199
200
201
202
203 static void * ATTRIBUTE_MALLOC
204 xmalloc (size_t size)
205 {
206 void *result = malloc (size);
207 if (result == NULL)
208 {
209 perror ("malloc");
210 exit (EXIT_FAILURE);
211 }
212 return result;
213 }
214
215
216
217 static void *
218 xrealloc (void *ptr, size_t size)
219 {
220 void *result = realloc (ptr, size);
221 if (result == NULL)
222 {
223 perror ("realloc");
224 exit (EXIT_FAILURE);
225 }
226 return result;
227 }
228
229
230
231 static char * ATTRIBUTE_MALLOC
232 xstrdup (const char *s)
233 {
234 char *result = strdup (s);
235 if (result == NULL)
236 {
237 perror ("strdup");
238 exit (EXIT_FAILURE);
239 }
240 return result;
241 }
242
243
244 #if !defined HAVE_GET_CURRENT_DIR_NAME || defined BROKEN_GET_CURRENT_DIR_NAME
245
246 char *get_current_dir_name (void);
247
248
249
250
251 char *
252 get_current_dir_name (void)
253 {
254
255
256 ptrdiff_t dirsize_max = min (PTRDIFF_MAX, SIZE_MAX) - 1;
257
258
259
260 ptrdiff_t bufsize_max = dirsize_max;
261 #ifdef PATH_MAX
262 bufsize_max = min (bufsize_max, PATH_MAX);
263 #endif
264
265 struct stat dotstat, pwdstat;
266 size_t pwdlen;
267
268
269
270 char const *pwd = egetenv ("PWD");
271 if (pwd
272 && (pwdlen = strnlen (pwd, bufsize_max)) < bufsize_max
273 && IS_DIRECTORY_SEP (pwd[pwdlen && IS_DEVICE_SEP (pwd[1]) ? 2 : 0])
274 && stat (pwd, &pwdstat) == 0
275 && stat (".", &dotstat) == 0
276 && dotstat.st_ino == pwdstat.st_ino
277 && dotstat.st_dev == pwdstat.st_dev)
278 return strdup (pwd);
279 else
280 {
281 ptrdiff_t buf_size = min (bufsize_max, 1024);
282 for (;;)
283 {
284 char *buf = malloc (buf_size);
285 if (!buf)
286 return NULL;
287 if (getcwd (buf, buf_size) == buf)
288 return buf;
289 free (buf);
290 if (errno != ERANGE || buf_size == bufsize_max)
291 return NULL;
292 buf_size = buf_size <= bufsize_max / 2 ? 2 * buf_size : bufsize_max;
293 }
294 }
295 }
296 #endif
297
298 #ifdef WINDOWSNT
299
300 # define REG_ROOT "SOFTWARE\\GNU\\Emacs"
301
302 char *w32_get_resource (HKEY, const char *, LPDWORD);
303
304
305
306
307 char *
308 w32_get_resource (HKEY predefined, const char *key, LPDWORD type)
309 {
310 HKEY hrootkey = NULL;
311 char *result = NULL;
312 DWORD cbData;
313
314 if (RegOpenKeyEx (predefined, REG_ROOT, 0, KEY_READ, &hrootkey)
315 == ERROR_SUCCESS)
316 {
317 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData)
318 == ERROR_SUCCESS)
319 {
320 result = xmalloc (cbData);
321
322 if ((RegQueryValueEx (hrootkey, key, NULL, type, (LPBYTE) result,
323 &cbData)
324 != ERROR_SUCCESS)
325 || *result == 0)
326 {
327 free (result);
328 result = NULL;
329 }
330 }
331
332 RegCloseKey (hrootkey);
333 }
334
335 return result;
336 }
337
338
339
340
341
342
343
344
345
346 char *
347 w32_getenv (const char *envvar)
348 {
349 char *value;
350 DWORD dwType;
351
352 if ((value = getenv (envvar)))
353
354
355 return xstrdup (value);
356
357 if (! (value = w32_get_resource (HKEY_CURRENT_USER, envvar, &dwType)) &&
358 ! (value = w32_get_resource (HKEY_LOCAL_MACHINE, envvar, &dwType)))
359 {
360
361 if (strcmp (envvar, "TERM") == 0)
362 return xstrdup ("w32console");
363
364 return NULL;
365 }
366
367 if (dwType == REG_SZ)
368
369 return value;
370
371 if (dwType == REG_EXPAND_SZ)
372 {
373 DWORD size;
374
375 if ((size = ExpandEnvironmentStrings (value, NULL, 0)))
376 {
377 char *buffer = xmalloc (size);
378 if (ExpandEnvironmentStrings (value, buffer, size))
379 {
380
381 free (value);
382 return buffer;
383 }
384
385
386 free (buffer);
387 }
388 }
389
390
391 free (value);
392 return NULL;
393 }
394
395 int w32_window_app (void);
396
397 int
398 w32_window_app (void)
399 {
400 static int window_app = -1;
401 char szTitle[MAX_PATH];
402
403 if (window_app < 0)
404 {
405
406
407 window_app = (GetConsoleTitleA (szTitle, MAX_PATH) == 0);
408 if (window_app)
409 InitCommonControls ();
410 }
411
412 return window_app;
413 }
414
415
416
417
418
419
420
421
422
423 int w32_execvp (const char *, char **);
424
425 int
426 w32_execvp (const char *path, char **argv)
427 {
428 int i;
429
430
431 argv[0] = (char *) alternate_editor;
432
433 for (i = 0; argv[i]; i++)
434 if (strchr (argv[i], ' '))
435 {
436 char *quoted = alloca (strlen (argv[i]) + 3);
437 sprintf (quoted, "\"%s\"", argv[i]);
438 argv[i] = quoted;
439 }
440
441 return execvp (path, argv);
442 }
443
444 # undef execvp
445 # define execvp w32_execvp
446
447
448 const char *ttyname (int);
449 const char *
450 ttyname (int fd)
451 {
452 return "CONOUT$";
453 }
454
455 #endif
456
457
458
459 static void message (bool, const char *, ...) ATTRIBUTE_FORMAT_PRINTF (2, 3);
460 static void
461 message (bool is_error, const char *format, ...)
462 {
463 va_list args;
464
465 va_start (args, format);
466
467 #ifdef WINDOWSNT
468 if (w32_window_app ())
469 {
470 char msg[2048];
471 vsnprintf (msg, sizeof msg, format, args);
472 msg[sizeof msg - 1] = '\0';
473
474 if (is_error)
475 MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
476 else
477 MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
478 }
479 else
480 #endif
481 {
482 FILE *f = is_error ? stderr : stdout;
483
484 vfprintf (f, format, args);
485 fflush (f);
486 }
487
488 va_end (args);
489 }
490
491
492
493
494 static void
495 decode_options (int argc, char **argv)
496 {
497 alternate_editor = egetenv ("ALTERNATE_EDITOR");
498 tramp_prefix = egetenv ("EMACSCLIENT_TRAMP");
499
500 while (true)
501 {
502 int opt = getopt_long_only (argc, argv, shortopts, longopts, NULL);
503 if (opt < 0)
504 break;
505
506 char* endptr;
507 switch (opt)
508 {
509 case 0:
510
511
512 break;
513
514 case 'a':
515 alternate_editor = optarg;
516 break;
517
518 #ifdef SOCKETS_IN_FILE_SYSTEM
519 case 's':
520 socket_name = optarg;
521 break;
522 #endif
523
524 case 'f':
525 server_file = optarg;
526 break;
527
528
529
530
531
532 case 'd':
533 display = optarg;
534 break;
535
536 case 'n':
537 nowait = true;
538 break;
539
540 case 'w':
541 timeout = strtoumax (optarg, &endptr, 10);
542 if (timeout <= 0 ||
543 ((timeout == INTMAX_MAX || timeout == INTMAX_MIN)
544 && errno == ERANGE))
545 {
546 fprintf (stderr, "Invalid timeout: \"%s\"\n", optarg);
547 exit (EXIT_FAILURE);
548 }
549 break;
550
551 case 'e':
552 eval = true;
553 break;
554
555 case 'q':
556 quiet = true;
557 break;
558
559 case 'u':
560 suppress_output = true;
561 break;
562
563 case 'V':
564 message (false, "emacsclient %s\n", PACKAGE_VERSION);
565 exit (EXIT_SUCCESS);
566 break;
567
568 case 't':
569 tty = true;
570 create_frame = true;
571 reuse_frame = false;
572 break;
573
574 case 'c':
575 create_frame = true;
576 break;
577
578 case 'r':
579 create_frame = true;
580 if (!tty)
581 reuse_frame = true;
582 break;
583
584 case 'p':
585 parent_id = optarg;
586 create_frame = true;
587 break;
588
589 case 'H':
590 print_help_and_exit ();
591 break;
592
593 case 'F':
594 frame_parameters = optarg;
595 break;
596
597 case 'T':
598 tramp_prefix = optarg;
599 break;
600
601 default:
602 message (true, "Try '%s --help' for more information\n", progname);
603 exit (EXIT_FAILURE);
604 break;
605 }
606 }
607
608
609
610
611
612
613
614
615
616
617
618
619 if (create_frame && !tty && !display)
620 {
621
622
623 #if defined (NS_IMPL_COCOA)
624 alt_display = "ns";
625 #elif defined (HAVE_NTGUI)
626 alt_display = "w32";
627 #elif defined (HAVE_HAIKU)
628 alt_display = "be";
629 #elif defined (HAVE_ANDROID)
630 alt_display = "android";
631 #endif
632
633 #ifdef HAVE_PGTK
634 display = egetenv ("WAYLAND_DISPLAY");
635 alt_display = egetenv ("DISPLAY");
636 #else
637 display = egetenv ("DISPLAY");
638 #endif
639 }
640
641 if (!display)
642 {
643 display = alt_display;
644 alt_display = NULL;
645 }
646
647
648 if (display && !display[0])
649 display = NULL;
650
651
652 if (create_frame && !display)
653 tty = true;
654
655 #ifdef WINDOWSNT
656
657
658
659
660
661
662 if (create_frame)
663 {
664 display = NULL;
665 tty = true;
666 }
667 #endif
668 }
669
670
671 static _Noreturn void
672 print_help_and_exit (void)
673 {
674
675
676
677
678 message (false,
679 "Usage: %s [OPTIONS] FILE...\n%s%s%s", progname, "\
680 Tell the Emacs server to visit the specified files.\n\
681 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
682 \n\
683 The following OPTIONS are accepted:\n\
684 -V, --version Just print version info and return\n\
685 -H, --help Print this usage information message\n\
686 -nw, -t, --tty Open a new Emacs frame on the current terminal\n\
687 -c, --create-frame Create a new frame instead of trying to\n\
688 use the current Emacs frame\n\
689 -r, --reuse-frame Create a new frame if none exists, otherwise\n\
690 use the current Emacs frame\n\
691 ", "\
692 -F ALIST, --frame-parameters=ALIST\n\
693 Set the parameters of a new frame\n\
694 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
695 -n, --no-wait Don't wait for the server to return\n\
696 -w, --timeout=SECONDS Seconds to wait before timing out\n\
697 -q, --quiet Don't display messages on success\n\
698 -u, --suppress-output Don't display return values from the server\n\
699 -d DISPLAY, --display=DISPLAY\n\
700 Visit the file in the given display\n\
701 ", "\
702 --parent-id=ID Open in parent window ID, via XEmbed\n"
703 #ifdef SOCKETS_IN_FILE_SYSTEM
704 "-s SOCKET, --socket-name=SOCKET\n\
705 Set filename of the UNIX socket for communication\n"
706 #endif
707 "-f SERVER, --server-file=SERVER\n\
708 Set filename of the TCP authentication file\n\
709 -a EDITOR, --alternate-editor=EDITOR\n\
710 Editor to fallback to if the server is not running\n"
711 " If EDITOR is the empty string, start Emacs in daemon\n\
712 mode and try connecting again\n"
713 "-T PREFIX, --tramp=PREFIX\n\
714 PREFIX to prepend to filenames sent by emacsclient\n\
715 for locating files remotely via Tramp\n"
716 "\n\
717 Report bugs with M-x report-emacs-bug.\n");
718 exit (EXIT_SUCCESS);
719 }
720
721
722
723
724
725 static _Noreturn void
726 fail (void)
727 {
728 if (alternate_editor)
729 {
730 size_t extra_args_size = (main_argc - optind + 1) * sizeof (char *);
731 size_t new_argv_size = extra_args_size;
732 char **new_argv = xmalloc (new_argv_size);
733 char *s = xstrdup (alternate_editor);
734 ptrdiff_t toks = 0;
735
736
737 for (char *tok = s; tok != NULL && *tok != '\0';)
738 {
739
740 ++toks;
741 new_argv = xrealloc (new_argv,
742 new_argv_size + toks * sizeof (char *));
743
744
745
746 size_t skip = strspn (tok, " \"");
747 tok += skip;
748 char sep = (skip > 0 && tok[-1] == '"') ? '"' : ' ';
749
750
751 new_argv[toks - 1] = tok;
752
753
754 tok = strchr (tok, sep);
755 if (tok != NULL)
756 *tok++ = '\0';
757 }
758
759
760 memcpy (&new_argv[toks], main_argv + optind, extra_args_size);
761
762 execvp (*new_argv, new_argv);
763 message (true, "%s: error executing alternate editor \"%s\"\n",
764 progname, alternate_editor);
765 }
766 exit (EXIT_FAILURE);
767 }
768
769
770 #ifdef SOCKETS_IN_FILE_SYSTEM
771 static void act_on_signals (HSOCKET);
772 #else
773 static void act_on_signals (HSOCKET s) {}
774 static void init_signals (void) {}
775 #endif
776
777 enum { AUTH_KEY_LENGTH = 64 };
778
779 static void
780 sock_err_message (const char *function_name)
781 {
782 #ifdef WINDOWSNT
783
784
785
786 if (w32_window_app () && alternate_editor)
787 return;
788
789 char *msg = NULL;
790
791 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
792 | FORMAT_MESSAGE_ALLOCATE_BUFFER
793 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
794 NULL, WSAGetLastError (), 0, (LPTSTR)&msg, 0, NULL);
795
796 message (true, "%s: %s: %s\n", progname, function_name, msg);
797
798 LocalFree (msg);
799 #else
800 message (true, "%s: %s: %s\n", progname, function_name, strerror (errno));
801 #endif
802 }
803
804
805
806
807
808
809 static void
810 send_to_emacs (HSOCKET s, const char *data)
811 {
812 enum { SEND_BUFFER_SIZE = 4096 };
813
814
815 static char send_buffer[SEND_BUFFER_SIZE + 1];
816
817
818 static int sblen;
819
820 for (ptrdiff_t dlen = strlen (data); dlen != 0; )
821 {
822 int part = min (dlen, SEND_BUFFER_SIZE - sblen);
823 memcpy (&send_buffer[sblen], data, part);
824 data += part;
825 sblen += part;
826
827 if (sblen == SEND_BUFFER_SIZE
828 || (0 < sblen && send_buffer[sblen - 1] == '\n'))
829 {
830 int sent;
831 while ((sent = send (s, send_buffer, sblen, 0)) < 0)
832 {
833 if (errno != EINTR)
834 {
835 message (true, "%s: failed to send %d bytes to socket: %s\n",
836 progname, sblen, strerror (errno));
837 fail ();
838 }
839
840
841
842 act_on_signals (INVALID_SOCKET);
843 }
844 sblen -= sent;
845 memmove (send_buffer, &send_buffer[sent], sblen);
846 }
847
848 dlen -= part;
849 }
850 }
851
852
853
854
855
856
857
858 static void
859 quote_argument (HSOCKET s, const char *str)
860 {
861 char *copy = xmalloc (strlen (str) * 2 + 1);
862 char *q = copy;
863 if (*str == '-')
864 *q++ = '&', *q++ = *str++;
865 for (; *str; str++)
866 {
867 char c = *str;
868 if (c == ' ')
869 *q++ = '&', c = '_';
870 else if (c == '\n')
871 *q++ = '&', c = 'n';
872 else if (c == '&')
873 *q++ = '&';
874 *q++ = c;
875 }
876 *q = 0;
877
878 send_to_emacs (s, copy);
879
880 free (copy);
881 }
882
883
884
885
886
887 static char *
888 unquote_argument (char *str)
889 {
890 char const *p = str;
891 char *q = str;
892 char c;
893
894 do
895 {
896 c = *p++;
897 if (c == '&')
898 {
899 c = *p++;
900 if (c == '_')
901 c = ' ';
902 else if (c == 'n')
903 c = '\n';
904 }
905 *q++ = c;
906 }
907 while (c);
908
909 return str;
910 }
911
912
913 #ifdef WINDOWSNT
914
915 void __cdecl close_winsock (void);
916 void __cdecl
917 close_winsock (void)
918 {
919 WSACleanup ();
920 }
921
922
923 void initialize_sockets (void);
924 void
925 initialize_sockets (void)
926 {
927 WSADATA wsaData;
928
929 if (WSAStartup (MAKEWORD (2, 0), &wsaData))
930 {
931 message (true, "%s: error initializing WinSock2\n", progname);
932 exit (EXIT_FAILURE);
933 }
934
935 atexit (close_winsock);
936 }
937 #endif
938
939
940
941
942
943
944 static FILE *
945 open_config (char const *home, char const *xdg, char const *config_file)
946 {
947 ptrdiff_t xdgsubdirsize = xdg ? strlen (xdg) + sizeof "/emacs/server/" : 0;
948 ptrdiff_t homesuffixsizemax = max (sizeof "/.config/emacs/server/",
949 sizeof "/.emacs.d/server/");
950 ptrdiff_t homesubdirsizemax = home ? strlen (home) + homesuffixsizemax : 0;
951 char *configname = xmalloc (max (xdgsubdirsize, homesubdirsizemax)
952 + strlen (config_file));
953 FILE *config;
954
955 if (home)
956 {
957 strcpy (stpcpy (stpcpy (configname, home), "/.emacs.d/server/"),
958 config_file);
959 config = fopen (configname, "rb");
960 }
961 else
962 config = NULL;
963
964 if (! config && (xdg || home))
965 {
966 strcpy ((xdg
967 ? stpcpy (stpcpy (configname, xdg), "/emacs/server/")
968 : stpcpy (stpcpy (configname, home), "/.config/emacs/server/")),
969 config_file);
970 config = fopen (configname, "rb");
971 }
972
973 free (configname);
974 return config;
975 }
976
977
978
979
980 static bool
981 get_server_config (const char *config_file, struct sockaddr_in *server,
982 char *authentication)
983 {
984 char dotted[32];
985 char *port;
986 FILE *config;
987
988 if (IS_ABSOLUTE_FILE_NAME (config_file))
989 config = fopen (config_file, "rb");
990 else
991 {
992 char const *xdg = egetenv ("XDG_CONFIG_HOME");
993 config = open_config (egetenv ("HOME"), xdg, config_file);
994 #ifdef WINDOWSNT
995 if (!config)
996 config = open_config (egetenv ("APPDATA"), xdg, config_file);
997 #endif
998 }
999
1000 if (! config)
1001 return false;
1002
1003 if (fgets (dotted, sizeof dotted, config)
1004 && (port = strchr (dotted, ':')))
1005 *port++ = '\0';
1006 else
1007 {
1008 message (true, "%s: invalid configuration info\n", progname);
1009 exit (EXIT_FAILURE);
1010 }
1011
1012 memset (server, 0, sizeof *server);
1013 server->sin_family = AF_INET;
1014 server->sin_addr.s_addr = inet_addr (dotted);
1015 server->sin_port = htons (atoi (port));
1016
1017 if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
1018 {
1019 message (true, "%s: cannot read authentication info\n", progname);
1020 exit (EXIT_FAILURE);
1021 }
1022
1023 fclose (config);
1024
1025 return true;
1026 }
1027
1028
1029
1030
1031 static HSOCKET
1032 cloexec_socket (int domain, int type, int protocol)
1033 {
1034 #ifdef SOCK_CLOEXEC
1035 return socket (domain, type | SOCK_CLOEXEC, protocol);
1036 #else
1037 HSOCKET s = socket (domain, type, protocol);
1038 # ifndef WINDOWSNT
1039 if (0 <= s)
1040 fcntl (s, F_SETFD, FD_CLOEXEC);
1041 # endif
1042 return s;
1043 #endif
1044 }
1045
1046 static HSOCKET
1047 set_tcp_socket (const char *local_server_file)
1048 {
1049 union {
1050 struct sockaddr_in in;
1051 struct sockaddr sa;
1052 } server;
1053 struct linger l_arg = { .l_onoff = 1, .l_linger = 1 };
1054 char auth_string[AUTH_KEY_LENGTH + 1];
1055
1056 if (! get_server_config (local_server_file, &server.in, auth_string))
1057 return INVALID_SOCKET;
1058
1059 if (server.in.sin_addr.s_addr != inet_addr ("127.0.0.1") && !quiet)
1060 message (false, "%s: connected to remote socket at %s\n",
1061 progname, inet_ntoa (server.in.sin_addr));
1062
1063
1064 HSOCKET s = cloexec_socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1065 if (s < 0)
1066 {
1067
1068
1069
1070
1071 sock_err_message ("socket");
1072 return INVALID_SOCKET;
1073 }
1074
1075
1076 if (connect (s, &server.sa, sizeof server.in) != 0)
1077 {
1078 sock_err_message ("connect");
1079 CLOSE_SOCKET (s);
1080 return INVALID_SOCKET;
1081 }
1082
1083
1084
1085 int ret = setsockopt (s, SOL_SOCKET, SO_LINGER, (const char *) &l_arg, sizeof l_arg);
1086 if (ret < 0)
1087 sock_err_message ("setsockopt");
1088
1089
1090 auth_string[AUTH_KEY_LENGTH] = '\0';
1091
1092 send_to_emacs (s, "-auth ");
1093 send_to_emacs (s, auth_string);
1094 send_to_emacs (s, " ");
1095
1096 return s;
1097 }
1098
1099
1100
1101 static bool
1102 strprefix (const char *prefix, const char *string)
1103 {
1104 return !strncmp (prefix, string, strlen (prefix));
1105 }
1106
1107
1108
1109
1110
1111 static bool
1112 find_tty (const char **tty_type, const char **tty_name, bool noabort)
1113 {
1114 const char *type = egetenv ("TERM");
1115 const char *name = ttyname (STDOUT_FILENO);
1116
1117 if (!name)
1118 {
1119 if (noabort)
1120 return false;
1121 message (true, "%s: could not get terminal name\n", progname);
1122 fail ();
1123 }
1124
1125 if (!type)
1126 {
1127 if (noabort)
1128 return false;
1129 message (true, "%s: please set the TERM variable to your terminal type\n",
1130 progname);
1131 fail ();
1132 }
1133
1134 const char *inside_emacs = egetenv ("INSIDE_EMACS");
1135 if (inside_emacs && strstr (inside_emacs, ",term:")
1136 && strprefix ("eterm", type))
1137 {
1138 if (noabort)
1139 return false;
1140
1141 message (true, ("%s: opening a frame in an Emacs term buffer"
1142 " is not supported\n"),
1143 progname);
1144 fail ();
1145 }
1146
1147 *tty_name = name;
1148 *tty_type = type;
1149 return true;
1150 }
1151
1152
1153
1154
1155
1156
1157
1158
1159 static pid_t
1160 process_grouping (void)
1161 {
1162 #ifdef SOCKETS_IN_FILE_SYSTEM
1163 pid_t tcpgrp = tcgetpgrp (STDOUT_FILENO);
1164 if (0 <= tcpgrp)
1165 {
1166 pid_t pgrp = getpgrp ();
1167 return tcpgrp == pgrp ? pgrp : -pgrp;
1168 }
1169 #endif
1170 return 0;
1171 }
1172
1173 #ifdef SOCKETS_IN_FILE_SYSTEM
1174
1175 # include <acl.h>
1176
1177 # ifndef O_PATH
1178 # define O_PATH O_SEARCH
1179 # endif
1180
1181
1182 union local_sockaddr
1183 {
1184 struct sockaddr_un un;
1185 struct sockaddr sa;
1186 };
1187
1188
1189
1190
1191
1192
1193 static int
1194 connect_socket (int dirfd, char const *addr, int s, uid_t uid)
1195 {
1196 int sock_status = 0;
1197
1198 union local_sockaddr server;
1199 if (sizeof server.un.sun_path <= strlen (addr))
1200 return ENAMETOOLONG;
1201 server.un.sun_family = AF_UNIX;
1202 strcpy (server.un.sun_path, addr);
1203
1204
1205
1206
1207 static int wdfd = -1;
1208
1209 if (dirfd != AT_FDCWD)
1210 {
1211
1212 struct stat st;
1213 if (fstat (dirfd, &st) != 0)
1214 return errno;
1215 if (st.st_uid != uid || (st.st_mode & (S_IWGRP | S_IWOTH)))
1216 return -1;
1217
1218 if (wdfd == -1)
1219 {
1220
1221 wdfd = open (".", O_PATH | O_CLOEXEC);
1222 if (wdfd < 0)
1223 wdfd = -1 - errno;
1224 }
1225 if (wdfd < 0)
1226 return -1 - wdfd;
1227 if (fchdir (dirfd) != 0)
1228 return errno;
1229
1230
1231
1232 int has_acl = file_has_acl (".", &st);
1233 if (has_acl)
1234 sock_status = has_acl < 0 ? errno : -1;
1235 }
1236
1237 if (!sock_status)
1238 sock_status = connect (s, &server.sa, sizeof server.un) == 0 ? 0 : errno;
1239
1240
1241
1242 if (dirfd != AT_FDCWD && fchdir (wdfd) != 0)
1243 {
1244 message (true, "%s: .: %s\n", progname, strerror (errno));
1245 exit (EXIT_FAILURE);
1246 }
1247
1248 return sock_status;
1249 }
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265 static void
1266 reinstall_handler_if_needed (int sig, void (*handler) (int))
1267 {
1268 # ifndef SA_RESETHAND
1269
1270 signal (sig, handler);
1271 # endif
1272 }
1273
1274
1275
1276 static sig_atomic_t volatile
1277 got_sigcont, got_sigtstp, got_sigttou, got_sigwinch;
1278
1279 static void
1280 handle_sigcont (int sig)
1281 {
1282 got_sigcont = 1;
1283 reinstall_handler_if_needed (sig, handle_sigcont);
1284 }
1285 static void
1286 handle_sigtstp (int sig)
1287 {
1288 got_sigtstp = 1;
1289 reinstall_handler_if_needed (sig, handle_sigtstp);
1290 }
1291 static void
1292 handle_sigttou (int sig)
1293 {
1294 got_sigttou = 1;
1295 reinstall_handler_if_needed (sig, handle_sigttou);
1296 }
1297 static void
1298 handle_sigwinch (int sig)
1299 {
1300 got_sigwinch = 1;
1301 reinstall_handler_if_needed (sig, handle_sigwinch);
1302 }
1303
1304
1305
1306
1307
1308 static void
1309 install_handler (int sig, void (*handler) (int), sig_atomic_t volatile *flag)
1310 {
1311 # ifdef SA_RESETHAND
1312 if (flag)
1313 {
1314 struct sigaction oact;
1315 if (sigaction (sig, NULL, &oact) == 0 && oact.sa_handler == SIG_IGN)
1316 return;
1317 }
1318 struct sigaction act = { .sa_handler = handler };
1319 sigemptyset (&act.sa_mask);
1320 sigaction (sig, &act, NULL);
1321 # else
1322 void (*ohandler) (int) = signal (sig, handler);
1323 if (flag)
1324 {
1325 if (ohandler == SIG_IGN)
1326 {
1327 signal (sig, SIG_IGN);
1328
1329
1330 *flag = 0;
1331 }
1332 }
1333 # endif
1334 }
1335
1336
1337
1338 static void
1339 init_signals (void)
1340 {
1341 install_handler (SIGCONT, handle_sigcont, &got_sigcont);
1342 install_handler (SIGTSTP, handle_sigtstp, &got_sigtstp);
1343 install_handler (SIGTTOU, handle_sigttou, &got_sigttou);
1344 install_handler (SIGWINCH, handle_sigwinch, &got_sigwinch);
1345
1346
1347
1348 }
1349
1350
1351
1352
1353 static void
1354 act_on_tty_signal (int sig, void (*handler) (int), HSOCKET emacs_socket)
1355 {
1356
1357
1358
1359
1360
1361 send_to_emacs (emacs_socket, "-suspend \n");
1362
1363
1364
1365 install_handler (sig, SIG_DFL, NULL);
1366 raise (sig);
1367 install_handler (sig, handler, NULL);
1368 }
1369
1370
1371
1372
1373 static void
1374 act_on_signals (HSOCKET emacs_socket)
1375 {
1376 while (true)
1377 {
1378 bool took_action = false;
1379
1380 if (emacs_socket != INVALID_SOCKET)
1381 {
1382 if (got_sigcont)
1383 {
1384 got_sigcont = 0;
1385 took_action = true;
1386 pid_t grouping = process_grouping ();
1387 if (grouping < 0)
1388 {
1389 if (tty)
1390 {
1391
1392 kill (grouping, SIGTTIN);
1393 }
1394 }
1395 else
1396 send_to_emacs (emacs_socket, "-resume \n");
1397 }
1398
1399 if (got_sigtstp)
1400 {
1401 got_sigtstp = 0;
1402 took_action = true;
1403 act_on_tty_signal (SIGTSTP, handle_sigtstp, emacs_socket);
1404 }
1405 if (got_sigttou)
1406 {
1407 got_sigttou = 0;
1408 took_action = true;
1409 act_on_tty_signal (SIGTTOU, handle_sigttou, emacs_socket);
1410 }
1411 }
1412
1413 if (emacs_pid && got_sigwinch)
1414 {
1415 got_sigwinch = 0;
1416 took_action = true;
1417 kill (emacs_pid, SIGWINCH);
1418 }
1419
1420 if (!took_action)
1421 break;
1422 }
1423 }
1424
1425 enum { socknamesize = sizeof ((struct sockaddr_un *) NULL)->sun_path };
1426
1427
1428
1429
1430
1431
1432
1433
1434 static int
1435 local_sockname (int s, char sockname[socknamesize], int tmpdirlen,
1436 uid_t uid, char const *server_name)
1437 {
1438
1439
1440
1441 if (! (0 <= tmpdirlen && tmpdirlen < socknamesize))
1442 return ENAMETOOLONG;
1443
1444
1445
1446 uintmax_t uidmax = uid;
1447 int suffixlen = snprintf (sockname + tmpdirlen, socknamesize - tmpdirlen,
1448 "/emacs%"PRIuMAX"/%s", uidmax, server_name);
1449 if (! (0 <= suffixlen && suffixlen < socknamesize - tmpdirlen))
1450 return ENAMETOOLONG;
1451
1452
1453
1454
1455
1456 char *emacsdirend = sockname + tmpdirlen + suffixlen -
1457 strlen(server_name) - 1;
1458 *emacsdirend = '\0';
1459 int dir = open (sockname, O_PATH | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
1460 *emacsdirend = '/';
1461 if (dir < 0)
1462 return errno;
1463 int sock_status = connect_socket (dir, server_name, s, uid);
1464 close (dir);
1465 return sock_status;
1466 }
1467
1468
1469
1470
1471
1472
1473 static HSOCKET
1474 set_local_socket (char const *server_name)
1475 {
1476 union local_sockaddr server;
1477 int sock_status;
1478 char *sockname = server.un.sun_path;
1479 int tmpdirlen = -1;
1480 int socknamelen = -1;
1481 uid_t uid = geteuid ();
1482 bool tmpdir_used = false;
1483 int s = cloexec_socket (AF_UNIX, SOCK_STREAM, 0);
1484 if (s < 0)
1485 {
1486 message (true, "%s: can't create socket: %s\n",
1487 progname, strerror (errno));
1488 fail ();
1489 }
1490
1491 if (strchr (server_name, '/')
1492 || (ISSLASH ('\\') && strchr (server_name, '\\')))
1493 {
1494 socknamelen = snprintf (sockname, socknamesize, "%s", server_name);
1495 sock_status = (0 <= socknamelen && socknamelen < socknamesize
1496 ? connect_socket (AT_FDCWD, sockname, s, 0)
1497 : ENAMETOOLONG);
1498 }
1499 else
1500 {
1501
1502 char const *xdg_runtime_dir = egetenv ("XDG_RUNTIME_DIR");
1503 if (xdg_runtime_dir)
1504 {
1505 socknamelen = snprintf (sockname, socknamesize, "%s/emacs/%s",
1506 xdg_runtime_dir, server_name);
1507 sock_status = (0 <= socknamelen && socknamelen < socknamesize
1508 ? connect_socket (AT_FDCWD, sockname, s, 0)
1509 : ENAMETOOLONG);
1510 }
1511 else
1512 {
1513 char const *tmpdir = egetenv ("TMPDIR");
1514 if (tmpdir)
1515 tmpdirlen = snprintf (sockname, socknamesize, "%s", tmpdir);
1516 else
1517 {
1518 # ifdef DARWIN_OS
1519 # ifndef _CS_DARWIN_USER_TEMP_DIR
1520 # define _CS_DARWIN_USER_TEMP_DIR 65537
1521 # endif
1522 size_t n = confstr (_CS_DARWIN_USER_TEMP_DIR,
1523 sockname, socknamesize);
1524 if (0 < n && n < (size_t) -1)
1525 tmpdirlen = min (n - 1, socknamesize);
1526 # endif
1527 if (tmpdirlen < 0)
1528 tmpdirlen = snprintf (sockname, socknamesize, "/tmp");
1529 }
1530 sock_status = local_sockname (s, sockname, tmpdirlen,
1531 uid, server_name);
1532 tmpdir_used = true;
1533 }
1534 }
1535
1536 if (sock_status == 0)
1537 return s;
1538
1539 if (sock_status == ENAMETOOLONG)
1540 {
1541 message (true, "%s: socket-name %s... too long\n", progname, sockname);
1542 fail ();
1543 }
1544
1545 if (tmpdir_used)
1546 {
1547
1548
1549
1550
1551
1552 char const *user_name = egetenv ("LOGNAME");
1553
1554 if (!user_name)
1555 user_name = egetenv ("USER");
1556
1557 if (user_name)
1558 {
1559 struct passwd *pw = getpwnam (user_name);
1560
1561 if (pw && pw->pw_uid != uid)
1562 {
1563
1564 sock_status = local_sockname (s, sockname, tmpdirlen,
1565 pw->pw_uid, server_name);
1566 if (sock_status == 0)
1567 return s;
1568 if (sock_status == ENAMETOOLONG)
1569 {
1570 message (true, "%s: socket-name %s... too long\n",
1571 progname, sockname);
1572 exit (EXIT_FAILURE);
1573 }
1574 }
1575 }
1576 }
1577
1578 close (s);
1579
1580 if (sock_status == -1)
1581 message (true,
1582 "%s: Invalid permissions on parent directory of socket: %s\n",
1583 progname, sockname);
1584 else if (sock_status == ENOENT)
1585 {
1586 if (tmpdir_used)
1587 {
1588 uintmax_t id = uid;
1589 char sockdirname[socknamesize];
1590 int sockdirnamelen = snprintf (sockdirname, sizeof sockdirname,
1591 "/run/user/%"PRIuMAX, id);
1592 if (0 <= sockdirnamelen && sockdirnamelen < sizeof sockdirname
1593 && faccessat (AT_FDCWD, sockdirname, X_OK, AT_EACCESS) == 0)
1594 message
1595 (true,
1596 ("%s: Should XDG_RUNTIME_DIR='%s' be in the environment?\n"
1597 "%s: (Be careful: XDG_RUNTIME_DIR is security-related.)\n"),
1598 progname, sockdirname, progname);
1599 }
1600
1601
1602
1603 if (!quiet || !alternate_editor)
1604 {
1605 message (true,
1606 ("%s: can't find socket; have you started the server?\n"
1607 "%s: To start the server in Emacs,"
1608 " type \"M-x server-start\".\n"),
1609 progname, progname);
1610 }
1611 }
1612 else
1613 message (true, "%s: can't connect to %s: %s\n",
1614 progname, sockname, strerror (sock_status));
1615
1616 return INVALID_SOCKET;
1617 }
1618 #endif
1619
1620 static HSOCKET
1621 set_socket (bool no_exit_if_error)
1622 {
1623 HSOCKET s;
1624 const char *local_server_file = server_file;
1625
1626 INITIALIZE ();
1627
1628 #ifdef SOCKETS_IN_FILE_SYSTEM
1629 if (!socket_name)
1630 socket_name = egetenv ("EMACS_SOCKET_NAME");
1631
1632 if (socket_name)
1633 {
1634
1635 s = set_local_socket (socket_name);
1636 if (s != INVALID_SOCKET || no_exit_if_error)
1637 return s;
1638 message (true, "%s: error accessing socket \"%s\"\n",
1639 progname, socket_name);
1640 exit (EXIT_FAILURE);
1641 }
1642 #endif
1643
1644
1645 if (!local_server_file)
1646 local_server_file = egetenv ("EMACS_SERVER_FILE");
1647
1648 if (local_server_file)
1649 {
1650 s = set_tcp_socket (local_server_file);
1651 if (s != INVALID_SOCKET || no_exit_if_error)
1652 return s;
1653
1654 message (true, "%s: error accessing server file \"%s\"\n",
1655 progname, local_server_file);
1656 exit (EXIT_FAILURE);
1657 }
1658
1659 #ifdef SOCKETS_IN_FILE_SYSTEM
1660
1661 s = set_local_socket ("server");
1662 if (s != INVALID_SOCKET)
1663 return s;
1664 #endif
1665
1666
1667 s = set_tcp_socket ("server");
1668 if (s != INVALID_SOCKET || no_exit_if_error)
1669 return s;
1670
1671
1672 message (true, "%s: No socket or alternate editor. Please use:\n\n"
1673 #ifdef SOCKETS_IN_FILE_SYSTEM
1674 "\t--socket-name\n"
1675 #endif
1676 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1677 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1678 progname);
1679 exit (EXIT_FAILURE);
1680 }
1681
1682 #ifdef HAVE_NTGUI
1683 FARPROC set_fg;
1684 FARPROC get_wc;
1685
1686 void w32_set_user_model_id (void);
1687
1688 void
1689 w32_set_user_model_id (void)
1690 {
1691 HMODULE shell;
1692 HRESULT (WINAPI * set_user_model) (const wchar_t * id);
1693
1694
1695
1696
1697 shell = LoadLibrary ("shell32.dll");
1698 if (shell)
1699 {
1700 set_user_model
1701 = (void *) GetProcAddress (shell,
1702 "SetCurrentProcessExplicitAppUserModelID");
1703
1704
1705
1706
1707
1708 if (set_user_model)
1709 set_user_model (L"GNU.Emacs");
1710
1711 FreeLibrary (shell);
1712 }
1713 }
1714
1715 BOOL CALLBACK w32_find_emacs_process (HWND, LPARAM);
1716
1717 BOOL CALLBACK
1718 w32_find_emacs_process (HWND hWnd, LPARAM lParam)
1719 {
1720 DWORD pid;
1721 char class[6];
1722
1723
1724 if (! get_wc (hWnd, class, sizeof (class))
1725 || strcmp (class, "Emacs"))
1726 return TRUE;
1727
1728
1729 (void) GetWindowThreadProcessId (hWnd, &pid);
1730
1731
1732 if (pid != (DWORD) emacs_pid) return TRUE;
1733
1734
1735 set_fg (emacs_pid);
1736
1737
1738 return FALSE;
1739 }
1740
1741
1742
1743 void w32_give_focus (void);
1744
1745 void
1746 w32_give_focus (void)
1747 {
1748 HANDLE user32;
1749
1750
1751 if (!emacs_pid) return;
1752
1753 user32 = GetModuleHandle ("user32.dll");
1754
1755 if (!user32)
1756 return;
1757
1758
1759
1760
1761
1762 if ((set_fg = GetProcAddress (user32, "AllowSetForegroundWindow"))
1763 && (get_wc = GetProcAddress (user32, "RealGetWindowClassA")))
1764 EnumWindows (w32_find_emacs_process, (LPARAM) 0);
1765 }
1766 #endif
1767
1768
1769
1770 static HSOCKET
1771 start_daemon_and_retry_set_socket (void)
1772 {
1773 #ifndef WINDOWSNT
1774 pid_t dpid;
1775 int status;
1776
1777 dpid = fork ();
1778
1779 if (dpid > 0)
1780 {
1781 pid_t w = waitpid (dpid, &status, WUNTRACED | WCONTINUED);
1782
1783 if (w < 0 || !WIFEXITED (status) || WEXITSTATUS (status))
1784 {
1785 message (true, "Error: Could not start the Emacs daemon\n");
1786 exit (EXIT_FAILURE);
1787 }
1788
1789
1790 if (!quiet)
1791 message (true,
1792 "Emacs daemon should have started, trying to connect again\n");
1793 }
1794 else if (dpid < 0)
1795 {
1796 fprintf (stderr, "Error: Cannot fork!\n");
1797 exit (EXIT_FAILURE);
1798 }
1799 else
1800 {
1801 char emacs[] = "emacs";
1802 char daemon_option[] = "--daemon";
1803 char *d_argv[3];
1804 d_argv[0] = emacs;
1805 d_argv[1] = daemon_option;
1806 d_argv[2] = 0;
1807 # ifdef SOCKETS_IN_FILE_SYSTEM
1808 if (socket_name != NULL)
1809 {
1810
1811 const char *deq = "--daemon=";
1812 char *daemon_arg = xmalloc (strlen (deq)
1813 + strlen (socket_name) + 1);
1814 strcpy (stpcpy (daemon_arg, deq), socket_name);
1815 d_argv[1] = daemon_arg;
1816 }
1817 # endif
1818 execvp ("emacs", d_argv);
1819 message (true, "%s: error starting emacs daemon\n", progname);
1820 exit (EXIT_FAILURE);
1821 }
1822 #else
1823 DWORD wait_result;
1824 HANDLE w32_daemon_event;
1825 STARTUPINFO si;
1826 PROCESS_INFORMATION pi;
1827
1828 ZeroMemory (&si, sizeof si);
1829 si.cb = sizeof si;
1830 ZeroMemory (&pi, sizeof pi);
1831
1832
1833
1834
1835
1836 if (!CreateProcess (NULL, (LPSTR)"emacs --daemon", NULL, NULL, FALSE,
1837 CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
1838 {
1839 char* msg = NULL;
1840
1841 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
1842 | FORMAT_MESSAGE_ALLOCATE_BUFFER
1843 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1844 NULL, GetLastError (), 0, (LPTSTR)&msg, 0, NULL);
1845 message (true, "%s: error starting emacs daemon (%s)\n", progname, msg);
1846 exit (EXIT_FAILURE);
1847 }
1848
1849 w32_daemon_event = CreateEvent (NULL, TRUE, FALSE, W32_DAEMON_EVENT);
1850 if (w32_daemon_event == NULL)
1851 {
1852 message (true, "Couldn't create Windows daemon event");
1853 exit (EXIT_FAILURE);
1854 }
1855 if ((wait_result = WaitForSingleObject (w32_daemon_event, INFINITE))
1856 != WAIT_OBJECT_0)
1857 {
1858 const char *msg = NULL;
1859
1860 switch (wait_result)
1861 {
1862 case WAIT_ABANDONED:
1863 msg = "The daemon exited unexpectedly";
1864 break;
1865 case WAIT_TIMEOUT:
1866
1867 default:
1868 case WAIT_FAILED:
1869 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
1870 | FORMAT_MESSAGE_ALLOCATE_BUFFER
1871 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1872 NULL, GetLastError (), 0, (LPTSTR)&msg, 0, NULL);
1873 break;
1874 }
1875 message (true, "Error: Could not start the Emacs daemon: %s\n", msg);
1876 exit (EXIT_FAILURE);
1877 }
1878 CloseHandle (w32_daemon_event);
1879
1880
1881
1882
1883 if (!quiet && !w32_window_app ())
1884 message (true,
1885 "Emacs daemon should have started, trying to connect again\n");
1886 #endif
1887
1888 HSOCKET emacs_socket = set_socket (true);
1889 if (emacs_socket == INVALID_SOCKET)
1890 {
1891 message (true,
1892 "Error: Cannot connect even after starting the Emacs daemon\n");
1893 exit (EXIT_FAILURE);
1894 }
1895 return emacs_socket;
1896 }
1897
1898 static void
1899 set_socket_timeout (HSOCKET socket, int seconds)
1900 {
1901 int ret;
1902
1903 #ifndef WINDOWSNT
1904 struct timeval timeout;
1905 timeout.tv_sec = seconds;
1906 timeout.tv_usec = 0;
1907 ret = setsockopt (socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof timeout);
1908 #else
1909 DWORD timeout;
1910
1911 if (seconds > INT_MAX / 1000)
1912 timeout = INT_MAX;
1913 else
1914 timeout = seconds * 1000;
1915 ret = setsockopt (socket, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, sizeof timeout);
1916 #endif
1917
1918 if (ret < 0)
1919 sock_err_message ("setsockopt");
1920 }
1921
1922 static bool
1923 check_socket_timeout (int rl)
1924 {
1925 #ifndef WINDOWSNT
1926 return (rl == -1)
1927 && (errno == EAGAIN)
1928 && (errno == EWOULDBLOCK);
1929 #else
1930 return (rl == SOCKET_ERROR)
1931 && (WSAGetLastError() == WSAETIMEDOUT);
1932 #endif
1933 }
1934
1935 int
1936 main (int argc, char **argv)
1937 {
1938 main_argc = argc;
1939 main_argv = argv;
1940 progname = argv[0] ? argv[0] : "emacsclient";
1941
1942 int rl = 0;
1943 bool skiplf = true;
1944 char string[BUFSIZ + 1];
1945 int exit_status = EXIT_SUCCESS;
1946
1947 #ifdef HAVE_NTGUI
1948
1949
1950
1951
1952 w32_set_user_model_id ();
1953 #endif
1954
1955
1956 decode_options (argc, argv);
1957
1958 if (! (optind < argc || eval || create_frame))
1959 {
1960 message (true, ("%s: file name or argument required\n"
1961 "Try '%s --help' for more information\n"),
1962 progname, progname);
1963 exit (EXIT_FAILURE);
1964 }
1965
1966 #ifdef SOCKETS_IN_FILE_SYSTEM
1967 if (tty)
1968 {
1969 pid_t grouping = process_grouping ();
1970 if (grouping < 0)
1971 kill (grouping, SIGTTIN);
1972 }
1973 #endif
1974
1975
1976
1977 bool start_daemon_if_needed = alternate_editor && !alternate_editor[0];
1978
1979 HSOCKET emacs_socket = set_socket (alternate_editor
1980 || start_daemon_if_needed);
1981 if (emacs_socket == INVALID_SOCKET)
1982 {
1983 if (! start_daemon_if_needed)
1984 fail ();
1985
1986 emacs_socket = start_daemon_and_retry_set_socket ();
1987 }
1988
1989 char *cwd = get_current_dir_name ();
1990 if (cwd == 0)
1991 {
1992 message (true, "%s: %s\n", progname,
1993 "Cannot get current working directory");
1994 fail ();
1995 }
1996
1997 #ifdef HAVE_NTGUI
1998 if (display && !strcmp (display, "w32"))
1999 w32_give_focus ();
2000 #endif
2001
2002
2003 if (create_frame)
2004 {
2005 for (char *const *e = environ; *e; e++)
2006 {
2007 send_to_emacs (emacs_socket, "-env ");
2008 quote_argument (emacs_socket, *e);
2009 send_to_emacs (emacs_socket, " ");
2010 }
2011 }
2012 send_to_emacs (emacs_socket, "-dir ");
2013 if (tramp_prefix)
2014 quote_argument (emacs_socket, tramp_prefix);
2015 quote_argument (emacs_socket, cwd);
2016 free (cwd);
2017 send_to_emacs (emacs_socket, "/");
2018 send_to_emacs (emacs_socket, " ");
2019
2020 retry:
2021 if (nowait)
2022 send_to_emacs (emacs_socket, "-nowait ");
2023
2024 if (!create_frame || reuse_frame)
2025 send_to_emacs (emacs_socket, "-current-frame ");
2026
2027 if (display)
2028 {
2029 send_to_emacs (emacs_socket, "-display ");
2030 quote_argument (emacs_socket, display);
2031 send_to_emacs (emacs_socket, " ");
2032 }
2033
2034 if (parent_id)
2035 {
2036 send_to_emacs (emacs_socket, "-parent-id ");
2037 quote_argument (emacs_socket, parent_id);
2038 send_to_emacs (emacs_socket, " ");
2039 }
2040
2041 if (frame_parameters && create_frame)
2042 {
2043 send_to_emacs (emacs_socket, "-frame-parameters ");
2044 quote_argument (emacs_socket, frame_parameters);
2045 send_to_emacs (emacs_socket, " ");
2046 }
2047
2048
2049
2050
2051 if (create_frame || !eval)
2052 {
2053 const char *tty_type, *tty_name;
2054
2055 if (find_tty (&tty_type, &tty_name, !tty))
2056 {
2057
2058
2059 init_signals ();
2060
2061 send_to_emacs (emacs_socket, "-tty ");
2062 quote_argument (emacs_socket, tty_name);
2063 send_to_emacs (emacs_socket, " ");
2064 quote_argument (emacs_socket, tty_type);
2065 send_to_emacs (emacs_socket, " ");
2066 }
2067 }
2068
2069 if (create_frame && !tty)
2070 send_to_emacs (emacs_socket, "-window-system ");
2071
2072 if (optind < argc)
2073 {
2074 for (int i = optind; i < argc; i++)
2075 {
2076
2077 if (eval)
2078 {
2079
2080 send_to_emacs (emacs_socket, "-eval ");
2081 quote_argument (emacs_socket, argv[i]);
2082 send_to_emacs (emacs_socket, " ");
2083 continue;
2084 }
2085
2086 char *p = argv[i];
2087 if (*p == '+')
2088 {
2089 unsigned char c;
2090 do
2091 c = *++p;
2092 while (isdigit (c) || c == ':');
2093
2094 if (c == 0)
2095 {
2096 send_to_emacs (emacs_socket, "-position ");
2097 quote_argument (emacs_socket, argv[i]);
2098 send_to_emacs (emacs_socket, " ");
2099 continue;
2100 }
2101 }
2102 #ifdef WINDOWSNT
2103 else if (! IS_ABSOLUTE_FILE_NAME (argv[i])
2104 && (isalpha (argv[i][0]) && argv[i][1] == ':'))
2105
2106
2107
2108
2109
2110
2111 {
2112 char *filename = xmalloc (MAX_PATH);
2113 DWORD size;
2114
2115 size = GetFullPathName (argv[i], MAX_PATH, filename, NULL);
2116 if (size > 0 && size < MAX_PATH)
2117 argv[i] = filename;
2118 else
2119 free (filename);
2120 }
2121 #endif
2122
2123 send_to_emacs (emacs_socket, "-file ");
2124 if (tramp_prefix && IS_ABSOLUTE_FILE_NAME (argv[i]))
2125 quote_argument (emacs_socket, tramp_prefix);
2126 quote_argument (emacs_socket, argv[i]);
2127 send_to_emacs (emacs_socket, " ");
2128 }
2129 }
2130 else if (eval)
2131 {
2132
2133 while (fgets (string, BUFSIZ, stdin))
2134 {
2135 send_to_emacs (emacs_socket, "-eval ");
2136 quote_argument (emacs_socket, string);
2137 }
2138 send_to_emacs (emacs_socket, " ");
2139 }
2140
2141 send_to_emacs (emacs_socket, "\n");
2142
2143
2144 if (!eval && !tty && !nowait && !quiet && 0 <= process_grouping ())
2145 {
2146 printf ("Waiting for Emacs...");
2147 skiplf = false;
2148 }
2149 fflush (stdout);
2150
2151 set_socket_timeout (emacs_socket, timeout > 0 ? timeout : DEFAULT_TIMEOUT);
2152 bool saw_response = false;
2153
2154 while (exit_status == EXIT_SUCCESS)
2155 {
2156 bool retry = true;
2157 bool msg_showed = quiet;
2158 do
2159 {
2160 act_on_signals (emacs_socket);
2161 rl = recv (emacs_socket, string, BUFSIZ, 0);
2162 retry = check_socket_timeout (rl);
2163 if (retry && !saw_response)
2164 {
2165 if (timeout > 0)
2166 {
2167
2168 fprintf (stderr, "\nServer not responding; timed out after %ju seconds",
2169 timeout);
2170 retry = false;
2171 }
2172 else if (!msg_showed)
2173 {
2174 msg_showed = true;
2175 fprintf (stderr, "\nServer not responding; use Ctrl+C to break");
2176 }
2177 }
2178 }
2179 while ((rl < 0 && errno == EINTR) || retry);
2180
2181 if (rl <= 0)
2182 break;
2183
2184 saw_response = true;
2185 string[rl] = '\0';
2186
2187
2188 char *p = string;
2189 for (char *end_p = p; end_p && *end_p != '\0'; p = end_p)
2190 {
2191 end_p = strchr (p, '\n');
2192 if (end_p != NULL)
2193 *end_p++ = '\0';
2194
2195 if (strprefix ("-emacs-pid ", p))
2196 {
2197
2198 emacs_pid = strtoumax (p + strlen ("-emacs-pid"), NULL, 10);
2199 }
2200 else if (strprefix ("-window-system-unsupported ", p))
2201 {
2202
2203
2204
2205 if (alt_display)
2206 {
2207 display = alt_display;
2208 alt_display = NULL;
2209 }
2210 else
2211 {
2212 nowait = false;
2213 tty = true;
2214 }
2215
2216 goto retry;
2217 }
2218 else if (strprefix ("-print ", p))
2219 {
2220
2221 if (!suppress_output)
2222 {
2223 char *str = unquote_argument (p + strlen ("-print "));
2224 printf (&"\n%s"[skiplf], str);
2225 if (str[0])
2226 skiplf = str[strlen (str) - 1] == '\n';
2227 }
2228 }
2229 else if (strprefix ("-print-nonl ", p))
2230 {
2231
2232
2233 if (!suppress_output)
2234 {
2235 char *str = unquote_argument (p + strlen ("-print-nonl "));
2236 printf ("%s", str);
2237 if (str[0])
2238 skiplf = str[strlen (str) - 1] == '\n';
2239 }
2240 }
2241 else if (strprefix ("-error ", p))
2242 {
2243
2244 char *str = unquote_argument (p + strlen ("-error "));
2245 if (!skiplf)
2246 printf ("\n");
2247 message (true, "*ERROR*: %s", str);
2248 if (str[0])
2249 skiplf = str[strlen (str) - 1] == '\n';
2250 exit_status = EXIT_FAILURE;
2251 }
2252 #ifndef WINDOWSNT
2253 else if (strprefix ("-suspend ", p))
2254 {
2255
2256 if (!skiplf)
2257 printf ("\n");
2258 skiplf = true;
2259 kill (0, SIGSTOP);
2260 }
2261 #endif
2262 else
2263 {
2264
2265 printf (&"\n*ERROR*: Unknown message: %s\n"[skiplf], p);
2266 skiplf = true;
2267 }
2268 }
2269 }
2270
2271 if (!skiplf && 0 <= process_grouping ())
2272 printf ("\n");
2273
2274 if (rl < 0)
2275 exit_status = EXIT_FAILURE;
2276
2277 CLOSE_SOCKET (emacs_socket);
2278 return exit_status;
2279 }