fish: New command 'sparse', like 'alloc' but to generate sparse files.
[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     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 (1);
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 (1);
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, i;
181   FILE *fp;
182   XDR xdr, xdr2;
183   guestfish_hello hello;
184   guestfish_call call;
185   guestfish_reply reply;
186   char **argv;
187   int argc;
188
189   memset (&hello, 0, sizeof hello);
190   memset (&call, 0, sizeof call);
191
192   pid = fork ();
193   if (pid == -1) {
194     perror ("fork");
195     exit (1);
196   }
197
198   if (pid > 0) {
199     /* Parent process. */
200     printf ("export GUESTFISH_PID=%d\n", pid);
201     fflush (stdout);
202     _exit (0);
203   }
204
205   /* Child process.
206    *
207    * Create the listening socket for accepting commands.
208    *
209    * Unfortunately there is a small but unavoidable race here.  We
210    * don't know the PID until after we've forked, so we cannot be
211    * sure the socket is created from the point of view of the parent
212    * (if the child is very slow).
213    */
214   pid = getpid ();
215   create_sockpath (pid, sockpath, sizeof sockpath, &addr);
216
217   sock = socket (AF_UNIX, SOCK_STREAM, 0);
218   if (sock == -1) {
219     perror ("socket");
220     exit (1);
221   }
222   unlink (sockpath);
223   if (bind (sock, (struct sockaddr *) &addr, sizeof addr) == -1) {
224     perror (sockpath);
225     exit (1);
226   }
227   if (listen (sock, 4) == -1) {
228     perror ("listen");
229     exit (1);
230   }
231
232   /* Now close stdout and substitute /dev/null.  This is necessary
233    * so that eval `guestfish --listen` doesn't block forever.
234    */
235   close_stdout();
236
237   /* Read commands and execute them. */
238   while (!quit) {
239     s = accept (sock, NULL, NULL);
240     if (s == -1)
241       perror ("accept");
242     else {
243       receive_stdout(s);
244
245       fp = fdopen (s, "r+");
246       xdrstdio_create (&xdr, fp, XDR_DECODE);
247
248       if (!xdr_guestfish_hello (&xdr, &hello)) {
249         fprintf (stderr, _("guestfish: protocol error: could not read 'hello' message\n"));
250         goto error;
251       }
252
253       if (strcmp (hello.vers, PACKAGE_VERSION) != 0) {
254         fprintf (stderr, _("guestfish: protocol error: version mismatch, server version '%s' does not match client version '%s'.  The two versions must match exactly.\n"),
255                  PACKAGE_VERSION,
256                  hello.vers);
257         xdr_free ((xdrproc_t) xdr_guestfish_hello, (char *) &hello);
258         goto error;
259       }
260       xdr_free ((xdrproc_t) xdr_guestfish_hello, (char *) &hello);
261
262       while (xdr_guestfish_call (&xdr, &call)) {
263         /* We have to extend and NULL-terminate the argv array. */
264         argc = call.args.args_len;
265         argv = realloc (call.args.args_val, (argc+1) * sizeof (char *));
266         if (argv == NULL) {
267           perror ("realloc");
268           exit (1);
269         }
270         call.args.args_val = argv;
271         argv[argc] = NULL;
272
273         if (verbose) {
274           fprintf (stderr, "guestfish(%d): %s", pid, call.cmd);
275           for (i = 0; i < argc; ++i)
276             fprintf (stderr, " %s", argv[i]);
277           fprintf (stderr, "\n");
278         }
279
280         /* Run the command. */
281         reply.r = issue_command (call.cmd, argv, NULL);
282
283         xdr_free ((xdrproc_t) xdr_guestfish_call, (char *) &call);
284
285         /* Send the reply. */
286         xdrstdio_create (&xdr2, fp, XDR_ENCODE);
287         (void) xdr_guestfish_reply (&xdr2, &reply);
288         xdr_destroy (&xdr2);
289
290         /* Exit on error? */
291         if (call.exit_on_error && reply.r == -1) {
292           unlink (sockpath);
293           exit (1);
294         }
295       }
296
297     error:
298       xdr_destroy (&xdr);       /* NB. This doesn't close 'fp'. */
299       fclose (fp);              /* Closes the underlying socket 's'. */
300       close_stdout(); /* Re-close stdout */
301     }
302   }
303
304   unlink (sockpath);
305   exit (0);
306 }
307
308 /* Remote control client. */
309 int
310 rc_remote (int pid, const char *cmd, int argc, char *argv[],
311            int exit_on_error)
312 {
313   guestfish_hello hello;
314   guestfish_call call;
315   guestfish_reply reply;
316   char sockpath[128];
317   struct sockaddr_un addr;
318   int sock;
319   FILE *fp;
320   XDR xdr;
321
322   memset (&reply, 0, sizeof reply);
323
324   /* This is fine as long as we never try to xdr_free this struct. */
325   hello.vers = (char *) PACKAGE_VERSION;
326
327   /* Check the other end is still running. */
328   if (kill (pid, 0) == -1) {
329     fprintf (stderr, _("guestfish: remote: looks like the server is not running\n"));
330     return -1;
331   }
332
333   create_sockpath (pid, sockpath, sizeof sockpath, &addr);
334
335   sock = socket (AF_UNIX, SOCK_STREAM, 0);
336   if (sock == -1) {
337     perror ("socket");
338     return -1;
339   }
340
341   if (connect (sock, (struct sockaddr *) &addr, sizeof addr) == -1) {
342     perror (sockpath);
343     fprintf (stderr, _("guestfish: remote: looks like the server is not running\n"));
344     close (sock);
345     return -1;
346   }
347
348   send_stdout(sock);
349
350   /* Send the greeting. */
351   fp = fdopen (sock, "r+");
352   xdrstdio_create (&xdr, fp, XDR_ENCODE);
353
354   if (!xdr_guestfish_hello (&xdr, &hello)) {
355     fprintf (stderr, _("guestfish: protocol error: could not send initial greeting to server\n"));
356     xdr_destroy (&xdr);
357     fclose (fp);
358     return -1;
359   }
360
361   /* Send the command.  The server supports reading multiple commands
362    * per connection, but this code only ever sends one command.
363    */
364   call.cmd = (char *) cmd;
365   call.args.args_len = argc;
366   call.args.args_val = argv;
367   call.exit_on_error = exit_on_error;
368   if (!xdr_guestfish_call (&xdr, &call)) {
369     fprintf (stderr, _("guestfish: protocol error: could not send initial greeting to server\n"));
370     xdr_destroy (&xdr);
371     fclose (fp);
372     return -1;
373   }
374   xdr_destroy (&xdr);
375
376   /* Wait for the reply. */
377   xdrstdio_create (&xdr, fp, XDR_DECODE);
378
379   if (!xdr_guestfish_reply (&xdr, &reply)) {
380     fprintf (stderr, _("guestfish: protocol error: could not decode reply from server\n"));
381     xdr_destroy (&xdr);
382     fclose (fp);
383     return -1;
384   }
385
386   xdr_destroy (&xdr);
387   fclose (fp);
388
389   return reply.r;
390 }