fish: Add --listen --csh to for csh, tcsh compatibility.
[libguestfs.git] / fish / rc.c
1 /* guestfish - the filesystem interactive shell
2  * Copyright (C) 2009 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  */
18
19 #include <config.h>
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <sys/un.h>
29 #include <signal.h>
30 #include <sys/socket.h>
31
32 #include <rpc/types.h>
33 #include <rpc/xdr.h>
34
35 #include "fish.h"
36 #include "rc_protocol.h"
37
38 static void
39 create_sockpath (pid_t pid, char *sockpath, int len, struct sockaddr_un *addr)
40 {
41   char dir[128];
42   uid_t euid = geteuid ();
43
44   snprintf (dir, sizeof dir, "/tmp/.guestfish-%d", euid);
45   mkdir (dir, 0700);
46
47   snprintf (sockpath, len, "/tmp/.guestfish-%d/socket-%d", euid, pid);
48
49   addr->sun_family = AF_UNIX;
50   strcpy (addr->sun_path, sockpath);
51 }
52
53 static const socklen_t controllen = CMSG_LEN (sizeof (int));
54
55 static void
56 receive_stdout (int s)
57 {
58   static struct cmsghdr *cmptr = NULL, *h;
59   struct msghdr         msg;
60   struct iovec          iov[1];
61
62   /* Our 1 byte buffer */
63   char buf[1];
64
65   if (NULL == cmptr) {
66     cmptr = malloc (controllen);
67     if (NULL == cmptr) {
68       perror ("malloc");
69       exit (EXIT_FAILURE);
70     }
71   }
72
73   /* Don't specify a source */
74   msg.msg_name = NULL;
75   msg.msg_namelen = 0;
76
77   /* Initialise the msghdr to receive zero byte */
78   iov[0].iov_base = buf;
79   iov[0].iov_len  = 1;
80   msg.msg_iov     = iov;
81   msg.msg_iovlen  = 1;
82
83   /* Initialise the control data */
84   msg.msg_control     = cmptr;
85   msg.msg_controllen  = controllen;
86
87   /* Read a message from the socket */
88   ssize_t n = recvmsg (s, &msg, 0);
89   if (n < 0) {
90     perror ("recvmsg stdout fd");
91     exit (EXIT_FAILURE);
92   }
93
94   h = CMSG_FIRSTHDR(&msg);
95   if (NULL == h) {
96     fprintf (stderr, "didn't receive a stdout file descriptor\n");
97   }
98
99   else {
100     /* Extract the transferred file descriptor from the control data */
101     unsigned char *data = CMSG_DATA (h);
102     int fd = *(int *)data;
103
104     /* Duplicate the received file descriptor to stdout */
105     dup2 (fd, STDOUT_FILENO);
106     close (fd);
107   }
108 }
109
110 static void
111 send_stdout (int s)
112 {
113   static struct cmsghdr *cmptr = NULL;
114   struct msghdr         msg;
115   struct iovec          iov[1];
116
117   /* Our 1 byte dummy buffer */
118   char buf[1];
119
120   /* Don't specify a destination */
121   msg.msg_name    = NULL;
122   msg.msg_namelen = 0;
123
124   /* Initialise the msghdr to send zero byte */
125   iov[0].iov_base = buf;
126   iov[0].iov_len  = 1;
127   msg.msg_iov     = iov;
128   msg.msg_iovlen  = 1;
129
130   /* Initialize the zero byte */
131   buf[0] = 0;
132
133   /* Initialize the control data */
134   if (NULL == cmptr) {
135     cmptr = malloc (controllen);
136     if (NULL == cmptr) {
137       perror ("malloc");
138       exit (EXIT_FAILURE);
139     }
140   }
141   cmptr->cmsg_level = SOL_SOCKET;
142   cmptr->cmsg_type  = SCM_RIGHTS;
143   cmptr->cmsg_len   = controllen;
144
145   /* Add control header to the message */
146   msg.msg_control     = cmptr;
147   msg.msg_controllen  = controllen;
148
149   /* Add STDOUT to the control data */
150   unsigned char *data = CMSG_DATA (cmptr);
151   *(int *)data = STDOUT_FILENO;
152
153   if (sendmsg (s, &msg, 0) != 1) {
154     perror ("sendmsg stdout fd");
155     exit (EXIT_FAILURE);
156   }
157 }
158
159 static void
160 close_stdout (void)
161 {
162   int fd;
163
164   fd = open ("/dev/null", O_WRONLY);
165   if (fd == -1)
166     perror ("/dev/null");
167   else {
168     dup2 (fd, STDOUT_FILENO);
169     close (fd);
170   }
171 }
172
173 /* Remote control server. */
174 void
175 rc_listen (void)
176 {
177   char sockpath[128];
178   pid_t pid;
179   struct sockaddr_un addr;
180   int sock, s;
181   size_t i;
182   FILE *fp;
183   XDR xdr, xdr2;
184   guestfish_hello hello;
185   guestfish_call call;
186   guestfish_reply reply;
187   char **argv;
188   size_t argc;
189
190   memset (&hello, 0, sizeof hello);
191   memset (&call, 0, sizeof call);
192
193   pid = fork ();
194   if (pid == -1) {
195     perror ("fork");
196     exit (EXIT_FAILURE);
197   }
198
199   if (pid > 0) {
200     /* Parent process. */
201
202     if (!remote_control_csh)
203       printf ("GUESTFISH_PID=%d; export GUESTFISH_PID\n", pid);
204     else
205       printf ("setenv GUESTFISH_PID %d\n", pid);
206
207     fflush (stdout);
208     _exit (0);
209   }
210
211   /* Child process.
212    *
213    * Create the listening socket for accepting commands.
214    *
215    * Unfortunately there is a small but unavoidable race here.  We
216    * don't know the PID until after we've forked, so we cannot be
217    * sure the socket is created from the point of view of the parent
218    * (if the child is very slow).
219    */
220   pid = getpid ();
221   create_sockpath (pid, sockpath, sizeof sockpath, &addr);
222
223   sock = socket (AF_UNIX, SOCK_STREAM, 0);
224   if (sock == -1) {
225     perror ("socket");
226     exit (EXIT_FAILURE);
227   }
228   unlink (sockpath);
229   if (bind (sock, (struct sockaddr *) &addr, sizeof addr) == -1) {
230     perror (sockpath);
231     exit (EXIT_FAILURE);
232   }
233   if (listen (sock, 4) == -1) {
234     perror ("listen");
235     exit (EXIT_FAILURE);
236   }
237
238   /* Now close stdout and substitute /dev/null.  This is necessary
239    * so that eval `guestfish --listen` doesn't block forever.
240    */
241   close_stdout();
242
243   /* Read commands and execute them. */
244   while (!quit) {
245     s = accept (sock, NULL, NULL);
246     if (s == -1)
247       perror ("accept");
248     else {
249       receive_stdout(s);
250
251       fp = fdopen (s, "r+");
252       xdrstdio_create (&xdr, fp, XDR_DECODE);
253
254       if (!xdr_guestfish_hello (&xdr, &hello)) {
255         fprintf (stderr, _("guestfish: protocol error: could not read 'hello' message\n"));
256         goto error;
257       }
258
259       if (STRNEQ (hello.vers, PACKAGE_VERSION)) {
260         fprintf (stderr, _("guestfish: protocol error: version mismatch, server version '%s' does not match client version '%s'.  The two versions must match exactly.\n"),
261                  PACKAGE_VERSION,
262                  hello.vers);
263         xdr_free ((xdrproc_t) xdr_guestfish_hello, (char *) &hello);
264         goto error;
265       }
266       xdr_free ((xdrproc_t) xdr_guestfish_hello, (char *) &hello);
267
268       while (xdr_guestfish_call (&xdr, &call)) {
269         /* We have to extend and NULL-terminate the argv array. */
270         argc = call.args.args_len;
271         argv = realloc (call.args.args_val, (argc+1) * sizeof (char *));
272         if (argv == NULL) {
273           perror ("realloc");
274           exit (EXIT_FAILURE);
275         }
276         call.args.args_val = argv;
277         argv[argc] = NULL;
278
279         if (verbose) {
280           fprintf (stderr, "guestfish(%d): %s", pid, call.cmd);
281           for (i = 0; i < argc; ++i)
282             fprintf (stderr, " %s", argv[i]);
283           fprintf (stderr, "\n");
284         }
285
286         /* Run the command. */
287         reply.r = issue_command (call.cmd, argv, NULL);
288
289         xdr_free ((xdrproc_t) xdr_guestfish_call, (char *) &call);
290
291         /* Send the reply. */
292         xdrstdio_create (&xdr2, fp, XDR_ENCODE);
293         (void) xdr_guestfish_reply (&xdr2, &reply);
294         xdr_destroy (&xdr2);
295
296         /* Exit on error? */
297         if (call.exit_on_error && reply.r == -1) {
298           unlink (sockpath);
299           exit (EXIT_FAILURE);
300         }
301       }
302
303     error:
304       xdr_destroy (&xdr);       /* NB. This doesn't close 'fp'. */
305       fclose (fp);              /* Closes the underlying socket 's'. */
306       close_stdout(); /* Re-close stdout */
307     }
308   }
309
310   unlink (sockpath);
311   exit (EXIT_SUCCESS);
312 }
313
314 /* Remote control client. */
315 int
316 rc_remote (int pid, const char *cmd, size_t argc, char *argv[],
317            int exit_on_error)
318 {
319   guestfish_hello hello;
320   guestfish_call call;
321   guestfish_reply reply;
322   char sockpath[128];
323   struct sockaddr_un addr;
324   int sock;
325   FILE *fp;
326   XDR xdr;
327
328   memset (&reply, 0, sizeof reply);
329
330   /* This is fine as long as we never try to xdr_free this struct. */
331   hello.vers = (char *) PACKAGE_VERSION;
332
333   /* Check the other end is still running. */
334   if (kill (pid, 0) == -1) {
335     fprintf (stderr, _("guestfish: remote: looks like the server is not running\n"));
336     return -1;
337   }
338
339   create_sockpath (pid, sockpath, sizeof sockpath, &addr);
340
341   sock = socket (AF_UNIX, SOCK_STREAM, 0);
342   if (sock == -1) {
343     perror ("socket");
344     return -1;
345   }
346
347   if (connect (sock, (struct sockaddr *) &addr, sizeof addr) == -1) {
348     perror (sockpath);
349     fprintf (stderr, _("guestfish: remote: looks like the server is not running\n"));
350     close (sock);
351     return -1;
352   }
353
354   send_stdout(sock);
355
356   /* Send the greeting. */
357   fp = fdopen (sock, "r+");
358   xdrstdio_create (&xdr, fp, XDR_ENCODE);
359
360   if (!xdr_guestfish_hello (&xdr, &hello)) {
361     fprintf (stderr, _("guestfish: protocol error: could not send initial greeting to server\n"));
362     xdr_destroy (&xdr);
363     fclose (fp);
364     return -1;
365   }
366
367   /* Send the command.  The server supports reading multiple commands
368    * per connection, but this code only ever sends one command.
369    */
370   call.cmd = (char *) cmd;
371   call.args.args_len = argc;
372   call.args.args_val = argv;
373   call.exit_on_error = exit_on_error;
374   if (!xdr_guestfish_call (&xdr, &call)) {
375     fprintf (stderr, _("guestfish: protocol error: could not send initial greeting to server\n"));
376     xdr_destroy (&xdr);
377     fclose (fp);
378     return -1;
379   }
380   xdr_destroy (&xdr);
381
382   /* Wait for the reply. */
383   xdrstdio_create (&xdr, fp, XDR_DECODE);
384
385   if (!xdr_guestfish_reply (&xdr, &reply)) {
386     fprintf (stderr, _("guestfish: protocol error: could not decode reply from server\n"));
387     xdr_destroy (&xdr);
388     fclose (fp);
389     return -1;
390   }
391
392   xdr_destroy (&xdr);
393   fclose (fp);
394
395   return reply.r;
396 }