xstrncpy saga
[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
221         {
222                 const char *const_p;
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
231         p = res = (char *)malloc(i + 2 + 1);
232         *p++ = '\"';
233         for (; *s; p++, s++) {
234                 switch (*s) {
235                 case '\\':
236                         *p++ = '\\';
237                         *p = '\\';
238                         break;
239                 case '\"':
240                         *p++ = '\\';
241                         *p = '\"';
242                         break;
243                 case '\004':
244                         *p++ = '\\';
245                         *p++ = 'C';
246                         *p++ = '-';
247                         *p = 'd';
248                         break;
249                 default:
250                         *p = *s;
251                 }
252         }
253         *p++ = '\"';
254         *p = '\0';
255         return res;
256 }
257
258 #define GET_ARGUMENT(var, desc)                                         \
259         do {                                                            \
260                 if (*(p + 1)) {                                         \
261                         (var) = p + 1;                                  \
262                 } else {                                                \
263                         if (!argv[++i]) {                               \
264                                 fprintf(stderr, "%s: `%s' must be "     \
265                                         "followed by an argument\n",    \
266                                         progname, desc);                \
267                                 exit (1);                               \
268                         }                                               \
269                         (var) = argv[i];                                \
270                 }                                                       \
271                 over = 1;                                               \
272         } while (0)
273
274 /* A strdup imitation. */
275 static char *my_strdup(const char *s)
276 {
277         char *new_s = (char *)malloc(strlen(s) + 1);
278         if (new_s)
279                 strcpy(new_s, s);
280         return new_s;
281 }
282
283 int main(int argc, char *argv[])
284 {
285         int starting_line = 1;  /* line to start editing at */
286         char command[MAXPATHLEN + 50];  /* emacs command buffer */
287         char fullpath[MAXPATHLEN + 1];  /* full pathname to file */
288         char *eval_form = NULL; /* form to evaluate with `-eval' */
289         char *eval_function = NULL;     /* function to evaluate with `-f' */
290         char *load_library = NULL;      /* library to load */
291         int quick = 0;          /* quick edit, don't wait for user to
292                                    finish */
293         int batch = 0;          /* batch mode */
294         int view = 0;           /* view only. */
295         int nofiles = 0;
296         int errflg = 0;         /* option error */
297         int s;                  /* socket / msqid to server */
298         int connect_type;       /* CONN_UNIX, CONN_INTERNET, or
299                                  * CONN_IPC */
300         int suppress_windows_system = 0;
301         char *display = NULL;
302 #ifdef INTERNET_DOMAIN_SOCKETS
303         char *hostarg = NULL;   /* remote hostname */
304         char *remotearg;
305         char thishost[HOSTNAMSZ];       /* this hostname */
306         char remotepath[MAXPATHLEN + 1];        /* remote pathname */
307         int rflg = 0;           /* pathname given on cmdline */
308         char *portarg;
309         unsigned short port = 0;        /* port to server */
310 #endif                          /* INTERNET_DOMAIN_SOCKETS */
311         char *path;             /* used indiscriminately */
312 #ifdef SYSV_IPC
313         struct msgbuf *msgp;    /* message */
314 #endif                          /* SYSV_IPC */
315         char *tty = NULL;
316         char buffer[GSERV_BUFSZ + 1];   /* buffer to read pid */
317         char result[GSERV_BUFSZ + 1];
318         int i;
319         int sz;
320         size_t msz;
321
322 #ifdef INTERNET_DOMAIN_SOCKETS
323         memset(remotepath, 0, sizeof(remotepath));
324 #endif                          /* INTERNET_DOMAIN_SOCKETS */
325
326         progname = strrchr(argv[0], '/');
327         if (progname)
328                 ++progname;
329         else
330                 progname = argv[0];
331
332 #ifdef USE_TMPDIR
333         tmpdir = getenv("TMPDIR");
334 #endif
335         if (!tmpdir)
336                 tmpdir = "/tmp";
337
338         display = getenv("DISPLAY");
339         if (display)
340                 display = my_strdup(display);
341         else
342                 suppress_windows_system = 1;
343
344         for (i = 1; argv[i] && !errflg; i++) {
345                 if (*argv[i] != '-')
346                         break;
347                 else if (*argv[i] == '-'
348                          && (*(argv[i] + 1) == '\0'
349                              || (*(argv[i] + 1) == '-'
350                                  && *(argv[i] + 2) == '\0'))) {
351                         /* `-' or `--' */
352                         ++i;
353                         break;
354                 }
355
356                 if (!strcmp(argv[i], "-batch") || !strcmp(argv[i], "--batch"))
357                         batch = 1;
358                 else if (!strcmp(argv[i], "-eval")
359                          || !strcmp(argv[i], "--eval")) {
360                         if (!argv[++i]) {
361                                 fprintf(stderr,
362                                         "%s: `-eval' must be followed by an argument\n",
363                                         progname);
364                                 exit(1);
365                         }
366                         eval_form = argv[i];
367                 } else if (!strcmp(argv[i], "-display")
368                            || !strcmp(argv[i], "--display")) {
369                         suppress_windows_system = 0;
370                         if (!argv[++i]) {
371                                 fprintf(stderr,
372                                         "%s: `-display' must be followed by an argument\n",
373                                         progname);
374                                 exit(1);
375                         }
376                         if (display)
377                                 free(display);
378                         /* no need to strdup. */
379                         display = argv[i];
380                 } else if (!strcmp(argv[i], "-nw"))
381                         suppress_windows_system = 1;
382                 else {
383                         /* Iterate over one-letter options. */
384                         char *p;
385                         int over = 0;
386                         for (p = argv[i] + 1; *p && !over; p++) {
387                                 switch (*p) {
388                                 case 'q':
389                                         quick = 1;
390                                         break;
391                                 case 'v':
392                                         view = 1;
393                                         break;
394                                 case 'f':
395                                         GET_ARGUMENT(eval_function, "-f");
396                                         break;
397                                 case 'l':
398                                         GET_ARGUMENT(load_library, "-l");
399                                         break;
400 #ifdef INTERNET_DOMAIN_SOCKETS
401                                 case 'h':
402                                         GET_ARGUMENT(hostarg, "-h");
403                                         break;
404                                 case 'p':
405                                         GET_ARGUMENT(portarg, "-p");
406                                         port = atoi(portarg);
407                                         break;
408                                 case 'r':
409                                         GET_ARGUMENT(remotearg, "-r");
410                                         xstrncpy(remotepath, remotearg, sizeof(remotepath));
411                                         remotepath[sizeof(remotepath)-1]='\0';
412                                         rflg = 1;
413                                         break;
414 #endif                          /* INTERNET_DOMAIN_SOCKETS */
415                                 default:
416                                         errflg = 1;
417                                 }
418                         }       /* for */
419                 }               /* else */
420         }                       /* for */
421
422         if (errflg) {
423                 fprintf(stderr,
424 #ifdef INTERNET_DOMAIN_SOCKETS
425                         "Usage: %s [-nw] [-display display] [-q] [-v] [-l library]\n"
426                         "       [-batch] [-f function] [-eval form]\n"
427                         "       [-h host] [-p port] [-r remote-path] [[+line] file] ...\n",
428 #else                           /* !INTERNET_DOMAIN_SOCKETS */
429                         "Usage: %s [-nw] [-q] [-v] [-l library] [-f function] [-eval form] "
430                         "[[+line] path] ...\n",
431 #endif                          /* !INTERNET_DOMAIN_SOCKETS */
432                         progname);
433                 exit(1);
434         }
435         if (batch && argv[i]) {
436                 fprintf(stderr, "%s: Cannot specify `-batch' with file names\n",
437                         progname);
438                 exit(1);
439         }
440 #if defined(INTERNET_DOMAIN_SOCKETS)
441         if (suppress_windows_system && hostarg) {
442                 fprintf(stderr, "%s: Remote editing is available only on X\n",
443                         progname);
444                 exit(1);
445         }
446 #endif
447         *result = '\0';
448         if (eval_function || eval_form || load_library) {
449 #if defined(INTERNET_DOMAIN_SOCKETS)
450                 connect_type = make_connection(hostarg, port, &s);
451 #else
452                 connect_type = make_connection(NULL, 0, &s);
453 #endif
454                 SNPRINTF(sz, command, sizeof(command),
455                          "(gnuserv-eval%s '(progn ", quick ? "-quickly" : "");
456                 send_string(s, command);
457                 if (load_library) {
458                         send_string(s, "(load-library ");
459                         send_string(s, clean_string(load_library));
460                         send_string(s, ") ");
461                 }
462                 if (eval_form) {
463                         send_string(s, eval_form);
464                 }
465                 if (eval_function) {
466                         send_string(s, "(");
467                         send_string(s, eval_function);
468                         send_string(s, ")");
469                 }
470                 send_string(s, "))");
471                 /* disconnect already sends EOT_STR */
472 #ifdef SYSV_IPC
473                 if (connect_type == (int)CONN_IPC)
474                         disconnect_from_ipc_server(s, msgp, batch && !quick);
475 #else                           /* !SYSV_IPC */
476                 if (connect_type != (int)CONN_IPC)
477                         disconnect_from_server(s, batch && !quick);
478 #endif                          /* !SYSV_IPC */
479         } /* eval_function || eval_form || load_library */
480         else if (batch) {
481                 /* no sexp on the command line, so read it from stdin */
482                 int nb;
483
484 #if defined(INTERNET_DOMAIN_SOCKETS)
485                 connect_type = make_connection(hostarg, port, &s);
486 #else
487                 connect_type = make_connection(NULL, 0, &s);
488 #endif
489                 SNPRINTF(sz, command, sizeof(command),
490                          "(gnuserv-eval%s '(progn ", quick ? "-quickly" : "");
491                 send_string(s, command);
492
493                 while ((nb = read(fileno(stdin), buffer, GSERV_BUFSZ - 1)) > 0) {
494                         buffer[nb] = '\0';
495                         send_string(s, buffer);
496                 }
497                 send_string(s, "))");
498                 /* disconnect already sends EOT_STR */
499 #ifdef SYSV_IPC
500                 if (connect_type == (int)CONN_IPC)
501                         disconnect_from_ipc_server(s, msgp, batch && !quick);
502 #else                           /* !SYSV_IPC */
503                 if (connect_type != (int)CONN_IPC)
504                         disconnect_from_server(s, batch && !quick);
505 #endif                          /* !SYSV_IPC */
506         }
507
508         if (!batch) {
509                 if (suppress_windows_system) {
510                         tty = ttyname(0);
511                         if (!tty) {
512                                 fprintf(stderr, "%s: Not connected to a tty",
513                                         progname);
514                                 exit(1);
515                         }
516 #if defined(INTERNET_DOMAIN_SOCKETS)
517                         connect_type = make_connection(hostarg, port, &s);
518 #else
519                         connect_type = make_connection(NULL, 0, &s);
520 #endif
521                         send_string(s, "(gnuserv-eval '(emacs-pid))");
522                         send_string(s, EOT_STR);
523
524                         if (read_line(s, buffer) == 0) {
525                                 fprintf(stderr,
526                                         "%s: Could not establish Emacs process id\n",
527                                         progname);
528                                 exit(1);
529                         }
530                         /* Don't do disconnect_from_server because we have already read
531                            data, and disconnect doesn't do anything else. */
532 #ifdef SYSV_IPC
533                         if (connect_type == (int)CONN_IPC)
534                                 disconnect_from_ipc_server(s, msgp, FALSE);
535 #endif                          /* !SYSV_IPC */
536
537                         emacs_pid = (pid_t) atol(buffer);
538                         initialize_signals();
539                 }
540                 /* suppress_windows_system */
541 #if defined(INTERNET_DOMAIN_SOCKETS)
542                 connect_type = make_connection(hostarg, port, &s);
543 #else
544                 connect_type = make_connection(NULL, 0, &s);
545 #endif
546
547 #ifdef INTERNET_DOMAIN_SOCKETS
548                 if (connect_type == (int)CONN_INTERNET) {
549                         char *ptr;
550                         gethostname(thishost, HOSTNAMSZ);
551                         if (!rflg) {    /* attempt to generate a path
552                                          * to this machine */
553                                 if ((ptr = getenv("GNU_NODE")) != NULL) {
554                                         /* user specified a path */
555                                         xstrncpy(remotepath, ptr, sizeof(remotepath)-1);
556                                         remotepath[sizeof(remotepath)-1]='\0';
557                                 }
558                         }
559 #if 0                           /* This is really bogus... re-enable it if you must have it! */
560 #if defined (hp9000s300) || defined (hp9000s800)
561                         else if (strcmp(thishost, hostarg)) {   /* try /net/thishost */
562                                 strcpy(remotepath, "/net/");    /* (this fails using internet
563                                                                    addresses) */
564                                 strcat(remotepath, thishost);
565                         }
566 #endif
567 #endif
568                 } else {        /* same machines, no need for path */
569                         remotepath[0] = '\0';   /* default is the empty path */
570                 }
571 #endif                          /* INTERNET_DOMAIN_SOCKETS */
572
573 #ifdef SYSV_IPC
574                 if ((msgp = (struct msgbuf *)
575                      malloc(sizeof *msgp + GSERV_BUFSZ)) == NULL) {
576                         fprintf(stderr,
577                                 "%s: not enough memory for message buffer\n",
578                                 progname);
579                         exit(1);
580                 }
581                 /* if */
582                 msgp->mtext[0] = '\0';  /* ready for later strcats */
583 #endif                          /* SYSV_IPC */
584
585                 if (suppress_windows_system) {
586                         char *term = getenv("TERM");
587                         pid_t pid = getpid();
588
589                         if (!term) {
590                                 fprintf(stderr, "%s: unknown terminal type\n",
591                                         progname);
592                                 exit(1);
593                         }
594                         SNPRINTF(sz, command, sizeof(command),
595                                  "(gnuserv-edit-files '(tty %s %s %d) '(",
596                                  clean_string(tty), clean_string(term),
597                                  (int)pid);
598                 } else {        /* !suppress_windows_system */
599
600                         if (0) ;
601 #ifdef HAVE_X_WINDOWS
602                         else if (display) {
603                                 SNPRINTF(sz, command, sizeof(command),
604                                          "(gnuserv-edit-files '(x %s) '(",
605                                          clean_string(display));
606                         }
607 #endif
608                 }               /* !suppress_windows_system */
609                 send_string(s, command);
610
611                 if (!argv[i])
612                         nofiles = 1;
613
614                 for (; argv[i]; i++) {
615                         if (i < argc - 1 && *argv[i] == '+') {
616                                 starting_line = atoi(argv[i++]);
617                         } else {
618                                 starting_line = 1;
619                         }
620                         /* If the last argument is +something, treat it as a
621                            file. */
622                         if (i == argc) {
623                                 starting_line = 1;
624                                 --i;
625                         }
626                         filename_expand(fullpath, argv[i], sizeof(fullpath));
627 #ifdef INTERNET_DOMAIN_SOCKETS
628                         msz = strlen(remotepath) + strlen(fullpath) + 1;
629                         path = (char*)malloc(msz);
630                         SNPRINTF(sz, path, msz, "%s%s", remotepath, fullpath);
631 #else  /* !INTERNET_DOMAIN_SOCKETS */
632                         path = my_strdup(fullpath);
633 #endif  /* INTERNET_DOMAIN_SOCKETS */
634                         SNPRINTF(sz, command, sizeof(command),
635                                 "(%d . %s)", starting_line, clean_string(path));
636                         send_string(s, command);
637                         free(path);
638                 }
639
640                 SNPRINTF(sz, command, sizeof(command), ")%s%s",
641                          (quick || (nofiles && !suppress_windows_system))
642                          ? " 'quick"
643                          : "",
644                          view ? " 'view" : "");
645                 send_string(s, command);
646                 send_string(s, ")");
647
648 #ifdef SYSV_IPC
649                 if (connect_type == (int)CONN_IPC)
650                         disconnect_from_ipc_server(s, msgp, FALSE);
651 #else                           /* !SYSV_IPC */
652                 if (connect_type != (int)CONN_IPC)
653                         disconnect_from_server(s, FALSE);
654 #endif                          /* !SYSV_IPC */
655         }
656
657         /* not batch */
658         return 0;
659
660 }
661
662 #endif  /* SYSV_IPC || UNIX_DOMAIN_SOCKETS || INTERNET_DOMAIN_SOCKETS */