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