daemon: debug segv correct use of dereferencing NULL.
[libguestfs.git] / daemon / debug.c
1 /* libguestfs - the guestfsd daemon
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 <sys/types.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <dirent.h>
29 #include <sys/resource.h>
30
31 #include "guestfs_protocol.h"
32 #include "daemon.h"
33 #include "actions.h"
34
35 /* This command exposes debugging information, internals and
36  * status.  There is no comprehensive documentation for this
37  * command.  You have to look at the source code in this file
38  * to find out what you can do.
39  *
40  * Commands always output a freeform string.
41  *
42  * Since libguestfs 1.5.7, the debug command has been enabled
43  * by default for all builds (previously you had to enable it
44  * in configure).  This command is not part of the stable ABI
45  * and may change at any time.
46  */
47
48 struct cmd {
49   const char *cmd;
50   char * (*f) (const char *subcmd, int argc, char *const *const argv);
51 };
52
53 static char *debug_help (const char *subcmd, int argc, char *const *const argv);
54 static char *debug_binaries (const char *subcmd, int argc, char *const *const argv);
55 static char *debug_core_pattern (const char *subcmd, int argc, char *const *const argv);
56 static char *debug_env (const char *subcmd, int argc, char *const *const argv);
57 static char *debug_fds (const char *subcmd, int argc, char *const *const argv);
58 static char *debug_ldd (const char *subcmd, int argc, char *const *const argv);
59 static char *debug_ls (const char *subcmd, int argc, char *const *const argv);
60 static char *debug_ll (const char *subcmd, int argc, char *const *const argv);
61 static char *debug_progress (const char *subcmd, int argc, char *const *const argv);
62 static char *debug_qtrace (const char *subcmd, int argc, char *const *const argv);
63 static char *debug_segv (const char *subcmd, int argc, char *const *const argv);
64 static char *debug_sh (const char *subcmd, int argc, char *const *const argv);
65
66 static struct cmd cmds[] = {
67   { "help", debug_help },
68   { "binaries", debug_binaries },
69   { "core_pattern", debug_core_pattern },
70   { "env", debug_env },
71   { "fds", debug_fds },
72   { "ldd", debug_ldd },
73   { "ls", debug_ls },
74   { "ll", debug_ll },
75   { "progress", debug_progress },
76   { "qtrace", debug_qtrace },
77   { "segv", debug_segv },
78   { "sh", debug_sh },
79   { NULL, NULL }
80 };
81
82 char *
83 do_debug (const char *subcmd, char *const *argv)
84 {
85   int argc, i;
86
87   for (i = argc = 0; argv[i] != NULL; ++i)
88     argc++;
89
90   for (i = 0; cmds[i].cmd != NULL; ++i) {
91     if (STRCASEEQ (subcmd, cmds[i].cmd))
92       return cmds[i].f (subcmd, argc, argv);
93   }
94
95   reply_with_error ("use 'debug help 0' to list the supported commands");
96   return NULL;
97 }
98
99 static char *
100 debug_help (const char *subcmd, int argc, char *const *const argv)
101 {
102   int len, i;
103   char *r, *p;
104
105   r = strdup ("Commands supported:");
106   if (!r) {
107     reply_with_perror ("strdup");
108     return NULL;
109   }
110
111   len = strlen (r);
112   for (i = 0; cmds[i].cmd != NULL; ++i) {
113     len += strlen (cmds[i].cmd) + 1; /* space + new command */
114     p = realloc (r, len + 1);        /* +1 for the final NUL */
115     if (p == NULL) {
116       reply_with_perror ("realloc");
117       free (r);
118       return NULL;
119     }
120     r = p;
121
122     strcat (r, " ");
123     strcat (r, cmds[i].cmd);
124   }
125
126   return r;
127 }
128
129 /* Show open FDs. */
130 static char *
131 debug_fds (const char *subcmd, int argc, char *const *const argv)
132 {
133   int r;
134   char *out;
135   size_t size;
136   FILE *fp;
137   DIR *dir;
138   struct dirent *d;
139   char fname[256], link[256];
140   struct stat statbuf;
141
142   fp = open_memstream (&out, &size);
143   if (!fp) {
144     reply_with_perror ("open_memstream");
145     return NULL;
146   }
147
148   dir = opendir ("/proc/self/fd");
149   if (!dir) {
150     reply_with_perror ("opendir: /proc/self/fd");
151     fclose (fp);
152     return NULL;
153   }
154
155   while ((d = readdir (dir)) != NULL) {
156     if (STREQ (d->d_name, ".") || STREQ (d->d_name, ".."))
157       continue;
158
159     snprintf (fname, sizeof fname, "/proc/self/fd/%s", d->d_name);
160
161     r = lstat (fname, &statbuf);
162     if (r == -1) {
163       reply_with_perror ("stat: %s", fname);
164       fclose (fp);
165       free (out);
166       closedir (dir);
167       return NULL;
168     }
169
170     if (S_ISLNK (statbuf.st_mode)) {
171       r = readlink (fname, link, sizeof link - 1);
172       if (r == -1) {
173         reply_with_perror ("readline: %s", fname);
174         fclose (fp);
175         free (out);
176         closedir (dir);
177         return NULL;
178       }
179       link[r] = '\0';
180
181       fprintf (fp, "%2s %s\n", d->d_name, link);
182     } else
183       fprintf (fp, "%2s 0%o\n", d->d_name, statbuf.st_mode);
184   }
185
186   fclose (fp);
187
188   if (closedir (dir) == -1) {
189     reply_with_perror ("closedir");
190     free (out);
191     return NULL;
192   }
193
194   return out;
195 }
196
197 /* Force a segfault in the daemon. */
198 static char *
199 debug_segv (const char *subcmd, int argc, char *const *const argv)
200 {
201   /* http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html
202    * "Dereferencing a NULL Pointer: contrary to popular belief,
203    * dereferencing a null pointer in C is undefined. It is not defined
204    * to trap [...]"
205    */
206   volatile int *ptr = NULL;
207   *ptr = 1;
208   return NULL;
209 }
210
211 /* Run an arbitrary shell command using /bin/sh from the appliance.
212  *
213  * Note this is somewhat different from the ordinary guestfs_sh command
214  * because it's not using the guest shell, and is not chrooted.
215  */
216 static char *
217 debug_sh (const char *subcmd, int argc, char *const *const argv)
218 {
219   if (argc < 1) {
220     reply_with_error ("sh: expecting a command to run");
221     return NULL;
222   }
223
224   char *cmd;
225   int len, i, j;
226
227   /* guestfish splits the parameter(s) into a list of strings,
228    * and we have to reassemble them here.  Not ideal. XXX
229    */
230   for (i = len = 0; i < argc; ++i)
231     len += strlen (argv[i]) + 1;
232   cmd = malloc (len);
233   if (!cmd) {
234     reply_with_perror ("malloc");
235     return NULL;
236   }
237   for (i = j = 0; i < argc; ++i) {
238     len = strlen (argv[i]);
239     memcpy (&cmd[j], argv[i], len);
240     j += len;
241     cmd[j] = ' ';
242     j++;
243   }
244   cmd[j-1] = '\0';
245
246   /* Set up some environment variables. */
247   setenv ("root", sysroot, 1);
248   if (access ("/sys/block/sda", F_OK) == 0)
249     setenv ("sd", "sd", 1);
250   else if (access ("/sys/block/hda", F_OK) == 0)
251     setenv ("sd", "hd", 1);
252   else if (access ("/sys/block/vda", F_OK) == 0)
253     setenv ("sd", "vd", 1);
254
255   char *err;
256   int r = commandf (NULL, &err, COMMAND_FLAG_FOLD_STDOUT_ON_STDERR,
257                     "/bin/sh", "-c", cmd, NULL);
258   free (cmd);
259
260   if (r == -1) {
261     reply_with_error ("%s", err);
262     free (err);
263     return NULL;
264   }
265
266   return err;
267 }
268
269 /* Print the environment that commands get (by running external printenv). */
270 static char *
271 debug_env (const char *subcmd, int argc, char *const *const argv)
272 {
273   int r;
274   char *out, *err;
275
276   r = command (&out, &err, "printenv", NULL);
277   if (r == -1) {
278     reply_with_error ("printenv: %s", err);
279     free (out);
280     free (err);
281     return NULL;
282   }
283
284   free (err);
285
286   return out;
287 }
288
289 /* Return binaries in the appliance.
290  * See tests/regressions/rhbz727178.sh
291  */
292 static char *
293 debug_binaries (const char *subcmd, int argc, char *const *const argv)
294 {
295   int r;
296   char *out, *err;
297
298   const char cmd[] =
299     "find / -xdev -type f -executable "
300     "| xargs file -i "
301     "| grep application/x-executable "
302     "| gawk -F: '{print $1}'";
303
304   r = command (&out, &err, "sh", "-c", cmd, NULL);
305   if (r == -1) {
306     reply_with_error ("find: %s", err);
307     free (out);
308     free (err);
309     return NULL;
310   }
311
312   free (err);
313
314   return out;
315 }
316
317 /* Run 'ldd' on a file from the appliance.
318  * See tests/regressions/rhbz727178.sh
319  */
320 static char *
321 debug_ldd (const char *subcmd, int argc, char *const *const argv)
322 {
323   int r;
324   char *out, *err, *ret;
325
326   if (argc != 1) {
327     reply_with_error ("ldd: no file argument");
328     return NULL;
329   }
330
331   /* Note that 'ldd' doesn't fail if it finds errors.  We have to grep
332    * for errors in the regression test instead.  'ldd' only fails here
333    * if the binary is not a binary at all (eg. for shell scripts).
334    * Also 'ldd' randomly sends messages to stderr and errors to stdout
335    * depending on the phase of the moon.
336    */
337   r = command (&out, &err, "ldd", "-r", argv[0], NULL);
338   if (r == -1) {
339     reply_with_error ("ldd: %s: %s", argv[0], err);
340     free (out);
341     free (err);
342     return NULL;
343   }
344
345   /* Concatenate stdout and stderr in the result. */
346   ret = realloc (out, strlen (out) + strlen (err) + 1);
347   if (ret == NULL) {
348     reply_with_perror ("realloc");
349     free (out);
350     free (err);
351     return NULL;
352   }
353
354   strcat (ret, err);
355   free (err);
356
357   return ret;
358 }
359
360 /* List files in the appliance. */
361 static char *
362 debug_ls (const char *subcmd, int argc, char *const *const argv)
363 {
364   int len = count_strings (argv);
365   const char *cargv[len+3];
366   int i;
367
368   cargv[0] = "ls";
369   cargv[1] = "-a";
370   for (i = 0; i < len; ++i)
371     cargv[2+i] = argv[i];
372   cargv[2+len] = NULL;
373
374   int r;
375   char *out, *err;
376
377   r = commandv (&out, &err, (void *) cargv);
378   if (r == -1) {
379     reply_with_error ("ls: %s", err);
380     free (out);
381     free (err);
382     return NULL;
383   }
384
385   free (err);
386
387   return out;
388 }
389
390 /* List files in the appliance. */
391 static char *
392 debug_ll (const char *subcmd, int argc, char *const *const argv)
393 {
394   int len = count_strings (argv);
395   const char *cargv[len+3];
396   int i;
397
398   cargv[0] = "ls";
399   cargv[1] = "-la";
400   for (i = 0; i < len; ++i)
401     cargv[2+i] = argv[i];
402   cargv[2+len] = NULL;
403
404   int r;
405   char *out, *err;
406
407   r = commandv (&out, &err, (void *) cargv);
408   if (r == -1) {
409     reply_with_error ("ll: %s", err);
410     free (out);
411     free (err);
412     return NULL;
413   }
414
415   free (err);
416
417   return out;
418 }
419
420 /* Generate progress notification messages in order to test progress bars. */
421 static char *
422 debug_progress (const char *subcmd, int argc, char *const *const argv)
423 {
424   if (argc < 1) {
425   error:
426     reply_with_error ("progress: expecting arg (time in seconds as string)");
427     return NULL;
428   }
429
430   char *secs_str = argv[0];
431   unsigned secs;
432   if (sscanf (secs_str, "%u", &secs) != 1 || secs == 0)
433     goto error;
434
435   unsigned i;
436   unsigned tsecs = secs * 10;   /* 1/10ths of seconds */
437   for (i = 1; i <= tsecs; ++i) {
438     usleep (100000);
439     notify_progress ((uint64_t) i, (uint64_t) tsecs);
440   }
441
442   char *ret = strdup ("ok");
443   if (ret == NULL) {
444     reply_with_perror ("strdup");
445     return NULL;
446   }
447
448   return ret;
449 }
450
451 /* Enable core dumping to the given core pattern.
452  * Note that this pattern is relative to any chroot of the process which
453  * crashes. This means that if you want to write the core file to the guest's
454  * storage the pattern must start with /sysroot only if the command which
455  * crashes doesn't chroot.
456  */
457 static char *
458 debug_core_pattern (const char *subcmd, int argc, char *const *const argv)
459 {
460   if (argc < 1) {
461     reply_with_error ("core_pattern: expecting a core pattern");
462     return NULL;
463   }
464
465   const char *pattern = argv[0];
466   const size_t pattern_len = strlen(pattern);
467
468 #define CORE_PATTERN "/proc/sys/kernel/core_pattern"
469   int fd = open (CORE_PATTERN, O_WRONLY);
470   if (fd == -1) {
471     reply_with_perror ("open: " CORE_PATTERN);
472     return NULL;
473   }
474   if (write (fd, pattern, pattern_len) < (ssize_t) pattern_len) {
475     reply_with_perror ("write: " CORE_PATTERN);
476     return NULL;
477   }
478   if (close (fd) == -1) {
479     reply_with_perror ("close: " CORE_PATTERN);
480     return NULL;
481   }
482
483   struct rlimit limit = {
484     .rlim_cur = RLIM_INFINITY,
485     .rlim_max = RLIM_INFINITY
486   };
487   if (setrlimit (RLIMIT_CORE, &limit) == -1) {
488     reply_with_perror ("setrlimit (RLIMIT_CORE)");
489     return NULL;
490   }
491
492   char *ret = strdup ("ok");
493   if (NULL == ret) {
494     reply_with_perror ("strdup");
495     return NULL;
496   }
497
498   return ret;
499 }
500
501 static int
502 write_cb (void *fd_ptr, const void *buf, size_t len)
503 {
504   int fd = *(int *)fd_ptr;
505   return xwrite (fd, buf, len);
506 }
507
508 /* This requires a non-upstream qemu patch.  See contrib/visualize-alignment/
509  * directory in the libguestfs source tree.
510  */
511 static char *
512 debug_qtrace (const char *subcmd, int argc, char *const *const argv)
513 {
514   int enable;
515
516   if (argc != 2) {
517   bad_args:
518     reply_with_error ("qtrace <device> <on|off>");
519     return NULL;
520   }
521
522   if (STREQ (argv[1], "on"))
523     enable = 1;
524   else if (STREQ (argv[1], "off"))
525     enable = 0;
526   else
527     goto bad_args;
528
529   /* This does a sync and flushes all caches. */
530   if (do_drop_caches (3) == -1)
531     return NULL;
532
533   /* Note this doesn't do device name translation or check this is a device. */
534   int fd = open (argv[0], O_RDONLY | O_DIRECT);
535   if (fd == -1) {
536     reply_with_perror ("qtrace: %s: open", argv[0]);
537     return NULL;
538   }
539
540   /* The pattern of reads is what signals to the analysis program that
541    * tracing should be started or stopped.  Note this assumes both 512
542    * byte sectors, and that O_DIRECT will let us do 512 byte aligned
543    * reads.  We ought to read the sector size of the device and use
544    * that instead (XXX).  The analysis program currently assumes 512
545    * byte sectors anyway.
546    */
547 #define QTRACE_SIZE 512
548   const int patterns[2][5] = {
549     { 2, 15, 21, 2, -1 }, /* disable trace */
550     { 2, 21, 15, 2, -1 }  /* enable trace */
551   };
552   void *buf;
553   size_t i;
554
555   /* For O_DIRECT, buffer must be aligned too (thanks Matt).
556    * Note posix_memalign has this strange errno behaviour.
557    */
558   errno = posix_memalign (&buf, QTRACE_SIZE, QTRACE_SIZE);
559   if (errno != 0) {
560     reply_with_perror ("posix_memalign");
561     close (fd);
562     return NULL;
563   }
564
565   for (i = 0; patterns[enable][i] >= 0; ++i) {
566     if (lseek (fd, patterns[enable][i]*QTRACE_SIZE, SEEK_SET) == -1) {
567       reply_with_perror ("qtrace: %s: lseek", argv[0]);
568       close (fd);
569       free (buf);
570       return NULL;
571     }
572
573     if (read (fd, buf, QTRACE_SIZE) == -1) {
574       reply_with_perror ("qtrace: %s: read", argv[0]);
575       close (fd);
576       free (buf);
577       return NULL;
578     }
579   }
580
581   close (fd);
582   free (buf);
583
584   /* This does a sync and flushes all caches. */
585   if (do_drop_caches (3) == -1)
586     return NULL;
587
588   char *ret = strdup ("ok");
589   if (NULL == ret) {
590     reply_with_perror ("strdup");
591     return NULL;
592   }
593
594   return ret;
595 }
596
597 /* Has one FileIn parameter. */
598 int
599 do_debug_upload (const char *filename, int mode)
600 {
601   /* Not chrooted - this command lets you upload a file to anywhere
602    * in the appliance.
603    */
604   int fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, mode);
605
606   if (fd == -1) {
607     int err = errno;
608     cancel_receive ();
609     errno = err;
610     reply_with_perror ("%s", filename);
611     return -1;
612   }
613
614   int r = receive_file (write_cb, &fd);
615   if (r == -1) {                /* write error */
616     int err = errno;
617     cancel_receive ();
618     errno = err;
619     reply_with_error ("write error: %s", filename);
620     close (fd);
621     return -1;
622   }
623   if (r == -2) {                /* cancellation from library */
624     /* This error is ignored by the library since it initiated the
625      * cancel.  Nevertheless we must send an error reply here.
626      */
627     reply_with_error ("file upload cancelled");
628     close (fd);
629     return -1;
630   }
631
632   if (close (fd) == -1) {
633     reply_with_perror ("close: %s", filename);
634     return -1;
635   }
636
637   return 0;
638 }