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 #endif
630
631 #ifdef HAVE_PGTK
632 display = egetenv ("WAYLAND_DISPLAY");
633 alt_display = egetenv ("DISPLAY");
634 #else
635 display = egetenv ("DISPLAY");
636 #endif
637 }
638
639 if (!display)
640 {
641 display = alt_display;
642 alt_display = NULL;
643 }
644
645
646 if (display && !display[0])
647 display = NULL;
648
649
650 if (create_frame && !display)
651 tty = true;
652
653 #ifdef WINDOWSNT
654
655
656
657
658
659
660 if (create_frame)
661 {
662 display = NULL;
663 tty = true;
664 }
665 #endif
666 }
667
668
669 static _Noreturn void
670 print_help_and_exit (void)
671 {
672
673
674
675
676 message (false,
677 "Usage: %s [OPTIONS] FILE...\n%s%s%s", progname, "\
678 Tell the Emacs server to visit the specified files.\n\
679 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
680 \n\
681 The following OPTIONS are accepted:\n\
682 -V, --version Just print version info and return\n\
683 -H, --help Print this usage information message\n\
684 -nw, -t, --tty Open a new Emacs frame on the current terminal\n\
685 -c, --create-frame Create a new frame instead of trying to\n\
686 use the current Emacs frame\n\
687 -r, --reuse-frame Create a new frame if none exists, otherwise\n\
688 use the current Emacs frame\n\
689 ", "\
690 -F ALIST, --frame-parameters=ALIST\n\
691 Set the parameters of a new frame\n\
692 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
693 -n, --no-wait Don't wait for the server to return\n\
694 -w, --timeout=SECONDS Seconds to wait before timing out\n\
695 -q, --quiet Don't display messages on success\n\
696 -u, --suppress-output Don't display return values from the server\n\
697 -d DISPLAY, --display=DISPLAY\n\
698 Visit the file in the given display\n\
699 ", "\
700 --parent-id=ID Open in parent window ID, via XEmbed\n"
701 #ifdef SOCKETS_IN_FILE_SYSTEM
702 "-s SOCKET, --socket-name=SOCKET\n\
703 Set filename of the UNIX socket for communication\n"
704 #endif
705 "-f SERVER, --server-file=SERVER\n\
706 Set filename of the TCP authentication file\n\
707 -a EDITOR, --alternate-editor=EDITOR\n\
708 Editor to fallback to if the server is not running\n"
709 " If EDITOR is the empty string, start Emacs in daemon\n\
710 mode and try connecting again\n"
711 "-T PREFIX, --tramp=PREFIX\n\
712 PREFIX to prepend to filenames sent by emacsclient\n\
713 for locating files remotely via Tramp\n"
714 "\n\
715 Report bugs with M-x report-emacs-bug.\n");
716 exit (EXIT_SUCCESS);
717 }
718
719
720
721
722
723 static _Noreturn void
724 fail (void)
725 {
726 if (alternate_editor)
727 {
728 size_t extra_args_size = (main_argc - optind + 1) * sizeof (char *);
729 size_t new_argv_size = extra_args_size;
730 char **new_argv = xmalloc (new_argv_size);
731 char *s = xstrdup (alternate_editor);
732 ptrdiff_t toks = 0;
733
734
735 for (char *tok = s; tok != NULL && *tok != '\0';)
736 {
737
738 ++toks;
739 new_argv = xrealloc (new_argv,
740 new_argv_size + toks * sizeof (char *));
741
742
743
744 size_t skip = strspn (tok, " \"");
745 tok += skip;
746 char sep = (skip > 0 && tok[-1] == '"') ? '"' : ' ';
747
748
749 new_argv[toks - 1] = tok;
750
751
752 tok = strchr (tok, sep);
753 if (tok != NULL)
754 *tok++ = '\0';
755 }
756
757
758 memcpy (&new_argv[toks], main_argv + optind, extra_args_size);
759
760 execvp (*new_argv, new_argv);
761 message (true, "%s: error executing alternate editor \"%s\"\n",
762 progname, alternate_editor);
763 }
764 exit (EXIT_FAILURE);
765 }
766
767
768 #ifdef SOCKETS_IN_FILE_SYSTEM
769 static void act_on_signals (HSOCKET);
770 #else
771 static void act_on_signals (HSOCKET s) {}
772 static void init_signals (void) {}
773 #endif
774
775 enum { AUTH_KEY_LENGTH = 64 };
776
777 static void
778 sock_err_message (const char *function_name)
779 {
780 #ifdef WINDOWSNT
781
782
783
784 if (w32_window_app () && alternate_editor)
785 return;
786
787 char *msg = NULL;
788
789 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
790 | FORMAT_MESSAGE_ALLOCATE_BUFFER
791 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
792 NULL, WSAGetLastError (), 0, (LPTSTR)&msg, 0, NULL);
793
794 message (true, "%s: %s: %s\n", progname, function_name, msg);
795
796 LocalFree (msg);
797 #else
798 message (true, "%s: %s: %s\n", progname, function_name, strerror (errno));
799 #endif
800 }
801
802
803
804
805
806
807 static void
808 send_to_emacs (HSOCKET s, const char *data)
809 {
810 enum { SEND_BUFFER_SIZE = 4096 };
811
812
813 static char send_buffer[SEND_BUFFER_SIZE + 1];
814
815
816 static int sblen;
817
818 for (ptrdiff_t dlen = strlen (data); dlen != 0; )
819 {
820 int part = min (dlen, SEND_BUFFER_SIZE - sblen);
821 memcpy (&send_buffer[sblen], data, part);
822 data += part;
823 sblen += part;
824
825 if (sblen == SEND_BUFFER_SIZE
826 || (0 < sblen && send_buffer[sblen - 1] == '\n'))
827 {
828 int sent;
829 while ((sent = send (s, send_buffer, sblen, 0)) < 0)
830 {
831 if (errno != EINTR)
832 {
833 message (true, "%s: failed to send %d bytes to socket: %s\n",
834 progname, sblen, strerror (errno));
835 fail ();
836 }
837
838
839
840 act_on_signals (INVALID_SOCKET);
841 }
842 sblen -= sent;
843 memmove (send_buffer, &send_buffer[sent], sblen);
844 }
845
846 dlen -= part;
847 }
848 }
849
850
851
852
853
854
855
856 static void
857 quote_argument (HSOCKET s, const char *str)
858 {
859 char *copy = xmalloc (strlen (str) * 2 + 1);
860 char *q = copy;
861 if (*str == '-')
862 *q++ = '&', *q++ = *str++;
863 for (; *str; str++)
864 {
865 char c = *str;
866 if (c == ' ')
867 *q++ = '&', c = '_';
868 else if (c == '\n')
869 *q++ = '&', c = 'n';
870 else if (c == '&')
871 *q++ = '&';
872 *q++ = c;
873 }
874 *q = 0;
875
876 send_to_emacs (s, copy);
877
878 free (copy);
879 }
880
881
882
883
884
885 static char *
886 unquote_argument (char *str)
887 {
888 char const *p = str;
889 char *q = str;
890 char c;
891
892 do
893 {
894 c = *p++;
895 if (c == '&')
896 {
897 c = *p++;
898 if (c == '_')
899 c = ' ';
900 else if (c == 'n')
901 c = '\n';
902 }
903 *q++ = c;
904 }
905 while (c);
906
907 return str;
908 }
909
910
911 #ifdef WINDOWSNT
912
913 void __cdecl close_winsock (void);
914 void __cdecl
915 close_winsock (void)
916 {
917 WSACleanup ();
918 }
919
920
921 void initialize_sockets (void);
922 void
923 initialize_sockets (void)
924 {
925 WSADATA wsaData;
926
927 if (WSAStartup (MAKEWORD (2, 0), &wsaData))
928 {
929 message (true, "%s: error initializing WinSock2\n", progname);
930 exit (EXIT_FAILURE);
931 }
932
933 atexit (close_winsock);
934 }
935 #endif
936
937
938
939
940
941
942 static FILE *
943 open_config (char const *home, char const *xdg, char const *config_file)
944 {
945 ptrdiff_t xdgsubdirsize = xdg ? strlen (xdg) + sizeof "/emacs/server/" : 0;
946 ptrdiff_t homesuffixsizemax = max (sizeof "/.config/emacs/server/",
947 sizeof "/.emacs.d/server/");
948 ptrdiff_t homesubdirsizemax = home ? strlen (home) + homesuffixsizemax : 0;
949 char *configname = xmalloc (max (xdgsubdirsize, homesubdirsizemax)
950 + strlen (config_file));
951 FILE *config;
952
953 if (home)
954 {
955 strcpy (stpcpy (stpcpy (configname, home), "/.emacs.d/server/"),
956 config_file);
957 config = fopen (configname, "rb");
958 }
959 else
960 config = NULL;
961
962 if (! config && (xdg || home))
963 {
964 strcpy ((xdg
965 ? stpcpy (stpcpy (configname, xdg), "/emacs/server/")
966 : stpcpy (stpcpy (configname, home), "/.config/emacs/server/")),
967 config_file);
968 config = fopen (configname, "rb");
969 }
970
971 free (configname);
972 return config;
973 }
974
975
976
977
978 static bool
979 get_server_config (const char *config_file, struct sockaddr_in *server,
980 char *authentication)
981 {
982 char dotted[32];
983 char *port;
984 FILE *config;
985
986 if (IS_ABSOLUTE_FILE_NAME (config_file))
987 config = fopen (config_file, "rb");
988 else
989 {
990 char const *xdg = egetenv ("XDG_CONFIG_HOME");
991 config = open_config (egetenv ("HOME"), xdg, config_file);
992 #ifdef WINDOWSNT
993 if (!config)
994 config = open_config (egetenv ("APPDATA"), xdg, config_file);
995 #endif
996 }
997
998 if (! config)
999 return false;
1000
1001 if (fgets (dotted, sizeof dotted, config)
1002 && (port = strchr (dotted, ':')))
1003 *port++ = '\0';
1004 else
1005 {
1006 message (true, "%s: invalid configuration info\n", progname);
1007 exit (EXIT_FAILURE);
1008 }
1009
1010 memset (server, 0, sizeof *server);
1011 server->sin_family = AF_INET;
1012 server->sin_addr.s_addr = inet_addr (dotted);
1013 server->sin_port = htons (atoi (port));
1014
1015 if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
1016 {
1017 message (true, "%s: cannot read authentication info\n", progname);
1018 exit (EXIT_FAILURE);
1019 }
1020
1021 fclose (config);
1022
1023 return true;
1024 }
1025
1026
1027
1028
1029 static HSOCKET
1030 cloexec_socket (int domain, int type, int protocol)
1031 {
1032 #ifdef SOCK_CLOEXEC
1033 return socket (domain, type | SOCK_CLOEXEC, protocol);
1034 #else
1035 HSOCKET s = socket (domain, type, protocol);
1036 # ifndef WINDOWSNT
1037 if (0 <= s)
1038 fcntl (s, F_SETFD, FD_CLOEXEC);
1039 # endif
1040 return s;
1041 #endif
1042 }
1043
1044 static HSOCKET
1045 set_tcp_socket (const char *local_server_file)
1046 {
1047 union {
1048 struct sockaddr_in in;
1049 struct sockaddr sa;
1050 } server;
1051 struct linger l_arg = { .l_onoff = 1, .l_linger = 1 };
1052 char auth_string[AUTH_KEY_LENGTH + 1];
1053
1054 if (! get_server_config (local_server_file, &server.in, auth_string))
1055 return INVALID_SOCKET;
1056
1057 if (server.in.sin_addr.s_addr != inet_addr ("127.0.0.1") && !quiet)
1058 message (false, "%s: connected to remote socket at %s\n",
1059 progname, inet_ntoa (server.in.sin_addr));
1060
1061
1062 HSOCKET s = cloexec_socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1063 if (s < 0)
1064 {
1065
1066
1067
1068
1069 sock_err_message ("socket");
1070 return INVALID_SOCKET;
1071 }
1072
1073
1074 if (connect (s, &server.sa, sizeof server.in) != 0)
1075 {
1076 sock_err_message ("connect");
1077 CLOSE_SOCKET (s);
1078 return INVALID_SOCKET;
1079 }
1080
1081
1082
1083 int ret = setsockopt (s, SOL_SOCKET, SO_LINGER, (const char *) &l_arg, sizeof l_arg);
1084 if (ret < 0)
1085 sock_err_message ("setsockopt");
1086
1087
1088 auth_string[AUTH_KEY_LENGTH] = '\0';
1089
1090 send_to_emacs (s, "-auth ");
1091 send_to_emacs (s, auth_string);
1092 send_to_emacs (s, " ");
1093
1094 return s;
1095 }
1096
1097
1098
1099 static bool
1100 strprefix (const char *prefix, const char *string)
1101 {
1102 return !strncmp (prefix, string, strlen (prefix));
1103 }
1104
1105
1106
1107
1108
1109 static bool
1110 find_tty (const char **tty_type, const char **tty_name, bool noabort)
1111 {
1112 const char *type = egetenv ("TERM");
1113 const char *name = ttyname (STDOUT_FILENO);
1114
1115 if (!name)
1116 {
1117 if (noabort)
1118 return false;
1119 message (true, "%s: could not get terminal name\n", progname);
1120 fail ();
1121 }
1122
1123 if (!type)
1124 {
1125 if (noabort)
1126 return false;
1127 message (true, "%s: please set the TERM variable to your terminal type\n",
1128 progname);
1129 fail ();
1130 }
1131
1132 const char *inside_emacs = egetenv ("INSIDE_EMACS");
1133 if (inside_emacs && strstr (inside_emacs, ",term:")
1134 && strprefix ("eterm", type))
1135 {
1136 if (noabort)
1137 return false;
1138
1139 message (true, ("%s: opening a frame in an Emacs term buffer"
1140 " is not supported\n"),
1141 progname);
1142 fail ();
1143 }
1144
1145 *tty_name = name;
1146 *tty_type = type;
1147 return true;
1148 }
1149
1150
1151
1152
1153
1154
1155
1156
1157 static pid_t
1158 process_grouping (void)
1159 {
1160 #ifdef SOCKETS_IN_FILE_SYSTEM
1161 pid_t tcpgrp = tcgetpgrp (STDOUT_FILENO);
1162 if (0 <= tcpgrp)
1163 {
1164 pid_t pgrp = getpgrp ();
1165 return tcpgrp == pgrp ? pgrp : -pgrp;
1166 }
1167 #endif
1168 return 0;
1169 }
1170
1171 #ifdef SOCKETS_IN_FILE_SYSTEM
1172
1173 # include <acl.h>
1174
1175 # ifndef O_PATH
1176 # define O_PATH O_SEARCH
1177 # endif
1178
1179
1180 union local_sockaddr
1181 {
1182 struct sockaddr_un un;
1183 struct sockaddr sa;
1184 };
1185
1186
1187
1188
1189
1190
1191 static int
1192 connect_socket (int dirfd, char const *addr, int s, uid_t uid)
1193 {
1194 int sock_status = 0;
1195
1196 union local_sockaddr server;
1197 if (sizeof server.un.sun_path <= strlen (addr))
1198 return ENAMETOOLONG;
1199 server.un.sun_family = AF_UNIX;
1200 strcpy (server.un.sun_path, addr);
1201
1202
1203
1204
1205 static int wdfd = -1;
1206
1207 if (dirfd != AT_FDCWD)
1208 {
1209
1210 struct stat st;
1211 if (fstat (dirfd, &st) != 0)
1212 return errno;
1213 if (st.st_uid != uid || (st.st_mode & (S_IWGRP | S_IWOTH)))
1214 return -1;
1215
1216 if (wdfd == -1)
1217 {
1218
1219 wdfd = open (".", O_PATH | O_CLOEXEC);
1220 if (wdfd < 0)
1221 wdfd = -1 - errno;
1222 }
1223 if (wdfd < 0)
1224 return -1 - wdfd;
1225 if (fchdir (dirfd) != 0)
1226 return errno;
1227
1228
1229
1230 int has_acl = file_has_acl (".", &st);
1231 if (has_acl)
1232 sock_status = has_acl < 0 ? errno : -1;
1233 }
1234
1235 if (!sock_status)
1236 sock_status = connect (s, &server.sa, sizeof server.un) == 0 ? 0 : errno;
1237
1238
1239
1240 if (dirfd != AT_FDCWD && fchdir (wdfd) != 0)
1241 {
1242 message (true, "%s: .: %s\n", progname, strerror (errno));
1243 exit (EXIT_FAILURE);
1244 }
1245
1246 return sock_status;
1247 }
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263 static void
1264 reinstall_handler_if_needed (int sig, void (*handler) (int))
1265 {
1266 # ifndef SA_RESETHAND
1267
1268 signal (sig, handler);
1269 # endif
1270 }
1271
1272
1273
1274 static sig_atomic_t volatile
1275 got_sigcont, got_sigtstp, got_sigttou, got_sigwinch;
1276
1277 static void
1278 handle_sigcont (int sig)
1279 {
1280 got_sigcont = 1;
1281 reinstall_handler_if_needed (sig, handle_sigcont);
1282 }
1283 static void
1284 handle_sigtstp (int sig)
1285 {
1286 got_sigtstp = 1;
1287 reinstall_handler_if_needed (sig, handle_sigtstp);
1288 }
1289 static void
1290 handle_sigttou (int sig)
1291 {
1292 got_sigttou = 1;
1293 reinstall_handler_if_needed (sig, handle_sigttou);
1294 }
1295 static void
1296 handle_sigwinch (int sig)
1297 {
1298 got_sigwinch = 1;
1299 reinstall_handler_if_needed (sig, handle_sigwinch);
1300 }
1301
1302
1303
1304
1305
1306 static void
1307 install_handler (int sig, void (*handler) (int), sig_atomic_t volatile *flag)
1308 {
1309 # ifdef SA_RESETHAND
1310 if (flag)
1311 {
1312 struct sigaction oact;
1313 if (sigaction (sig, NULL, &oact) == 0 && oact.sa_handler == SIG_IGN)
1314 return;
1315 }
1316 struct sigaction act = { .sa_handler = handler };
1317 sigemptyset (&act.sa_mask);
1318 sigaction (sig, &act, NULL);
1319 # else
1320 void (*ohandler) (int) = signal (sig, handler);
1321 if (flag)
1322 {
1323 if (ohandler == SIG_IGN)
1324 {
1325 signal (sig, SIG_IGN);
1326
1327
1328 *flag = 0;
1329 }
1330 }
1331 # endif
1332 }
1333
1334
1335
1336 static void
1337 init_signals (void)
1338 {
1339 install_handler (SIGCONT, handle_sigcont, &got_sigcont);
1340 install_handler (SIGTSTP, handle_sigtstp, &got_sigtstp);
1341 install_handler (SIGTTOU, handle_sigttou, &got_sigttou);
1342 install_handler (SIGWINCH, handle_sigwinch, &got_sigwinch);
1343
1344
1345
1346 }
1347
1348
1349
1350
1351 static void
1352 act_on_tty_signal (int sig, void (*handler) (int), HSOCKET emacs_socket)
1353 {
1354
1355
1356
1357
1358
1359 send_to_emacs (emacs_socket, "-suspend \n");
1360
1361
1362
1363 install_handler (sig, SIG_DFL, NULL);
1364 raise (sig);
1365 install_handler (sig, handler, NULL);
1366 }
1367
1368
1369
1370
1371 static void
1372 act_on_signals (HSOCKET emacs_socket)
1373 {
1374 while (true)
1375 {
1376 bool took_action = false;
1377
1378 if (emacs_socket != INVALID_SOCKET)
1379 {
1380 if (got_sigcont)
1381 {
1382 got_sigcont = 0;
1383 took_action = true;
1384 pid_t grouping = process_grouping ();
1385 if (grouping < 0)
1386 {
1387 if (tty)
1388 {
1389
1390 kill (grouping, SIGTTIN);
1391 }
1392 }
1393 else
1394 send_to_emacs (emacs_socket, "-resume \n");
1395 }
1396
1397 if (got_sigtstp)
1398 {
1399 got_sigtstp = 0;
1400 took_action = true;
1401 act_on_tty_signal (SIGTSTP, handle_sigtstp, emacs_socket);
1402 }
1403 if (got_sigttou)
1404 {
1405 got_sigttou = 0;
1406 took_action = true;
1407 act_on_tty_signal (SIGTTOU, handle_sigttou, emacs_socket);
1408 }
1409 }
1410
1411 if (emacs_pid && got_sigwinch)
1412 {
1413 got_sigwinch = 0;
1414 took_action = true;
1415 kill (emacs_pid, SIGWINCH);
1416 }
1417
1418 if (!took_action)
1419 break;
1420 }
1421 }
1422
1423 enum { socknamesize = sizeof ((struct sockaddr_un *) NULL)->sun_path };
1424
1425
1426
1427
1428
1429
1430
1431
1432 static int
1433 local_sockname (int s, char sockname[socknamesize], int tmpdirlen,
1434 uid_t uid, char const *server_name)
1435 {
1436
1437
1438
1439 if (! (0 <= tmpdirlen && tmpdirlen < socknamesize))
1440 return ENAMETOOLONG;
1441
1442
1443
1444 uintmax_t uidmax = uid;
1445 int suffixlen = snprintf (sockname + tmpdirlen, socknamesize - tmpdirlen,
1446 "/emacs%"PRIuMAX"/%s", uidmax, server_name);
1447 if (! (0 <= suffixlen && suffixlen < socknamesize - tmpdirlen))
1448 return ENAMETOOLONG;
1449
1450
1451
1452
1453
1454 char *emacsdirend = sockname + tmpdirlen + suffixlen -
1455 strlen(server_name) - 1;
1456 *emacsdirend = '\0';
1457 int dir = open (sockname, O_PATH | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
1458 *emacsdirend = '/';
1459 if (dir < 0)
1460 return errno;
1461 int sock_status = connect_socket (dir, server_name, s, uid);
1462 close (dir);
1463 return sock_status;
1464 }
1465
1466
1467
1468
1469
1470
1471 static HSOCKET
1472 set_local_socket (char const *server_name)
1473 {
1474 union local_sockaddr server;
1475 int sock_status;
1476 char *sockname = server.un.sun_path;
1477 int tmpdirlen = -1;
1478 int socknamelen = -1;
1479 uid_t uid = geteuid ();
1480 bool tmpdir_used = false;
1481 int s = cloexec_socket (AF_UNIX, SOCK_STREAM, 0);
1482 if (s < 0)
1483 {
1484 message (true, "%s: can't create socket: %s\n",
1485 progname, strerror (errno));
1486 fail ();
1487 }
1488
1489 if (strchr (server_name, '/')
1490 || (ISSLASH ('\\') && strchr (server_name, '\\')))
1491 {
1492 socknamelen = snprintf (sockname, socknamesize, "%s", server_name);
1493 sock_status = (0 <= socknamelen && socknamelen < socknamesize
1494 ? connect_socket (AT_FDCWD, sockname, s, 0)
1495 : ENAMETOOLONG);
1496 }
1497 else
1498 {
1499
1500 char const *xdg_runtime_dir = egetenv ("XDG_RUNTIME_DIR");
1501 if (xdg_runtime_dir)
1502 {
1503 socknamelen = snprintf (sockname, socknamesize, "%s/emacs/%s",
1504 xdg_runtime_dir, server_name);
1505 sock_status = (0 <= socknamelen && socknamelen < socknamesize
1506 ? connect_socket (AT_FDCWD, sockname, s, 0)
1507 : ENAMETOOLONG);
1508 }
1509 else
1510 {
1511 char const *tmpdir = egetenv ("TMPDIR");
1512 if (tmpdir)
1513 tmpdirlen = snprintf (sockname, socknamesize, "%s", tmpdir);
1514 else
1515 {
1516 # ifdef DARWIN_OS
1517 # ifndef _CS_DARWIN_USER_TEMP_DIR
1518 # define _CS_DARWIN_USER_TEMP_DIR 65537
1519 # endif
1520 size_t n = confstr (_CS_DARWIN_USER_TEMP_DIR,
1521 sockname, socknamesize);
1522 if (0 < n && n < (size_t) -1)
1523 tmpdirlen = min (n - 1, socknamesize);
1524 # endif
1525 if (tmpdirlen < 0)
1526 tmpdirlen = snprintf (sockname, socknamesize, "/tmp");
1527 }
1528 sock_status = local_sockname (s, sockname, tmpdirlen,
1529 uid, server_name);
1530 tmpdir_used = true;
1531 }
1532 }
1533
1534 if (sock_status == 0)
1535 return s;
1536
1537 if (sock_status == ENAMETOOLONG)
1538 {
1539 message (true, "%s: socket-name %s... too long\n", progname, sockname);
1540 fail ();
1541 }
1542
1543 if (tmpdir_used)
1544 {
1545
1546
1547
1548
1549
1550 char const *user_name = egetenv ("LOGNAME");
1551
1552 if (!user_name)
1553 user_name = egetenv ("USER");
1554
1555 if (user_name)
1556 {
1557 struct passwd *pw = getpwnam (user_name);
1558
1559 if (pw && pw->pw_uid != uid)
1560 {
1561
1562 sock_status = local_sockname (s, sockname, tmpdirlen,
1563 pw->pw_uid, server_name);
1564 if (sock_status == 0)
1565 return s;
1566 if (sock_status == ENAMETOOLONG)
1567 {
1568 message (true, "%s: socket-name %s... too long\n",
1569 progname, sockname);
1570 exit (EXIT_FAILURE);
1571 }
1572 }
1573 }
1574 }
1575
1576 close (s);
1577
1578 if (sock_status == -1)
1579 message (true,
1580 "%s: Invalid permissions on parent directory of socket: %s\n",
1581 progname, sockname);
1582 else if (sock_status == ENOENT)
1583 {
1584 if (tmpdir_used)
1585 {
1586 uintmax_t id = uid;
1587 char sockdirname[socknamesize];
1588 int sockdirnamelen = snprintf (sockdirname, sizeof sockdirname,
1589 "/run/user/%"PRIuMAX, id);
1590 if (0 <= sockdirnamelen && sockdirnamelen < sizeof sockdirname
1591 && faccessat (AT_FDCWD, sockdirname, X_OK, AT_EACCESS) == 0)
1592 message
1593 (true,
1594 ("%s: Should XDG_RUNTIME_DIR='%s' be in the environment?\n"
1595 "%s: (Be careful: XDG_RUNTIME_DIR is security-related.)\n"),
1596 progname, sockdirname, progname);
1597 }
1598
1599
1600
1601 if (!quiet || !alternate_editor)
1602 {
1603 message (true,
1604 ("%s: can't find socket; have you started the server?\n"
1605 "%s: To start the server in Emacs,"
1606 " type \"M-x server-start\".\n"),
1607 progname, progname);
1608 }
1609 }
1610 else
1611 message (true, "%s: can't connect to %s: %s\n",
1612 progname, sockname, strerror (sock_status));
1613
1614 return INVALID_SOCKET;
1615 }
1616 #endif
1617
1618 static HSOCKET
1619 set_socket (bool no_exit_if_error)
1620 {
1621 HSOCKET s;
1622 const char *local_server_file = server_file;
1623
1624 INITIALIZE ();
1625
1626 #ifdef SOCKETS_IN_FILE_SYSTEM
1627 if (!socket_name)
1628 socket_name = egetenv ("EMACS_SOCKET_NAME");
1629
1630 if (socket_name)
1631 {
1632
1633 s = set_local_socket (socket_name);
1634 if (s != INVALID_SOCKET || no_exit_if_error)
1635 return s;
1636 message (true, "%s: error accessing socket \"%s\"\n",
1637 progname, socket_name);
1638 exit (EXIT_FAILURE);
1639 }
1640 #endif
1641
1642
1643 if (!local_server_file)
1644 local_server_file = egetenv ("EMACS_SERVER_FILE");
1645
1646 if (local_server_file)
1647 {
1648 s = set_tcp_socket (local_server_file);
1649 if (s != INVALID_SOCKET || no_exit_if_error)
1650 return s;
1651
1652 message (true, "%s: error accessing server file \"%s\"\n",
1653 progname, local_server_file);
1654 exit (EXIT_FAILURE);
1655 }
1656
1657 #ifdef SOCKETS_IN_FILE_SYSTEM
1658
1659 s = set_local_socket ("server");
1660 if (s != INVALID_SOCKET)
1661 return s;
1662 #endif
1663
1664
1665 s = set_tcp_socket ("server");
1666 if (s != INVALID_SOCKET || no_exit_if_error)
1667 return s;
1668
1669
1670 message (true, "%s: No socket or alternate editor. Please use:\n\n"
1671 #ifdef SOCKETS_IN_FILE_SYSTEM
1672 "\t--socket-name\n"
1673 #endif
1674 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1675 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1676 progname);
1677 exit (EXIT_FAILURE);
1678 }
1679
1680 #ifdef HAVE_NTGUI
1681 FARPROC set_fg;
1682 FARPROC get_wc;
1683
1684 void w32_set_user_model_id (void);
1685
1686 void
1687 w32_set_user_model_id (void)
1688 {
1689 HMODULE shell;
1690 HRESULT (WINAPI * set_user_model) (const wchar_t * id);
1691
1692
1693
1694
1695 shell = LoadLibrary ("shell32.dll");
1696 if (shell)
1697 {
1698 set_user_model
1699 = (void *) GetProcAddress (shell,
1700 "SetCurrentProcessExplicitAppUserModelID");
1701
1702
1703
1704
1705
1706 if (set_user_model)
1707 set_user_model (L"GNU.Emacs");
1708
1709 FreeLibrary (shell);
1710 }
1711 }
1712
1713 BOOL CALLBACK w32_find_emacs_process (HWND, LPARAM);
1714
1715 BOOL CALLBACK
1716 w32_find_emacs_process (HWND hWnd, LPARAM lParam)
1717 {
1718 DWORD pid;
1719 char class[6];
1720
1721
1722 if (! get_wc (hWnd, class, sizeof (class))
1723 || strcmp (class, "Emacs"))
1724 return TRUE;
1725
1726
1727 (void) GetWindowThreadProcessId (hWnd, &pid);
1728
1729
1730 if (pid != (DWORD) emacs_pid) return TRUE;
1731
1732
1733 set_fg (emacs_pid);
1734
1735
1736 return FALSE;
1737 }
1738
1739
1740
1741 void w32_give_focus (void);
1742
1743 void
1744 w32_give_focus (void)
1745 {
1746 HANDLE user32;
1747
1748
1749 if (!emacs_pid) return;
1750
1751 user32 = GetModuleHandle ("user32.dll");
1752
1753 if (!user32)
1754 return;
1755
1756
1757
1758
1759
1760 if ((set_fg = GetProcAddress (user32, "AllowSetForegroundWindow"))
1761 && (get_wc = GetProcAddress (user32, "RealGetWindowClassA")))
1762 EnumWindows (w32_find_emacs_process, (LPARAM) 0);
1763 }
1764 #endif
1765
1766
1767
1768 static HSOCKET
1769 start_daemon_and_retry_set_socket (void)
1770 {
1771 #ifndef WINDOWSNT
1772 pid_t dpid;
1773 int status;
1774
1775 dpid = fork ();
1776
1777 if (dpid > 0)
1778 {
1779 pid_t w = waitpid (dpid, &status, WUNTRACED | WCONTINUED);
1780
1781 if (w < 0 || !WIFEXITED (status) || WEXITSTATUS (status))
1782 {
1783 message (true, "Error: Could not start the Emacs daemon\n");
1784 exit (EXIT_FAILURE);
1785 }
1786
1787
1788 if (!quiet)
1789 message (true,
1790 "Emacs daemon should have started, trying to connect again\n");
1791 }
1792 else if (dpid < 0)
1793 {
1794 fprintf (stderr, "Error: Cannot fork!\n");
1795 exit (EXIT_FAILURE);
1796 }
1797 else
1798 {
1799 char emacs[] = "emacs";
1800 char daemon_option[] = "--daemon";
1801 char *d_argv[3];
1802 d_argv[0] = emacs;
1803 d_argv[1] = daemon_option;
1804 d_argv[2] = 0;
1805 # ifdef SOCKETS_IN_FILE_SYSTEM
1806 if (socket_name != NULL)
1807 {
1808
1809 const char *deq = "--daemon=";
1810 char *daemon_arg = xmalloc (strlen (deq)
1811 + strlen (socket_name) + 1);
1812 strcpy (stpcpy (daemon_arg, deq), socket_name);
1813 d_argv[1] = daemon_arg;
1814 }
1815 # endif
1816 execvp ("emacs", d_argv);
1817 message (true, "%s: error starting emacs daemon\n", progname);
1818 exit (EXIT_FAILURE);
1819 }
1820 #else
1821 DWORD wait_result;
1822 HANDLE w32_daemon_event;
1823 STARTUPINFO si;
1824 PROCESS_INFORMATION pi;
1825
1826 ZeroMemory (&si, sizeof si);
1827 si.cb = sizeof si;
1828 ZeroMemory (&pi, sizeof pi);
1829
1830
1831
1832
1833
1834 if (!CreateProcess (NULL, (LPSTR)"emacs --daemon", NULL, NULL, FALSE,
1835 CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
1836 {
1837 char* msg = NULL;
1838
1839 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
1840 | FORMAT_MESSAGE_ALLOCATE_BUFFER
1841 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1842 NULL, GetLastError (), 0, (LPTSTR)&msg, 0, NULL);
1843 message (true, "%s: error starting emacs daemon (%s)\n", progname, msg);
1844 exit (EXIT_FAILURE);
1845 }
1846
1847 w32_daemon_event = CreateEvent (NULL, TRUE, FALSE, W32_DAEMON_EVENT);
1848 if (w32_daemon_event == NULL)
1849 {
1850 message (true, "Couldn't create Windows daemon event");
1851 exit (EXIT_FAILURE);
1852 }
1853 if ((wait_result = WaitForSingleObject (w32_daemon_event, INFINITE))
1854 != WAIT_OBJECT_0)
1855 {
1856 const char *msg = NULL;
1857
1858 switch (wait_result)
1859 {
1860 case WAIT_ABANDONED:
1861 msg = "The daemon exited unexpectedly";
1862 break;
1863 case WAIT_TIMEOUT:
1864
1865 default:
1866 case WAIT_FAILED:
1867 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
1868 | FORMAT_MESSAGE_ALLOCATE_BUFFER
1869 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1870 NULL, GetLastError (), 0, (LPTSTR)&msg, 0, NULL);
1871 break;
1872 }
1873 message (true, "Error: Could not start the Emacs daemon: %s\n", msg);
1874 exit (EXIT_FAILURE);
1875 }
1876 CloseHandle (w32_daemon_event);
1877
1878
1879
1880
1881 if (!quiet && !w32_window_app ())
1882 message (true,
1883 "Emacs daemon should have started, trying to connect again\n");
1884 #endif
1885
1886 HSOCKET emacs_socket = set_socket (true);
1887 if (emacs_socket == INVALID_SOCKET)
1888 {
1889 message (true,
1890 "Error: Cannot connect even after starting the Emacs daemon\n");
1891 exit (EXIT_FAILURE);
1892 }
1893 return emacs_socket;
1894 }
1895
1896 static void
1897 set_socket_timeout (HSOCKET socket, int seconds)
1898 {
1899 int ret;
1900
1901 #ifndef WINDOWSNT
1902 struct timeval timeout;
1903 timeout.tv_sec = seconds;
1904 timeout.tv_usec = 0;
1905 ret = setsockopt (socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof timeout);
1906 #else
1907 DWORD timeout;
1908
1909 if (seconds > INT_MAX / 1000)
1910 timeout = INT_MAX;
1911 else
1912 timeout = seconds * 1000;
1913 ret = setsockopt (socket, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, sizeof timeout);
1914 #endif
1915
1916 if (ret < 0)
1917 sock_err_message ("setsockopt");
1918 }
1919
1920 static bool
1921 check_socket_timeout (int rl)
1922 {
1923 #ifndef WINDOWSNT
1924 return (rl == -1)
1925 && (errno == EAGAIN)
1926 && (errno == EWOULDBLOCK);
1927 #else
1928 return (rl == SOCKET_ERROR)
1929 && (WSAGetLastError() == WSAETIMEDOUT);
1930 #endif
1931 }
1932
1933 int
1934 main (int argc, char **argv)
1935 {
1936 main_argc = argc;
1937 main_argv = argv;
1938 progname = argv[0] ? argv[0] : "emacsclient";
1939
1940 int rl = 0;
1941 bool skiplf = true;
1942 char string[BUFSIZ + 1];
1943 int exit_status = EXIT_SUCCESS;
1944
1945 #ifdef HAVE_NTGUI
1946
1947
1948
1949
1950 w32_set_user_model_id ();
1951 #endif
1952
1953
1954 decode_options (argc, argv);
1955
1956 if (! (optind < argc || eval || create_frame))
1957 {
1958 message (true, ("%s: file name or argument required\n"
1959 "Try '%s --help' for more information\n"),
1960 progname, progname);
1961 exit (EXIT_FAILURE);
1962 }
1963
1964 #ifdef SOCKETS_IN_FILE_SYSTEM
1965 if (tty)
1966 {
1967 pid_t grouping = process_grouping ();
1968 if (grouping < 0)
1969 kill (grouping, SIGTTIN);
1970 }
1971 #endif
1972
1973
1974
1975 bool start_daemon_if_needed = alternate_editor && !alternate_editor[0];
1976
1977 HSOCKET emacs_socket = set_socket (alternate_editor
1978 || start_daemon_if_needed);
1979 if (emacs_socket == INVALID_SOCKET)
1980 {
1981 if (! start_daemon_if_needed)
1982 fail ();
1983
1984 emacs_socket = start_daemon_and_retry_set_socket ();
1985 }
1986
1987 char *cwd = get_current_dir_name ();
1988 if (cwd == 0)
1989 {
1990 message (true, "%s: %s\n", progname,
1991 "Cannot get current working directory");
1992 fail ();
1993 }
1994
1995 #ifdef HAVE_NTGUI
1996 if (display && !strcmp (display, "w32"))
1997 w32_give_focus ();
1998 #endif
1999
2000
2001 if (create_frame)
2002 {
2003 for (char *const *e = environ; *e; e++)
2004 {
2005 send_to_emacs (emacs_socket, "-env ");
2006 quote_argument (emacs_socket, *e);
2007 send_to_emacs (emacs_socket, " ");
2008 }
2009 }
2010 send_to_emacs (emacs_socket, "-dir ");
2011 if (tramp_prefix)
2012 quote_argument (emacs_socket, tramp_prefix);
2013 quote_argument (emacs_socket, cwd);
2014 free (cwd);
2015 send_to_emacs (emacs_socket, "/");
2016 send_to_emacs (emacs_socket, " ");
2017
2018 retry:
2019 if (nowait)
2020 send_to_emacs (emacs_socket, "-nowait ");
2021
2022 if (!create_frame || reuse_frame)
2023 send_to_emacs (emacs_socket, "-current-frame ");
2024
2025 if (display)
2026 {
2027 send_to_emacs (emacs_socket, "-display ");
2028 quote_argument (emacs_socket, display);
2029 send_to_emacs (emacs_socket, " ");
2030 }
2031
2032 if (parent_id)
2033 {
2034 send_to_emacs (emacs_socket, "-parent-id ");
2035 quote_argument (emacs_socket, parent_id);
2036 send_to_emacs (emacs_socket, " ");
2037 }
2038
2039 if (frame_parameters && create_frame)
2040 {
2041 send_to_emacs (emacs_socket, "-frame-parameters ");
2042 quote_argument (emacs_socket, frame_parameters);
2043 send_to_emacs (emacs_socket, " ");
2044 }
2045
2046
2047
2048
2049 if (create_frame || !eval)
2050 {
2051 const char *tty_type, *tty_name;
2052
2053 if (find_tty (&tty_type, &tty_name, !tty))
2054 {
2055
2056
2057 init_signals ();
2058
2059 send_to_emacs (emacs_socket, "-tty ");
2060 quote_argument (emacs_socket, tty_name);
2061 send_to_emacs (emacs_socket, " ");
2062 quote_argument (emacs_socket, tty_type);
2063 send_to_emacs (emacs_socket, " ");
2064 }
2065 }
2066
2067 if (create_frame && !tty)
2068 send_to_emacs (emacs_socket, "-window-system ");
2069
2070 if (optind < argc)
2071 {
2072 for (int i = optind; i < argc; i++)
2073 {
2074
2075 if (eval)
2076 {
2077
2078 send_to_emacs (emacs_socket, "-eval ");
2079 quote_argument (emacs_socket, argv[i]);
2080 send_to_emacs (emacs_socket, " ");
2081 continue;
2082 }
2083
2084 char *p = argv[i];
2085 if (*p == '+')
2086 {
2087 unsigned char c;
2088 do
2089 c = *++p;
2090 while (isdigit (c) || c == ':');
2091
2092 if (c == 0)
2093 {
2094 send_to_emacs (emacs_socket, "-position ");
2095 quote_argument (emacs_socket, argv[i]);
2096 send_to_emacs (emacs_socket, " ");
2097 continue;
2098 }
2099 }
2100 #ifdef WINDOWSNT
2101 else if (! IS_ABSOLUTE_FILE_NAME (argv[i])
2102 && (isalpha (argv[i][0]) && argv[i][1] == ':'))
2103
2104
2105
2106
2107
2108
2109 {
2110 char *filename = xmalloc (MAX_PATH);
2111 DWORD size;
2112
2113 size = GetFullPathName (argv[i], MAX_PATH, filename, NULL);
2114 if (size > 0 && size < MAX_PATH)
2115 argv[i] = filename;
2116 else
2117 free (filename);
2118 }
2119 #endif
2120
2121 send_to_emacs (emacs_socket, "-file ");
2122 if (tramp_prefix && IS_ABSOLUTE_FILE_NAME (argv[i]))
2123 quote_argument (emacs_socket, tramp_prefix);
2124 quote_argument (emacs_socket, argv[i]);
2125 send_to_emacs (emacs_socket, " ");
2126 }
2127 }
2128 else if (eval)
2129 {
2130
2131 while (fgets (string, BUFSIZ, stdin))
2132 {
2133 send_to_emacs (emacs_socket, "-eval ");
2134 quote_argument (emacs_socket, string);
2135 }
2136 send_to_emacs (emacs_socket, " ");
2137 }
2138
2139 send_to_emacs (emacs_socket, "\n");
2140
2141
2142 if (!eval && !tty && !nowait && !quiet && 0 <= process_grouping ())
2143 {
2144 printf ("Waiting for Emacs...");
2145 skiplf = false;
2146 }
2147 fflush (stdout);
2148
2149 set_socket_timeout (emacs_socket, timeout > 0 ? timeout : DEFAULT_TIMEOUT);
2150 bool saw_response = false;
2151
2152 while (exit_status == EXIT_SUCCESS)
2153 {
2154 bool retry = true;
2155 bool msg_showed = quiet;
2156 do
2157 {
2158 act_on_signals (emacs_socket);
2159 rl = recv (emacs_socket, string, BUFSIZ, 0);
2160 retry = check_socket_timeout (rl);
2161 if (retry && !saw_response)
2162 {
2163 if (timeout > 0)
2164 {
2165
2166 fprintf (stderr, "\nServer not responding; timed out after %ju seconds",
2167 timeout);
2168 retry = false;
2169 }
2170 else if (!msg_showed)
2171 {
2172 msg_showed = true;
2173 fprintf (stderr, "\nServer not responding; use Ctrl+C to break");
2174 }
2175 }
2176 }
2177 while ((rl < 0 && errno == EINTR) || retry);
2178
2179 if (rl <= 0)
2180 break;
2181
2182 saw_response = true;
2183 string[rl] = '\0';
2184
2185
2186 char *p = string;
2187 for (char *end_p = p; end_p && *end_p != '\0'; p = end_p)
2188 {
2189 end_p = strchr (p, '\n');
2190 if (end_p != NULL)
2191 *end_p++ = '\0';
2192
2193 if (strprefix ("-emacs-pid ", p))
2194 {
2195
2196 emacs_pid = strtoumax (p + strlen ("-emacs-pid"), NULL, 10);
2197 }
2198 else if (strprefix ("-window-system-unsupported ", p))
2199 {
2200
2201
2202
2203 if (alt_display)
2204 {
2205 display = alt_display;
2206 alt_display = NULL;
2207 }
2208 else
2209 {
2210 nowait = false;
2211 tty = true;
2212 }
2213
2214 goto retry;
2215 }
2216 else if (strprefix ("-print ", p))
2217 {
2218
2219 if (!suppress_output)
2220 {
2221 char *str = unquote_argument (p + strlen ("-print "));
2222 printf (&"\n%s"[skiplf], str);
2223 if (str[0])
2224 skiplf = str[strlen (str) - 1] == '\n';
2225 }
2226 }
2227 else if (strprefix ("-print-nonl ", p))
2228 {
2229
2230
2231 if (!suppress_output)
2232 {
2233 char *str = unquote_argument (p + strlen ("-print-nonl "));
2234 printf ("%s", str);
2235 if (str[0])
2236 skiplf = str[strlen (str) - 1] == '\n';
2237 }
2238 }
2239 else if (strprefix ("-error ", p))
2240 {
2241
2242 char *str = unquote_argument (p + strlen ("-error "));
2243 if (!skiplf)
2244 printf ("\n");
2245 message (true, "*ERROR*: %s", str);
2246 if (str[0])
2247 skiplf = str[strlen (str) - 1] == '\n';
2248 exit_status = EXIT_FAILURE;
2249 }
2250 #ifndef WINDOWSNT
2251 else if (strprefix ("-suspend ", p))
2252 {
2253
2254 if (!skiplf)
2255 printf ("\n");
2256 skiplf = true;
2257 kill (0, SIGSTOP);
2258 }
2259 #endif
2260 else
2261 {
2262
2263 printf (&"\n*ERROR*: Unknown message: %s\n"[skiplf], p);
2264 skiplf = true;
2265 }
2266 }
2267 }
2268
2269 if (!skiplf && 0 <= process_grouping ())
2270 printf ("\n");
2271
2272 if (rl < 0)
2273 exit_status = EXIT_FAILURE;
2274
2275 CLOSE_SOCKET (emacs_socket);
2276 return exit_status;
2277 }