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