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