mirrored from git://git.sv.gnu.org/emacs.git
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathemacsclient.c
2314 lines (1967 loc) · 61.1 KB
/
emacsclient.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Client process that communicates with GNU Emacs acting as server.
Copyright (C) 1986-2025 Free Software Foundation, Inc.
This file is part of GNU Emacs.
GNU Emacs is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
#include <config.h>
#ifdef WINDOWSNT
/* ms-w32.h defines these, which disables sockets altogether! */
# undef _WINSOCKAPI_
# undef _WINSOCK_H
# include <malloc.h>
# include <windows.h>
# include <commctrl.h>
# include <io.h>
# include <winsock2.h>
# define HSOCKET SOCKET
# define CLOSE_SOCKET closesocket
# define INITIALIZE() initialize_sockets ()
char *w32_getenv (const char *);
# define egetenv(VAR) w32_getenv (VAR)
# undef signal
#else /* !WINDOWSNT */
# ifdef HAVE_NTGUI
# include <windows.h>
# endif
# include "syswait.h"
# include <arpa/inet.h>
# include <fcntl.h>
# include <netinet/in.h>
# include <sys/socket.h>
# include <sys/un.h>
# define SOCKETS_IN_FILE_SYSTEM
# define INVALID_SOCKET (-1)
# define HSOCKET int
# define CLOSE_SOCKET close
# define INITIALIZE()
# define egetenv(VAR) getenv (VAR)
#endif /* !WINDOWSNT */
#define DEFAULT_TIMEOUT (30)
#include <errno.h>
#include <getopt.h>
#include <inttypes.h>
#include <pwd.h>
#include <signal.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <attribute.h>
#include <c-ctype.h>
#include <filename.h>
#include <intprops.h>
#include <min-max.h>
#include <pathmax.h>
#include <unlocked-io.h>
/* Work around GCC bug 88251. */
#if GNUC_PREREQ (7, 0, 0)
# pragma GCC diagnostic ignored "-Wformat-truncation=2"
#endif
/* Name used to invoke this program. */
static char const *progname;
/* The first argument to main. */
static int main_argc;
/* The second argument to main. */
static char *const *main_argv;
/* True means don't wait for a response from Emacs. --no-wait. */
static bool nowait;
/* True means don't print messages for successful operations. --quiet. */
static bool quiet;
/* True means don't print values returned from emacs. --suppress-output. */
static bool suppress_output;
/* True means args are expressions to be evaluated. --eval. */
static bool eval;
/* True means open a new frame. --create-frame etc. */
static bool create_frame;
/* True means reuse a frame if it already exists. */
static bool reuse_frame;
/* The display on which Emacs should work. --display. */
static char const *display;
/* The alternate display we should try if Emacs does not support display. */
static char const *alt_display;
/* The parent window ID, if we are opening a frame via XEmbed. */
static char *parent_id;
/* True means open a new Emacs frame on the current terminal. */
static bool tty;
/* If non-NULL, the name of an editor to fallback to if the server
is not running. --alternate-editor. */
static char *alternate_editor;
#ifdef SOCKETS_IN_FILE_SYSTEM
/* If non-NULL, the filename of the UNIX socket. */
static char const *socket_name;
#endif
/* If non-NULL, the filename of the authentication file. */
static char const *server_file;
/* Seconds to wait before timing out (0 means wait forever). */
static uintmax_t timeout;
/* If non-NULL, the tramp prefix emacs must use to find the files. */
static char const *tramp_prefix;
/* If nonzero, PID of the Emacs server process. */
static pid_t emacs_pid;
/* If non-NULL, a string that should form a frame parameter alist to
be used for the new frame. */
static char const *frame_parameters;
static _Noreturn void print_help_and_exit (void);
/* Long command-line options. */
static struct option const longopts[] =
{
{ "no-wait", no_argument, NULL, 'n' },
{ "quiet", no_argument, NULL, 'q' },
{ "suppress-output", no_argument, NULL, 'u' },
{ "eval", no_argument, NULL, 'e' },
{ "help", no_argument, NULL, 'H' },
{ "version", no_argument, NULL, 'V' },
{ "tty", no_argument, NULL, 't' },
{ "nw", no_argument, NULL, 't' },
{ "no-window-system", no_argument, NULL, 't' },
{ "create-frame", no_argument, NULL, 'c' },
{ "reuse-frame", no_argument, NULL, 'r' },
{ "alternate-editor", required_argument, NULL, 'a' },
{ "frame-parameters", required_argument, NULL, 'F' },
#ifdef SOCKETS_IN_FILE_SYSTEM
{ "socket-name", required_argument, NULL, 's' },
#endif
{ "server-file", required_argument, NULL, 'f' },
{ "display", required_argument, NULL, 'd' },
{ "parent-id", required_argument, NULL, 'p' },
{ "timeout", required_argument, NULL, 'w' },
{ "tramp", required_argument, NULL, 'T' },
{ 0, 0, 0, 0 }
};
/* Short options, in the same order as the corresponding long options.
There is no '-p' short option. */
static char const shortopts[] =
"nqueHVtca:F:w:"
#ifdef SOCKETS_IN_FILE_SYSTEM
"s:"
#endif
"f:d:T:";
/* Like malloc but get fatal error if memory is exhausted. */
static void * ATTRIBUTE_MALLOC
xmalloc (size_t size)
{
void *result = malloc (size);
if (result == NULL)
{
perror ("malloc");
exit (EXIT_FAILURE);
}
return result;
}
/* Like realloc but get fatal error if memory is exhausted. */
static void *
xrealloc (void *ptr, size_t size)
{
void *result = realloc (ptr, size);
if (result == NULL)
{
perror ("realloc");
exit (EXIT_FAILURE);
}
return result;
}
/* Like strdup but get a fatal error if memory is exhausted. */
static char * ATTRIBUTE_MALLOC
xstrdup (const char *s)
{
char *result = strdup (s);
if (result == NULL)
{
perror ("strdup");
exit (EXIT_FAILURE);
}
return result;
}
/* From sysdep.c */
#if !defined HAVE_GET_CURRENT_DIR_NAME || defined BROKEN_GET_CURRENT_DIR_NAME
char *get_current_dir_name (void);
/* Return the current working directory. Returns NULL on errors.
Any other returned value must be freed with free. This is used
only when get_current_dir_name is not defined on the system. */
char *
get_current_dir_name (void)
{
/* The maximum size of a directory name, including the terminating NUL.
Leave room so that the caller can append a trailing slash. */
ptrdiff_t dirsize_max = min (PTRDIFF_MAX, SIZE_MAX) - 1;
/* The maximum size of a buffer for a file name, including the
terminating NUL. This is bounded by PATH_MAX, if available. */
ptrdiff_t bufsize_max = dirsize_max;
#ifdef PATH_MAX
bufsize_max = min (bufsize_max, PATH_MAX);
#endif
struct stat dotstat, pwdstat;
size_t pwdlen;
/* If PWD is accurate, use it instead of calling getcwd. PWD is
sometimes a nicer name, and using it may avoid a fatal error if a
parent directory is searchable but not readable. */
char const *pwd = egetenv ("PWD");
if (pwd
&& (pwdlen = strnlen (pwd, bufsize_max)) < bufsize_max
&& IS_DIRECTORY_SEP (pwd[pwdlen && IS_DEVICE_SEP (pwd[1]) ? 2 : 0])
&& stat (pwd, &pwdstat) == 0
&& stat (".", &dotstat) == 0
&& dotstat.st_ino == pwdstat.st_ino
&& dotstat.st_dev == pwdstat.st_dev)
return strdup (pwd);
else
{
ptrdiff_t buf_size = min (bufsize_max, 1024);
for (;;)
{
char *buf = malloc (buf_size);
if (!buf)
return NULL;
if (getcwd (buf, buf_size) == buf)
return buf;
free (buf);
if (errno != ERANGE || buf_size == bufsize_max)
return NULL;
buf_size = buf_size <= bufsize_max / 2 ? 2 * buf_size : bufsize_max;
}
}
}
#endif
#ifdef WINDOWSNT
# define REG_ROOT "SOFTWARE\\GNU\\Emacs"
char *w32_get_resource (HKEY, const char *, LPDWORD);
/* Retrieve an environment variable from the Emacs subkeys of the registry.
Return NULL if the variable was not found, or it was empty.
This code is based on w32_get_resource (w32.c). */
char *
w32_get_resource (HKEY predefined, const char *key, LPDWORD type)
{
HKEY hrootkey = NULL;
char *result = NULL;
DWORD cbData;
if (RegOpenKeyEx (predefined, REG_ROOT, 0, KEY_READ, &hrootkey)
== ERROR_SUCCESS)
{
if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData)
== ERROR_SUCCESS)
{
result = xmalloc (cbData);
if ((RegQueryValueEx (hrootkey, key, NULL, type, (LPBYTE) result,
&cbData)
!= ERROR_SUCCESS)
|| *result == 0)
{
free (result);
result = NULL;
}
}
RegCloseKey (hrootkey);
}
return result;
}
/*
getenv wrapper for Windows
Value is allocated on the heap, and can be free'd.
This is needed to duplicate Emacs's behavior, which is to look for
environment variables in the registry if they don't appear in the
environment. */
char *
w32_getenv (const char *envvar)
{
char *value;
DWORD dwType;
if ((value = getenv (envvar)))
/* Found in the environment. strdup it, because values returned
by getenv cannot be free'd. */
return xstrdup (value);
if (! (value = w32_get_resource (HKEY_CURRENT_USER, envvar, &dwType)) &&
! (value = w32_get_resource (HKEY_LOCAL_MACHINE, envvar, &dwType)))
{
/* "w32console" is what Emacs on Windows uses for tty-type under -nw. */
if (strcmp (envvar, "TERM") == 0)
return xstrdup ("w32console");
/* Found neither in the environment nor in the registry. */
return NULL;
}
if (dwType == REG_SZ)
/* Registry; no need to expand. */
return value;
if (dwType == REG_EXPAND_SZ)
{
DWORD size;
if ((size = ExpandEnvironmentStrings (value, NULL, 0)))
{
char *buffer = xmalloc (size);
if (ExpandEnvironmentStrings (value, buffer, size))
{
/* Found and expanded. */
free (value);
return buffer;
}
/* Error expanding. */
free (buffer);
}
}
/* Not the right type, or not correctly expanded. */
free (value);
return NULL;
}
int w32_window_app (void);
int
w32_window_app (void)
{
static int window_app = -1;
char szTitle[MAX_PATH];
if (window_app < 0)
{
/* Checking for STDOUT does not work; it's a valid handle also in
nonconsole apps. Testing for the console title seems to work. */
window_app = (GetConsoleTitleA (szTitle, MAX_PATH) == 0);
if (window_app)
InitCommonControls ();
}
return window_app;
}
/* execvp wrapper for Windows. Quotes arguments with embedded spaces.
This is necessary due to the broken implementation of exec* routines in
the Microsoft libraries: they concatenate the arguments together without
quoting special characters, and pass the result to CreateProcess, with
predictably bad results. By contrast, POSIX execvp passes the arguments
directly into the argv array of the child process. */
int w32_execvp (const char *, char **);
int
w32_execvp (const char *path, char **argv)
{
int i;
/* Required to allow a .BAT script as alternate editor. */
argv[0] = (char *) alternate_editor;
for (i = 0; argv[i]; i++)
if (strchr (argv[i], ' '))
{
char *quoted = alloca (strlen (argv[i]) + 3);
sprintf (quoted, "\"%s\"", argv[i]);
argv[i] = quoted;
}
return execvp (path, argv);
}
# undef execvp
# define execvp w32_execvp
/* Emulation of ttyname for Windows. */
const char *ttyname (int);
const char *
ttyname (int fd)
{
return "CONOUT$";
}
#endif /* WINDOWSNT */
/* Display a normal or error message.
On Windows, use a message box if compiled as a Windows app. */
static void message (bool, const char *, ...) ATTRIBUTE_FORMAT_PRINTF (2, 3);
static void
message (bool is_error, const char *format, ...)
{
va_list args;
va_start (args, format);
#ifdef WINDOWSNT
if (w32_window_app ())
{
char msg[2048];
vsnprintf (msg, sizeof msg, format, args);
msg[sizeof msg - 1] = '\0';
if (is_error)
MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
else
MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
}
else
#endif
{
FILE *f = is_error ? stderr : stdout;
vfprintf (f, format, args);
fflush (f);
}
va_end (args);
}
/* Decode the options from argv and argc.
The global variable 'optind' will say how many arguments we used up. */
static void
decode_options (int argc, char **argv)
{
alternate_editor = egetenv ("ALTERNATE_EDITOR");
tramp_prefix = egetenv ("EMACSCLIENT_TRAMP");
while (true)
{
int opt = getopt_long_only (argc, argv, shortopts, longopts, NULL);
if (opt < 0)
break;
char* endptr;
switch (opt)
{
case 0:
/* If getopt returns 0, then it has already processed a
long-named option. We should do nothing. */
break;
case 'a':
alternate_editor = optarg;
break;
#ifdef SOCKETS_IN_FILE_SYSTEM
case 's':
socket_name = optarg;
break;
#endif
case 'f':
server_file = optarg;
break;
/* We used to disallow this argument in w32, but it seems better
to allow it, for the occasional case where the user is
connecting with a w32 client to a server compiled with X11
support. */
case 'd':
display = optarg;
break;
case 'n':
nowait = true;
break;
case 'w':
timeout = strtoumax (optarg, &endptr, 10);
if (timeout <= 0 ||
((timeout == INTMAX_MAX || timeout == INTMAX_MIN)
&& errno == ERANGE))
{
fprintf (stderr, "Invalid timeout: \"%s\"\n", optarg);
exit (EXIT_FAILURE);
}
break;
case 'e':
eval = true;
break;
case 'q':
quiet = true;
break;
case 'u':
suppress_output = true;
break;
case 'V':
message (false, "emacsclient %s\n", PACKAGE_VERSION);
exit (EXIT_SUCCESS);
break;
case 't':
tty = true;
create_frame = true;
reuse_frame = false;
break;
case 'c':
create_frame = true;
break;
case 'r':
create_frame = true;
if (!tty)
reuse_frame = true;
break;
case 'p':
parent_id = optarg;
create_frame = true;
break;
case 'H':
print_help_and_exit ();
break;
case 'F':
frame_parameters = optarg;
break;
case 'T':
tramp_prefix = optarg;
break;
default:
message (true, "Try '%s --help' for more information\n", progname);
exit (EXIT_FAILURE);
break;
}
}
/* If the -c option is used (without -t) and no --display argument
is provided, try $DISPLAY.
Without the -c option, we used to set 'display' to $DISPLAY by
default, but this changed the default behavior and is sometimes
inconvenient. So we force users to use "--display $DISPLAY" if
they want Emacs to connect to their current display.
Some window systems have a notion of default display not
reflected in the DISPLAY variable. If the user didn't give us an
explicit display, try this platform-specific after trying the
display in DISPLAY (if any). */
if (create_frame && !tty && !display)
{
#ifndef HAVE_ANDROID
/* Set these here so we use a default_display only when the user
didn't give us an explicit display. */
#if defined (NS_IMPL_COCOA)
alt_display = "ns";
#elif defined (HAVE_NTGUI)
alt_display = "w32";
#elif defined (HAVE_HAIKU)
alt_display = "be";
#endif /* NS_IMPL_COCOA */
#ifdef HAVE_PGTK
display = egetenv ("WAYLAND_DISPLAY");
alt_display = egetenv ("DISPLAY");
#else /* !HAVE_PGTK */
display = egetenv ("DISPLAY");
#endif /* HAVE_PGTK */
#else /* HAVE_ANDROID */
/* Disregard the DISPLAY environment variable under Android.
Several terminal emulator programs furnish their own X
servers and set DISPLAY, but an Android build is incapable of
displaying X frames. */
alt_display = NULL;
display = "android";
#endif /* !HAVE_ANDROID */
}
if (!display)
{
display = alt_display;
alt_display = NULL;
}
/* A null-string display is invalid. */
if (display && !display[0])
display = NULL;
/* If no display is available, new frames are tty frames. */
if (create_frame && !display)
tty = true;
#ifdef WINDOWSNT
/* Emacs on Windows does not support graphical and text terminal
frames in the same instance. So, treat the -t and -c options as
equivalent, and open a new frame on the server's terminal.
Ideally, we would set tty = true only if the server is running in a
console, but alas we don't know that. As a workaround, always
ask for a tty frame, and let server.el figure it out. */
if (create_frame)
{
display = NULL;
tty = true;
}
#endif /* WINDOWSNT */
}
static _Noreturn void
print_help_and_exit (void)
{
/* Spaces and tabs are significant in this message; they're chosen so the
message aligns properly both in a tty and in a Windows message box.
Please try to preserve them; otherwise the output is very hard to read
when using emacsclientw. */
message (false,
"Usage: %s [OPTIONS] FILE...\n%s%s%s", progname, "\
Tell the Emacs server to visit the specified files.\n\
Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
\n\
The following OPTIONS are accepted:\n\
-V, --version Just print version info and return\n\
-H, --help Print this usage information message\n\
-nw, -t, --tty, --no-window-system\n\
Open a new Emacs frame on the current terminal\n\
-c, --create-frame Create a new frame instead of trying to\n\
use the current Emacs frame\n\
-r, --reuse-frame Create a new frame if none exists, otherwise\n\
use the current Emacs frame\n\
", "\
-F ALIST, --frame-parameters=ALIST\n\
Set the parameters of a new frame\n\
-e, --eval Evaluate the FILE arguments as Elisp expressions\n\
-n, --no-wait Don't wait for the server to return\n\
-w, --timeout=SECONDS Seconds to wait before timing out\n\
-q, --quiet Don't display messages on success\n\
-u, --suppress-output Don't display return values from the server\n\
-d DISPLAY, --display=DISPLAY\n\
Visit the file in the given display\n\
", "\
--parent-id=ID Open in parent window ID, via XEmbed\n"
#ifdef SOCKETS_IN_FILE_SYSTEM
"-s SOCKET, --socket-name=SOCKET\n\
Set filename of the UNIX socket for communication\n"
#endif
"-f SERVER, --server-file=SERVER\n\
Set filename of the TCP authentication file\n\
-a EDITOR, --alternate-editor=EDITOR\n\
Editor to fallback to if the server is not running\n"
" If EDITOR is the empty string, start Emacs in daemon\n\
mode and try connecting again\n"
"-T PREFIX, --tramp=PREFIX\n\
PREFIX to prepend to filenames sent by emacsclient\n\
for locating files remotely via Tramp\n"
"\n\
Report bugs with M-x report-emacs-bug.\n");
exit (EXIT_SUCCESS);
}
/* Try to run a different command, or --if no alternate editor is
defined-- exit with an error code.
Uses argv, but gets it from the global variable main_argv. */
static _Noreturn void
fail (void)
{
if (alternate_editor)
{
size_t extra_args_size = (main_argc - optind + 1) * sizeof (char *);
size_t new_argv_size = extra_args_size;
char **new_argv = xmalloc (new_argv_size);
char *s = xstrdup (alternate_editor);
ptrdiff_t toks = 0;
/* Unpack alternate_editor's space-separated tokens into new_argv. */
for (char *tok = s; tok != NULL && *tok != '\0';)
{
/* Allocate new token. */
++toks;
new_argv = xrealloc (new_argv,
new_argv_size + toks * sizeof (char *));
/* Skip leading delimiters, and set separator, skipping any
opening quote. */
size_t skip = strspn (tok, " \"");
tok += skip;
char sep = (skip > 0 && tok[-1] == '"') ? '"' : ' ';
/* Record start of token. */
new_argv[toks - 1] = tok;
/* Find end of token and overwrite it with NUL. */
tok = strchr (tok, sep);
if (tok != NULL)
*tok++ = '\0';
}
/* Append main_argv arguments to new_argv. */
memcpy (&new_argv[toks], main_argv + optind, extra_args_size);
execvp (*new_argv, new_argv);
message (true, "%s: error executing alternate editor \"%s\"\n",
progname, alternate_editor);
}
exit (EXIT_FAILURE);
}
#ifdef SOCKETS_IN_FILE_SYSTEM
static void act_on_signals (HSOCKET);
#else
static void act_on_signals (HSOCKET s) {}
static void init_signals (void) {}
#endif
enum { AUTH_KEY_LENGTH = 64 };
static void
sock_err_message (const char *function_name)
{
#ifdef WINDOWSNT
/* On Windows, the socket library was historically separate from the
standard C library, so errors are handled differently. */
if (w32_window_app () && alternate_editor)
return;
char *msg = NULL;
FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_ARGUMENT_ARRAY,
NULL, WSAGetLastError (), 0, (LPTSTR)&msg, 0, NULL);
message (true, "%s: %s: %s\n", progname, function_name, msg);
LocalFree (msg);
#else
message (true, "%s: %s: %s\n", progname, function_name, strerror (errno));
#endif
}
/* Send to S the data in *DATA when either
- the data's last byte is '\n', or
- the buffer is full (but this shouldn't happen)
Otherwise, just accumulate the data. */
static void
send_to_emacs (HSOCKET s, const char *data)
{
enum { SEND_BUFFER_SIZE = 4096 };
/* Buffer to accumulate data to send in TCP connections. */
static char send_buffer[SEND_BUFFER_SIZE + 1];
/* Fill pointer for the send buffer. */
static int sblen;
for (ptrdiff_t dlen = strlen (data); dlen != 0; )
{
int part = min (dlen, SEND_BUFFER_SIZE - sblen);
memcpy (&send_buffer[sblen], data, part);
data += part;
sblen += part;
if (sblen == SEND_BUFFER_SIZE
|| (0 < sblen && send_buffer[sblen - 1] == '\n'))
{
int sent;
while ((sent = send (s, send_buffer, sblen, 0)) < 0)
{
if (errno != EINTR)
{
message (true, "%s: failed to send %d bytes to socket: %s\n",
progname, sblen, strerror (errno));
fail ();
}
/* Act on signals not requiring communication to Emacs,
but defer action on the others to avoid confusing the
communication currently in progress. */
act_on_signals (INVALID_SOCKET);
}
sblen -= sent;
memmove (send_buffer, &send_buffer[sent], sblen);
}
dlen -= part;
}
}
/* In STR, insert a & before each &, each space, each newline, and
any initial -. Change spaces to underscores, too, so that the
return value never contains a space.
Does not change the string. Outputs the result to S. */
static void
quote_argument (HSOCKET s, const char *str)
{
char *copy = xmalloc (strlen (str) * 2 + 1);
char *q = copy;
if (*str == '-')
*q++ = '&', *q++ = *str++;
for (; *str; str++)
{
char c = *str;
if (c == ' ')
*q++ = '&', c = '_';
else if (c == '\n')
*q++ = '&', c = 'n';
else if (c == '&')
*q++ = '&';
*q++ = c;
}
*q = 0;
send_to_emacs (s, copy);
free (copy);
}
/* The inverse of quote_argument. Remove quoting in string STR by
modifying the addressed string in place. Return STR. */
static char *
unquote_argument (char *str)
{
char const *p = str;
char *q = str;
char c;
do
{
c = *p++;
if (c == '&')
{
c = *p++;
if (c == '_')
c = ' ';
else if (c == 'n')
c = '\n';
}
*q++ = c;
}
while (c);
return str;
}
#ifdef WINDOWSNT
/* Wrapper to make WSACleanup a cdecl, as required by atexit. */
void __cdecl close_winsock (void);
void __cdecl
close_winsock (void)
{
WSACleanup ();
}
/* Initialize the WinSock2 library. */
void initialize_sockets (void);
void
initialize_sockets (void)
{
WSADATA wsaData;
if (WSAStartup (MAKEWORD (2, 0), &wsaData))
{
message (true, "%s: error initializing WinSock2\n", progname);
exit (EXIT_FAILURE);
}
atexit (close_winsock);
}
#endif /* WINDOWSNT */
/* If the home directory is HOME, and XDG_CONFIG_HOME's value is XDG,
return the configuration file with basename CONFIG_FILE. Fail if
the configuration file could not be opened. */
static FILE *
open_config (char const *home, char const *xdg, char const *config_file)
{
ptrdiff_t xdgsubdirsize = xdg ? strlen (xdg) + sizeof "/emacs/server/" : 0;
ptrdiff_t homesuffixsizemax = max (sizeof "/.config/emacs/server/",
sizeof "/.emacs.d/server/");
ptrdiff_t homesubdirsizemax = home ? strlen (home) + homesuffixsizemax : 0;
char *configname = xmalloc (max (xdgsubdirsize, homesubdirsizemax)
+ strlen (config_file));
FILE *config;
if (home)
{
strcpy (stpcpy (stpcpy (configname, home), "/.emacs.d/server/"),
config_file);
config = fopen (configname, "rb");
}
else
config = NULL;
if (! config && (xdg || home))
{
strcpy ((xdg
? stpcpy (stpcpy (configname, xdg), "/emacs/server/")
: stpcpy (stpcpy (configname, home), "/.config/emacs/server/")),
config_file);
config = fopen (configname, "rb");
}
free (configname);
return config;
}
/* Read the information needed to set up a TCP comm channel with
the Emacs server: host, port, and authentication string. */
static bool
get_server_config (const char *config_file, struct sockaddr_in *server,
char *authentication)
{
char dotted[32];
char *port;
FILE *config;
if (IS_ABSOLUTE_FILE_NAME (config_file))
config = fopen (config_file, "rb");
else
{