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