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