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    */
426   size_t count = 0;
427   for (i = 0; i < g->nr_fses; ++i)
428     if (g->fses[i].is_root)
429       count++;
430
431   char **ret = calloc (count+1, sizeof (char *));
432   if (ret == NULL) {
433     perrorf (g, "calloc");
434     guestfs___free_inspect_info (g);
435     return NULL;
436   }
437
438   count = 0;
439   for (i = 0; i < g->nr_fses; ++i) {
440     if (g->fses[i].is_root) {
441       ret[count] = safe_strdup (g, g->fses[i].device);
442       count++;
443     }
444   }
445   ret[count] = NULL;
446
447   return ret;
448 }
449
450 void
451 guestfs___free_inspect_info (guestfs_h *g)
452 {
453   size_t i;
454   for (i = 0; i < g->nr_fses; ++i) {
455     free (g->fses[i].device);
456     free (g->fses[i].product_name);
457     free (g->fses[i].arch);
458     free (g->fses[i].windows_systemroot);
459     size_t j;
460     for (j = 0; j < g->fses[i].nr_fstab; ++j) {
461       free (g->fses[i].fstab[j].device);
462       free (g->fses[i].fstab[j].mountpoint);
463     }
464     free (g->fses[i].fstab);
465   }
466   free (g->fses);
467   g->nr_fses = 0;
468   g->fses = NULL;
469 }
470
471 static void
472 free_string_list (char **argv)
473 {
474   size_t i;
475   for (i = 0; argv[i] != NULL; ++i)
476     free (argv[i]);
477   free (argv);
478 }
479
480 /* In the Perl code this is a public function. */
481 static int
482 feature_available (guestfs_h *g, const char *feature)
483 {
484   /* If there's an error we should ignore it, so to do that we have to
485    * temporarily replace the error handler with a null one.
486    */
487   guestfs_error_handler_cb old_error_cb = g->error_cb;
488   g->error_cb = NULL;
489
490   const char *groups[] = { feature, NULL };
491   int r = guestfs_available (g, (char * const *) groups);
492
493   g->error_cb = old_error_cb;
494
495   return r == 0 ? 1 : 0;
496 }
497
498 /* Find out if 'device' contains a filesystem.  If it does, add
499  * another entry in g->fses.
500  */
501 static int check_filesystem (guestfs_h *g, const char *device);
502 static int check_linux_root (guestfs_h *g, struct inspect_fs *fs);
503 static int check_fstab (guestfs_h *g, struct inspect_fs *fs);
504 static int check_windows_root (guestfs_h *g, struct inspect_fs *fs);
505 static int check_windows_arch (guestfs_h *g, struct inspect_fs *fs);
506 static int check_windows_registry (guestfs_h *g, struct inspect_fs *fs);
507 static char *resolve_windows_path_silently (guestfs_h *g, const char *);
508 static int extend_fses (guestfs_h *g);
509 static int parse_unsigned_int (guestfs_h *g, const char *str);
510 static int add_fstab_entry (guestfs_h *g, struct inspect_fs *fs,
511                             const char *spec, const char *mp);
512 static char *resolve_fstab_device (guestfs_h *g, const char *spec);
513
514 static int
515 check_for_filesystem_on (guestfs_h *g, const char *device)
516 {
517   /* Get vfs-type in order to check if it's a Linux(?) swap device.
518    * If there's an error we should ignore it, so to do that we have to
519    * temporarily replace the error handler with a null one.
520    */
521   guestfs_error_handler_cb old_error_cb = g->error_cb;
522   g->error_cb = NULL;
523   char *vfs_type = guestfs_vfs_type (g, device);
524   g->error_cb = old_error_cb;
525
526   int is_swap = vfs_type && STREQ (vfs_type, "swap");
527
528   if (g->verbose)
529     fprintf (stderr, "check_for_filesystem_on: %s (%s)\n",
530              device, vfs_type ? vfs_type : "failed to get vfs type");
531
532   if (is_swap) {
533     free (vfs_type);
534     if (extend_fses (g) == -1)
535       return -1;
536     g->fses[g->nr_fses-1].is_swap = 1;
537     return 0;
538   }
539
540   /* Try mounting the device.  As above, ignore errors. */
541   g->error_cb = NULL;
542   int r = guestfs_mount_ro (g, device, "/");
543   if (r == -1 && vfs_type && STREQ (vfs_type, "ufs")) /* Hack for the *BSDs. */
544     r = guestfs_mount_vfs (g, "ro,ufstype=ufs2", "ufs", device, "/");
545   free (vfs_type);
546   g->error_cb = old_error_cb;
547   if (r == -1)
548     return 0;
549
550   /* Do the rest of the checks. */
551   r = check_filesystem (g, device);
552
553   /* Unmount the filesystem. */
554   if (guestfs_umount_all (g) == -1)
555     return -1;
556
557   return r;
558 }
559
560 static int
561 check_filesystem (guestfs_h *g, const char *device)
562 {
563   if (extend_fses (g) == -1)
564     return -1;
565
566   struct inspect_fs *fs = &g->fses[g->nr_fses-1];
567
568   fs->device = safe_strdup (g, device);
569   fs->is_mountable = 1;
570
571   /* Grub /boot? */
572   if (guestfs_is_file (g, "/grub/menu.lst") > 0 ||
573       guestfs_is_file (g, "/grub/grub.conf") > 0)
574     fs->content = FS_CONTENT_LINUX_BOOT;
575   /* Linux root? */
576   else if (guestfs_is_dir (g, "/etc") > 0 &&
577            guestfs_is_dir (g, "/bin") > 0 &&
578            guestfs_is_file (g, "/etc/fstab") > 0) {
579     fs->is_root = 1;
580     fs->content = FS_CONTENT_LINUX_ROOT;
581     if (check_linux_root (g, fs) == -1)
582       return -1;
583   }
584   /* Linux /usr/local? */
585   else if (guestfs_is_dir (g, "/etc") > 0 &&
586            guestfs_is_dir (g, "/bin") > 0 &&
587            guestfs_is_dir (g, "/share") > 0 &&
588            guestfs_exists (g, "/local") == 0 &&
589            guestfs_is_file (g, "/etc/fstab") == 0)
590     fs->content = FS_CONTENT_LINUX_USR_LOCAL;
591   /* Linux /usr? */
592   else if (guestfs_is_dir (g, "/etc") > 0 &&
593            guestfs_is_dir (g, "/bin") > 0 &&
594            guestfs_is_dir (g, "/share") > 0 &&
595            guestfs_exists (g, "/local") > 0 &&
596            guestfs_is_file (g, "/etc/fstab") == 0)
597     fs->content = FS_CONTENT_LINUX_USR;
598   /* Linux /var? */
599   else if (guestfs_is_dir (g, "/log") > 0 &&
600            guestfs_is_dir (g, "/run") > 0 &&
601            guestfs_is_dir (g, "/spool") > 0)
602     fs->content = FS_CONTENT_LINUX_VAR;
603   /* Windows root? */
604   else if (guestfs_is_file (g, "/AUTOEXEC.BAT") > 0 ||
605            guestfs_is_file (g, "/autoexec.bat") > 0 ||
606            guestfs_is_dir (g, "/Program Files") > 0 ||
607            guestfs_is_dir (g, "/WINDOWS") > 0 ||
608            guestfs_is_dir (g, "/Windows") > 0 ||
609            guestfs_is_dir (g, "/windows") > 0 ||
610            guestfs_is_dir (g, "/WIN32") > 0 ||
611            guestfs_is_dir (g, "/Win32") > 0 ||
612            guestfs_is_dir (g, "/WINNT") > 0 ||
613            guestfs_is_file (g, "/boot.ini") > 0 ||
614            guestfs_is_file (g, "/ntldr") > 0) {
615     fs->is_root = 1;
616     fs->content = FS_CONTENT_WINDOWS_ROOT;
617     if (check_windows_root (g, fs) == -1)
618       return -1;
619   }
620
621   return 0;
622 }
623
624 /* Set fs->product_name to the first line of the release file. */
625 static int
626 parse_release_file (guestfs_h *g, struct inspect_fs *fs,
627                     const char *release_filename)
628 {
629   char **product_name = guestfs_head_n (g, 1, release_filename);
630   if (product_name == NULL)
631     return -1;
632   if (product_name[0] == NULL) {
633     error (g, "%s: file is empty", release_filename);
634     free_string_list (product_name);
635     return -1;
636   }
637
638   /* Note that this string becomes owned by the handle and will
639    * be freed by guestfs___free_inspect_info.
640    */
641   fs->product_name = product_name[0];
642   free (product_name);
643
644   return 0;
645 }
646
647 /* Parse generic MAJOR.MINOR from the fs->product_name string. */
648 static int
649 parse_major_minor (guestfs_h *g, struct inspect_fs *fs)
650 {
651   char *major, *minor;
652
653   if (match2 (g, fs->product_name, re_major_minor, &major, &minor)) {
654     fs->major_version = parse_unsigned_int (g, major);
655     free (major);
656     if (fs->major_version == -1) {
657       free (minor);
658       return -1;
659     }
660     fs->minor_version = parse_unsigned_int (g, minor);
661     free (minor);
662     if (fs->minor_version == -1)
663       return -1;
664   }
665   return 0;
666 }
667
668 /* Ubuntu has /etc/lsb-release containing:
669  *   DISTRIB_ID=Ubuntu                                # Distro
670  *   DISTRIB_RELEASE=10.04                            # Version
671  *   DISTRIB_CODENAME=lucid
672  *   DISTRIB_DESCRIPTION="Ubuntu 10.04.1 LTS"         # Product name
673  * In theory other distros could have this LSB file, but none do.
674  */
675 static int
676 parse_lsb_release (guestfs_h *g, struct inspect_fs *fs)
677 {
678   char **lines;
679   size_t i;
680   int r = 0;
681
682   lines = guestfs_head_n (g, 10, "/etc/lsb-release");
683   if (lines == NULL)
684     return -1;
685
686   for (i = 0; lines[i] != NULL; ++i) {
687     if (fs->distro == 0 &&
688         STREQ (lines[i], "DISTRIB_ID=Ubuntu")) {
689       fs->distro = OS_DISTRO_UBUNTU;
690       r = 1;
691     }
692     else if (STRPREFIX (lines[i], "DISTRIB_RELEASE=")) {
693       char *major, *minor;
694       if (match2 (g, &lines[i][16], re_major_minor, &major, &minor)) {
695         fs->major_version = parse_unsigned_int (g, major);
696         free (major);
697         if (fs->major_version == -1) {
698           free (minor);
699           free_string_list (lines);
700           return -1;
701         }
702         fs->minor_version = parse_unsigned_int (g, minor);
703         free (minor);
704         if (fs->minor_version == -1) {
705           free_string_list (lines);
706           return -1;
707         }
708       }
709     }
710     else if (fs->product_name == NULL &&
711              (STRPREFIX (lines[i], "DISTRIB_DESCRIPTION=\"") ||
712               STRPREFIX (lines[i], "DISTRIB_DESCRIPTION='"))) {
713       size_t len = strlen (lines[i]) - 21 - 1;
714       fs->product_name = safe_strndup (g, &lines[i][21], len);
715       r = 1;
716     }
717     else if (fs->product_name == NULL &&
718              STRPREFIX (lines[i], "DISTRIB_DESCRIPTION=")) {
719       size_t len = strlen (lines[i]) - 20;
720       fs->product_name = safe_strndup (g, &lines[i][20], len);
721       r = 1;
722     }
723   }
724
725   free_string_list (lines);
726   return r;
727 }
728
729 /* The currently mounted device is known to be a Linux root.  Try to
730  * determine from this the distro, version, etc.  Also parse
731  * /etc/fstab to determine the arrangement of mountpoints and
732  * associated devices.
733  */
734 static int
735 check_linux_root (guestfs_h *g, struct inspect_fs *fs)
736 {
737   int r;
738
739   fs->type = OS_TYPE_LINUX;
740
741   if (guestfs_exists (g, "/etc/lsb-release") > 0) {
742     r = parse_lsb_release (g, fs);
743     if (r == -1)        /* error */
744       return -1;
745     if (r == 1)         /* ok - detected the release from this file */
746       goto skip_release_checks;
747   }
748
749   if (guestfs_exists (g, "/etc/redhat-release") > 0) {
750     fs->distro = OS_DISTRO_REDHAT_BASED; /* Something generic Red Hat-like. */
751
752     if (parse_release_file (g, fs, "/etc/redhat-release") == -1)
753       return -1;
754
755     char *major, *minor;
756     if ((major = match1 (g, fs->product_name, re_fedora)) != NULL) {
757       fs->distro = OS_DISTRO_FEDORA;
758       fs->major_version = parse_unsigned_int (g, major);
759       free (major);
760       if (fs->major_version == -1)
761         return -1;
762     }
763     else if (match2 (g, fs->product_name, re_rhel_old, &major, &minor) ||
764              match2 (g, fs->product_name, re_rhel, &major, &minor)) {
765       fs->distro = OS_DISTRO_RHEL;
766       fs->major_version = parse_unsigned_int (g, major);
767       free (major);
768       if (fs->major_version == -1) {
769         free (minor);
770         return -1;
771       }
772       fs->minor_version = parse_unsigned_int (g, minor);
773       free (minor);
774       if (fs->minor_version == -1)
775         return -1;
776     }
777     else if ((major = match1 (g, fs->product_name, re_rhel_no_minor)) != NULL) {
778       fs->distro = OS_DISTRO_RHEL;
779       fs->major_version = parse_unsigned_int (g, major);
780       free (major);
781       if (fs->major_version == -1)
782         return -1;
783       fs->minor_version = 0;
784     }
785   }
786   else if (guestfs_exists (g, "/etc/debian_version") > 0) {
787     fs->distro = OS_DISTRO_DEBIAN;
788
789     if (parse_release_file (g, fs, "/etc/debian_version") == -1)
790       return -1;
791
792     if (parse_major_minor (g, fs) == -1)
793       return -1;
794   }
795   else if (guestfs_exists (g, "/etc/pardus-release") > 0) {
796     fs->distro = OS_DISTRO_PARDUS;
797
798     if (parse_release_file (g, fs, "/etc/pardus-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/arch-release") > 0) {
805     fs->distro = OS_DISTRO_ARCHLINUX;
806
807     /* /etc/arch-release file is empty and I can't see a way to
808      * determine the actual release or product string.
809      */
810   }
811   else if (guestfs_exists (g, "/etc/gentoo-release") > 0) {
812     fs->distro = OS_DISTRO_GENTOO;
813
814     if (parse_release_file (g, fs, "/etc/gentoo-release") == -1)
815       return -1;
816
817     if (parse_major_minor (g, fs) == -1)
818       return -1;
819   }
820   else if (guestfs_exists (g, "/etc/meego-release") > 0) {
821     fs->distro = OS_DISTRO_MEEGO;
822
823     if (parse_release_file (g, fs, "/etc/meego-release") == -1)
824       return -1;
825
826     if (parse_major_minor (g, fs) == -1)
827       return -1;
828   }
829
830  skip_release_checks:;
831
832   /* Determine the architecture. */
833   const char *binaries[] =
834     { "/bin/bash", "/bin/ls", "/bin/echo", "/bin/rm", "/bin/sh" };
835   size_t i;
836   for (i = 0; i < sizeof binaries / sizeof binaries[0]; ++i) {
837     if (guestfs_is_file (g, binaries[i]) > 0) {
838       /* Ignore errors from file_architecture call. */
839       guestfs_error_handler_cb old_error_cb = g->error_cb;
840       g->error_cb = NULL;
841       char *arch = guestfs_file_architecture (g, binaries[i]);
842       g->error_cb = old_error_cb;
843
844       if (arch) {
845         /* String will be owned by handle, freed by
846          * guestfs___free_inspect_info.
847          */
848         fs->arch = arch;
849         break;
850       }
851     }
852   }
853
854   /* We already know /etc/fstab exists because it's part of the test
855    * for Linux root above.  We must now parse this file to determine
856    * which filesystems are used by the operating system and how they
857    * are mounted.
858    * XXX What if !feature_available (g, "augeas")?
859    */
860   if (guestfs_aug_init (g, "/", 16|32) == -1)
861     return -1;
862
863   /* Tell Augeas to only load /etc/fstab (thanks Raphaël Pinson). */
864   guestfs_aug_rm (g, "/augeas/load//incl[. != \"/etc/fstab\"]");
865   guestfs_aug_load (g);
866
867   r = check_fstab (g, fs);
868   guestfs_aug_close (g);
869   if (r == -1)
870     return -1;
871
872   return 0;
873 }
874
875 static int
876 check_fstab (guestfs_h *g, struct inspect_fs *fs)
877 {
878   char **lines = guestfs_aug_ls (g, "/files/etc/fstab");
879   if (lines == NULL)
880     return -1;
881
882   if (lines[0] == NULL) {
883     error (g, "could not parse /etc/fstab or empty file");
884     free_string_list (lines);
885     return -1;
886   }
887
888   size_t i;
889   char augpath[256];
890   for (i = 0; lines[i] != NULL; ++i) {
891     /* Ignore comments.  Only care about sequence lines which
892      * match m{/\d+$}.
893      */
894     if (match (g, lines[i], re_aug_seq)) {
895       snprintf (augpath, sizeof augpath, "%s/spec", lines[i]);
896       char *spec = guestfs_aug_get (g, augpath);
897       if (spec == NULL) {
898         free_string_list (lines);
899         return -1;
900       }
901
902       snprintf (augpath, sizeof augpath, "%s/file", lines[i]);
903       char *mp = guestfs_aug_get (g, augpath);
904       if (mp == NULL) {
905         free_string_list (lines);
906         free (spec);
907         return -1;
908       }
909
910       int r = add_fstab_entry (g, fs, spec, mp);
911       free (spec);
912       free (mp);
913
914       if (r == -1) {
915         free_string_list (lines);
916         return -1;
917       }
918     }
919   }
920
921   free_string_list (lines);
922   return 0;
923 }
924
925 /* Add a filesystem and possibly a mountpoint entry for
926  * the root filesystem 'fs'.
927  *
928  * 'spec' is the fstab spec field, which might be a device name or a
929  * pseudodevice or 'UUID=...' or 'LABEL=...'.
930  *
931  * 'mp' is the mount point, which could also be 'swap' or 'none'.
932  */
933 static int
934 add_fstab_entry (guestfs_h *g, struct inspect_fs *fs,
935                  const char *spec, const char *mp)
936 {
937   /* Ignore certain mountpoints. */
938   if (STRPREFIX (mp, "/dev/") ||
939       STREQ (mp, "/dev") ||
940       STRPREFIX (mp, "/media/") ||
941       STRPREFIX (mp, "/proc/") ||
942       STREQ (mp, "/proc") ||
943       STRPREFIX (mp, "/selinux/") ||
944       STREQ (mp, "/selinux") ||
945       STRPREFIX (mp, "/sys/") ||
946       STREQ (mp, "/sys"))
947     return 0;
948
949   /* Ignore /dev/fd (floppy disks) (RHBZ#642929) and CD-ROM drives. */
950   if ((STRPREFIX (spec, "/dev/fd") && c_isdigit (spec[7])) ||
951       STREQ (spec, "/dev/floppy") ||
952       STREQ (spec, "/dev/cdrom"))
953     return 0;
954
955   /* Resolve UUID= and LABEL= to the actual device. */
956   char *device = NULL;
957   if (STRPREFIX (spec, "UUID="))
958     device = guestfs_findfs_uuid (g, &spec[5]);
959   else if (STRPREFIX (spec, "LABEL="))
960     device = guestfs_findfs_label (g, &spec[6]);
961   /* Ignore "/.swap" (Pardus) and pseudo-devices like "tmpfs". */
962   else if (STRPREFIX (spec, "/dev/"))
963     /* Resolve guest block device names. */
964     device = resolve_fstab_device (g, spec);
965
966   /* If we haven't resolved the device successfully by this point,
967    * we don't care, just ignore it.
968    */
969   if (device == NULL)
970     return 0;
971
972   char *mountpoint = safe_strdup (g, mp);
973
974   /* Add this to the fstab entry in 'fs'.
975    * Note these are further filtered by guestfs_inspect_get_mountpoints
976    * and guestfs_inspect_get_filesystems.
977    */
978   size_t n = fs->nr_fstab + 1;
979   struct inspect_fstab_entry *p;
980
981   p = realloc (fs->fstab, n * sizeof (struct inspect_fstab_entry));
982   if (p == NULL) {
983     perrorf (g, "realloc");
984     free (device);
985     free (mountpoint);
986     return -1;
987   }
988
989   fs->fstab = p;
990   fs->nr_fstab = n;
991
992   /* These are owned by the handle and freed by guestfs___free_inspect_info. */
993   fs->fstab[n-1].device = device;
994   fs->fstab[n-1].mountpoint = mountpoint;
995
996   if (g->verbose)
997     fprintf (stderr, "fstab: device=%s mountpoint=%s\n", device, mountpoint);
998
999   return 0;
1000 }
1001
1002 /* Resolve block device name to the libguestfs device name, eg.
1003  * /dev/xvdb1 => /dev/vdb1; and /dev/mapper/VG-LV => /dev/VG/LV.  This
1004  * assumes that disks were added in the same order as they appear to
1005  * the real VM, which is a reasonable assumption to make.  Return
1006  * anything we don't recognize unchanged.
1007  */
1008 static char *
1009 resolve_fstab_device (guestfs_h *g, const char *spec)
1010 {
1011   char *a1;
1012   char *device = NULL;
1013
1014   if (STRPREFIX (spec, "/dev/mapper/")) {
1015     /* LVM2 does some strange munging on /dev/mapper paths for VGs and
1016      * LVs which contain '-' character:
1017      *
1018      * ><fs> lvcreate LV--test VG--test 32
1019      * ><fs> debug ls /dev/mapper
1020      * VG----test-LV----test
1021      *
1022      * This makes it impossible to reverse those paths directly, so
1023      * we have implemented lvm_canonical_lv_name in the daemon.
1024      */
1025     device = guestfs_lvm_canonical_lv_name (g, spec);
1026   }
1027   else if ((a1 = match1 (g, spec, re_xdev)) != NULL) {
1028     char **devices = guestfs_list_devices (g);
1029     if (devices == NULL)
1030       return NULL;
1031
1032     size_t count;
1033     for (count = 0; devices[count] != NULL; count++)
1034       ;
1035
1036     size_t i = a1[0] - 'a'; /* a1[0] is always [a-z] because of regex. */
1037     if (i < count) {
1038       size_t len = strlen (devices[i]) + strlen (a1) + 16;
1039       device = safe_malloc (g, len);
1040       snprintf (device, len, "%s%s", devices[i], &a1[1]);
1041     }
1042
1043     free (a1);
1044     free_string_list (devices);
1045   }
1046   else {
1047     /* Didn't match device pattern, return original spec unchanged. */
1048     device = safe_strdup (g, spec);
1049   }
1050
1051   return device;
1052 }
1053
1054 /* XXX Handling of boot.ini in the Perl version was pretty broken.  It
1055  * essentially didn't do anything for modern Windows guests.
1056  * Therefore I've omitted all that code.
1057  */
1058 static int
1059 check_windows_root (guestfs_h *g, struct inspect_fs *fs)
1060 {
1061   fs->type = OS_TYPE_WINDOWS;
1062   fs->distro = OS_DISTRO_WINDOWS;
1063
1064   /* Try to find Windows systemroot using some common locations. */
1065   const char *systemroots[] =
1066     { "/windows", "/winnt", "/win32", "/win" };
1067   size_t i;
1068   char *systemroot = NULL;
1069   for (i = 0;
1070        systemroot == NULL && i < sizeof systemroots / sizeof systemroots[0];
1071        ++i) {
1072     systemroot = resolve_windows_path_silently (g, systemroots[i]);
1073   }
1074
1075   if (!systemroot) {
1076     error (g, _("cannot resolve Windows %%SYSTEMROOT%%"));
1077     return -1;
1078   }
1079
1080   if (g->verbose)
1081     fprintf (stderr, "windows %%SYSTEMROOT%% = %s", systemroot);
1082
1083   /* Freed by guestfs___free_inspect_info. */
1084   fs->windows_systemroot = systemroot;
1085
1086   if (check_windows_arch (g, fs) == -1)
1087     return -1;
1088
1089   if (check_windows_registry (g, fs) == -1)
1090     return -1;
1091
1092   return 0;
1093 }
1094
1095 static int
1096 check_windows_arch (guestfs_h *g, struct inspect_fs *fs)
1097 {
1098   size_t len = strlen (fs->windows_systemroot) + 32;
1099   char cmd_exe[len];
1100   snprintf (cmd_exe, len, "%s/system32/cmd.exe", fs->windows_systemroot);
1101
1102   char *cmd_exe_path = resolve_windows_path_silently (g, cmd_exe);
1103   if (!cmd_exe_path)
1104     return 0;
1105
1106   char *arch = guestfs_file_architecture (g, cmd_exe_path);
1107   free (cmd_exe_path);
1108
1109   if (arch)
1110     fs->arch = arch;        /* freed by guestfs___free_inspect_info */
1111
1112   return 0;
1113 }
1114
1115 /* At the moment, pull just the ProductName and version numbers from
1116  * the registry.  In future there is a case for making many more
1117  * registry fields available to callers.
1118  */
1119 static int
1120 check_windows_registry (guestfs_h *g, struct inspect_fs *fs)
1121 {
1122   TMP_TEMPLATE_ON_STACK (dir);
1123 #define dir_len (strlen (dir))
1124 #define software_hive_len (dir_len + 16)
1125   char software_hive[software_hive_len];
1126 #define cmd_len (dir_len + 16)
1127   char cmd[cmd_len];
1128
1129   size_t len = strlen (fs->windows_systemroot) + 64;
1130   char software[len];
1131   snprintf (software, len, "%s/system32/config/software",
1132             fs->windows_systemroot);
1133
1134   char *software_path = resolve_windows_path_silently (g, software);
1135   if (!software_path)
1136     /* If the software hive doesn't exist, just accept that we cannot
1137      * find product_name etc.
1138      */
1139     return 0;
1140
1141   int ret = -1;
1142   hive_h *h = NULL;
1143   hive_value_h *values = NULL;
1144
1145   if (mkdtemp (dir) == NULL) {
1146     perrorf (g, "mkdtemp");
1147     goto out;
1148   }
1149
1150   snprintf (software_hive, software_hive_len, "%s/software", dir);
1151
1152   if (guestfs_download (g, software_path, software_hive) == -1)
1153     goto out;
1154
1155   h = hivex_open (software_hive, g->verbose ? HIVEX_OPEN_VERBOSE : 0);
1156   if (h == NULL) {
1157     perrorf (g, "hivex_open");
1158     goto out;
1159   }
1160
1161   hive_node_h node = hivex_root (h);
1162   const char *hivepath[] =
1163     { "Microsoft", "Windows NT", "CurrentVersion" };
1164   size_t i;
1165   for (i = 0;
1166        node != 0 && i < sizeof hivepath / sizeof hivepath[0];
1167        ++i) {
1168     node = hivex_node_get_child (h, node, hivepath[i]);
1169   }
1170
1171   if (node == 0) {
1172     perrorf (g, "hivex: cannot locate HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
1173     goto out;
1174   }
1175
1176   values = hivex_node_values (h, node);
1177
1178   for (i = 0; values[i] != 0; ++i) {
1179     char *key = hivex_value_key (h, values[i]);
1180     if (key == NULL) {
1181       perrorf (g, "hivex_value_key");
1182       goto out;
1183     }
1184
1185     if (STRCASEEQ (key, "ProductName")) {
1186       fs->product_name = hivex_value_string (h, values[i]);
1187       if (!fs->product_name) {
1188         perrorf (g, "hivex_value_string");
1189         free (key);
1190         goto out;
1191       }
1192     }
1193     else if (STRCASEEQ (key, "CurrentVersion")) {
1194       char *version = hivex_value_string (h, values[i]);
1195       if (!version) {
1196         perrorf (g, "hivex_value_string");
1197         free (key);
1198         goto out;
1199       }
1200       char *major, *minor;
1201       if (match2 (g, version, re_windows_version, &major, &minor)) {
1202         fs->major_version = parse_unsigned_int (g, major);
1203         free (major);
1204         if (fs->major_version == -1) {
1205           free (minor);
1206           free (key);
1207           free (version);
1208           goto out;
1209         }
1210         fs->minor_version = parse_unsigned_int (g, minor);
1211         free (minor);
1212         if (fs->minor_version == -1) {
1213           free (key);
1214           free (version);
1215           return -1;
1216         }
1217       }
1218
1219       free (version);
1220     }
1221
1222     free (key);
1223   }
1224
1225   ret = 0;
1226
1227  out:
1228   if (h) hivex_close (h);
1229   free (values);
1230   free (software_path);
1231
1232   /* Free up the temporary directory.  Note the directory name cannot
1233    * contain shell meta-characters because of the way it was
1234    * constructed above.
1235    */
1236   snprintf (cmd, cmd_len, "rm -rf %s", dir);
1237   ignore_value (system (cmd));
1238 #undef dir_len
1239 #undef software_hive_len
1240 #undef cmd_len
1241
1242   return ret;
1243 }
1244
1245 static char *
1246 resolve_windows_path_silently (guestfs_h *g, const char *path)
1247 {
1248   guestfs_error_handler_cb old_error_cb = g->error_cb;
1249   g->error_cb = NULL;
1250   char *ret = guestfs_case_sensitive_path (g, path);
1251   g->error_cb = old_error_cb;
1252   return ret;
1253 }
1254
1255 static int
1256 extend_fses (guestfs_h *g)
1257 {
1258   size_t n = g->nr_fses + 1;
1259   struct inspect_fs *p;
1260
1261   p = realloc (g->fses, n * sizeof (struct inspect_fs));
1262   if (p == NULL) {
1263     perrorf (g, "realloc");
1264     return -1;
1265   }
1266
1267   g->fses = p;
1268   g->nr_fses = n;
1269
1270   memset (&g->fses[n-1], 0, sizeof (struct inspect_fs));
1271
1272   return 0;
1273 }
1274
1275 /* Parse small, unsigned ints, as used in version numbers. */
1276 static int
1277 parse_unsigned_int (guestfs_h *g, const char *str)
1278 {
1279   long ret;
1280   int r = xstrtol (str, NULL, 10, &ret, "");
1281   if (r != LONGINT_OK) {
1282     error (g, "could not parse integer in version number: %s", str);
1283     return -1;
1284   }
1285   return ret;
1286 }
1287
1288 static struct inspect_fs *
1289 search_for_root (guestfs_h *g, const char *root)
1290 {
1291   if (g->nr_fses == 0) {
1292     error (g, _("no inspection data: call guestfs_inspect_os first"));
1293     return NULL;
1294   }
1295
1296   size_t i;
1297   struct inspect_fs *fs;
1298   for (i = 0; i < g->nr_fses; ++i) {
1299     fs = &g->fses[i];
1300     if (fs->is_root && STREQ (root, fs->device))
1301       return fs;
1302   }
1303
1304   error (g, _("%s: root device not found: only call this function with a root device previously returned by guestfs_inspect_os"),
1305          root);
1306   return NULL;
1307 }
1308
1309 char *
1310 guestfs__inspect_get_type (guestfs_h *g, const char *root)
1311 {
1312   struct inspect_fs *fs = search_for_root (g, root);
1313   if (!fs)
1314     return NULL;
1315
1316   char *ret;
1317   switch (fs->type) {
1318   case OS_TYPE_LINUX: ret = safe_strdup (g, "linux"); break;
1319   case OS_TYPE_WINDOWS: ret = safe_strdup (g, "windows"); break;
1320   case OS_TYPE_UNKNOWN: default: ret = safe_strdup (g, "unknown"); break;
1321   }
1322
1323   return ret;
1324 }
1325
1326 char *
1327 guestfs__inspect_get_arch (guestfs_h *g, const char *root)
1328 {
1329   struct inspect_fs *fs = search_for_root (g, root);
1330   if (!fs)
1331     return NULL;
1332
1333   return safe_strdup (g, fs->arch ? : "unknown");
1334 }
1335
1336 char *
1337 guestfs__inspect_get_distro (guestfs_h *g, const char *root)
1338 {
1339   struct inspect_fs *fs = search_for_root (g, root);
1340   if (!fs)
1341     return NULL;
1342
1343   char *ret;
1344   switch (fs->distro) {
1345   case OS_DISTRO_ARCHLINUX: ret = safe_strdup (g, "archlinux"); break;
1346   case OS_DISTRO_DEBIAN: ret = safe_strdup (g, "debian"); break;
1347   case OS_DISTRO_FEDORA: ret = safe_strdup (g, "fedora"); break;
1348   case OS_DISTRO_GENTOO: ret = safe_strdup (g, "gentoo"); break;
1349   case OS_DISTRO_MEEGO: ret = safe_strdup (g, "meego"); break;
1350   case OS_DISTRO_PARDUS: ret = safe_strdup (g, "pardus"); break;
1351   case OS_DISTRO_REDHAT_BASED: ret = safe_strdup (g, "redhat-based"); break;
1352   case OS_DISTRO_RHEL: ret = safe_strdup (g, "rhel"); break;
1353   case OS_DISTRO_WINDOWS: ret = safe_strdup (g, "windows"); break;
1354   case OS_DISTRO_UBUNTU: ret = safe_strdup (g, "ubuntu"); break;
1355   case OS_DISTRO_UNKNOWN: default: ret = safe_strdup (g, "unknown"); break;
1356   }
1357
1358   return ret;
1359 }
1360
1361 int
1362 guestfs__inspect_get_major_version (guestfs_h *g, const char *root)
1363 {
1364   struct inspect_fs *fs = search_for_root (g, root);
1365   if (!fs)
1366     return -1;
1367
1368   return fs->major_version;
1369 }
1370
1371 int
1372 guestfs__inspect_get_minor_version (guestfs_h *g, const char *root)
1373 {
1374   struct inspect_fs *fs = search_for_root (g, root);
1375   if (!fs)
1376     return -1;
1377
1378   return fs->minor_version;
1379 }
1380
1381 char *
1382 guestfs__inspect_get_product_name (guestfs_h *g, const char *root)
1383 {
1384   struct inspect_fs *fs = search_for_root (g, root);
1385   if (!fs)
1386     return NULL;
1387
1388   return safe_strdup (g, fs->product_name ? : "unknown");
1389 }
1390
1391 char *
1392 guestfs__inspect_get_windows_systemroot (guestfs_h *g, const char *root)
1393 {
1394   struct inspect_fs *fs = search_for_root (g, root);
1395   if (!fs)
1396     return NULL;
1397
1398   if (!fs->windows_systemroot) {
1399     error (g, _("not a Windows guest, or systemroot could not be determined"));
1400     return NULL;
1401   }
1402
1403   return safe_strdup (g, fs->windows_systemroot);
1404 }
1405
1406 char **
1407 guestfs__inspect_get_mountpoints (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   char **ret;
1414
1415   /* If no fstab information (Windows) return just the root. */
1416   if (fs->nr_fstab == 0) {
1417     ret = calloc (3, sizeof (char *));
1418     ret[0] = safe_strdup (g, "/");
1419     ret[1] = safe_strdup (g, root);
1420     ret[2] = NULL;
1421     return ret;
1422   }
1423
1424 #define CRITERION fs->fstab[i].mountpoint[0] == '/'
1425   size_t i, count = 0;
1426   for (i = 0; i < fs->nr_fstab; ++i)
1427     if (CRITERION)
1428       count++;
1429
1430   /* Hashtables have 2N+1 entries. */
1431   ret = calloc (2*count+1, sizeof (char *));
1432   if (ret == NULL) {
1433     perrorf (g, "calloc");
1434     return NULL;
1435   }
1436
1437   count = 0;
1438   for (i = 0; i < fs->nr_fstab; ++i)
1439     if (CRITERION) {
1440       ret[2*count] = safe_strdup (g, fs->fstab[i].mountpoint);
1441       ret[2*count+1] = safe_strdup (g, fs->fstab[i].device);
1442       count++;
1443     }
1444 #undef CRITERION
1445
1446   return ret;
1447 }
1448
1449 char **
1450 guestfs__inspect_get_filesystems (guestfs_h *g, const char *root)
1451 {
1452   struct inspect_fs *fs = search_for_root (g, root);
1453   if (!fs)
1454     return NULL;
1455
1456   char **ret;
1457
1458   /* If no fstab information (Windows) return just the root. */
1459   if (fs->nr_fstab == 0) {
1460     ret = calloc (2, sizeof (char *));
1461     ret[0] = safe_strdup (g, root);
1462     ret[1] = NULL;
1463     return ret;
1464   }
1465
1466   ret = calloc (fs->nr_fstab + 1, sizeof (char *));
1467   if (ret == NULL) {
1468     perrorf (g, "calloc");
1469     return NULL;
1470   }
1471
1472   size_t i;
1473   for (i = 0; i < fs->nr_fstab; ++i)
1474     ret[i] = safe_strdup (g, fs->fstab[i].device);
1475
1476   return ret;
1477 }
1478
1479 /* List filesystems.
1480  *
1481  * The current implementation just uses guestfs_vfs_type and doesn't
1482  * try mounting anything, but we reserve the right in future to try
1483  * mounting filesystems.
1484  */
1485
1486 static void remove_from_list (char **list, const char *item);
1487 static void check_with_vfs_type (guestfs_h *g, const char *dev, char ***ret, size_t *ret_size);
1488
1489 char **
1490 guestfs__list_filesystems (guestfs_h *g)
1491 {
1492   size_t i;
1493   char **ret;
1494   size_t ret_size;
1495
1496   ret = safe_malloc (g, sizeof (char *));
1497   ret[0] = NULL;
1498   ret_size = 0;
1499
1500   /* Look to see if any devices directly contain filesystems
1501    * (RHBZ#590167).  However vfs-type will fail to tell us anything
1502    * useful about devices which just contain partitions, so we also
1503    * get the list of partitions and exclude the corresponding devices
1504    * by using part-to-dev.
1505    */
1506   char **devices;
1507   devices = guestfs_list_devices (g);
1508   if (devices == NULL) {
1509     free_string_list (ret);
1510     return NULL;
1511   }
1512   char **partitions;
1513   partitions = guestfs_list_partitions (g);
1514   if (partitions == NULL) {
1515     free_string_list (devices);
1516     free_string_list (ret);
1517     return NULL;
1518   }
1519
1520   for (i = 0; partitions[i] != NULL; ++i) {
1521     char *dev = guestfs_part_to_dev (g, partitions[i]);
1522     if (dev)
1523       remove_from_list (devices, dev);
1524     free (dev);
1525   }
1526
1527   /* Use vfs-type to check for filesystems on devices. */
1528   for (i = 0; devices[i] != NULL; ++i)
1529     check_with_vfs_type (g, devices[i], &ret, &ret_size);
1530   free_string_list (devices);
1531
1532   /* Use vfs-type to check for filesystems on partitions. */
1533   for (i = 0; partitions[i] != NULL; ++i)
1534     check_with_vfs_type (g, partitions[i], &ret, &ret_size);
1535   free_string_list (partitions);
1536
1537   if (feature_available (g, "lvm2")) {
1538     /* Use vfs-type to check for filesystems on LVs. */
1539     char **lvs;
1540     lvs = guestfs_lvs (g);
1541     if (lvs == NULL) {
1542       free_string_list (ret);
1543       return NULL;
1544     }
1545
1546     for (i = 0; lvs[i] != NULL; ++i)
1547       check_with_vfs_type (g, lvs[i], &ret, &ret_size);
1548     free_string_list (lvs);
1549   }
1550
1551   return ret;
1552 }
1553
1554 /* If 'item' occurs in 'list', remove and free it. */
1555 static void
1556 remove_from_list (char **list, const char *item)
1557 {
1558   size_t i;
1559
1560   for (i = 0; list[i] != NULL; ++i)
1561     if (STREQ (list[i], item)) {
1562       free (list[i]);
1563       for (; list[i+1] != NULL; ++i)
1564         list[i] = list[i+1];
1565       list[i] = NULL;
1566       return;
1567     }
1568 }
1569
1570 /* Use vfs-type to look for a filesystem of some sort on 'dev'.
1571  * Apart from some types which we ignore, add the result to the
1572  * 'ret' string list.
1573  */
1574 static void
1575 check_with_vfs_type (guestfs_h *g, const char *device,
1576                      char ***ret, size_t *ret_size)
1577 {
1578   char *v;
1579
1580   guestfs_error_handler_cb old_error_cb = g->error_cb;
1581   g->error_cb = NULL;
1582   char *vfs_type = guestfs_vfs_type (g, device);
1583   g->error_cb = old_error_cb;
1584
1585   if (!vfs_type)
1586     v = safe_strdup (g, "unknown");
1587   else {
1588     /* Ignore all "*_member" strings.  In libblkid these are returned
1589      * for things which are members of some RAID or LVM set, most
1590      * importantly "LVM2_member" which is a PV.
1591      */
1592     size_t n = strlen (vfs_type);
1593     if (n >= 7 && STREQ (&vfs_type[n-7], "_member")) {
1594       free (vfs_type);
1595       return;
1596     }
1597
1598     /* Ignore LUKS-encrypted partitions.  These are also containers. */
1599     if (STREQ (vfs_type, "crypto_LUKS")) {
1600       free (vfs_type);
1601       return;
1602     }
1603
1604     v = vfs_type;
1605   }
1606
1607   /* Extend the return array. */
1608   size_t i = *ret_size;
1609   *ret_size += 2;
1610   *ret = safe_realloc (g, *ret, (*ret_size + 1) * sizeof (char *));
1611   (*ret)[i] = safe_strdup (g, device);
1612   (*ret)[i+1] = v;
1613   (*ret)[i+2] = NULL;
1614 }