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