Merge remote-tracking branch 'origin/master' into for-steve
[sxemacs] / lib-src / gnuclient.c
1 /* -*-C-*-
2  Client code to allow local and remote editing of files by XEmacs.
3  Copyright (C) 1989 Free Software Foundation, Inc.
4  Copyright (C) 1995 Sun Microsystems, Inc.
5  Copyright (C) 1997 Free Software Foundation, Inc.
6
7 This file is part of SXEmacs.
8
9 SXEmacs is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13
14 SXEmacs is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
22  Author: Andy Norman (ange@hplb.hpl.hp.com), based on
23          'etc/emacsclient.c' from the GNU Emacs 18.52 distribution.
24
25  Please mail bugs and suggestions to the XEmacs maintainer.
26 */
27
28 /*
29  * This file incorporates new features added by Bob Weiner <weiner@mot.com>,
30  * Darrell Kindred <dkindred@cmu.edu> and Arup Mukherjee <arup@cmu.edu>.
31  * GNUATTACH support added by Ben Wing <wing@xemacs.org>.
32  * Please see the note at the end of the README file for details.
33  *
34  * (If gnuserv came bundled with your emacs, the README file is probably
35  * ../etc/gnuserv.README relative to the directory containing this file)
36  */
37
38 #include "gnuserv.h"
39
40 char gnuserv_version[] = "gnuclient version " GNUSERV_VERSION;
41
42 #ifdef HAVE_GETOPT_H
43 #include <getopt.h>
44 #endif
45
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <sys/types.h>
49 #include <sysfile.h>
50 #include <assert.h>
51
52 #ifdef HAVE_STRING_H
53 #include <string.h>
54 #endif                          /* HAVE_STRING_H */
55
56 #ifdef HAVE_UNISTD_H
57 #include <unistd.h>
58 #endif                          /* HAVE_UNISTD_H */
59
60 #include <signal.h>
61
62 #if !defined(SYSV_IPC) && !defined(UNIX_DOMAIN_SOCKETS) && \
63     !defined(INTERNET_DOMAIN_SOCKETS)
64 int main(int argc, char *argv[])
65 {
66         fprintf(stderr, "Sorry, the Emacs server is only "
67                 "supported on systems that have\n");
68         fprintf(stderr, "Unix Domain sockets, Internet Domain "
69                 "sockets or System V IPC.\n");
70         exit(1);
71 }                               /* main */
72 #else                           /* SYSV_IPC || UNIX_DOMAIN_SOCKETS || INTERNET_DOMAIN_SOCKETS */
73
74 static char cwd[MAXPATHLEN + 2];        /* current working directory when calculated */
75 static char *cp = NULL;         /* ptr into valid bit of cwd above */
76
77 static pid_t emacs_pid;         /* Process id for emacs process */
78
79 static void
80 initialize_signals(void);
81
82 static void tell_emacs_to_resume(int sig)
83 {
84         char buffer[GSERV_BUFSZ + 1];
85         int sz;
86         int s;                  /* socket / msqid to server */
87         int connect_type;       /* CONN_UNIX, CONN_INTERNET, or
88                                    ONN_IPC */
89
90         /* Why is SYSV so retarded? */
91         /* We want emacs to realize that we are resuming */
92 #ifdef SIGCONT
93         signal(SIGCONT, tell_emacs_to_resume);
94 #endif
95
96         connect_type = make_connection(NULL, 0, &s);
97
98         SNPRINTF(sz, buffer, sizeof(buffer),
99                  "(gnuserv-eval '(resume-pid-console %d))", (int)getpid());
100         send_string(s, buffer);
101
102 #ifdef SYSV_IPC
103         if (connect_type == (int)CONN_IPC)
104                 disconnect_from_ipc_server(s, msgp, FALSE);
105 #else                           /* !SYSV_IPC */
106         if (connect_type != (int)CONN_IPC)
107                 disconnect_from_server(s, FALSE);
108 #endif                          /* !SYSV_IPC */
109 }
110
111 static void
112 pass_signal_to_emacs(int sig)
113 {
114         if (kill(emacs_pid, sig) == -1) {
115                 fprintf(stderr,
116                         "gnuclient: Could not pass signal to emacs process\n");
117                 exit(1);
118         }
119         initialize_signals();
120 }
121
122 static void
123 initialize_signals(void)
124 {
125         /* Set up signal handler to pass relevant signals to emacs process.
126            We used to send SIGSEGV, SIGBUS, SIGPIPE, SIGILL and others to
127            Emacs, but I think it's better not to.  I can see no reason why
128            Emacs should SIGSEGV whenever gnuclient SIGSEGV-s, etc.  */
129         signal(SIGQUIT, pass_signal_to_emacs);
130         signal(SIGINT, pass_signal_to_emacs);
131 #ifdef SIGWINCH
132         signal(SIGWINCH, pass_signal_to_emacs);
133 #endif
134
135 #ifdef SIGCONT
136         /* We want emacs to realize that we are resuming */
137         signal(SIGCONT, tell_emacs_to_resume);
138 #endif
139 }
140
141 /*
142   get_current_working_directory -- return the cwd.
143 */
144 static char *get_current_working_directory(void)
145 {
146         if (cp == NULL) {       /* haven't calculated it yet */
147 #ifdef HAVE_GETCWD
148                 if (getcwd(cwd, MAXPATHLEN) == NULL)
149 #else
150                 if (getwd(cwd) == 0)
151 #endif                          /* HAVE_GETCWD */
152                 {
153                         perror(progname);
154                         fprintf(stderr,
155                                 "%s: unable to get current working directory\n",
156                                 progname);
157                         exit(1);
158                 }
159
160                 /* if */
161                 /* on some systems, cwd can look like '@machine/' ... */
162                 /* ignore everything before the first '/' */
163                 for (cp = cwd; *cp && *cp != '/'; ++cp) ;
164
165         }
166         /* if */
167         return cp;
168
169 }                               /* get_current_working_directory */
170
171 /*
172   filename_expand -- try to convert the given filename into a fully-qualified
173                      pathname.
174 */
175 static void
176 filename_expand(char *fullpath, char *filename, size_t fullsize)
177 {
178 /* fullpath - returned full pathname */
179 /* filename - filename to expand */
180         size_t len;
181         fullpath[0] = '\0';
182
183         if (filename[0] && filename[0] == '/') {
184                 /* Absolute (unix-style) pathname.  Do nothing */
185                 strncat(fullpath, filename, fullsize-1);
186         } else {
187                 /* Assume relative Unix style path.  Get the current directory
188                  * and prepend it.  FIXME: need to fix the case of DOS paths
189                  * like "\foo", where we need to get the current drive. */
190                 strncat(fullpath, get_current_working_directory(), fullsize-1);
191                 len = strlen(fullpath);
192
193                 /* trailing slash already? */
194                 if (len > 0 && fullpath[len - 1] == '/') {
195                         /* yep */
196                         ;
197                 } else if (len < fullsize-1) {
198                         /* nope, append trailing slash */
199                         strcat(fullpath, "/");
200                 }
201                 /* Don't forget to add the filename! */
202                 strncat(fullpath, filename, fullsize - len - 1);
203         }
204         return;
205 }
206
207 /* Encase the string in quotes, escape all the backslashes and quotes
208    in string.  */
209 static char *clean_string(const char *s)
210 {
211         int i = 0;
212         char *p, *res;
213
214         {
215                 const char *const_p;
216                 for (const_p = s; *const_p; const_p++, i++) {
217                         if (*const_p == '\\' || *const_p == '\"')
218                                 ++i;
219                         else if (*const_p == '\004')
220                                 i += 3;
221                 }
222         }
223
224         p = res = (char *)malloc(i + 2 + 1);
225         *p++ = '\"';
226         for (; *s; p++, s++) {
227                 switch (*s) {
228                 case '\\':
229                         *p++ = '\\';
230                         *p = '\\';
231                         break;
232                 case '\"':
233                         *p++ = '\\';
234                         *p = '\"';
235                         break;
236                 case '\004':
237                         *p++ = '\\';
238                         *p++ = 'C';
239                         *p++ = '-';
240                         *p = 'd';
241                         break;
242                 default:
243                         *p = *s;
244                 }
245         }
246         *p++ = '\"';
247         *p = '\0';
248         return res;
249 }
250
251 #define GET_ARGUMENT(var, desc)                                         \
252         do {                                                            \
253                 if (*(p + 1)) {                                         \
254                         (var) = p + 1;                                  \
255                 } else {                                                \
256                         if (!argv[++i]) {                               \
257                                 fprintf(stderr, "%s: `%s' must be "     \
258                                         "followed by an argument\n",    \
259                                         progname, desc);                \
260                                 exit (1);                               \
261                         }                                               \
262                         (var) = argv[i];                                \
263                 }                                                       \
264                 over = 1;                                               \
265         } while (0)
266
267 /* A strdup imitation. */
268 static char *my_strdup(const char *s)
269 {
270         char *new_s = (char *)malloc(strlen(s) + 1);
271         if (new_s)
272                 strcpy(new_s, s);
273         return new_s;
274 }
275
276 int main(int argc, char *argv[])
277 {
278         int starting_line = 1;  /* line to start editing at */
279         char command[MAXPATHLEN + 50];  /* emacs command buffer */
280         char fullpath[MAXPATHLEN + 1];  /* full pathname to file */
281         char *eval_form = NULL; /* form to evaluate with `-eval' */
282         char *eval_function = NULL;     /* function to evaluate with `-f' */
283         char *load_library = NULL;      /* library to load */
284         int quick = 0;          /* quick edit, don't wait for user to
285                                    finish */
286         int batch = 0;          /* batch mode */
287         int view = 0;           /* view only. */
288         int nofiles = 0;
289         int errflg = 0;         /* option error */
290         int s;                  /* socket / msqid to server */
291         int connect_type;       /* CONN_UNIX, CONN_INTERNET, or
292                                  * CONN_IPC */
293         int suppress_windows_system = 0;
294         char *display = NULL;
295 #ifdef INTERNET_DOMAIN_SOCKETS
296         char *hostarg = NULL;   /* remote hostname */
297         char *remotearg;
298         char thishost[HOSTNAMSZ];       /* this hostname */
299         char remotepath[MAXPATHLEN + 1];        /* remote pathname */
300         int rflg = 0;           /* pathname given on cmdline */
301         char *portarg;
302         unsigned short port = 0;        /* port to server */
303 #endif                          /* INTERNET_DOMAIN_SOCKETS */
304         char *path;             /* used indiscriminately */
305 #ifdef SYSV_IPC
306         struct msgbuf *msgp;    /* message */
307 #endif                          /* SYSV_IPC */
308         char *tty = NULL;
309         char buffer[GSERV_BUFSZ + 1];   /* buffer to read pid */
310         char result[GSERV_BUFSZ + 1];
311         int i;
312         int sz;
313         size_t msz;
314
315 #ifdef INTERNET_DOMAIN_SOCKETS
316         memset(remotepath, 0, sizeof(remotepath));
317 #endif                          /* INTERNET_DOMAIN_SOCKETS */
318
319         progname = strrchr(argv[0], '/');
320         if (progname)
321                 ++progname;
322         else
323                 progname = argv[0];
324
325 #ifdef USE_TMPDIR
326         tmpdir = getenv("TMPDIR");
327 #endif
328         if (!tmpdir)
329                 tmpdir = "/tmp";
330
331         display = getenv("DISPLAY");
332         if (display)
333                 display = my_strdup(display);
334         else
335                 suppress_windows_system = 1;
336
337         for (i = 1; argv[i] && !errflg; i++) {
338                 if (*argv[i] != '-')
339                         break;
340                 else if (*argv[i] == '-'
341                          && (*(argv[i] + 1) == '\0'
342                              || (*(argv[i] + 1) == '-'
343                                  && *(argv[i] + 2) == '\0'))) {
344                         /* `-' or `--' */
345                         ++i;
346                         break;
347                 }
348
349                 if (!strcmp(argv[i], "-batch") || !strcmp(argv[i], "--batch"))
350                         batch = 1;
351                 else if (!strcmp(argv[i], "-eval")
352                          || !strcmp(argv[i], "--eval")) {
353                         if (!argv[++i]) {
354                                 fprintf(stderr,
355                                         "%s: `-eval' must be followed by an argument\n",
356                                         progname);
357                                 exit(1);
358                         }
359                         eval_form = argv[i];
360                 } else if (!strcmp(argv[i], "-display")
361                            || !strcmp(argv[i], "--display")) {
362                         suppress_windows_system = 0;
363                         if (!argv[++i]) {
364                                 fprintf(stderr,
365                                         "%s: `-display' must be followed by an argument\n",
366                                         progname);
367                                 exit(1);
368                         }
369                         if (display)
370                                 free(display);
371                         /* no need to strdup. */
372                         display = argv[i];
373                 } else if (!strcmp(argv[i], "-nw"))
374                         suppress_windows_system = 1;
375                 else {
376                         /* Iterate over one-letter options. */
377                         char *p;
378                         int over = 0;
379                         for (p = argv[i] + 1; *p && !over; p++) {
380                                 switch (*p) {
381                                 case 'q':
382                                         quick = 1;
383                                         break;
384                                 case 'v':
385                                         view = 1;
386                                         break;
387                                 case 'f':
388                                         GET_ARGUMENT(eval_function, "-f");
389                                         break;
390                                 case 'l':
391                                         GET_ARGUMENT(load_library, "-l");
392                                         break;
393 #ifdef INTERNET_DOMAIN_SOCKETS
394                                 case 'h':
395                                         GET_ARGUMENT(hostarg, "-h");
396                                         break;
397                                 case 'p':
398                                         GET_ARGUMENT(portarg, "-p");
399                                         port = atoi(portarg);
400                                         break;
401                                 case 'r':
402                                         GET_ARGUMENT(remotearg, "-r");
403                                         strncpy(remotepath, remotearg, sizeof(remotepath));
404                                         remotepath[sizeof(remotepath)-1]='\0';
405                                         rflg = 1;
406                                         break;
407 #endif                          /* INTERNET_DOMAIN_SOCKETS */
408                                 default:
409                                         errflg = 1;
410                                 }
411                         }       /* for */
412                 }               /* else */
413         }                       /* for */
414
415         if (errflg) {
416                 fprintf(stderr,
417 #ifdef INTERNET_DOMAIN_SOCKETS
418                         "Usage: %s [-nw] [-display display] [-q] [-v] [-l library]\n"
419                         "       [-batch] [-f function] [-eval form]\n"
420                         "       [-h host] [-p port] [-r remote-path] [[+line] file] ...\n",
421 #else                           /* !INTERNET_DOMAIN_SOCKETS */
422                         "Usage: %s [-nw] [-q] [-v] [-l library] [-f function] [-eval form] "
423                         "[[+line] path] ...\n",
424 #endif                          /* !INTERNET_DOMAIN_SOCKETS */
425                         progname);
426                 exit(1);
427         }
428         if (batch && argv[i]) {
429                 fprintf(stderr, "%s: Cannot specify `-batch' with file names\n",
430                         progname);
431                 exit(1);
432         }
433 #if defined(INTERNET_DOMAIN_SOCKETS)
434         if (suppress_windows_system && hostarg) {
435                 fprintf(stderr, "%s: Remote editing is available only on X\n",
436                         progname);
437                 exit(1);
438         }
439 #endif
440         *result = '\0';
441         if (eval_function || eval_form || load_library) {
442 #if defined(INTERNET_DOMAIN_SOCKETS)
443                 connect_type = make_connection(hostarg, port, &s);
444 #else
445                 connect_type = make_connection(NULL, 0, &s);
446 #endif
447                 SNPRINTF(sz, command, sizeof(command),
448                          "(gnuserv-eval%s '(progn ", quick ? "-quickly" : "");
449                 send_string(s, command);
450                 if (load_library) {
451                         send_string(s, "(load-library ");
452                         send_string(s, clean_string(load_library));
453                         send_string(s, ") ");
454                 }
455                 if (eval_form) {
456                         send_string(s, eval_form);
457                 }
458                 if (eval_function) {
459                         send_string(s, "(");
460                         send_string(s, eval_function);
461                         send_string(s, ")");
462                 }
463                 send_string(s, "))");
464                 /* disconnect already sends EOT_STR */
465 #ifdef SYSV_IPC
466                 if (connect_type == (int)CONN_IPC)
467                         disconnect_from_ipc_server(s, msgp, batch && !quick);
468 #else                           /* !SYSV_IPC */
469                 if (connect_type != (int)CONN_IPC)
470                         disconnect_from_server(s, batch && !quick);
471 #endif                          /* !SYSV_IPC */
472         } /* eval_function || eval_form || load_library */
473         else if (batch) {
474                 /* no sexp on the command line, so read it from stdin */
475                 int nb;
476
477 #if defined(INTERNET_DOMAIN_SOCKETS)
478                 connect_type = make_connection(hostarg, port, &s);
479 #else
480                 connect_type = make_connection(NULL, 0, &s);
481 #endif
482                 SNPRINTF(sz, command, sizeof(command),
483                          "(gnuserv-eval%s '(progn ", quick ? "-quickly" : "");
484                 send_string(s, command);
485
486                 while ((nb = read(fileno(stdin), buffer, GSERV_BUFSZ - 1)) > 0) {
487                         buffer[nb] = '\0';
488                         send_string(s, buffer);
489                 }
490                 send_string(s, "))");
491                 /* disconnect already sends EOT_STR */
492 #ifdef SYSV_IPC
493                 if (connect_type == (int)CONN_IPC)
494                         disconnect_from_ipc_server(s, msgp, batch && !quick);
495 #else                           /* !SYSV_IPC */
496                 if (connect_type != (int)CONN_IPC)
497                         disconnect_from_server(s, batch && !quick);
498 #endif                          /* !SYSV_IPC */
499         }
500
501         if (!batch) {
502                 if (suppress_windows_system) {
503                         tty = ttyname(0);
504                         if (!tty) {
505                                 fprintf(stderr, "%s: Not connected to a tty",
506                                         progname);
507                                 exit(1);
508                         }
509 #if defined(INTERNET_DOMAIN_SOCKETS)
510                         connect_type = make_connection(hostarg, port, &s);
511 #else
512                         connect_type = make_connection(NULL, 0, &s);
513 #endif
514                         send_string(s, "(gnuserv-eval '(emacs-pid))");
515                         send_string(s, EOT_STR);
516
517                         if (read_line(s, buffer) == 0) {
518                                 fprintf(stderr,
519                                         "%s: Could not establish Emacs process id\n",
520                                         progname);
521                                 exit(1);
522                         }
523                         /* Don't do disconnect_from_server because we have already read
524                            data, and disconnect doesn't do anything else. */
525 #ifdef SYSV_IPC
526                         if (connect_type == (int)CONN_IPC)
527                                 disconnect_from_ipc_server(s, msgp, FALSE);
528 #endif                          /* !SYSV_IPC */
529
530                         emacs_pid = (pid_t) atol(buffer);
531                         initialize_signals();
532                 }
533                 /* suppress_windows_system */
534 #if defined(INTERNET_DOMAIN_SOCKETS)
535                 connect_type = make_connection(hostarg, port, &s);
536 #else
537                 connect_type = make_connection(NULL, 0, &s);
538 #endif
539
540 #ifdef INTERNET_DOMAIN_SOCKETS
541                 if (connect_type == (int)CONN_INTERNET) {
542                         char *ptr;
543                         gethostname(thishost, HOSTNAMSZ);
544                         if (!rflg) {    /* attempt to generate a path
545                                          * to this machine */
546                                 if ((ptr = getenv("GNU_NODE")) != NULL) {
547                                         /* user specified a path */
548                                         strncpy(remotepath, ptr, sizeof(remotepath)-1);
549                                         remotepath[sizeof(remotepath)-1]='\0';
550                                 }
551                         }
552 #if 0                           /* This is really bogus... re-enable it if you must have it! */
553 #if defined (hp9000s300) || defined (hp9000s800)
554                         else if (strcmp(thishost, hostarg)) {   /* try /net/thishost */
555                                 strcpy(remotepath, "/net/");    /* (this fails using internet
556                                                                    addresses) */
557                                 strcat(remotepath, thishost);
558                         }
559 #endif
560 #endif
561                 } else {        /* same machines, no need for path */
562                         remotepath[0] = '\0';   /* default is the empty path */
563                 }
564 #endif                          /* INTERNET_DOMAIN_SOCKETS */
565
566 #ifdef SYSV_IPC
567                 if ((msgp = (struct msgbuf *)
568                      malloc(sizeof *msgp + GSERV_BUFSZ)) == NULL) {
569                         fprintf(stderr,
570                                 "%s: not enough memory for message buffer\n",
571                                 progname);
572                         exit(1);
573                 }
574                 /* if */
575                 msgp->mtext[0] = '\0';  /* ready for later strcats */
576 #endif                          /* SYSV_IPC */
577
578                 if (suppress_windows_system) {
579                         char *term = getenv("TERM");
580                         pid_t pid = getpid();
581
582                         if (!term) {
583                                 fprintf(stderr, "%s: unknown terminal type\n",
584                                         progname);
585                                 exit(1);
586                         }
587                         SNPRINTF(sz, command, sizeof(command),
588                                  "(gnuserv-edit-files '(tty %s %s %d) '(",
589                                  clean_string(tty), clean_string(term),
590                                  (int)pid);
591                 } else {        /* !suppress_windows_system */
592
593                         if (0) ;
594 #ifdef HAVE_X_WINDOWS
595                         else if (display) {
596                                 SNPRINTF(sz, command, sizeof(command),
597                                          "(gnuserv-edit-files '(x %s) '(",
598                                          clean_string(display));
599                         }
600 #endif
601                 }               /* !suppress_windows_system */
602                 send_string(s, command);
603
604                 if (!argv[i])
605                         nofiles = 1;
606
607                 for (; argv[i]; i++) {
608                         if (i < argc - 1 && *argv[i] == '+') {
609                                 starting_line = atoi(argv[i++]);
610                         } else {
611                                 starting_line = 1;
612                         }
613                         /* If the last argument is +something, treat it as a
614                            file. */
615                         if (i == argc) {
616                                 starting_line = 1;
617                                 --i;
618                         }
619                         filename_expand(fullpath, argv[i], sizeof(fullpath));
620 #ifdef INTERNET_DOMAIN_SOCKETS
621                         msz = strlen(remotepath) + strlen(fullpath) + 1;
622                         path = (char*)malloc(msz);
623                         SNPRINTF(sz, path, msz, "%s%s", remotepath, fullpath);
624 #else  /* !INTERNET_DOMAIN_SOCKETS */
625                         path = my_strdup(fullpath);
626 #endif  /* INTERNET_DOMAIN_SOCKETS */
627                         SNPRINTF(sz, command, sizeof(command),
628                                 "(%d . %s)", starting_line, clean_string(path));
629                         send_string(s, command);
630                         free(path);
631                 }
632
633                 SNPRINTF(sz, command, sizeof(command), ")%s%s",
634                          (quick || (nofiles && !suppress_windows_system))
635                          ? " 'quick"
636                          : "",
637                          view ? " 'view" : "");
638                 send_string(s, command);
639                 send_string(s, ")");
640
641 #ifdef SYSV_IPC
642                 if (connect_type == (int)CONN_IPC)
643                         disconnect_from_ipc_server(s, msgp, FALSE);
644 #else                           /* !SYSV_IPC */
645                 if (connect_type != (int)CONN_IPC)
646                         disconnect_from_server(s, FALSE);
647 #endif                          /* !SYSV_IPC */
648         }
649
650         /* not batch */
651         return 0;
652
653 }
654
655 #endif  /* SYSV_IPC || UNIX_DOMAIN_SOCKETS || INTERNET_DOMAIN_SOCKETS */