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