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