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