inspect: win64 regexp was dead code.
[libguestfs.git] / src / inspect.c
1 /* libguestfs
2  * Copyright (C) 2010 Red Hat Inc.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library 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 GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; 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 <stdint.h>
24 #include <inttypes.h>
25 #include <unistd.h>
26 #include <string.h>
27 #include <sys/stat.h>
28
29 #include <pcre.h>
30 #include <magic.h>
31 #include <hivex.h>
32
33 #include "c-ctype.h"
34 #include "ignore-value.h"
35 #include "xstrtol.h"
36
37 #include "guestfs.h"
38 #include "guestfs-internal.h"
39 #include "guestfs-internal-actions.h"
40 #include "guestfs_protocol.h"
41
42 /* Compile all the regular expressions once when the shared library is
43  * loaded.  PCRE is thread safe so we're supposedly OK here if
44  * multiple threads call into the libguestfs API functions below
45  * simultaneously.
46  */
47 static pcre *re_file_elf;
48 static pcre *re_elf_ppc64;
49 static pcre *re_fedora;
50 static pcre *re_rhel_old;
51 static pcre *re_rhel;
52 static pcre *re_rhel_no_minor;
53 static pcre *re_major_minor;
54 static pcre *re_aug_seq;
55 static pcre *re_xdev;
56 static pcre *re_windows_version;
57
58 static void compile_regexps (void) __attribute__((constructor));
59 static void free_regexps (void) __attribute__((destructor));
60
61 static void
62 compile_regexps (void)
63 {
64   const char *err;
65   int offset;
66
67 #define COMPILE(re,pattern,options)                                     \
68   do {                                                                  \
69     re = pcre_compile ((pattern), (options), &err, &offset, NULL);      \
70     if (re == NULL) {                                                   \
71       ignore_value (write (2, err, strlen (err)));                      \
72       abort ();                                                         \
73     }                                                                   \
74   } while (0)
75
76   COMPILE (re_file_elf,
77            "ELF.*(?:executable|shared object|relocatable), (.+?),", 0);
78   COMPILE (re_elf_ppc64, "64.*PowerPC", 0);
79   COMPILE (re_fedora, "Fedora release (\\d+)", 0);
80   COMPILE (re_rhel_old,
81            "(?:Red Hat Enterprise Linux|CentOS|Scientific Linux).*release (\\d+).*Update (\\d+)", 0);
82   COMPILE (re_rhel,
83            "(?:Red Hat Enterprise Linux|CentOS|Scientific Linux).*release (\\d+)\\.(\\d+)", 0);
84   COMPILE (re_rhel_no_minor,
85            "(?:Red Hat Enterprise Linux|CentOS|Scientific Linux).*release (\\d+)", 0);
86   COMPILE (re_major_minor, "(\\d+)\\.(\\d+)", 0);
87   COMPILE (re_aug_seq, "/\\d+$", 0);
88   COMPILE (re_xdev, "^/dev/(?:h|s|v|xv)d([a-z]\\d*)$", 0);
89   COMPILE (re_windows_version, "^(\\d+)\\.(\\d+)", 0);
90 }
91
92 static void
93 free_regexps (void)
94 {
95   pcre_free (re_file_elf);
96   pcre_free (re_elf_ppc64);
97   pcre_free (re_fedora);
98   pcre_free (re_rhel_old);
99   pcre_free (re_rhel);
100   pcre_free (re_rhel_no_minor);
101   pcre_free (re_major_minor);
102   pcre_free (re_aug_seq);
103   pcre_free (re_xdev);
104   pcre_free (re_windows_version);
105 }
106
107 /* Match a regular expression which contains no captures.  Returns
108  * true if it matches or false if it doesn't.
109  */
110 static int
111 match (guestfs_h *g, const char *str, const pcre *re)
112 {
113   size_t len = strlen (str);
114   int vec[30], r;
115
116   r = pcre_exec (re, NULL, str, len, 0, 0, vec, sizeof vec / sizeof vec[0]);
117   if (r == PCRE_ERROR_NOMATCH)
118     return 0;
119   if (r != 1) {
120     /* Internal error -- should not happen. */
121     fprintf (stderr, "libguestfs: %s: %s: internal error: pcre_exec returned unexpected error code %d when matching against the string \"%s\"\n",
122              __FILE__, __func__, r, str);
123     return 0;
124   }
125
126   return 1;
127 }
128
129 /* Match a regular expression which contains exactly one capture.  If
130  * the string matches, return the capture, otherwise return NULL.  The
131  * caller must free the result.
132  */
133 static char *
134 match1 (guestfs_h *g, const char *str, const pcre *re)
135 {
136   size_t len = strlen (str);
137   int vec[30], r;
138
139   r = pcre_exec (re, NULL, str, len, 0, 0, vec, sizeof vec / sizeof vec[0]);
140   if (r == PCRE_ERROR_NOMATCH)
141     return NULL;
142   if (r != 2) {
143     /* Internal error -- should not happen. */
144     fprintf (stderr, "libguestfs: %s: %s: internal error: pcre_exec returned unexpected error code %d when matching against the string \"%s\"\n",
145              __FILE__, __func__, r, str);
146     return NULL;
147   }
148
149   return safe_strndup (g, &str[vec[2]], vec[3]-vec[2]);
150 }
151
152 /* Match a regular expression which contains exactly two captures. */
153 static int
154 match2 (guestfs_h *g, const char *str, const pcre *re, char **ret1, char **ret2)
155 {
156   size_t len = strlen (str);
157   int vec[30], r;
158
159   r = pcre_exec (re, NULL, str, len, 0, 0, vec, 30);
160   if (r == PCRE_ERROR_NOMATCH)
161     return 0;
162   if (r != 3) {
163     /* Internal error -- should not happen. */
164     fprintf (stderr, "libguestfs: %s: %s: internal error: pcre_exec returned unexpected error code %d when matching against the string \"%s\"\n",
165              __FILE__, __func__, r, str);
166     return 0;
167   }
168
169   *ret1 = safe_strndup (g, &str[vec[2]], vec[3]-vec[2]);
170   *ret2 = safe_strndup (g, &str[vec[4]], vec[5]-vec[4]);
171
172   return 1;
173 }
174
175 /* Convert output from 'file' command on ELF files to the canonical
176  * architecture string.  Caller must free the result.
177  */
178 static char *
179 canonical_elf_arch (guestfs_h *g, const char *elf_arch)
180 {
181   const char *r;
182
183   if (strstr (elf_arch, "Intel 80386"))
184     r = "i386";
185   else if (strstr (elf_arch, "Intel 80486"))
186     r = "i486";
187   else if (strstr (elf_arch, "x86-64"))
188     r = "x86_64";
189   else if (strstr (elf_arch, "AMD x86-64"))
190     r = "x86_64";
191   else if (strstr (elf_arch, "SPARC32"))
192     r = "sparc";
193   else if (strstr (elf_arch, "SPARC V9"))
194     r = "sparc64";
195   else if (strstr (elf_arch, "IA-64"))
196     r = "ia64";
197   else if (match (g, elf_arch, re_elf_ppc64))
198     r = "ppc64";
199   else if (strstr (elf_arch, "PowerPC"))
200     r = "ppc";
201   else
202     r = elf_arch;
203
204   char *ret = safe_strdup (g, r);
205   return ret;
206 }
207
208 static int
209 is_regular_file (const char *filename)
210 {
211   struct stat statbuf;
212
213   return lstat (filename, &statbuf) == 0 && S_ISREG (statbuf.st_mode);
214 }
215
216 /* Download and uncompress the cpio file to find binaries within.
217  * Notes:
218  * (1) Two lists must be identical.
219  * (2) Implicit limit of 31 bytes for length of each element (see code
220  * below).
221  */
222 #define INITRD_BINARIES1 "bin/ls bin/rm bin/modprobe sbin/modprobe bin/sh bin/bash bin/dash bin/nash"
223 #define INITRD_BINARIES2 {"bin/ls", "bin/rm", "bin/modprobe", "sbin/modprobe", "bin/sh", "bin/bash", "bin/dash", "bin/nash"}
224
225 static char *
226 cpio_arch (guestfs_h *g, const char *file, const char *path)
227 {
228   TMP_TEMPLATE_ON_STACK (dir);
229 #define dir_len (strlen (dir))
230 #define initrd_len (dir_len + 16)
231   char initrd[initrd_len];
232 #define cmd_len (dir_len + 256)
233   char cmd[cmd_len];
234 #define bin_len (dir_len + 32)
235   char bin[bin_len];
236
237   char *ret = NULL;
238
239   const char *method;
240   if (strstr (file, "gzip"))
241     method = "zcat";
242   else if (strstr (file, "bzip2"))
243     method = "bzcat";
244   else
245     method = "cat";
246
247   if (mkdtemp (dir) == NULL) {
248     perrorf (g, "mkdtemp");
249     goto out;
250   }
251
252   snprintf (initrd, initrd_len, "%s/initrd", dir);
253   if (guestfs_download (g, path, initrd) == -1)
254     goto out;
255
256   snprintf (cmd, cmd_len,
257             "cd %s && %s initrd | cpio --quiet -id " INITRD_BINARIES1,
258             dir, method);
259   int r = system (cmd);
260   if (r == -1 || WEXITSTATUS (r) != 0) {
261     perrorf (g, "cpio command failed");
262     goto out;
263   }
264
265   const char *bins[] = INITRD_BINARIES2;
266   size_t i;
267   for (i = 0; i < sizeof bins / sizeof bins[0]; ++i) {
268     snprintf (bin, bin_len, "%s/%s", dir, bins[i]);
269
270     if (is_regular_file (bin)) {
271       int flags = g->verbose ? MAGIC_DEBUG : 0;
272       flags |= MAGIC_ERROR | MAGIC_RAW;
273
274       magic_t m = magic_open (flags);
275       if (m == NULL) {
276         perrorf (g, "magic_open");
277         goto out;
278       }
279
280       if (magic_load (m, NULL) == -1) {
281         perrorf (g, "magic_load: default magic database file");
282         magic_close (m);
283         goto out;
284       }
285
286       const char *line = magic_file (m, bin);
287       if (line == NULL) {
288         perrorf (g, "magic_file: %s", bin);
289         magic_close (m);
290         goto out;
291       }
292
293       char *elf_arch;
294       if ((elf_arch = match1 (g, line, re_file_elf)) != NULL) {
295         ret = canonical_elf_arch (g, elf_arch);
296         free (elf_arch);
297         magic_close (m);
298         goto out;
299       }
300       magic_close (m);
301     }
302   }
303   error (g, "file_architecture: could not determine architecture of cpio archive");
304
305  out:
306   /* Free up the temporary directory.  Note the directory name cannot
307    * contain shell meta-characters because of the way it was
308    * constructed above.
309    */
310   snprintf (cmd, cmd_len, "rm -rf %s", dir);
311   ignore_value (system (cmd));
312
313   return ret;
314 #undef dir_len
315 #undef initrd_len
316 #undef cmd_len
317 #undef bin_len
318 }
319
320 char *
321 guestfs__file_architecture (guestfs_h *g, const char *path)
322 {
323   char *file = NULL;
324   char *elf_arch = NULL;
325   char *ret = NULL;
326
327   /* Get the output of the "file" command.  Note that because this
328    * runs in the daemon, LANG=C so it's in English.
329    */
330   file = guestfs_file (g, path);
331   if (file == NULL)
332     return NULL;
333
334   if ((elf_arch = match1 (g, file, re_file_elf)) != NULL)
335     ret = canonical_elf_arch (g, elf_arch);
336   else if (strstr (file, "PE32 executable"))
337     ret = safe_strdup (g, "i386");
338   else if (strstr (file, "PE32+ executable"))
339     ret = safe_strdup (g, "x86_64");
340   else if (strstr (file, "cpio archive"))
341     ret = cpio_arch (g, file, path);
342   else
343     error (g, "file_architecture: unknown architecture: %s", path);
344
345   free (file);
346   free (elf_arch);
347   return ret;                   /* caller frees */
348 }
349
350 /* The main inspection code. */
351 static int feature_available (guestfs_h *g, const char *feature);
352 static void free_string_list (char **);
353 static int check_for_filesystem_on (guestfs_h *g, const char *device);
354
355 char **
356 guestfs__inspect_os (guestfs_h *g)
357 {
358   /* Remove any information previously stored in the handle. */
359   guestfs___free_inspect_info (g);
360
361   if (guestfs_umount_all (g) == -1)
362     return NULL;
363
364   /* Iterate over all possible devices.  Try to mount each
365    * (read-only).  Examine ones which contain filesystems and add that
366    * information to the handle.
367    */
368   /* Look to see if any devices directly contain filesystems (RHBZ#590167). */
369   char **devices;
370   devices = guestfs_list_devices (g);
371   if (devices == NULL)
372     return NULL;
373
374   size_t i;
375   for (i = 0; devices[i] != NULL; ++i) {
376     if (check_for_filesystem_on (g, devices[i]) == -1) {
377       free_string_list (devices);
378       guestfs___free_inspect_info (g);
379       return NULL;
380     }
381   }
382   free_string_list (devices);
383
384   /* Look at all partitions. */
385   char **partitions;
386   partitions = guestfs_list_partitions (g);
387   if (partitions == NULL) {
388     guestfs___free_inspect_info (g);
389     return NULL;
390   }
391
392   for (i = 0; partitions[i] != NULL; ++i) {
393     if (check_for_filesystem_on (g, partitions[i]) == -1) {
394       free_string_list (partitions);
395       guestfs___free_inspect_info (g);
396       return NULL;
397     }
398   }
399   free_string_list (partitions);
400
401   /* Look at all LVs. */
402   if (feature_available (g, "lvm2")) {
403     char **lvs;
404     lvs = guestfs_lvs (g);
405     if (lvs == NULL) {
406       guestfs___free_inspect_info (g);
407       return NULL;
408     }
409
410     for (i = 0; lvs[i] != NULL; ++i) {
411       if (check_for_filesystem_on (g, lvs[i]) == -1) {
412         free_string_list (lvs);
413         guestfs___free_inspect_info (g);
414         return NULL;
415       }
416     }
417     free_string_list (lvs);
418   }
419
420   /* At this point we have, in the handle, a list of all filesystems
421    * found and data about each one.  Now we assemble the list of
422    * filesystems which are root devices and return that to the user.
423    * Fall through to guestfs__inspect_get_roots to do that.
424    */
425   char **ret = guestfs__inspect_get_roots (g);
426   if (ret == NULL)
427     guestfs___free_inspect_info (g);
428   return ret;
429 }
430
431 void
432 guestfs___free_inspect_info (guestfs_h *g)
433 {
434   size_t i;
435   for (i = 0; i < g->nr_fses; ++i) {
436     free (g->fses[i].device);
437     free (g->fses[i].product_name);
438     free (g->fses[i].arch);
439     free (g->fses[i].windows_systemroot);
440     size_t j;
441     for (j = 0; j < g->fses[i].nr_fstab; ++j) {
442       free (g->fses[i].fstab[j].device);
443       free (g->fses[i].fstab[j].mountpoint);
444     }
445     free (g->fses[i].fstab);
446   }
447   free (g->fses);
448   g->nr_fses = 0;
449   g->fses = NULL;
450 }
451
452 static void
453 free_string_list (char **argv)
454 {
455   size_t i;
456   for (i = 0; argv[i] != NULL; ++i)
457     free (argv[i]);
458   free (argv);
459 }
460
461 /* In the Perl code this is a public function. */
462 static int
463 feature_available (guestfs_h *g, const char *feature)
464 {
465   /* If there's an error we should ignore it, so to do that we have to
466    * temporarily replace the error handler with a null one.
467    */
468   guestfs_error_handler_cb old_error_cb = g->error_cb;
469   g->error_cb = NULL;
470
471   const char *groups[] = { feature, NULL };
472   int r = guestfs_available (g, (char * const *) groups);
473
474   g->error_cb = old_error_cb;
475
476   return r == 0 ? 1 : 0;
477 }
478
479 /* Find out if 'device' contains a filesystem.  If it does, add
480  * another entry in g->fses.
481  */
482 static int check_filesystem (guestfs_h *g, const char *device);
483 static int check_linux_root (guestfs_h *g, struct inspect_fs *fs);
484 static int check_fstab (guestfs_h *g, struct inspect_fs *fs);
485 static int check_windows_root (guestfs_h *g, struct inspect_fs *fs);
486 static int check_windows_arch (guestfs_h *g, struct inspect_fs *fs);
487 static int check_windows_registry (guestfs_h *g, struct inspect_fs *fs);
488 static char *resolve_windows_path_silently (guestfs_h *g, const char *);
489 static int extend_fses (guestfs_h *g);
490 static int parse_unsigned_int (guestfs_h *g, const char *str);
491 static int add_fstab_entry (guestfs_h *g, struct inspect_fs *fs,
492                             const char *spec, const char *mp);
493 static char *resolve_fstab_device (guestfs_h *g, const char *spec);
494
495 static int
496 check_for_filesystem_on (guestfs_h *g, const char *device)
497 {
498   /* Get vfs-type in order to check if it's a Linux(?) swap device.
499    * If there's an error we should ignore it, so to do that we have to
500    * temporarily replace the error handler with a null one.
501    */
502   guestfs_error_handler_cb old_error_cb = g->error_cb;
503   g->error_cb = NULL;
504   char *vfs_type = guestfs_vfs_type (g, device);
505   g->error_cb = old_error_cb;
506
507   int is_swap = vfs_type && STREQ (vfs_type, "swap");
508
509   if (g->verbose)
510     fprintf (stderr, "check_for_filesystem_on: %s (%s)\n",
511              device, vfs_type ? vfs_type : "failed to get vfs type");
512
513   if (is_swap) {
514     free (vfs_type);
515     if (extend_fses (g) == -1)
516       return -1;
517     g->fses[g->nr_fses-1].is_swap = 1;
518     return 0;
519   }
520
521   /* Try mounting the device.  As above, ignore errors. */
522   g->error_cb = NULL;
523   int r = guestfs_mount_ro (g, device, "/");
524   if (r == -1 && vfs_type && STREQ (vfs_type, "ufs")) /* Hack for the *BSDs. */
525     r = guestfs_mount_vfs (g, "ro,ufstype=ufs2", "ufs", device, "/");
526   free (vfs_type);
527   g->error_cb = old_error_cb;
528   if (r == -1)
529     return 0;
530
531   /* Do the rest of the checks. */
532   r = check_filesystem (g, device);
533
534   /* Unmount the filesystem. */
535   if (guestfs_umount_all (g) == -1)
536     return -1;
537
538   return r;
539 }
540
541 static int
542 check_filesystem (guestfs_h *g, const char *device)
543 {
544   if (extend_fses (g) == -1)
545     return -1;
546
547   struct inspect_fs *fs = &g->fses[g->nr_fses-1];
548
549   fs->device = safe_strdup (g, device);
550   fs->is_mountable = 1;
551
552   /* Grub /boot? */
553   if (guestfs_is_file (g, "/grub/menu.lst") > 0 ||
554       guestfs_is_file (g, "/grub/grub.conf") > 0)
555     fs->content = FS_CONTENT_LINUX_BOOT;
556   /* Linux root? */
557   else if (guestfs_is_dir (g, "/etc") > 0 &&
558            guestfs_is_dir (g, "/bin") > 0 &&
559            guestfs_is_file (g, "/etc/fstab") > 0) {
560     fs->is_root = 1;
561     fs->content = FS_CONTENT_LINUX_ROOT;
562     if (check_linux_root (g, fs) == -1)
563       return -1;
564   }
565   /* Linux /usr/local? */
566   else if (guestfs_is_dir (g, "/etc") > 0 &&
567            guestfs_is_dir (g, "/bin") > 0 &&
568            guestfs_is_dir (g, "/share") > 0 &&
569            guestfs_exists (g, "/local") == 0 &&
570            guestfs_is_file (g, "/etc/fstab") == 0)
571     fs->content = FS_CONTENT_LINUX_USR_LOCAL;
572   /* Linux /usr? */
573   else if (guestfs_is_dir (g, "/etc") > 0 &&
574            guestfs_is_dir (g, "/bin") > 0 &&
575            guestfs_is_dir (g, "/share") > 0 &&
576            guestfs_exists (g, "/local") > 0 &&
577            guestfs_is_file (g, "/etc/fstab") == 0)
578     fs->content = FS_CONTENT_LINUX_USR;
579   /* Linux /var? */
580   else if (guestfs_is_dir (g, "/log") > 0 &&
581            guestfs_is_dir (g, "/run") > 0 &&
582            guestfs_is_dir (g, "/spool") > 0)
583     fs->content = FS_CONTENT_LINUX_VAR;
584   /* Windows root? */
585   else if (guestfs_is_file (g, "/AUTOEXEC.BAT") > 0 ||
586            guestfs_is_file (g, "/autoexec.bat") > 0 ||
587            guestfs_is_dir (g, "/Program Files") > 0 ||
588            guestfs_is_dir (g, "/WINDOWS") > 0 ||
589            guestfs_is_dir (g, "/Windows") > 0 ||
590            guestfs_is_dir (g, "/windows") > 0 ||
591            guestfs_is_dir (g, "/WIN32") > 0 ||
592            guestfs_is_dir (g, "/Win32") > 0 ||
593            guestfs_is_dir (g, "/WINNT") > 0 ||
594            guestfs_is_file (g, "/boot.ini") > 0 ||
595            guestfs_is_file (g, "/ntldr") > 0) {
596     fs->is_root = 1;
597     fs->content = FS_CONTENT_WINDOWS_ROOT;
598     if (check_windows_root (g, fs) == -1)
599       return -1;
600   }
601
602   return 0;
603 }
604
605 /* Set fs->product_name to the first line of the release file. */
606 static int
607 parse_release_file (guestfs_h *g, struct inspect_fs *fs,
608                     const char *release_filename)
609 {
610   char **product_name = guestfs_head_n (g, 1, release_filename);
611   if (product_name == NULL)
612     return -1;
613   if (product_name[0] == NULL) {
614     error (g, "%s: file is empty", release_filename);
615     free_string_list (product_name);
616     return -1;
617   }
618
619   /* Note that this string becomes owned by the handle and will
620    * be freed by guestfs___free_inspect_info.
621    */
622   fs->product_name = product_name[0];
623   free (product_name);
624
625   return 0;
626 }
627
628 /* Parse generic MAJOR.MINOR from the fs->product_name string. */
629 static int
630 parse_major_minor (guestfs_h *g, struct inspect_fs *fs)
631 {
632   char *major, *minor;
633
634   if (match2 (g, fs->product_name, re_major_minor, &major, &minor)) {
635     fs->major_version = parse_unsigned_int (g, major);
636     free (major);
637     if (fs->major_version == -1) {
638       free (minor);
639       return -1;
640     }
641     fs->minor_version = parse_unsigned_int (g, minor);
642     free (minor);
643     if (fs->minor_version == -1)
644       return -1;
645   }
646   return 0;
647 }
648
649 /* Ubuntu has /etc/lsb-release containing:
650  *   DISTRIB_ID=Ubuntu                                # Distro
651  *   DISTRIB_RELEASE=10.04                            # Version
652  *   DISTRIB_CODENAME=lucid
653  *   DISTRIB_DESCRIPTION="Ubuntu 10.04.1 LTS"         # Product name
654  * In theory other distros could have this LSB file, but none do.
655  */
656 static int
657 parse_lsb_release (guestfs_h *g, struct inspect_fs *fs)
658 {
659   char **lines;
660   size_t i;
661   int r = 0;
662
663   lines = guestfs_head_n (g, 10, "/etc/lsb-release");
664   if (lines == NULL)
665     return -1;
666
667   for (i = 0; lines[i] != NULL; ++i) {
668     if (fs->distro == 0 &&
669         STREQ (lines[i], "DISTRIB_ID=Ubuntu")) {
670       fs->distro = OS_DISTRO_UBUNTU;
671       r = 1;
672     }
673     else if (STRPREFIX (lines[i], "DISTRIB_RELEASE=")) {
674       char *major, *minor;
675       if (match2 (g, &lines[i][16], re_major_minor, &major, &minor)) {
676         fs->major_version = parse_unsigned_int (g, major);
677         free (major);
678         if (fs->major_version == -1) {
679           free (minor);
680           free_string_list (lines);
681           return -1;
682         }
683         fs->minor_version = parse_unsigned_int (g, minor);
684         free (minor);
685         if (fs->minor_version == -1) {
686           free_string_list (lines);
687           return -1;
688         }
689       }
690     }
691     else if (fs->product_name == NULL &&
692              (STRPREFIX (lines[i], "DISTRIB_DESCRIPTION=\"") ||
693               STRPREFIX (lines[i], "DISTRIB_DESCRIPTION='"))) {
694       size_t len = strlen (lines[i]) - 21 - 1;
695       fs->product_name = safe_strndup (g, &lines[i][21], len);
696       r = 1;
697     }
698     else if (fs->product_name == NULL &&
699              STRPREFIX (lines[i], "DISTRIB_DESCRIPTION=")) {
700       size_t len = strlen (lines[i]) - 20;
701       fs->product_name = safe_strndup (g, &lines[i][20], len);
702       r = 1;
703     }
704   }
705
706   free_string_list (lines);
707   return r;
708 }
709
710 /* The currently mounted device is known to be a Linux root.  Try to
711  * determine from this the distro, version, etc.  Also parse
712  * /etc/fstab to determine the arrangement of mountpoints and
713  * associated devices.
714  */
715 static int
716 check_linux_root (guestfs_h *g, struct inspect_fs *fs)
717 {
718   int r;
719
720   fs->type = OS_TYPE_LINUX;
721
722   if (guestfs_exists (g, "/etc/lsb-release") > 0) {
723     r = parse_lsb_release (g, fs);
724     if (r == -1)        /* error */
725       return -1;
726     if (r == 1)         /* ok - detected the release from this file */
727       goto skip_release_checks;
728   }
729
730   if (guestfs_exists (g, "/etc/redhat-release") > 0) {
731     fs->distro = OS_DISTRO_REDHAT_BASED; /* Something generic Red Hat-like. */
732
733     if (parse_release_file (g, fs, "/etc/redhat-release") == -1)
734       return -1;
735
736     char *major, *minor;
737     if ((major = match1 (g, fs->product_name, re_fedora)) != NULL) {
738       fs->distro = OS_DISTRO_FEDORA;
739       fs->major_version = parse_unsigned_int (g, major);
740       free (major);
741       if (fs->major_version == -1)
742         return -1;
743     }
744     else if (match2 (g, fs->product_name, re_rhel_old, &major, &minor) ||
745              match2 (g, fs->product_name, re_rhel, &major, &minor)) {
746       fs->distro = OS_DISTRO_RHEL;
747       fs->major_version = parse_unsigned_int (g, major);
748       free (major);
749       if (fs->major_version == -1) {
750         free (minor);
751         return -1;
752       }
753       fs->minor_version = parse_unsigned_int (g, minor);
754       free (minor);
755       if (fs->minor_version == -1)
756         return -1;
757     }
758     else if ((major = match1 (g, fs->product_name, re_rhel_no_minor)) != NULL) {
759       fs->distro = OS_DISTRO_RHEL;
760       fs->major_version = parse_unsigned_int (g, major);
761       free (major);
762       if (fs->major_version == -1)
763         return -1;
764       fs->minor_version = 0;
765     }
766   }
767   else if (guestfs_exists (g, "/etc/debian_version") > 0) {
768     fs->distro = OS_DISTRO_DEBIAN;
769
770     if (parse_release_file (g, fs, "/etc/debian_version") == -1)
771       return -1;
772
773     if (parse_major_minor (g, fs) == -1)
774       return -1;
775   }
776   else if (guestfs_exists (g, "/etc/pardus-release") > 0) {
777     fs->distro = OS_DISTRO_PARDUS;
778
779     if (parse_release_file (g, fs, "/etc/pardus-release") == -1)
780       return -1;
781
782     if (parse_major_minor (g, fs) == -1)
783       return -1;
784   }
785   else if (guestfs_exists (g, "/etc/arch-release") > 0) {
786     fs->distro = OS_DISTRO_ARCHLINUX;
787
788     /* /etc/arch-release file is empty and I can't see a way to
789      * determine the actual release or product string.
790      */
791   }
792   else if (guestfs_exists (g, "/etc/gentoo-release") > 0) {
793     fs->distro = OS_DISTRO_GENTOO;
794
795     if (parse_release_file (g, fs, "/etc/gentoo-release") == -1)
796       return -1;
797
798     if (parse_major_minor (g, fs) == -1)
799       return -1;
800   }
801   else if (guestfs_exists (g, "/etc/meego-release") > 0) {
802     fs->distro = OS_DISTRO_MEEGO;
803
804     if (parse_release_file (g, fs, "/etc/meego-release") == -1)
805       return -1;
806
807     if (parse_major_minor (g, fs) == -1)
808       return -1;
809   }
810
811  skip_release_checks:;
812
813   /* Determine the architecture. */
814   const char *binaries[] =
815     { "/bin/bash", "/bin/ls", "/bin/echo", "/bin/rm", "/bin/sh" };
816   size_t i;
817   for (i = 0; i < sizeof binaries / sizeof binaries[0]; ++i) {
818     if (guestfs_is_file (g, binaries[i]) > 0) {
819       /* Ignore errors from file_architecture call. */
820       guestfs_error_handler_cb old_error_cb = g->error_cb;
821       g->error_cb = NULL;
822       char *arch = guestfs_file_architecture (g, binaries[i]);
823       g->error_cb = old_error_cb;
824
825       if (arch) {
826         /* String will be owned by handle, freed by
827          * guestfs___free_inspect_info.
828          */
829         fs->arch = arch;
830         break;
831       }
832     }
833   }
834
835   /* We already know /etc/fstab exists because it's part of the test
836    * for Linux root above.  We must now parse this file to determine
837    * which filesystems are used by the operating system and how they
838    * are mounted.
839    * XXX What if !feature_available (g, "augeas")?
840    */
841   if (guestfs_aug_init (g, "/", 16|32) == -1)
842     return -1;
843
844   /* Tell Augeas to only load /etc/fstab (thanks Raphaël Pinson). */
845   guestfs_aug_rm (g, "/augeas/load//incl[. != \"/etc/fstab\"]");
846   guestfs_aug_load (g);
847
848   r = check_fstab (g, fs);
849   guestfs_aug_close (g);
850   if (r == -1)
851     return -1;
852
853   return 0;
854 }
855
856 static int
857 check_fstab (guestfs_h *g, struct inspect_fs *fs)
858 {
859   char **lines = guestfs_aug_ls (g, "/files/etc/fstab");
860   if (lines == NULL)
861     return -1;
862
863   if (lines[0] == NULL) {
864     error (g, "could not parse /etc/fstab or empty file");
865     free_string_list (lines);
866     return -1;
867   }
868
869   size_t i;
870   char augpath[256];
871   for (i = 0; lines[i] != NULL; ++i) {
872     /* Ignore comments.  Only care about sequence lines which
873      * match m{/\d+$}.
874      */
875     if (match (g, lines[i], re_aug_seq)) {
876       snprintf (augpath, sizeof augpath, "%s/spec", lines[i]);
877       char *spec = guestfs_aug_get (g, augpath);
878       if (spec == NULL) {
879         free_string_list (lines);
880         return -1;
881       }
882
883       snprintf (augpath, sizeof augpath, "%s/file", lines[i]);
884       char *mp = guestfs_aug_get (g, augpath);
885       if (mp == NULL) {
886         free_string_list (lines);
887         free (spec);
888         return -1;
889       }
890
891       int r = add_fstab_entry (g, fs, spec, mp);
892       free (spec);
893       free (mp);
894
895       if (r == -1) {
896         free_string_list (lines);
897         return -1;
898       }
899     }
900   }
901
902   free_string_list (lines);
903   return 0;
904 }
905
906 /* Add a filesystem and possibly a mountpoint entry for
907  * the root filesystem 'fs'.
908  *
909  * 'spec' is the fstab spec field, which might be a device name or a
910  * pseudodevice or 'UUID=...' or 'LABEL=...'.
911  *
912  * 'mp' is the mount point, which could also be 'swap' or 'none'.
913  */
914 static int
915 add_fstab_entry (guestfs_h *g, struct inspect_fs *fs,
916                  const char *spec, const char *mp)
917 {
918   /* Ignore certain mountpoints. */
919   if (STRPREFIX (mp, "/dev/") ||
920       STREQ (mp, "/dev") ||
921       STRPREFIX (mp, "/media/") ||
922       STRPREFIX (mp, "/proc/") ||
923       STREQ (mp, "/proc") ||
924       STRPREFIX (mp, "/selinux/") ||
925       STREQ (mp, "/selinux") ||
926       STRPREFIX (mp, "/sys/") ||
927       STREQ (mp, "/sys"))
928     return 0;
929
930   /* Ignore /dev/fd (floppy disks) (RHBZ#642929) and CD-ROM drives. */
931   if ((STRPREFIX (spec, "/dev/fd") && c_isdigit (spec[7])) ||
932       STREQ (spec, "/dev/floppy") ||
933       STREQ (spec, "/dev/cdrom"))
934     return 0;
935
936   /* Resolve UUID= and LABEL= to the actual device. */
937   char *device = NULL;
938   if (STRPREFIX (spec, "UUID="))
939     device = guestfs_findfs_uuid (g, &spec[5]);
940   else if (STRPREFIX (spec, "LABEL="))
941     device = guestfs_findfs_label (g, &spec[6]);
942   /* Ignore "/.swap" (Pardus) and pseudo-devices like "tmpfs". */
943   else if (STRPREFIX (spec, "/dev/"))
944     /* Resolve guest block device names. */
945     device = resolve_fstab_device (g, spec);
946
947   /* If we haven't resolved the device successfully by this point,
948    * we don't care, just ignore it.
949    */
950   if (device == NULL)
951     return 0;
952
953   char *mountpoint = safe_strdup (g, mp);
954
955   /* Add this to the fstab entry in 'fs'.
956    * Note these are further filtered by guestfs_inspect_get_mountpoints
957    * and guestfs_inspect_get_filesystems.
958    */
959   size_t n = fs->nr_fstab + 1;
960   struct inspect_fstab_entry *p;
961
962   p = realloc (fs->fstab, n * sizeof (struct inspect_fstab_entry));
963   if (p == NULL) {
964     perrorf (g, "realloc");
965     free (device);
966     free (mountpoint);
967     return -1;
968   }
969
970   fs->fstab = p;
971   fs->nr_fstab = n;
972
973   /* These are owned by the handle and freed by guestfs___free_inspect_info. */
974   fs->fstab[n-1].device = device;
975   fs->fstab[n-1].mountpoint = mountpoint;
976
977   if (g->verbose)
978     fprintf (stderr, "fstab: device=%s mountpoint=%s\n", device, mountpoint);
979
980   return 0;
981 }
982
983 /* Resolve block device name to the libguestfs device name, eg.
984  * /dev/xvdb1 => /dev/vdb1; and /dev/mapper/VG-LV => /dev/VG/LV.  This
985  * assumes that disks were added in the same order as they appear to
986  * the real VM, which is a reasonable assumption to make.  Return
987  * anything we don't recognize unchanged.
988  */
989 static char *
990 resolve_fstab_device (guestfs_h *g, const char *spec)
991 {
992   char *a1;
993   char *device = NULL;
994
995   if (STRPREFIX (spec, "/dev/mapper/")) {
996     /* LVM2 does some strange munging on /dev/mapper paths for VGs and
997      * LVs which contain '-' character:
998      *
999      * ><fs> lvcreate LV--test VG--test 32
1000      * ><fs> debug ls /dev/mapper
1001      * VG----test-LV----test
1002      *
1003      * This makes it impossible to reverse those paths directly, so
1004      * we have implemented lvm_canonical_lv_name in the daemon.
1005      */
1006     device = guestfs_lvm_canonical_lv_name (g, spec);
1007   }
1008   else if ((a1 = match1 (g, spec, re_xdev)) != NULL) {
1009     char **devices = guestfs_list_devices (g);
1010     if (devices == NULL)
1011       return NULL;
1012
1013     size_t count;
1014     for (count = 0; devices[count] != NULL; count++)
1015       ;
1016
1017     size_t i = a1[0] - 'a'; /* a1[0] is always [a-z] because of regex. */
1018     if (i < count) {
1019       size_t len = strlen (devices[i]) + strlen (a1) + 16;
1020       device = safe_malloc (g, len);
1021       snprintf (device, len, "%s%s", devices[i], &a1[1]);
1022     }
1023
1024     free (a1);
1025     free_string_list (devices);
1026   }
1027   else {
1028     /* Didn't match device pattern, return original spec unchanged. */
1029     device = safe_strdup (g, spec);
1030   }
1031
1032   return device;
1033 }
1034
1035 /* XXX Handling of boot.ini in the Perl version was pretty broken.  It
1036  * essentially didn't do anything for modern Windows guests.
1037  * Therefore I've omitted all that code.
1038  */
1039 static int
1040 check_windows_root (guestfs_h *g, struct inspect_fs *fs)
1041 {
1042   fs->type = OS_TYPE_WINDOWS;
1043   fs->distro = OS_DISTRO_WINDOWS;
1044
1045   /* Try to find Windows systemroot using some common locations. */
1046   const char *systemroots[] =
1047     { "/windows", "/winnt", "/win32", "/win" };
1048   size_t i;
1049   char *systemroot = NULL;
1050   for (i = 0;
1051        systemroot == NULL && i < sizeof systemroots / sizeof systemroots[0];
1052        ++i) {
1053     systemroot = resolve_windows_path_silently (g, systemroots[i]);
1054   }
1055
1056   if (!systemroot) {
1057     error (g, _("cannot resolve Windows %%SYSTEMROOT%%"));
1058     return -1;
1059   }
1060
1061   if (g->verbose)
1062     fprintf (stderr, "windows %%SYSTEMROOT%% = %s", systemroot);
1063
1064   /* Freed by guestfs___free_inspect_info. */
1065   fs->windows_systemroot = systemroot;
1066
1067   if (check_windows_arch (g, fs) == -1)
1068     return -1;
1069
1070   if (check_windows_registry (g, fs) == -1)
1071     return -1;
1072
1073   return 0;
1074 }
1075
1076 static int
1077 check_windows_arch (guestfs_h *g, struct inspect_fs *fs)
1078 {
1079   size_t len = strlen (fs->windows_systemroot) + 32;
1080   char cmd_exe[len];
1081   snprintf (cmd_exe, len, "%s/system32/cmd.exe", fs->windows_systemroot);
1082
1083   char *cmd_exe_path = resolve_windows_path_silently (g, cmd_exe);
1084   if (!cmd_exe_path)
1085     return 0;
1086
1087   char *arch = guestfs_file_architecture (g, cmd_exe_path);
1088   free (cmd_exe_path);
1089
1090   if (arch)
1091     fs->arch = arch;        /* freed by guestfs___free_inspect_info */
1092
1093   return 0;
1094 }
1095
1096 /* At the moment, pull just the ProductName and version numbers from
1097  * the registry.  In future there is a case for making many more
1098  * registry fields available to callers.
1099  */
1100 static int
1101 check_windows_registry (guestfs_h *g, struct inspect_fs *fs)
1102 {
1103   TMP_TEMPLATE_ON_STACK (dir);
1104 #define dir_len (strlen (dir))
1105 #define software_hive_len (dir_len + 16)
1106   char software_hive[software_hive_len];
1107 #define cmd_len (dir_len + 16)
1108   char cmd[cmd_len];
1109
1110   size_t len = strlen (fs->windows_systemroot) + 64;
1111   char software[len];
1112   snprintf (software, len, "%s/system32/config/software",
1113             fs->windows_systemroot);
1114
1115   char *software_path = resolve_windows_path_silently (g, software);
1116   if (!software_path)
1117     /* If the software hive doesn't exist, just accept that we cannot
1118      * find product_name etc.
1119      */
1120     return 0;
1121
1122   int ret = -1;
1123   hive_h *h = NULL;
1124   hive_value_h *values = NULL;
1125
1126   if (mkdtemp (dir) == NULL) {
1127     perrorf (g, "mkdtemp");
1128     goto out;
1129   }
1130
1131   snprintf (software_hive, software_hive_len, "%s/software", dir);
1132
1133   if (guestfs_download (g, software_path, software_hive) == -1)
1134     goto out;
1135
1136   h = hivex_open (software_hive, g->verbose ? HIVEX_OPEN_VERBOSE : 0);
1137   if (h == NULL) {
1138     perrorf (g, "hivex_open");
1139     goto out;
1140   }
1141
1142   hive_node_h node = hivex_root (h);
1143   const char *hivepath[] =
1144     { "Microsoft", "Windows NT", "CurrentVersion" };
1145   size_t i;
1146   for (i = 0;
1147        node != 0 && i < sizeof hivepath / sizeof hivepath[0];
1148        ++i) {
1149     node = hivex_node_get_child (h, node, hivepath[i]);
1150   }
1151
1152   if (node == 0) {
1153     perrorf (g, "hivex: cannot locate HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
1154     goto out;
1155   }
1156
1157   values = hivex_node_values (h, node);
1158
1159   for (i = 0; values[i] != 0; ++i) {
1160     char *key = hivex_value_key (h, values[i]);
1161     if (key == NULL) {
1162       perrorf (g, "hivex_value_key");
1163       goto out;
1164     }
1165
1166     if (STRCASEEQ (key, "ProductName")) {
1167       fs->product_name = hivex_value_string (h, values[i]);
1168       if (!fs->product_name) {
1169         perrorf (g, "hivex_value_string");
1170         free (key);
1171         goto out;
1172       }
1173     }
1174     else if (STRCASEEQ (key, "CurrentVersion")) {
1175       char *version = hivex_value_string (h, values[i]);
1176       if (!version) {
1177         perrorf (g, "hivex_value_string");
1178         free (key);
1179         goto out;
1180       }
1181       char *major, *minor;
1182       if (match2 (g, version, re_windows_version, &major, &minor)) {
1183         fs->major_version = parse_unsigned_int (g, major);
1184         free (major);
1185         if (fs->major_version == -1) {
1186           free (minor);
1187           free (key);
1188           free (version);
1189           goto out;
1190         }
1191         fs->minor_version = parse_unsigned_int (g, minor);
1192         free (minor);
1193         if (fs->minor_version == -1) {
1194           free (key);
1195           free (version);
1196           return -1;
1197         }
1198       }
1199
1200       free (version);
1201     }
1202
1203     free (key);
1204   }
1205
1206   ret = 0;
1207
1208  out:
1209   if (h) hivex_close (h);
1210   free (values);
1211   free (software_path);
1212
1213   /* Free up the temporary directory.  Note the directory name cannot
1214    * contain shell meta-characters because of the way it was
1215    * constructed above.
1216    */
1217   snprintf (cmd, cmd_len, "rm -rf %s", dir);
1218   ignore_value (system (cmd));
1219 #undef dir_len
1220 #undef software_hive_len
1221 #undef cmd_len
1222
1223   return ret;
1224 }
1225
1226 static char *
1227 resolve_windows_path_silently (guestfs_h *g, const char *path)
1228 {
1229   guestfs_error_handler_cb old_error_cb = g->error_cb;
1230   g->error_cb = NULL;
1231   char *ret = guestfs_case_sensitive_path (g, path);
1232   g->error_cb = old_error_cb;
1233   return ret;
1234 }
1235
1236 static int
1237 extend_fses (guestfs_h *g)
1238 {
1239   size_t n = g->nr_fses + 1;
1240   struct inspect_fs *p;
1241
1242   p = realloc (g->fses, n * sizeof (struct inspect_fs));
1243   if (p == NULL) {
1244     perrorf (g, "realloc");
1245     return -1;
1246   }
1247
1248   g->fses = p;
1249   g->nr_fses = n;
1250
1251   memset (&g->fses[n-1], 0, sizeof (struct inspect_fs));
1252
1253   return 0;
1254 }
1255
1256 /* Parse small, unsigned ints, as used in version numbers. */
1257 static int
1258 parse_unsigned_int (guestfs_h *g, const char *str)
1259 {
1260   long ret;
1261   int r = xstrtol (str, NULL, 10, &ret, "");
1262   if (r != LONGINT_OK) {
1263     error (g, "could not parse integer in version number: %s", str);
1264     return -1;
1265   }
1266   return ret;
1267 }
1268
1269 static struct inspect_fs *
1270 search_for_root (guestfs_h *g, const char *root)
1271 {
1272   if (g->nr_fses == 0) {
1273     error (g, _("no inspection data: call guestfs_inspect_os first"));
1274     return NULL;
1275   }
1276
1277   size_t i;
1278   struct inspect_fs *fs;
1279   for (i = 0; i < g->nr_fses; ++i) {
1280     fs = &g->fses[i];
1281     if (fs->is_root && STREQ (root, fs->device))
1282       return fs;
1283   }
1284
1285   error (g, _("%s: root device not found: only call this function with a root device previously returned by guestfs_inspect_os"),
1286          root);
1287   return NULL;
1288 }
1289
1290 char **
1291 guestfs__inspect_get_roots (guestfs_h *g)
1292 {
1293   /* NB. Doesn't matter if g->nr_fses == 0.  We just return an empty
1294    * list in this case.
1295    */
1296
1297   size_t i;
1298   size_t count = 0;
1299   for (i = 0; i < g->nr_fses; ++i)
1300     if (g->fses[i].is_root)
1301       count++;
1302
1303   char **ret = calloc (count+1, sizeof (char *));
1304   if (ret == NULL) {
1305     perrorf (g, "calloc");
1306     return NULL;
1307   }
1308
1309   count = 0;
1310   for (i = 0; i < g->nr_fses; ++i) {
1311     if (g->fses[i].is_root) {
1312       ret[count] = safe_strdup (g, g->fses[i].device);
1313       count++;
1314     }
1315   }
1316   ret[count] = NULL;
1317
1318   return ret;
1319 }
1320
1321 char *
1322 guestfs__inspect_get_type (guestfs_h *g, const char *root)
1323 {
1324   struct inspect_fs *fs = search_for_root (g, root);
1325   if (!fs)
1326     return NULL;
1327
1328   char *ret;
1329   switch (fs->type) {
1330   case OS_TYPE_LINUX: ret = safe_strdup (g, "linux"); break;
1331   case OS_TYPE_WINDOWS: ret = safe_strdup (g, "windows"); break;
1332   case OS_TYPE_UNKNOWN: default: ret = safe_strdup (g, "unknown"); break;
1333   }
1334
1335   return ret;
1336 }
1337
1338 char *
1339 guestfs__inspect_get_arch (guestfs_h *g, const char *root)
1340 {
1341   struct inspect_fs *fs = search_for_root (g, root);
1342   if (!fs)
1343     return NULL;
1344
1345   return safe_strdup (g, fs->arch ? : "unknown");
1346 }
1347
1348 char *
1349 guestfs__inspect_get_distro (guestfs_h *g, const char *root)
1350 {
1351   struct inspect_fs *fs = search_for_root (g, root);
1352   if (!fs)
1353     return NULL;
1354
1355   char *ret;
1356   switch (fs->distro) {
1357   case OS_DISTRO_ARCHLINUX: ret = safe_strdup (g, "archlinux"); break;
1358   case OS_DISTRO_DEBIAN: ret = safe_strdup (g, "debian"); break;
1359   case OS_DISTRO_FEDORA: ret = safe_strdup (g, "fedora"); break;
1360   case OS_DISTRO_GENTOO: ret = safe_strdup (g, "gentoo"); break;
1361   case OS_DISTRO_MEEGO: ret = safe_strdup (g, "meego"); break;
1362   case OS_DISTRO_PARDUS: ret = safe_strdup (g, "pardus"); break;
1363   case OS_DISTRO_REDHAT_BASED: ret = safe_strdup (g, "redhat-based"); break;
1364   case OS_DISTRO_RHEL: ret = safe_strdup (g, "rhel"); break;
1365   case OS_DISTRO_WINDOWS: ret = safe_strdup (g, "windows"); break;
1366   case OS_DISTRO_UBUNTU: ret = safe_strdup (g, "ubuntu"); break;
1367   case OS_DISTRO_UNKNOWN: default: ret = safe_strdup (g, "unknown"); break;
1368   }
1369
1370   return ret;
1371 }
1372
1373 int
1374 guestfs__inspect_get_major_version (guestfs_h *g, const char *root)
1375 {
1376   struct inspect_fs *fs = search_for_root (g, root);
1377   if (!fs)
1378     return -1;
1379
1380   return fs->major_version;
1381 }
1382
1383 int
1384 guestfs__inspect_get_minor_version (guestfs_h *g, const char *root)
1385 {
1386   struct inspect_fs *fs = search_for_root (g, root);
1387   if (!fs)
1388     return -1;
1389
1390   return fs->minor_version;
1391 }
1392
1393 char *
1394 guestfs__inspect_get_product_name (guestfs_h *g, const char *root)
1395 {
1396   struct inspect_fs *fs = search_for_root (g, root);
1397   if (!fs)
1398     return NULL;
1399
1400   return safe_strdup (g, fs->product_name ? : "unknown");
1401 }
1402
1403 char *
1404 guestfs__inspect_get_windows_systemroot (guestfs_h *g, const char *root)
1405 {
1406   struct inspect_fs *fs = search_for_root (g, root);
1407   if (!fs)
1408     return NULL;
1409
1410   if (!fs->windows_systemroot) {
1411     error (g, _("not a Windows guest, or systemroot could not be determined"));
1412     return NULL;
1413   }
1414
1415   return safe_strdup (g, fs->windows_systemroot);
1416 }
1417
1418 char **
1419 guestfs__inspect_get_mountpoints (guestfs_h *g, const char *root)
1420 {
1421   struct inspect_fs *fs = search_for_root (g, root);
1422   if (!fs)
1423     return NULL;
1424
1425   char **ret;
1426
1427   /* If no fstab information (Windows) return just the root. */
1428   if (fs->nr_fstab == 0) {
1429     ret = calloc (3, sizeof (char *));
1430     ret[0] = safe_strdup (g, "/");
1431     ret[1] = safe_strdup (g, root);
1432     ret[2] = NULL;
1433     return ret;
1434   }
1435
1436 #define CRITERION fs->fstab[i].mountpoint[0] == '/'
1437   size_t i, count = 0;
1438   for (i = 0; i < fs->nr_fstab; ++i)
1439     if (CRITERION)
1440       count++;
1441
1442   /* Hashtables have 2N+1 entries. */
1443   ret = calloc (2*count+1, sizeof (char *));
1444   if (ret == NULL) {
1445     perrorf (g, "calloc");
1446     return NULL;
1447   }
1448
1449   count = 0;
1450   for (i = 0; i < fs->nr_fstab; ++i)
1451     if (CRITERION) {
1452       ret[2*count] = safe_strdup (g, fs->fstab[i].mountpoint);
1453       ret[2*count+1] = safe_strdup (g, fs->fstab[i].device);
1454       count++;
1455     }
1456 #undef CRITERION
1457
1458   return ret;
1459 }
1460
1461 char **
1462 guestfs__inspect_get_filesystems (guestfs_h *g, const char *root)
1463 {
1464   struct inspect_fs *fs = search_for_root (g, root);
1465   if (!fs)
1466     return NULL;
1467
1468   char **ret;
1469
1470   /* If no fstab information (Windows) return just the root. */
1471   if (fs->nr_fstab == 0) {
1472     ret = calloc (2, sizeof (char *));
1473     ret[0] = safe_strdup (g, root);
1474     ret[1] = NULL;
1475     return ret;
1476   }
1477
1478   ret = calloc (fs->nr_fstab + 1, sizeof (char *));
1479   if (ret == NULL) {
1480     perrorf (g, "calloc");
1481     return NULL;
1482   }
1483
1484   size_t i;
1485   for (i = 0; i < fs->nr_fstab; ++i)
1486     ret[i] = safe_strdup (g, fs->fstab[i].device);
1487
1488   return ret;
1489 }
1490
1491 /* List filesystems.
1492  *
1493  * The current implementation just uses guestfs_vfs_type and doesn't
1494  * try mounting anything, but we reserve the right in future to try
1495  * mounting filesystems.
1496  */
1497
1498 static void remove_from_list (char **list, const char *item);
1499 static void check_with_vfs_type (guestfs_h *g, const char *dev, char ***ret, size_t *ret_size);
1500
1501 char **
1502 guestfs__list_filesystems (guestfs_h *g)
1503 {
1504   size_t i;
1505   char **ret;
1506   size_t ret_size;
1507
1508   ret = safe_malloc (g, sizeof (char *));
1509   ret[0] = NULL;
1510   ret_size = 0;
1511
1512   /* Look to see if any devices directly contain filesystems
1513    * (RHBZ#590167).  However vfs-type will fail to tell us anything
1514    * useful about devices which just contain partitions, so we also
1515    * get the list of partitions and exclude the corresponding devices
1516    * by using part-to-dev.
1517    */
1518   char **devices;
1519   devices = guestfs_list_devices (g);
1520   if (devices == NULL) {
1521     free_string_list (ret);
1522     return NULL;
1523   }
1524   char **partitions;
1525   partitions = guestfs_list_partitions (g);
1526   if (partitions == NULL) {
1527     free_string_list (devices);
1528     free_string_list (ret);
1529     return NULL;
1530   }
1531
1532   for (i = 0; partitions[i] != NULL; ++i) {
1533     char *dev = guestfs_part_to_dev (g, partitions[i]);
1534     if (dev)
1535       remove_from_list (devices, dev);
1536     free (dev);
1537   }
1538
1539   /* Use vfs-type to check for filesystems on devices. */
1540   for (i = 0; devices[i] != NULL; ++i)
1541     check_with_vfs_type (g, devices[i], &ret, &ret_size);
1542   free_string_list (devices);
1543
1544   /* Use vfs-type to check for filesystems on partitions. */
1545   for (i = 0; partitions[i] != NULL; ++i)
1546     check_with_vfs_type (g, partitions[i], &ret, &ret_size);
1547   free_string_list (partitions);
1548
1549   if (feature_available (g, "lvm2")) {
1550     /* Use vfs-type to check for filesystems on LVs. */
1551     char **lvs;
1552     lvs = guestfs_lvs (g);
1553     if (lvs == NULL) {
1554       free_string_list (ret);
1555       return NULL;
1556     }
1557
1558     for (i = 0; lvs[i] != NULL; ++i)
1559       check_with_vfs_type (g, lvs[i], &ret, &ret_size);
1560     free_string_list (lvs);
1561   }
1562
1563   return ret;
1564 }
1565
1566 /* If 'item' occurs in 'list', remove and free it. */
1567 static void
1568 remove_from_list (char **list, const char *item)
1569 {
1570   size_t i;
1571
1572   for (i = 0; list[i] != NULL; ++i)
1573     if (STREQ (list[i], item)) {
1574       free (list[i]);
1575       for (; list[i+1] != NULL; ++i)
1576         list[i] = list[i+1];
1577       list[i] = NULL;
1578       return;
1579     }
1580 }
1581
1582 /* Use vfs-type to look for a filesystem of some sort on 'dev'.
1583  * Apart from some types which we ignore, add the result to the
1584  * 'ret' string list.
1585  */
1586 static void
1587 check_with_vfs_type (guestfs_h *g, const char *device,
1588                      char ***ret, size_t *ret_size)
1589 {
1590   char *v;
1591
1592   guestfs_error_handler_cb old_error_cb = g->error_cb;
1593   g->error_cb = NULL;
1594   char *vfs_type = guestfs_vfs_type (g, device);
1595   g->error_cb = old_error_cb;
1596
1597   if (!vfs_type)
1598     v = safe_strdup (g, "unknown");
1599   else {
1600     /* Ignore all "*_member" strings.  In libblkid these are returned
1601      * for things which are members of some RAID or LVM set, most
1602      * importantly "LVM2_member" which is a PV.
1603      */
1604     size_t n = strlen (vfs_type);
1605     if (n >= 7 && STREQ (&vfs_type[n-7], "_member")) {
1606       free (vfs_type);
1607       return;
1608     }
1609
1610     /* Ignore LUKS-encrypted partitions.  These are also containers. */
1611     if (STREQ (vfs_type, "crypto_LUKS")) {
1612       free (vfs_type);
1613       return;
1614     }
1615
1616     v = vfs_type;
1617   }
1618
1619   /* Extend the return array. */
1620   size_t i = *ret_size;
1621   *ret_size += 2;
1622   *ret = safe_realloc (g, *ret, (*ret_size + 1) * sizeof (char *));
1623   (*ret)[i] = safe_strdup (g, device);
1624   (*ret)[i+1] = v;
1625   (*ret)[i+2] = NULL;
1626 }