Update FSF address.
[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   *(int*)0 = 0;
202   return NULL;
203 }
204
205 /* Run an arbitrary shell command using /bin/sh from the appliance.
206  *
207  * Note this is somewhat different from the ordinary guestfs_sh command
208  * because it's not using the guest shell, and is not chrooted.
209  */
210 static char *
211 debug_sh (const char *subcmd, int argc, char *const *const argv)
212 {
213   if (argc < 1) {
214     reply_with_error ("sh: expecting a command to run");
215     return NULL;
216   }
217
218   char *cmd;
219   int len, i, j;
220
221   /* guestfish splits the parameter(s) into a list of strings,
222    * and we have to reassemble them here.  Not ideal. XXX
223    */
224   for (i = len = 0; i < argc; ++i)
225     len += strlen (argv[i]) + 1;
226   cmd = malloc (len);
227   if (!cmd) {
228     reply_with_perror ("malloc");
229     return NULL;
230   }
231   for (i = j = 0; i < argc; ++i) {
232     len = strlen (argv[i]);
233     memcpy (&cmd[j], argv[i], len);
234     j += len;
235     cmd[j] = ' ';
236     j++;
237   }
238   cmd[j-1] = '\0';
239
240   /* Set up some environment variables. */
241   setenv ("root", sysroot, 1);
242   if (access ("/sys/block/sda", F_OK) == 0)
243     setenv ("sd", "sd", 1);
244   else if (access ("/sys/block/hda", F_OK) == 0)
245     setenv ("sd", "hd", 1);
246   else if (access ("/sys/block/vda", F_OK) == 0)
247     setenv ("sd", "vd", 1);
248
249   char *err;
250   int r = commandf (NULL, &err, COMMAND_FLAG_FOLD_STDOUT_ON_STDERR,
251                     "/bin/sh", "-c", cmd, NULL);
252   free (cmd);
253
254   if (r == -1) {
255     reply_with_error ("%s", err);
256     free (err);
257     return NULL;
258   }
259
260   return err;
261 }
262
263 /* Print the environment that commands get (by running external printenv). */
264 static char *
265 debug_env (const char *subcmd, int argc, char *const *const argv)
266 {
267   int r;
268   char *out, *err;
269
270   r = command (&out, &err, "printenv", NULL);
271   if (r == -1) {
272     reply_with_error ("printenv: %s", err);
273     free (out);
274     free (err);
275     return NULL;
276   }
277
278   free (err);
279
280   return out;
281 }
282
283 /* Return binaries in the appliance.  See regressions/rhbz727178.sh */
284 static char *
285 debug_binaries (const char *subcmd, int argc, char *const *const argv)
286 {
287   int r;
288   char *out, *err;
289
290   const char cmd[] =
291     "find / -xdev -type f -executable "
292     "| xargs file -i "
293     "| grep application/x-executable "
294     "| gawk -F: '{print $1}'";
295
296   r = command (&out, &err, "sh", "-c", cmd, NULL);
297   if (r == -1) {
298     reply_with_error ("find: %s", err);
299     free (out);
300     free (err);
301     return NULL;
302   }
303
304   free (err);
305
306   return out;
307 }
308
309 /* Run 'ldd' on a file from the appliance.  See regressions/rhbz727178.sh */
310 static char *
311 debug_ldd (const char *subcmd, int argc, char *const *const argv)
312 {
313   int r;
314   char *out, *err, *ret;
315
316   if (argc != 1) {
317     reply_with_error ("ldd: no file argument");
318     return NULL;
319   }
320
321   /* Note that 'ldd' doesn't fail if it finds errors.  We have to grep
322    * for errors in the regression test instead.  'ldd' only fails here
323    * if the binary is not a binary at all (eg. for shell scripts).
324    * Also 'ldd' randomly sends messages to stderr and errors to stdout
325    * depending on the phase of the moon.
326    */
327   r = command (&out, &err, "ldd", "-r", argv[0], NULL);
328   if (r == -1) {
329     reply_with_error ("ldd: %s: %s", argv[0], err);
330     free (out);
331     free (err);
332     return NULL;
333   }
334
335   /* Concatenate stdout and stderr in the result. */
336   ret = realloc (out, strlen (out) + strlen (err) + 1);
337   if (ret == NULL) {
338     reply_with_perror ("realloc");
339     free (out);
340     free (err);
341     return NULL;
342   }
343
344   strcat (ret, err);
345   free (err);
346
347   return ret;
348 }
349
350 /* List files in the appliance. */
351 static char *
352 debug_ls (const char *subcmd, int argc, char *const *const argv)
353 {
354   int len = count_strings (argv);
355   const char *cargv[len+3];
356   int i;
357
358   cargv[0] = "ls";
359   cargv[1] = "-a";
360   for (i = 0; i < len; ++i)
361     cargv[2+i] = argv[i];
362   cargv[2+len] = NULL;
363
364   int r;
365   char *out, *err;
366
367   r = commandv (&out, &err, (void *) cargv);
368   if (r == -1) {
369     reply_with_error ("ls: %s", err);
370     free (out);
371     free (err);
372     return NULL;
373   }
374
375   free (err);
376
377   return out;
378 }
379
380 /* List files in the appliance. */
381 static char *
382 debug_ll (const char *subcmd, int argc, char *const *const argv)
383 {
384   int len = count_strings (argv);
385   const char *cargv[len+3];
386   int i;
387
388   cargv[0] = "ls";
389   cargv[1] = "-la";
390   for (i = 0; i < len; ++i)
391     cargv[2+i] = argv[i];
392   cargv[2+len] = NULL;
393
394   int r;
395   char *out, *err;
396
397   r = commandv (&out, &err, (void *) cargv);
398   if (r == -1) {
399     reply_with_error ("ll: %s", err);
400     free (out);
401     free (err);
402     return NULL;
403   }
404
405   free (err);
406
407   return out;
408 }
409
410 /* Generate progress notification messages in order to test progress bars. */
411 static char *
412 debug_progress (const char *subcmd, int argc, char *const *const argv)
413 {
414   if (argc < 1) {
415   error:
416     reply_with_error ("progress: expecting arg (time in seconds as string)");
417     return NULL;
418   }
419
420   char *secs_str = argv[0];
421   unsigned secs;
422   if (sscanf (secs_str, "%u", &secs) != 1 || secs == 0)
423     goto error;
424
425   unsigned i;
426   unsigned tsecs = secs * 10;   /* 1/10ths of seconds */
427   for (i = 1; i <= tsecs; ++i) {
428     usleep (100000);
429     notify_progress ((uint64_t) i, (uint64_t) tsecs);
430   }
431
432   char *ret = strdup ("ok");
433   if (ret == NULL) {
434     reply_with_perror ("strdup");
435     return NULL;
436   }
437
438   return ret;
439 }
440
441 /* Enable core dumping to the given core pattern.
442  * Note that this pattern is relative to any chroot of the process which
443  * crashes. This means that if you want to write the core file to the guest's
444  * storage the pattern must start with /sysroot only if the command which
445  * crashes doesn't chroot.
446  */
447 static char *
448 debug_core_pattern (const char *subcmd, int argc, char *const *const argv)
449 {
450   if (argc < 1) {
451     reply_with_error ("core_pattern: expecting a core pattern");
452     return NULL;
453   }
454
455   const char *pattern = argv[0];
456   const size_t pattern_len = strlen(pattern);
457
458 #define CORE_PATTERN "/proc/sys/kernel/core_pattern"
459   int fd = open (CORE_PATTERN, O_WRONLY);
460   if (fd == -1) {
461     reply_with_perror ("open: " CORE_PATTERN);
462     return NULL;
463   }
464   if (write (fd, pattern, pattern_len) < (ssize_t) pattern_len) {
465     reply_with_perror ("write: " CORE_PATTERN);
466     return NULL;
467   }
468   if (close (fd) == -1) {
469     reply_with_perror ("close: " CORE_PATTERN);
470     return NULL;
471   }
472
473   struct rlimit limit = {
474     .rlim_cur = RLIM_INFINITY,
475     .rlim_max = RLIM_INFINITY
476   };
477   if (setrlimit (RLIMIT_CORE, &limit) == -1) {
478     reply_with_perror ("setrlimit (RLIMIT_CORE)");
479     return NULL;
480   }
481
482   char *ret = strdup ("ok");
483   if (NULL == ret) {
484     reply_with_perror ("strdup");
485     return NULL;
486   }
487
488   return ret;
489 }
490
491 static int
492 write_cb (void *fd_ptr, const void *buf, size_t len)
493 {
494   int fd = *(int *)fd_ptr;
495   return xwrite (fd, buf, len);
496 }
497
498 /* This requires a non-upstream qemu patch.  See contrib/visualize-alignment/
499  * directory in the libguestfs source tree.
500  */
501 static char *
502 debug_qtrace (const char *subcmd, int argc, char *const *const argv)
503 {
504   int enable;
505
506   if (argc != 2) {
507   bad_args:
508     reply_with_error ("qtrace <device> <on|off>");
509     return NULL;
510   }
511
512   if (STREQ (argv[1], "on"))
513     enable = 1;
514   else if (STREQ (argv[1], "off"))
515     enable = 0;
516   else
517     goto bad_args;
518
519   /* This does a sync and flushes all caches. */
520   if (do_drop_caches (3) == -1)
521     return NULL;
522
523   /* Note this doesn't do device name translation or check this is a device. */
524   int fd = open (argv[0], O_RDONLY | O_DIRECT);
525   if (fd == -1) {
526     reply_with_perror ("qtrace: %s: open", argv[0]);
527     return NULL;
528   }
529
530   /* The pattern of reads is what signals to the analysis program that
531    * tracing should be started or stopped.  Note this assumes both 512
532    * byte sectors, and that O_DIRECT will let us do 512 byte aligned
533    * reads.  We ought to read the sector size of the device and use
534    * that instead (XXX).  The analysis program currently assumes 512
535    * byte sectors anyway.
536    */
537 #define QTRACE_SIZE 512
538   const int patterns[2][5] = {
539     { 2, 15, 21, 2, -1 }, /* disable trace */
540     { 2, 21, 15, 2, -1 }  /* enable trace */
541   };
542   void *buf;
543   size_t i;
544
545   /* For O_DIRECT, buffer must be aligned too (thanks Matt).
546    * Note posix_memalign has this strange errno behaviour.
547    */
548   errno = posix_memalign (&buf, QTRACE_SIZE, QTRACE_SIZE);
549   if (errno != 0) {
550     reply_with_perror ("posix_memalign");
551     close (fd);
552     return NULL;
553   }
554
555   for (i = 0; patterns[enable][i] >= 0; ++i) {
556     if (lseek (fd, patterns[enable][i]*QTRACE_SIZE, SEEK_SET) == -1) {
557       reply_with_perror ("qtrace: %s: lseek", argv[0]);
558       close (fd);
559       free (buf);
560       return NULL;
561     }
562
563     if (read (fd, buf, QTRACE_SIZE) == -1) {
564       reply_with_perror ("qtrace: %s: read", argv[0]);
565       close (fd);
566       free (buf);
567       return NULL;
568     }
569   }
570
571   close (fd);
572   free (buf);
573
574   /* This does a sync and flushes all caches. */
575   if (do_drop_caches (3) == -1)
576     return NULL;
577
578   char *ret = strdup ("ok");
579   if (NULL == ret) {
580     reply_with_perror ("strdup");
581     return NULL;
582   }
583
584   return ret;
585 }
586
587 /* Has one FileIn parameter. */
588 int
589 do_debug_upload (const char *filename, int mode)
590 {
591   /* Not chrooted - this command lets you upload a file to anywhere
592    * in the appliance.
593    */
594   int fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, mode);
595
596   if (fd == -1) {
597     int err = errno;
598     cancel_receive ();
599     errno = err;
600     reply_with_perror ("%s", filename);
601     return -1;
602   }
603
604   int r = receive_file (write_cb, &fd);
605   if (r == -1) {                /* write error */
606     int err = errno;
607     cancel_receive ();
608     errno = err;
609     reply_with_error ("write error: %s", filename);
610     close (fd);
611     return -1;
612   }
613   if (r == -2) {                /* cancellation from library */
614     /* This error is ignored by the library since it initiated the
615      * cancel.  Nevertheless we must send an error reply here.
616      */
617     reply_with_error ("file upload cancelled");
618     close (fd);
619     return -1;
620   }
621
622   if (close (fd) == -1) {
623     reply_with_perror ("close: %s", filename);
624     return -1;
625   }
626
627   return 0;
628 }