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