guestfish: Redirect stdout when executing remote commands
[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 (1);
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 (1);
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     int fd = *(int *)CMSG_DATA (h);
102
103     /* Duplicate the received file descriptor to stdout */
104     dup2 (fd, STDOUT_FILENO);
105     close (fd);
106   }
107 }
108
109 static void
110 send_stdout (int s)
111 {
112   static struct cmsghdr *cmptr = NULL;
113   struct msghdr         msg;
114   struct iovec          iov[1];
115
116   /* Our 1 byte dummy buffer */
117   char buf[1];
118
119   /* Don't specify a destination */
120   msg.msg_name    = NULL;
121   msg.msg_namelen = 0;
122
123   /* Initialise the msghdr to send zero byte */
124   iov[0].iov_base = buf;
125   iov[0].iov_len  = 1;
126   msg.msg_iov     = iov;
127   msg.msg_iovlen  = 1;
128
129   /* Initialize the zero byte */
130   buf[0] = 0;
131
132   /* Initialize the control data */
133   if (NULL == cmptr) {
134     cmptr = malloc (controllen);
135     if (NULL == cmptr) {
136       perror ("malloc");
137       exit (1);
138     }
139   }
140   cmptr->cmsg_level = SOL_SOCKET;
141   cmptr->cmsg_type  = SCM_RIGHTS;
142   cmptr->cmsg_len   = controllen;
143
144   /* Add control header to the message */
145   msg.msg_control     = cmptr;
146   msg.msg_controllen  = controllen;
147
148   /* Add STDOUT to the control data */
149   *(int *)CMSG_DATA (cmptr) = STDOUT_FILENO;
150
151   if (sendmsg (s, &msg, 0) != 1) {
152     perror ("sendmsg stdout fd");
153     exit (1);
154   }
155 }
156
157 static void
158 close_stdout (void)
159 {
160   int fd;
161
162   fd = open ("/dev/null", O_WRONLY);
163   if (fd == -1)
164     perror ("/dev/null");
165   else {
166     dup2 (fd, STDOUT_FILENO);
167     close (fd);
168   }
169 }
170
171 /* Remote control server. */
172 void
173 rc_listen (void)
174 {
175   char sockpath[128];
176   pid_t pid;
177   struct sockaddr_un addr;
178   int sock, s, i;
179   FILE *fp;
180   XDR xdr, xdr2;
181   guestfish_hello hello;
182   guestfish_call call;
183   guestfish_reply reply;
184   char **argv;
185   int argc;
186
187   memset (&hello, 0, sizeof hello);
188   memset (&call, 0, sizeof call);
189
190   pid = fork ();
191   if (pid == -1) {
192     perror ("fork");
193     exit (1);
194   }
195
196   if (pid > 0) {
197     /* Parent process. */
198     printf ("export GUESTFISH_PID=%d\n", pid);
199     fflush (stdout);
200     _exit (0);
201   }
202
203   /* Child process.
204    *
205    * Create the listening socket for accepting commands.
206    *
207    * Unfortunately there is a small but unavoidable race here.  We
208    * don't know the PID until after we've forked, so we cannot be
209    * sure the socket is created from the point of view of the parent
210    * (if the child is very slow).
211    */
212   pid = getpid ();
213   create_sockpath (pid, sockpath, sizeof sockpath, &addr);
214
215   sock = socket (AF_UNIX, SOCK_STREAM, 0);
216   if (sock == -1) {
217     perror ("socket");
218     exit (1);
219   }
220   unlink (sockpath);
221   if (bind (sock, (struct sockaddr *) &addr, sizeof addr) == -1) {
222     perror (sockpath);
223     exit (1);
224   }
225   if (listen (sock, 4) == -1) {
226     perror ("listen");
227     exit (1);
228   }
229
230   /* Now close stdout and substitute /dev/null.  This is necessary
231    * so that eval `guestfish --listen` doesn't block forever.
232    */
233   close_stdout();
234
235   /* Read commands and execute them. */
236   while (!quit) {
237     s = accept (sock, NULL, NULL);
238     if (s == -1)
239       perror ("accept");
240     else {
241       receive_stdout(s);
242
243       fp = fdopen (s, "r+");
244       xdrstdio_create (&xdr, fp, XDR_DECODE);
245
246       if (!xdr_guestfish_hello (&xdr, &hello)) {
247         fprintf (stderr, _("guestfish: protocol error: could not read 'hello' message\n"));
248         goto error;
249       }
250
251       if (strcmp (hello.vers, PACKAGE_VERSION) != 0) {
252         fprintf (stderr, _("guestfish: protocol error: version mismatch, server version '%s' does not match client version '%s'.  The two versions must match exactly.\n"),
253                  PACKAGE_VERSION,
254                  hello.vers);
255         xdr_free ((xdrproc_t) xdr_guestfish_hello, (char *) &hello);
256         goto error;
257       }
258       xdr_free ((xdrproc_t) xdr_guestfish_hello, (char *) &hello);
259
260       while (xdr_guestfish_call (&xdr, &call)) {
261         /* We have to extend and NULL-terminate the argv array. */
262         argc = call.args.args_len;
263         argv = realloc (call.args.args_val, (argc+1) * sizeof (char *));
264         if (argv == NULL) {
265           perror ("realloc");
266           exit (1);
267         }
268         call.args.args_val = argv;
269         argv[argc] = NULL;
270
271         if (verbose) {
272           fprintf (stderr, "guestfish(%d): %s", pid, call.cmd);
273           for (i = 0; i < argc; ++i)
274             fprintf (stderr, " %s", argv[i]);
275           fprintf (stderr, "\n");
276         }
277
278         /* Run the command. */
279         reply.r = issue_command (call.cmd, argv, NULL);
280
281         xdr_free ((xdrproc_t) xdr_guestfish_call, (char *) &call);
282
283         /* Send the reply. */
284         xdrstdio_create (&xdr2, fp, XDR_ENCODE);
285         (void) xdr_guestfish_reply (&xdr2, &reply);
286         xdr_destroy (&xdr2);
287
288         /* Exit on error? */
289         if (call.exit_on_error && reply.r == -1) {
290           unlink (sockpath);
291           exit (1);
292         }
293       }
294
295     error:
296       xdr_destroy (&xdr);       /* NB. This doesn't close 'fp'. */
297       fclose (fp);              /* Closes the underlying socket 's'. */
298       close_stdout(); /* Re-close stdout */
299     }
300   }
301
302   unlink (sockpath);
303   exit (0);
304 }
305
306 /* Remote control client. */
307 int
308 rc_remote (int pid, const char *cmd, int argc, char *argv[],
309            int exit_on_error)
310 {
311   guestfish_hello hello;
312   guestfish_call call;
313   guestfish_reply reply;
314   char sockpath[128];
315   struct sockaddr_un addr;
316   int sock;
317   FILE *fp;
318   XDR xdr;
319
320   memset (&reply, 0, sizeof reply);
321
322   /* This is fine as long as we never try to xdr_free this struct. */
323   hello.vers = (char *) PACKAGE_VERSION;
324
325   /* Check the other end is still running. */
326   if (kill (pid, 0) == -1) {
327     fprintf (stderr, _("guestfish: remote: looks like the server is not running\n"));
328     return -1;
329   }
330
331   create_sockpath (pid, sockpath, sizeof sockpath, &addr);
332
333   sock = socket (AF_UNIX, SOCK_STREAM, 0);
334   if (sock == -1) {
335     perror ("socket");
336     return -1;
337   }
338
339   if (connect (sock, (struct sockaddr *) &addr, sizeof addr) == -1) {
340     perror (sockpath);
341     fprintf (stderr, _("guestfish: remote: looks like the server is not running\n"));
342     close (sock);
343     return -1;
344   }
345
346   send_stdout(sock);
347
348   /* Send the greeting. */
349   fp = fdopen (sock, "r+");
350   xdrstdio_create (&xdr, fp, XDR_ENCODE);
351
352   if (!xdr_guestfish_hello (&xdr, &hello)) {
353     fprintf (stderr, _("guestfish: protocol error: could not send initial greeting to server\n"));
354     xdr_destroy (&xdr);
355     fclose (fp);
356     return -1;
357   }
358
359   /* Send the command.  The server supports reading multiple commands
360    * per connection, but this code only ever sends one command.
361    */
362   call.cmd = (char *) cmd;
363   call.args.args_len = argc;
364   call.args.args_val = argv;
365   call.exit_on_error = exit_on_error;
366   if (!xdr_guestfish_call (&xdr, &call)) {
367     fprintf (stderr, _("guestfish: protocol error: could not send initial greeting to server\n"));
368     xdr_destroy (&xdr);
369     fclose (fp);
370     return -1;
371   }
372   xdr_destroy (&xdr);
373
374   /* Wait for the reply. */
375   xdrstdio_create (&xdr, fp, XDR_DECODE);
376
377   if (!xdr_guestfish_reply (&xdr, &reply)) {
378     fprintf (stderr, _("guestfish: protocol error: could not decode reply from server\n"));
379     xdr_destroy (&xdr);
380     fclose (fp);
381     return -1;
382   }
383
384   xdr_destroy (&xdr);
385   fclose (fp);
386
387   return reply.r;
388 }