be98b0ddaf4cec718639ef813642f5f301c47f84
[libguestfs.git] / src / inspect.c
1 /* libguestfs
2  * Copyright (C) 2010-2011 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 #include <errno.h>
29 #include <endian.h>
30
31 #ifdef HAVE_PCRE
32 #include <pcre.h>
33 #endif
34
35 #ifdef HAVE_HIVEX
36 #include <hivex.h>
37 #endif
38
39 #include "c-ctype.h"
40 #include "ignore-value.h"
41 #include "xstrtol.h"
42
43 #include "guestfs.h"
44 #include "guestfs-internal.h"
45 #include "guestfs-internal-actions.h"
46 #include "guestfs_protocol.h"
47
48 #if defined(HAVE_PCRE) && defined(HAVE_HIVEX)
49
50 /* Some limits on what we will read, for safety. */
51
52 /* Small text configuration files.
53  *
54  * The upper limit is for general files that we grep or download.  The
55  * largest such file is probably "txtsetup.sif" from Windows CDs
56  * (~500K).  This number has to be larger than any legitimate file and
57  * smaller than the protocol message size.
58  *
59  * The lower limit is for files parsed by Augeas on the daemon side,
60  * where Augeas is running in reduced memory and can potentially
61  * create a lot of metadata so we really need to be careful about
62  * those.
63  */
64 #define MAX_SMALL_FILE_SIZE    (2 * 1000 * 1000)
65 #define MAX_AUGEAS_FILE_SIZE        (100 * 1000)
66
67 /* Maximum Windows Registry hive that we will download to /tmp.  Some
68  * registries can be legitimately very large.
69  */
70 #define MAX_REGISTRY_SIZE    (100 * 1000 * 1000)
71
72 /* Maximum RPM or dpkg database we will download to /tmp. */
73 #define MAX_PKG_DB_SIZE       (10 * 1000 * 1000)
74
75 /* Compile all the regular expressions once when the shared library is
76  * loaded.  PCRE is thread safe so we're supposedly OK here if
77  * multiple threads call into the libguestfs API functions below
78  * simultaneously.
79  */
80 static pcre *re_fedora;
81 static pcre *re_rhel_old;
82 static pcre *re_rhel;
83 static pcre *re_rhel_no_minor;
84 static pcre *re_major_minor;
85 static pcre *re_aug_seq;
86 static pcre *re_xdev;
87 static pcre *re_first_partition;
88 static pcre *re_freebsd;
89 static pcre *re_windows_version;
90
91 static void compile_regexps (void) __attribute__((constructor));
92 static void free_regexps (void) __attribute__((destructor));
93
94 static void
95 compile_regexps (void)
96 {
97   const char *err;
98   int offset;
99
100 #define COMPILE(re,pattern,options)                                     \
101   do {                                                                  \
102     re = pcre_compile ((pattern), (options), &err, &offset, NULL);      \
103     if (re == NULL) {                                                   \
104       ignore_value (write (2, err, strlen (err)));                      \
105       abort ();                                                         \
106     }                                                                   \
107   } while (0)
108
109   COMPILE (re_fedora, "Fedora release (\\d+)", 0);
110   COMPILE (re_rhel_old,
111            "(?:Red Hat|CentOS|Scientific Linux).*release (\\d+).*Update (\\d+)", 0);
112   COMPILE (re_rhel,
113            "(?:Red Hat|CentOS|Scientific Linux).*release (\\d+)\\.(\\d+)", 0);
114   COMPILE (re_rhel_no_minor,
115            "(?:Red Hat|CentOS|Scientific Linux).*release (\\d+)", 0);
116   COMPILE (re_major_minor, "(\\d+)\\.(\\d+)", 0);
117   COMPILE (re_aug_seq, "/\\d+$", 0);
118   COMPILE (re_xdev, "^/dev/(?:h|s|v|xv)d([a-z]\\d*)$", 0);
119   COMPILE (re_first_partition, "^/dev/(?:h|s|v)d.1$", 0);
120   COMPILE (re_freebsd, "^/dev/ad(\\d+)s(\\d+)([a-z])$", 0);
121   COMPILE (re_windows_version, "^(\\d+)\\.(\\d+)", 0);
122 }
123
124 static void
125 free_regexps (void)
126 {
127   pcre_free (re_fedora);
128   pcre_free (re_rhel_old);
129   pcre_free (re_rhel);
130   pcre_free (re_rhel_no_minor);
131   pcre_free (re_major_minor);
132   pcre_free (re_aug_seq);
133   pcre_free (re_xdev);
134   pcre_free (re_first_partition);
135   pcre_free (re_freebsd);
136   pcre_free (re_windows_version);
137 }
138
139 /* The main inspection code. */
140 static int check_for_filesystem_on (guestfs_h *g, const char *device, int is_block, int is_partnum);
141
142 char **
143 guestfs__inspect_os (guestfs_h *g)
144 {
145   /* Remove any information previously stored in the handle. */
146   guestfs___free_inspect_info (g);
147
148   if (guestfs_umount_all (g) == -1)
149     return NULL;
150
151   /* Iterate over all possible devices.  Try to mount each
152    * (read-only).  Examine ones which contain filesystems and add that
153    * information to the handle.
154    */
155   /* Look to see if any devices directly contain filesystems (RHBZ#590167). */
156   char **devices;
157   devices = guestfs_list_devices (g);
158   if (devices == NULL)
159     return NULL;
160
161   size_t i;
162   for (i = 0; devices[i] != NULL; ++i) {
163     if (check_for_filesystem_on (g, devices[i], 1, 0) == -1) {
164       guestfs___free_string_list (devices);
165       guestfs___free_inspect_info (g);
166       return NULL;
167     }
168   }
169   guestfs___free_string_list (devices);
170
171   /* Look at all partitions. */
172   char **partitions;
173   partitions = guestfs_list_partitions (g);
174   if (partitions == NULL) {
175     guestfs___free_inspect_info (g);
176     return NULL;
177   }
178
179   for (i = 0; partitions[i] != NULL; ++i) {
180     if (check_for_filesystem_on (g, partitions[i], 0, i+1) == -1) {
181       guestfs___free_string_list (partitions);
182       guestfs___free_inspect_info (g);
183       return NULL;
184     }
185   }
186   guestfs___free_string_list (partitions);
187
188   /* Look at all LVs. */
189   if (guestfs___feature_available (g, "lvm2")) {
190     char **lvs;
191     lvs = guestfs_lvs (g);
192     if (lvs == NULL) {
193       guestfs___free_inspect_info (g);
194       return NULL;
195     }
196
197     for (i = 0; lvs[i] != NULL; ++i) {
198       if (check_for_filesystem_on (g, lvs[i], 0, 0) == -1) {
199         guestfs___free_string_list (lvs);
200         guestfs___free_inspect_info (g);
201         return NULL;
202       }
203     }
204     guestfs___free_string_list (lvs);
205   }
206
207   /* At this point we have, in the handle, a list of all filesystems
208    * found and data about each one.  Now we assemble the list of
209    * filesystems which are root devices and return that to the user.
210    * Fall through to guestfs__inspect_get_roots to do that.
211    */
212   char **ret = guestfs__inspect_get_roots (g);
213   if (ret == NULL)
214     guestfs___free_inspect_info (g);
215   return ret;
216 }
217
218 /* Find out if 'device' contains a filesystem.  If it does, add
219  * another entry in g->fses.
220  */
221 static int check_filesystem (guestfs_h *g, const char *device, int is_block, int is_partnum);
222 static int check_linux_root (guestfs_h *g, struct inspect_fs *fs);
223 static int check_freebsd_root (guestfs_h *g, struct inspect_fs *fs);
224 static int check_installer_root (guestfs_h *g, struct inspect_fs *fs);
225 static void check_architecture (guestfs_h *g, struct inspect_fs *fs);
226 static int check_hostname_unix (guestfs_h *g, struct inspect_fs *fs);
227 static int check_hostname_redhat (guestfs_h *g, struct inspect_fs *fs);
228 static int check_hostname_freebsd (guestfs_h *g, struct inspect_fs *fs);
229 static int check_fstab (guestfs_h *g, struct inspect_fs *fs);
230 static int check_windows_root (guestfs_h *g, struct inspect_fs *fs);
231 static int check_windows_arch (guestfs_h *g, struct inspect_fs *fs);
232 static int check_windows_software_registry (guestfs_h *g, struct inspect_fs *fs);
233 static int check_windows_system_registry (guestfs_h *g, struct inspect_fs *fs);
234 static char *map_registry_disk_blob (guestfs_h *g, const char *blob);
235 static char *case_sensitive_path_silently (guestfs_h *g, const char *);
236 static int is_file_nocase (guestfs_h *g, const char *);
237 static int is_dir_nocase (guestfs_h *g, const char *);
238 static int extend_fses (guestfs_h *g);
239 static int parse_unsigned_int (guestfs_h *g, const char *str);
240 static int parse_unsigned_int_ignore_trailing (guestfs_h *g, const char *str);
241 static int add_fstab_entry (guestfs_h *g, struct inspect_fs *fs,
242                             const char *spec, const char *mp);
243 static char *resolve_fstab_device (guestfs_h *g, const char *spec);
244 static void check_package_format (guestfs_h *g, struct inspect_fs *fs);
245 static void check_package_management (guestfs_h *g, struct inspect_fs *fs);
246 static int download_to_tmp (guestfs_h *g, const char *filename, char *localtmp, int64_t max_size);
247 static int inspect_with_augeas (guestfs_h *g, struct inspect_fs *fs, const char *filename, int (*f) (guestfs_h *, struct inspect_fs *));
248 static char *first_line_of_file (guestfs_h *g, const char *filename);
249 static int first_egrep_of_file (guestfs_h *g, const char *filename, const char *eregex, int iflag, char **ret);
250
251 static int
252 check_for_filesystem_on (guestfs_h *g, const char *device,
253                          int is_block, int is_partnum)
254 {
255   /* Get vfs-type in order to check if it's a Linux(?) swap device.
256    * If there's an error we should ignore it, so to do that we have to
257    * temporarily replace the error handler with a null one.
258    */
259   guestfs_error_handler_cb old_error_cb = g->error_cb;
260   g->error_cb = NULL;
261   char *vfs_type = guestfs_vfs_type (g, device);
262   g->error_cb = old_error_cb;
263
264   int is_swap = vfs_type && STREQ (vfs_type, "swap");
265
266   debug (g, "check_for_filesystem_on: %s %d %d (%s)",
267          device, is_block, is_partnum,
268          vfs_type ? vfs_type : "failed to get vfs type");
269
270   if (is_swap) {
271     free (vfs_type);
272     if (extend_fses (g) == -1)
273       return -1;
274     g->fses[g->nr_fses-1].is_swap = 1;
275     return 0;
276   }
277
278   /* Try mounting the device.  As above, ignore errors. */
279   g->error_cb = NULL;
280   int r = guestfs_mount_ro (g, device, "/");
281   if (r == -1 && vfs_type && STREQ (vfs_type, "ufs")) /* Hack for the *BSDs. */
282     r = guestfs_mount_vfs (g, "ro,ufstype=ufs2", "ufs", device, "/");
283   free (vfs_type);
284   g->error_cb = old_error_cb;
285   if (r == -1)
286     return 0;
287
288   /* Do the rest of the checks. */
289   r = check_filesystem (g, device, is_block, is_partnum);
290
291   /* Unmount the filesystem. */
292   if (guestfs_umount_all (g) == -1)
293     return -1;
294
295   return r;
296 }
297
298 /* is_block and is_partnum are just hints: is_block is true if the
299  * filesystem is a whole block device (eg. /dev/sda).  is_partnum
300  * is > 0 if the filesystem is a direct partition, and in this case
301  * it is the partition number counting from 1
302  * (eg. /dev/sda1 => is_partnum == 1).
303  */
304 static int
305 check_filesystem (guestfs_h *g, const char *device,
306                   int is_block, int is_partnum)
307 {
308   if (extend_fses (g) == -1)
309     return -1;
310
311   struct inspect_fs *fs = &g->fses[g->nr_fses-1];
312
313   fs->device = safe_strdup (g, device);
314   fs->is_mountable = 1;
315
316   /* Optimize some of the tests by avoiding multiple tests of the same thing. */
317   int is_dir_etc = guestfs_is_dir (g, "/etc") > 0;
318   int is_dir_bin = guestfs_is_dir (g, "/bin") > 0;
319   int is_dir_share = guestfs_is_dir (g, "/share") > 0;
320
321   /* Grub /boot? */
322   if (guestfs_is_file (g, "/grub/menu.lst") > 0 ||
323       guestfs_is_file (g, "/grub/grub.conf") > 0)
324     fs->content = FS_CONTENT_LINUX_BOOT;
325   /* FreeBSD root? */
326   else if (is_dir_etc &&
327            is_dir_bin &&
328            guestfs_is_file (g, "/etc/freebsd-update.conf") > 0 &&
329            guestfs_is_file (g, "/etc/fstab") > 0) {
330     /* Ignore /dev/sda1 which is a shadow of the real root filesystem
331      * that is probably /dev/sda5 (see:
332      * http://www.freebsd.org/doc/handbook/disk-organization.html)
333      */
334     if (match (g, device, re_first_partition))
335       return 0;
336
337     fs->is_root = 1;
338     fs->content = FS_CONTENT_FREEBSD_ROOT;
339     fs->format = OS_FORMAT_INSTALLED;
340     if (check_freebsd_root (g, fs) == -1)
341       return -1;
342   }
343   /* Linux root? */
344   else if (is_dir_etc &&
345            is_dir_bin &&
346            guestfs_is_file (g, "/etc/fstab") > 0) {
347     fs->is_root = 1;
348     fs->content = FS_CONTENT_LINUX_ROOT;
349     fs->format = OS_FORMAT_INSTALLED;
350     if (check_linux_root (g, fs) == -1)
351       return -1;
352   }
353   /* Linux /usr/local? */
354   else if (is_dir_etc &&
355            is_dir_bin &&
356            is_dir_share &&
357            guestfs_exists (g, "/local") == 0 &&
358            guestfs_is_file (g, "/etc/fstab") == 0)
359     fs->content = FS_CONTENT_LINUX_USR_LOCAL;
360   /* Linux /usr? */
361   else if (is_dir_etc &&
362            is_dir_bin &&
363            is_dir_share &&
364            guestfs_exists (g, "/local") > 0 &&
365            guestfs_is_file (g, "/etc/fstab") == 0)
366     fs->content = FS_CONTENT_LINUX_USR;
367   /* Linux /var? */
368   else if (guestfs_is_dir (g, "/log") > 0 &&
369            guestfs_is_dir (g, "/run") > 0 &&
370            guestfs_is_dir (g, "/spool") > 0)
371     fs->content = FS_CONTENT_LINUX_VAR;
372   /* Windows root?
373    * Note that if a Windows guest has multiple disks and applications
374    * are installed on those other disks, then those other disks will
375    * contain "/Program Files" and "/System Volume Information".  Those
376    * would *not* be Windows root disks.  (RHBZ#674130)
377    */
378   else if (is_file_nocase (g, "/AUTOEXEC.BAT") > 0 ||
379            is_dir_nocase (g, "/WINDOWS") > 0 ||
380            is_dir_nocase (g, "/WIN32") > 0 ||
381            is_dir_nocase (g, "/WINNT") > 0 ||
382            is_file_nocase (g, "/boot.ini") > 0 ||
383            is_file_nocase (g, "/ntldr") > 0) {
384     fs->is_root = 1;
385     fs->content = FS_CONTENT_WINDOWS_ROOT;
386     fs->format = OS_FORMAT_INSTALLED;
387     if (check_windows_root (g, fs) == -1)
388       return -1;
389   }
390   /* Windows volume with installed applications (but not root)? */
391   else if (is_dir_nocase (g, "/System Volume Information") > 0 &&
392            is_dir_nocase (g, "/Program Files") > 0)
393     fs->content = FS_CONTENT_WINDOWS_VOLUME_WITH_APPS;
394   /* Windows volume (but not root)? */
395   else if (is_dir_nocase (g, "/System Volume Information") > 0)
396     fs->content = FS_CONTENT_WINDOWS_VOLUME;
397   /* Install CD/disk?  Skip these checks if it's not a whole device
398    * (eg. CD) or the first partition (eg. bootable USB key).
399    */
400   else if ((is_block || is_partnum == 1) &&
401            (guestfs_is_file (g, "/isolinux/isolinux.cfg") > 0 ||
402             guestfs_is_dir (g, "/EFI/BOOT") > 0 ||
403             guestfs_is_file (g, "/images/install.img") > 0 ||
404             guestfs_is_dir (g, "/.disk") > 0 ||
405             guestfs_is_file (g, "/.discinfo") > 0 ||
406             guestfs_is_file (g, "/i386/txtsetup.sif") > 0 ||
407             guestfs_is_file (g, "/amd64/txtsetup.sif")) > 0) {
408     fs->is_root = 1;
409     fs->content = FS_CONTENT_INSTALLER;
410     fs->format = OS_FORMAT_INSTALLER;
411     if (check_installer_root (g, fs) == -1)
412       return -1;
413   }
414
415   return 0;
416 }
417
418 /* Set fs->product_name to the first line of the release file. */
419 static int
420 parse_release_file (guestfs_h *g, struct inspect_fs *fs,
421                     const char *release_filename)
422 {
423   fs->product_name = first_line_of_file (g, release_filename);
424   if (fs->product_name == NULL)
425     return -1;
426   return 0;
427 }
428
429 /* Parse generic MAJOR.MINOR from the fs->product_name string. */
430 static int
431 parse_major_minor (guestfs_h *g, struct inspect_fs *fs)
432 {
433   char *major, *minor;
434
435   if (match2 (g, fs->product_name, re_major_minor, &major, &minor)) {
436     fs->major_version = parse_unsigned_int (g, major);
437     free (major);
438     if (fs->major_version == -1) {
439       free (minor);
440       return -1;
441     }
442     fs->minor_version = parse_unsigned_int (g, minor);
443     free (minor);
444     if (fs->minor_version == -1)
445       return -1;
446   }
447   return 0;
448 }
449
450 /* Ubuntu has /etc/lsb-release containing:
451  *   DISTRIB_ID=Ubuntu                                # Distro
452  *   DISTRIB_RELEASE=10.04                            # Version
453  *   DISTRIB_CODENAME=lucid
454  *   DISTRIB_DESCRIPTION="Ubuntu 10.04.1 LTS"         # Product name
455  *
456  * [Ubuntu-derived ...] Linux Mint was found to have this:
457  *   DISTRIB_ID=LinuxMint
458  *   DISTRIB_RELEASE=10
459  *   DISTRIB_CODENAME=julia
460  *   DISTRIB_DESCRIPTION="Linux Mint 10 Julia"
461  * Linux Mint also has /etc/linuxmint/info with more information,
462  * but we can use the LSB file.
463  *
464  * Mandriva has:
465  *   LSB_VERSION=lsb-4.0-amd64:lsb-4.0-noarch
466  *   DISTRIB_ID=MandrivaLinux
467  *   DISTRIB_RELEASE=2010.1
468  *   DISTRIB_CODENAME=Henry_Farman
469  *   DISTRIB_DESCRIPTION="Mandriva Linux 2010.1"
470  * Mandriva also has a normal release file called /etc/mandriva-release.
471  */
472 static int
473 parse_lsb_release (guestfs_h *g, struct inspect_fs *fs)
474 {
475   const char *filename = "/etc/lsb-release";
476   int64_t size;
477   char **lines;
478   size_t i;
479   int r = 0;
480
481   /* Don't trust guestfs_head_n not to break with very large files.
482    * Check the file size is something reasonable first.
483    */
484   size = guestfs_filesize (g, filename);
485   if (size == -1)
486     /* guestfs_filesize failed and has already set error in handle */
487     return -1;
488   if (size > MAX_SMALL_FILE_SIZE) {
489     error (g, _("size of %s is unreasonably large (%" PRIi64 " bytes)"),
490            filename, size);
491     return -1;
492   }
493
494   lines = guestfs_head_n (g, 10, filename);
495   if (lines == NULL)
496     return -1;
497
498   for (i = 0; lines[i] != NULL; ++i) {
499     if (fs->distro == 0 &&
500         STREQ (lines[i], "DISTRIB_ID=Ubuntu")) {
501       fs->distro = OS_DISTRO_UBUNTU;
502       r = 1;
503     }
504     else if (fs->distro == 0 &&
505              STREQ (lines[i], "DISTRIB_ID=LinuxMint")) {
506       fs->distro = OS_DISTRO_LINUX_MINT;
507       r = 1;
508     }
509     else if (fs->distro == 0 &&
510              STREQ (lines[i], "DISTRIB_ID=MandrivaLinux")) {
511       fs->distro = OS_DISTRO_MANDRIVA;
512       r = 1;
513     }
514     else if (STRPREFIX (lines[i], "DISTRIB_RELEASE=")) {
515       char *major, *minor;
516       if (match2 (g, &lines[i][16], re_major_minor, &major, &minor)) {
517         fs->major_version = parse_unsigned_int (g, major);
518         free (major);
519         if (fs->major_version == -1) {
520           free (minor);
521           guestfs___free_string_list (lines);
522           return -1;
523         }
524         fs->minor_version = parse_unsigned_int (g, minor);
525         free (minor);
526         if (fs->minor_version == -1) {
527           guestfs___free_string_list (lines);
528           return -1;
529         }
530       }
531     }
532     else if (fs->product_name == NULL &&
533              (STRPREFIX (lines[i], "DISTRIB_DESCRIPTION=\"") ||
534               STRPREFIX (lines[i], "DISTRIB_DESCRIPTION='"))) {
535       size_t len = strlen (lines[i]) - 21 - 1;
536       fs->product_name = safe_strndup (g, &lines[i][21], len);
537       r = 1;
538     }
539     else if (fs->product_name == NULL &&
540              STRPREFIX (lines[i], "DISTRIB_DESCRIPTION=")) {
541       size_t len = strlen (lines[i]) - 20;
542       fs->product_name = safe_strndup (g, &lines[i][20], len);
543       r = 1;
544     }
545   }
546
547   guestfs___free_string_list (lines);
548   return r;
549 }
550
551 /* The currently mounted device is known to be a Linux root.  Try to
552  * determine from this the distro, version, etc.  Also parse
553  * /etc/fstab to determine the arrangement of mountpoints and
554  * associated devices.
555  */
556 static int
557 check_linux_root (guestfs_h *g, struct inspect_fs *fs)
558 {
559   int r;
560
561   fs->type = OS_TYPE_LINUX;
562
563   if (guestfs_exists (g, "/etc/lsb-release") > 0) {
564     r = parse_lsb_release (g, fs);
565     if (r == -1)        /* error */
566       return -1;
567     if (r == 1)         /* ok - detected the release from this file */
568       goto skip_release_checks;
569   }
570
571   if (guestfs_exists (g, "/etc/redhat-release") > 0) {
572     fs->distro = OS_DISTRO_REDHAT_BASED; /* Something generic Red Hat-like. */
573
574     if (parse_release_file (g, fs, "/etc/redhat-release") == -1)
575       return -1;
576
577     char *major, *minor;
578     if ((major = match1 (g, fs->product_name, re_fedora)) != NULL) {
579       fs->distro = OS_DISTRO_FEDORA;
580       fs->major_version = parse_unsigned_int (g, major);
581       free (major);
582       if (fs->major_version == -1)
583         return -1;
584     }
585     else if (match2 (g, fs->product_name, re_rhel_old, &major, &minor) ||
586              match2 (g, fs->product_name, re_rhel, &major, &minor)) {
587       fs->distro = OS_DISTRO_RHEL;
588       fs->major_version = parse_unsigned_int (g, major);
589       free (major);
590       if (fs->major_version == -1) {
591         free (minor);
592         return -1;
593       }
594       fs->minor_version = parse_unsigned_int (g, minor);
595       free (minor);
596       if (fs->minor_version == -1)
597         return -1;
598     }
599     else if ((major = match1 (g, fs->product_name, re_rhel_no_minor)) != NULL) {
600       fs->distro = OS_DISTRO_RHEL;
601       fs->major_version = parse_unsigned_int (g, major);
602       free (major);
603       if (fs->major_version == -1)
604         return -1;
605       fs->minor_version = 0;
606     }
607   }
608   else if (guestfs_exists (g, "/etc/debian_version") > 0) {
609     fs->distro = OS_DISTRO_DEBIAN;
610
611     if (parse_release_file (g, fs, "/etc/debian_version") == -1)
612       return -1;
613
614     if (parse_major_minor (g, fs) == -1)
615       return -1;
616   }
617   else if (guestfs_exists (g, "/etc/pardus-release") > 0) {
618     fs->distro = OS_DISTRO_PARDUS;
619
620     if (parse_release_file (g, fs, "/etc/pardus-release") == -1)
621       return -1;
622
623     if (parse_major_minor (g, fs) == -1)
624       return -1;
625   }
626   else if (guestfs_exists (g, "/etc/arch-release") > 0) {
627     fs->distro = OS_DISTRO_ARCHLINUX;
628
629     /* /etc/arch-release file is empty and I can't see a way to
630      * determine the actual release or product string.
631      */
632   }
633   else if (guestfs_exists (g, "/etc/gentoo-release") > 0) {
634     fs->distro = OS_DISTRO_GENTOO;
635
636     if (parse_release_file (g, fs, "/etc/gentoo-release") == -1)
637       return -1;
638
639     if (parse_major_minor (g, fs) == -1)
640       return -1;
641   }
642   else if (guestfs_exists (g, "/etc/meego-release") > 0) {
643     fs->distro = OS_DISTRO_MEEGO;
644
645     if (parse_release_file (g, fs, "/etc/meego-release") == -1)
646       return -1;
647
648     if (parse_major_minor (g, fs) == -1)
649       return -1;
650   }
651   else if (guestfs_exists (g, "/etc/slackware-version") > 0) {
652     fs->distro = OS_DISTRO_SLACKWARE;
653
654     if (parse_release_file (g, fs, "/etc/slackware-version") == -1)
655       return -1;
656
657     if (parse_major_minor (g, fs) == -1)
658       return -1;
659   }
660
661  skip_release_checks:;
662
663   /* If distro test above was successful, work out the package format. */
664   check_package_format (g, fs);
665   check_package_management (g, fs);
666
667   /* Determine the architecture. */
668   check_architecture (g, fs);
669
670   /* We already know /etc/fstab exists because it's part of the test
671    * for Linux root above.  We must now parse this file to determine
672    * which filesystems are used by the operating system and how they
673    * are mounted.
674    */
675   if (inspect_with_augeas (g, fs, "/etc/fstab", check_fstab) == -1)
676     return -1;
677
678   /* Determine hostname. */
679   if (check_hostname_unix (g, fs) == -1)
680     return -1;
681
682   return 0;
683 }
684
685 /* The currently mounted device is known to be a FreeBSD root. */
686 static int
687 check_freebsd_root (guestfs_h *g, struct inspect_fs *fs)
688 {
689   fs->type = OS_TYPE_FREEBSD;
690
691   /* FreeBSD has no authoritative version file.  The version number is
692    * in /etc/motd, which the system administrator might edit, but
693    * we'll use that anyway.
694    */
695
696   if (guestfs_exists (g, "/etc/motd") > 0) {
697     if (parse_release_file (g, fs, "/etc/motd") == -1)
698       return -1;
699
700     if (parse_major_minor (g, fs) == -1)
701       return -1;
702   }
703
704   /* Determine the architecture. */
705   check_architecture (g, fs);
706
707   /* We already know /etc/fstab exists because it's part of the test above. */
708   if (inspect_with_augeas (g, fs, "/etc/fstab", check_fstab) == -1)
709     return -1;
710
711   /* Determine hostname. */
712   if (check_hostname_unix (g, fs) == -1)
713     return -1;
714
715   return 0;
716 }
717
718 /* Debian/Ubuntu install disks are easy ...
719  *
720  * These files are added by the debian-cd program, and it is worth
721  * looking at the source code to determine exact values, in
722  * particular '/usr/share/debian-cd/tools/start_new_disc'
723  *
724  * XXX Architecture?  We could parse it out of the product name
725  * string, but that seems quite hairy.  We could look for the names
726  * of packages.  Also note that some Debian install disks are
727  * multiarch.
728  */
729 static int
730 check_debian_installer_root (guestfs_h *g, struct inspect_fs *fs)
731 {
732   fs->product_name = first_line_of_file (g, "/.disk/info");
733   if (!fs->product_name)
734     return -1;
735
736   fs->type = OS_TYPE_LINUX;
737   if (STRPREFIX (fs->product_name, "Ubuntu"))
738     fs->distro = OS_DISTRO_UBUNTU;
739   else if (STRPREFIX (fs->product_name, "Debian"))
740     fs->distro = OS_DISTRO_DEBIAN;
741
742   (void) parse_major_minor (g, fs);
743
744   if (guestfs_is_file (g, "/.disk/cd_type") > 0) {
745     char *cd_type = first_line_of_file (g, "/.disk/cd_type");
746     if (!cd_type)
747       return -1;
748
749     if (STRPREFIX (cd_type, "dvd/single") ||
750         STRPREFIX (cd_type, "full_cd/single")) {
751       fs->is_multipart_disk = 0;
752       fs->is_netinst_disk = 0;
753     }
754     else if (STRPREFIX (cd_type, "dvd") ||
755              STRPREFIX (cd_type, "full_cd")) {
756       fs->is_multipart_disk = 1;
757       fs->is_netinst_disk = 0;
758     }
759     else if (STRPREFIX (cd_type, "not_complete")) {
760       fs->is_multipart_disk = 0;
761       fs->is_netinst_disk = 1;
762     }
763
764     free (cd_type);
765   }
766
767   return 0;
768 }
769
770 /* Take string which must look like "key = value" and find the value.
771  * There may or may not be spaces before and after the equals sign.
772  * This function is used by both check_fedora_installer_root and
773  * check_w2k3_installer_root.
774  */
775 static const char *
776 find_value (const char *kv)
777 {
778   const char *p;
779
780   p = strchr (kv, '=');
781   if (!p)
782     abort ();
783
784   do {
785     ++p;
786   } while (c_isspace (*p));
787
788   return p;
789 }
790
791 /* Fedora CDs and DVD (not netinst).  The /.treeinfo file contains
792  * an initial section somewhat like this:
793  *
794  * [general]
795  * version = 14
796  * arch = x86_64
797  * family = Fedora
798  * variant = Fedora
799  * discnum = 1
800  * totaldiscs = 1
801  */
802 static int
803 check_fedora_installer_root (guestfs_h *g, struct inspect_fs *fs)
804 {
805   char *str;
806   const char *v;
807   int r;
808   int discnum = 0, totaldiscs = 0;
809
810   fs->type = OS_TYPE_LINUX;
811
812   r = first_egrep_of_file (g, "/.treeinfo",
813                            "^family = Fedora$", 0, &str);
814   if (r == -1)
815     return -1;
816   if (r > 0) {
817     fs->distro = OS_DISTRO_FEDORA;
818     free (str);
819   }
820
821   r = first_egrep_of_file (g, "/.treeinfo",
822                            "^family = Red Hat Enterprise Linux$", 0, &str);
823   if (r == -1)
824     return -1;
825   if (r > 0) {
826     fs->distro = OS_DISTRO_RHEL;
827     free (str);
828   }
829
830   /* XXX should do major.minor before this */
831   r = first_egrep_of_file (g, "/.treeinfo",
832                            "^version = [[:digit:]]+", 0, &str);
833   if (r == -1)
834     return -1;
835   if (r > 0) {
836     v = find_value (str);
837     fs->major_version = parse_unsigned_int_ignore_trailing (g, v);
838     free (str);
839     if (fs->major_version == -1)
840       return -1;
841   }
842
843   r = first_egrep_of_file (g, "/.treeinfo",
844                            "^arch = [-_[:alnum:]]+$", 0, &str);
845   if (r == -1)
846     return -1;
847   if (r > 0) {
848     v = find_value (str);
849     fs->arch = safe_strdup (g, v);
850     free (str);
851   }
852
853   r = first_egrep_of_file (g, "/.treeinfo",
854                            "^discnum = [[:digit:]]+$", 0, &str);
855   if (r == -1)
856     return -1;
857   if (r > 0) {
858     v = find_value (str);
859     discnum = parse_unsigned_int (g, v);
860     free (str);
861     if (discnum == -1)
862       return -1;
863   }
864
865   r = first_egrep_of_file (g, "/.treeinfo",
866                            "^totaldiscs = [[:digit:]]+$", 0, &str);
867   if (r == -1)
868     return -1;
869   if (r > 0) {
870     v = find_value (str);
871     totaldiscs = parse_unsigned_int (g, v);
872     free (str);
873     if (totaldiscs == -1)
874       return -1;
875   }
876
877   fs->is_multipart_disk = totaldiscs > 0;
878   /* and what about discnum? */
879
880   return 0;
881 }
882
883 /* Linux with /isolinux/isolinux.cfg.
884  *
885  * This file is not easily parsable so we have to do our best.
886  * Look for the "menu title" line which contains:
887  *   menu title Welcome to Fedora 14!   # since at least Fedora 10
888  *   menu title Welcome to Red Hat Enterprise Linux 6.0!
889  */
890 static int
891 check_isolinux_installer_root (guestfs_h *g, struct inspect_fs *fs)
892 {
893   char *str;
894   int r;
895
896   fs->type = OS_TYPE_LINUX;
897
898   r = first_egrep_of_file (g, "/isolinux/isolinux.cfg",
899                            "^menu title Welcome to Fedora [[:digit:]]+",
900                            0, &str);
901   if (r == -1)
902     return -1;
903   if (r > 0) {
904     fs->distro = OS_DISTRO_FEDORA;
905     fs->major_version = parse_unsigned_int_ignore_trailing (g, &str[29]);
906     free (str);
907     if (fs->major_version == -1)
908       return -1;
909   }
910
911   /* XXX parse major.minor */
912   r = first_egrep_of_file (g, "/isolinux/isolinux.cfg",
913                            "^menu title Welcome to Red Hat Enterprise Linux [[:digit:]]+",
914                            0, &str);
915   if (r == -1)
916     return -1;
917   if (r > 0) {
918     fs->distro = OS_DISTRO_RHEL;
919     fs->major_version = parse_unsigned_int_ignore_trailing (g, &str[47]);
920     free (str);
921     if (fs->major_version == -1)
922       return -1;
923   }
924
925   return 0;
926 }
927
928 /* Windows 2003 and similar versions.
929  *
930  * NB: txtsetup file contains Windows \r\n line endings, which guestfs_grep
931  * does not remove.  We have to remove them by hand here.
932  */
933 static void
934 trim_cr (char *str)
935 {
936   size_t n = strlen (str);
937   if (n > 0 && str[n-1] == '\r')
938     str[n-1] = '\0';
939 }
940
941 static void
942 trim_quot (char *str)
943 {
944   size_t n = strlen (str);
945   if (n > 0 && str[n-1] == '"')
946     str[n-1] = '\0';
947 }
948
949 static int
950 check_w2k3_installer_root (guestfs_h *g, struct inspect_fs *fs,
951                            const char *txtsetup)
952 {
953   char *str;
954   const char *v;
955   int r;
956
957   fs->type = OS_TYPE_WINDOWS;
958   fs->distro = OS_DISTRO_WINDOWS;
959
960   r = first_egrep_of_file (g, txtsetup,
961                            "^productname[[:space:]]*=[[:space:]]*\"", 1, &str);
962   if (r == -1)
963     return -1;
964   if (r > 0) {
965     trim_cr (str);
966     trim_quot (str);
967     v = find_value (str);
968     fs->product_name = safe_strdup (g, v+1);
969     free (str);
970   }
971
972   r = first_egrep_of_file (g, txtsetup,
973                            "^majorversion[[:space:]]*=[[:space:]]*[[:digit:]]+",
974                            1, &str);
975   if (r == -1)
976     return -1;
977   if (r > 0) {
978     trim_cr (str);
979     v = find_value (str);
980     fs->major_version = parse_unsigned_int_ignore_trailing (g, v);
981     free (str);
982     if (fs->major_version == -1)
983       return -1;
984   }
985
986   r = first_egrep_of_file (g, txtsetup,
987                            "^minorversion[[:space:]]*=[[:space:]]*[[:digit:]]+",
988                            1, &str);
989   if (r == -1)
990     return -1;
991   if (r > 0) {
992     trim_cr (str);
993     v = find_value (str);
994     fs->minor_version = parse_unsigned_int_ignore_trailing (g, v);
995     free (str);
996     if (fs->minor_version == -1)
997       return -1;
998   }
999
1000   /* This is the windows systemroot that would be chosen on
1001    * installation by default, although not necessarily the one that
1002    * the user will finally choose.
1003    */
1004   r = first_egrep_of_file (g, txtsetup, "^defaultpath[[:space:]]*=[[:space:]]*",
1005                            1, &str);
1006   if (r == -1)
1007     return -1;
1008   if (r > 0) {
1009     trim_cr (str);
1010     v = find_value (str);
1011     fs->windows_systemroot = safe_strdup (g, v);
1012     free (str);
1013   }
1014
1015   return 0;
1016 }
1017
1018 /* The currently mounted device is very likely to be an installer. */
1019 static int
1020 check_installer_root (guestfs_h *g, struct inspect_fs *fs)
1021 {
1022   /* The presence of certain files indicates a live CD.
1023    *
1024    * XXX Fedora netinst contains a ~120MB squashfs called
1025    * /images/install.img.  However this is not a live CD (unlike the
1026    * Fedora live CDs which contain the same, but larger file).  We
1027    * need to unpack this and look inside to tell the difference.
1028    */
1029   if (guestfs_is_file (g, "/casper/filesystem.squashfs") > 0)
1030     fs->is_live_disk = 1;
1031
1032   /* Debian/Ubuntu. */
1033   if (guestfs_is_file (g, "/.disk/info") > 0) {
1034     if (check_debian_installer_root (g, fs) == -1)
1035       return -1;
1036   }
1037
1038   /* Fedora CDs and DVD (not netinst). */
1039   else if (guestfs_is_file (g, "/.treeinfo") > 0) {
1040     if (check_fedora_installer_root (g, fs) == -1)
1041       return -1;
1042   }
1043
1044   /* Linux with /isolinux/isolinux.cfg. */
1045   else if (guestfs_is_file (g, "/isolinux/isolinux.cfg") > 0) {
1046     if (check_isolinux_installer_root (g, fs) == -1)
1047       return -1;
1048   }
1049
1050   /* Windows 2003 64 bit */
1051   else if (guestfs_is_file (g, "/amd64/txtsetup.sif") > 0) {
1052     fs->arch = safe_strdup (g, "x86_64");
1053     if (check_w2k3_installer_root (g, fs, "/amd64/txtsetup.sif") == -1)
1054       return -1;
1055   }
1056
1057   /* Windows 2003 32 bit */
1058   else if (guestfs_is_file (g, "/i386/txtsetup.sif") > 0) {
1059     fs->arch = safe_strdup (g, "i386");
1060     if (check_w2k3_installer_root (g, fs, "/i386/txtsetup.sif") == -1)
1061       return -1;
1062   }
1063
1064   return 0;
1065 }
1066
1067 static void
1068 check_architecture (guestfs_h *g, struct inspect_fs *fs)
1069 {
1070   const char *binaries[] =
1071     { "/bin/bash", "/bin/ls", "/bin/echo", "/bin/rm", "/bin/sh" };
1072   size_t i;
1073
1074   for (i = 0; i < sizeof binaries / sizeof binaries[0]; ++i) {
1075     if (guestfs_is_file (g, binaries[i]) > 0) {
1076       /* Ignore errors from file_architecture call. */
1077       guestfs_error_handler_cb old_error_cb = g->error_cb;
1078       g->error_cb = NULL;
1079       char *arch = guestfs_file_architecture (g, binaries[i]);
1080       g->error_cb = old_error_cb;
1081
1082       if (arch) {
1083         /* String will be owned by handle, freed by
1084          * guestfs___free_inspect_info.
1085          */
1086         fs->arch = arch;
1087         break;
1088       }
1089     }
1090   }
1091 }
1092
1093 /* Try several methods to determine the hostname from a Linux or
1094  * FreeBSD guest.  Note that type and distro have been set, so we can
1095  * use that information to direct the search.
1096  */
1097 static int
1098 check_hostname_unix (guestfs_h *g, struct inspect_fs *fs)
1099 {
1100   switch (fs->type) {
1101   case OS_TYPE_LINUX:
1102     /* Red Hat-derived would be in /etc/sysconfig/network, and
1103      * Debian-derived in the file /etc/hostname.  Very old Debian and
1104      * SUSE use /etc/HOSTNAME.  It's best to just look for each of
1105      * these files in turn, rather than try anything clever based on
1106      * distro.
1107      */
1108     if (guestfs_is_file (g, "/etc/HOSTNAME")) {
1109       fs->hostname = first_line_of_file (g, "/etc/HOSTNAME");
1110       if (fs->hostname == NULL)
1111         return -1;
1112     }
1113     else if (guestfs_is_file (g, "/etc/hostname")) {
1114       fs->hostname = first_line_of_file (g, "/etc/hostname");
1115       if (fs->hostname == NULL)
1116         return -1;
1117     }
1118     else if (guestfs_is_file (g, "/etc/sysconfig/network")) {
1119       if (inspect_with_augeas (g, fs, "/etc/sysconfig/network",
1120                                check_hostname_redhat) == -1)
1121         return -1;
1122     }
1123     break;
1124
1125   case OS_TYPE_FREEBSD:
1126     /* /etc/rc.conf contains the hostname, but there is no Augeas lens
1127      * for this file.
1128      */
1129     if (guestfs_is_file (g, "/etc/rc.conf")) {
1130       if (check_hostname_freebsd (g, fs) == -1)
1131         return -1;
1132     }
1133     break;
1134
1135   case OS_TYPE_WINDOWS: /* not here, see check_windows_system_registry */
1136   case OS_TYPE_UNKNOWN:
1137   default:
1138     /* nothing, keep GCC warnings happy */;
1139   }
1140
1141   return 0;
1142 }
1143
1144 /* Parse the hostname from /etc/sysconfig/network.  This must be called
1145  * from the inspect_with_augeas wrapper.
1146  */
1147 static int
1148 check_hostname_redhat (guestfs_h *g, struct inspect_fs *fs)
1149 {
1150   char *hostname;
1151
1152   hostname = guestfs_aug_get (g, "/files/etc/sysconfig/network/HOSTNAME");
1153   if (!hostname)
1154     return -1;
1155
1156   fs->hostname = hostname;  /* freed by guestfs___free_inspect_info */
1157   return 0;
1158 }
1159
1160 /* Parse the hostname from /etc/rc.conf.  On FreeBSD this file
1161  * contains comments, blank lines and:
1162  *   hostname="freebsd8.example.com"
1163  *   ifconfig_re0="DHCP"
1164  *   keymap="uk.iso"
1165  *   sshd_enable="YES"
1166  */
1167 static int
1168 check_hostname_freebsd (guestfs_h *g, struct inspect_fs *fs)
1169 {
1170   const char *filename = "/etc/rc.conf";
1171   int64_t size;
1172   char **lines;
1173   size_t i;
1174
1175   /* Don't trust guestfs_read_lines not to break with very large files.
1176    * Check the file size is something reasonable first.
1177    */
1178   size = guestfs_filesize (g, filename);
1179   if (size == -1)
1180     /* guestfs_filesize failed and has already set error in handle */
1181     return -1;
1182   if (size > MAX_SMALL_FILE_SIZE) {
1183     error (g, _("size of %s is unreasonably large (%" PRIi64 " bytes)"),
1184            filename, size);
1185     return -1;
1186   }
1187
1188   lines = guestfs_read_lines (g, filename);
1189   if (lines == NULL)
1190     return -1;
1191
1192   for (i = 0; lines[i] != NULL; ++i) {
1193     if (STRPREFIX (lines[i], "hostname=\"") ||
1194         STRPREFIX (lines[i], "hostname='")) {
1195       size_t len = strlen (lines[i]) - 10 - 1;
1196       fs->hostname = safe_strndup (g, &lines[i][10], len);
1197       break;
1198     } else if (STRPREFIX (lines[i], "hostname=")) {
1199       size_t len = strlen (lines[i]) - 9;
1200       fs->hostname = safe_strndup (g, &lines[i][9], len);
1201       break;
1202     }
1203   }
1204
1205   guestfs___free_string_list (lines);
1206   return 0;
1207 }
1208
1209 static int
1210 check_fstab (guestfs_h *g, struct inspect_fs *fs)
1211 {
1212   char **lines = guestfs_aug_ls (g, "/files/etc/fstab");
1213   if (lines == NULL)
1214     return -1;
1215
1216   if (lines[0] == NULL) {
1217     error (g, _("could not parse /etc/fstab or empty file"));
1218     guestfs___free_string_list (lines);
1219     return -1;
1220   }
1221
1222   size_t i;
1223   char augpath[256];
1224   for (i = 0; lines[i] != NULL; ++i) {
1225     /* Ignore comments.  Only care about sequence lines which
1226      * match m{/\d+$}.
1227      */
1228     if (match (g, lines[i], re_aug_seq)) {
1229       snprintf (augpath, sizeof augpath, "%s/spec", lines[i]);
1230       char *spec = guestfs_aug_get (g, augpath);
1231       if (spec == NULL) {
1232         guestfs___free_string_list (lines);
1233         return -1;
1234       }
1235
1236       snprintf (augpath, sizeof augpath, "%s/file", lines[i]);
1237       char *mp = guestfs_aug_get (g, augpath);
1238       if (mp == NULL) {
1239         guestfs___free_string_list (lines);
1240         free (spec);
1241         return -1;
1242       }
1243
1244       int r = add_fstab_entry (g, fs, spec, mp);
1245       free (spec);
1246       free (mp);
1247
1248       if (r == -1) {
1249         guestfs___free_string_list (lines);
1250         return -1;
1251       }
1252     }
1253   }
1254
1255   guestfs___free_string_list (lines);
1256   return 0;
1257 }
1258
1259 /* Add a filesystem and possibly a mountpoint entry for
1260  * the root filesystem 'fs'.
1261  *
1262  * 'spec' is the fstab spec field, which might be a device name or a
1263  * pseudodevice or 'UUID=...' or 'LABEL=...'.
1264  *
1265  * 'mp' is the mount point, which could also be 'swap' or 'none'.
1266  */
1267 static int
1268 add_fstab_entry (guestfs_h *g, struct inspect_fs *fs,
1269                  const char *spec, const char *mp)
1270 {
1271   /* Ignore certain mountpoints. */
1272   if (STRPREFIX (mp, "/dev/") ||
1273       STREQ (mp, "/dev") ||
1274       STRPREFIX (mp, "/media/") ||
1275       STRPREFIX (mp, "/proc/") ||
1276       STREQ (mp, "/proc") ||
1277       STRPREFIX (mp, "/selinux/") ||
1278       STREQ (mp, "/selinux") ||
1279       STRPREFIX (mp, "/sys/") ||
1280       STREQ (mp, "/sys"))
1281     return 0;
1282
1283   /* Ignore /dev/fd (floppy disks) (RHBZ#642929) and CD-ROM drives. */
1284   if ((STRPREFIX (spec, "/dev/fd") && c_isdigit (spec[7])) ||
1285       STREQ (spec, "/dev/floppy") ||
1286       STREQ (spec, "/dev/cdrom"))
1287     return 0;
1288
1289   /* Resolve UUID= and LABEL= to the actual device. */
1290   char *device = NULL;
1291   if (STRPREFIX (spec, "UUID="))
1292     device = guestfs_findfs_uuid (g, &spec[5]);
1293   else if (STRPREFIX (spec, "LABEL="))
1294     device = guestfs_findfs_label (g, &spec[6]);
1295   /* Ignore "/.swap" (Pardus) and pseudo-devices like "tmpfs". */
1296   else if (STRPREFIX (spec, "/dev/"))
1297     /* Resolve guest block device names. */
1298     device = resolve_fstab_device (g, spec);
1299
1300   /* If we haven't resolved the device successfully by this point,
1301    * we don't care, just ignore it.
1302    */
1303   if (device == NULL)
1304     return 0;
1305
1306   char *mountpoint = safe_strdup (g, mp);
1307
1308   /* Add this to the fstab entry in 'fs'.
1309    * Note these are further filtered by guestfs_inspect_get_mountpoints
1310    * and guestfs_inspect_get_filesystems.
1311    */
1312   size_t n = fs->nr_fstab + 1;
1313   struct inspect_fstab_entry *p;
1314
1315   p = realloc (fs->fstab, n * sizeof (struct inspect_fstab_entry));
1316   if (p == NULL) {
1317     perrorf (g, "realloc");
1318     free (device);
1319     free (mountpoint);
1320     return -1;
1321   }
1322
1323   fs->fstab = p;
1324   fs->nr_fstab = n;
1325
1326   /* These are owned by the handle and freed by guestfs___free_inspect_info. */
1327   fs->fstab[n-1].device = device;
1328   fs->fstab[n-1].mountpoint = mountpoint;
1329
1330   debug (g, "fstab: device=%s mountpoint=%s", device, mountpoint);
1331
1332   return 0;
1333 }
1334
1335 /* Resolve block device name to the libguestfs device name, eg.
1336  * /dev/xvdb1 => /dev/vdb1; and /dev/mapper/VG-LV => /dev/VG/LV.  This
1337  * assumes that disks were added in the same order as they appear to
1338  * the real VM, which is a reasonable assumption to make.  Return
1339  * anything we don't recognize unchanged.
1340  */
1341 static char *
1342 resolve_fstab_device (guestfs_h *g, const char *spec)
1343 {
1344   char *a1;
1345   char *device = NULL;
1346   char *bsddisk, *bsdslice, *bsdpart;
1347
1348   if (STRPREFIX (spec, "/dev/mapper/")) {
1349     /* LVM2 does some strange munging on /dev/mapper paths for VGs and
1350      * LVs which contain '-' character:
1351      *
1352      * ><fs> lvcreate LV--test VG--test 32
1353      * ><fs> debug ls /dev/mapper
1354      * VG----test-LV----test
1355      *
1356      * This makes it impossible to reverse those paths directly, so
1357      * we have implemented lvm_canonical_lv_name in the daemon.
1358      */
1359     device = guestfs_lvm_canonical_lv_name (g, spec);
1360   }
1361   else if ((a1 = match1 (g, spec, re_xdev)) != NULL) {
1362     char **devices = guestfs_list_devices (g);
1363     if (devices == NULL)
1364       return NULL;
1365
1366     size_t count;
1367     for (count = 0; devices[count] != NULL; count++)
1368       ;
1369
1370     size_t i = a1[0] - 'a'; /* a1[0] is always [a-z] because of regex. */
1371     if (i < count) {
1372       size_t len = strlen (devices[i]) + strlen (a1) + 16;
1373       device = safe_malloc (g, len);
1374       snprintf (device, len, "%s%s", devices[i], &a1[1]);
1375     }
1376
1377     free (a1);
1378     guestfs___free_string_list (devices);
1379   }
1380   else if (match3 (g, spec, re_freebsd, &bsddisk, &bsdslice, &bsdpart)) {
1381     /* FreeBSD disks are organized quite differently.  See:
1382      * http://www.freebsd.org/doc/handbook/disk-organization.html
1383      * FreeBSD "partitions" are exposed as quasi-extended partitions
1384      * numbered from 5 in Linux.  I have no idea what happens when you
1385      * have multiple "slices" (the FreeBSD term for MBR partitions).
1386      */
1387     int disk = parse_unsigned_int (g, bsddisk);
1388     int slice = parse_unsigned_int (g, bsdslice);
1389     int part = bsdpart[0] - 'a' /* counting from 0 */;
1390     free (bsddisk);
1391     free (bsdslice);
1392     free (bsdpart);
1393
1394     if (disk == -1 || disk > 26 ||
1395         slice <= 0 || slice > 1 /* > 4 .. see comment above */ ||
1396         part < 0 || part >= 26)
1397       goto out;
1398
1399     device = safe_asprintf (g, "/dev/sd%c%d", disk + 'a', part + 5);
1400   }
1401
1402  out:
1403   /* Didn't match device pattern, return original spec unchanged. */
1404   if (device == NULL)
1405     device = safe_strdup (g, spec);
1406
1407   return device;
1408 }
1409
1410 /* XXX Handling of boot.ini in the Perl version was pretty broken.  It
1411  * essentially didn't do anything for modern Windows guests.
1412  * Therefore I've omitted all that code.
1413  */
1414 static int
1415 check_windows_root (guestfs_h *g, struct inspect_fs *fs)
1416 {
1417   fs->type = OS_TYPE_WINDOWS;
1418   fs->distro = OS_DISTRO_WINDOWS;
1419
1420   /* Try to find Windows systemroot using some common locations. */
1421   const char *systemroots[] =
1422     { "/windows", "/winnt", "/win32", "/win" };
1423   size_t i;
1424   char *systemroot = NULL;
1425   for (i = 0;
1426        systemroot == NULL && i < sizeof systemroots / sizeof systemroots[0];
1427        ++i) {
1428     systemroot = case_sensitive_path_silently (g, systemroots[i]);
1429   }
1430
1431   if (!systemroot) {
1432     error (g, _("cannot resolve Windows %%SYSTEMROOT%%"));
1433     return -1;
1434   }
1435
1436   debug (g, "windows %%SYSTEMROOT%% = %s", systemroot);
1437
1438   /* Freed by guestfs___free_inspect_info. */
1439   fs->windows_systemroot = systemroot;
1440
1441   if (check_windows_arch (g, fs) == -1)
1442     return -1;
1443
1444   /* Product name and version. */
1445   if (check_windows_software_registry (g, fs) == -1)
1446     return -1;
1447
1448   check_package_format (g, fs);
1449   check_package_management (g, fs);
1450
1451   /* Hostname. */
1452   if (check_windows_system_registry (g, fs) == -1)
1453     return -1;
1454
1455   return 0;
1456 }
1457
1458 static int
1459 check_windows_arch (guestfs_h *g, struct inspect_fs *fs)
1460 {
1461   size_t len = strlen (fs->windows_systemroot) + 32;
1462   char cmd_exe[len];
1463   snprintf (cmd_exe, len, "%s/system32/cmd.exe", fs->windows_systemroot);
1464
1465   char *cmd_exe_path = case_sensitive_path_silently (g, cmd_exe);
1466   if (!cmd_exe_path)
1467     return 0;
1468
1469   char *arch = guestfs_file_architecture (g, cmd_exe_path);
1470   free (cmd_exe_path);
1471
1472   if (arch)
1473     fs->arch = arch;        /* freed by guestfs___free_inspect_info */
1474
1475   return 0;
1476 }
1477
1478 /* At the moment, pull just the ProductName and version numbers from
1479  * the registry.  In future there is a case for making many more
1480  * registry fields available to callers.
1481  */
1482 static int
1483 check_windows_software_registry (guestfs_h *g, struct inspect_fs *fs)
1484 {
1485   TMP_TEMPLATE_ON_STACK (software_local);
1486
1487   size_t len = strlen (fs->windows_systemroot) + 64;
1488   char software[len];
1489   snprintf (software, len, "%s/system32/config/software",
1490             fs->windows_systemroot);
1491
1492   char *software_path = case_sensitive_path_silently (g, software);
1493   if (!software_path)
1494     /* If the software hive doesn't exist, just accept that we cannot
1495      * find product_name etc.
1496      */
1497     return 0;
1498
1499   int ret = -1;
1500   hive_h *h = NULL;
1501   hive_value_h *values = NULL;
1502
1503   if (download_to_tmp (g, software_path, software_local,
1504                        MAX_REGISTRY_SIZE) == -1)
1505     goto out;
1506
1507   h = hivex_open (software_local, g->verbose ? HIVEX_OPEN_VERBOSE : 0);
1508   if (h == NULL) {
1509     perrorf (g, "hivex_open");
1510     goto out;
1511   }
1512
1513   hive_node_h node = hivex_root (h);
1514   const char *hivepath[] =
1515     { "Microsoft", "Windows NT", "CurrentVersion" };
1516   size_t i;
1517   for (i = 0;
1518        node != 0 && i < sizeof hivepath / sizeof hivepath[0];
1519        ++i) {
1520     node = hivex_node_get_child (h, node, hivepath[i]);
1521   }
1522
1523   if (node == 0) {
1524     perrorf (g, "hivex: cannot locate HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
1525     goto out;
1526   }
1527
1528   values = hivex_node_values (h, node);
1529
1530   for (i = 0; values[i] != 0; ++i) {
1531     char *key = hivex_value_key (h, values[i]);
1532     if (key == NULL) {
1533       perrorf (g, "hivex_value_key");
1534       goto out;
1535     }
1536
1537     if (STRCASEEQ (key, "ProductName")) {
1538       fs->product_name = hivex_value_string (h, values[i]);
1539       if (!fs->product_name) {
1540         perrorf (g, "hivex_value_string");
1541         free (key);
1542         goto out;
1543       }
1544     }
1545     else if (STRCASEEQ (key, "CurrentVersion")) {
1546       char *version = hivex_value_string (h, values[i]);
1547       if (!version) {
1548         perrorf (g, "hivex_value_string");
1549         free (key);
1550         goto out;
1551       }
1552       char *major, *minor;
1553       if (match2 (g, version, re_windows_version, &major, &minor)) {
1554         fs->major_version = parse_unsigned_int (g, major);
1555         free (major);
1556         if (fs->major_version == -1) {
1557           free (minor);
1558           free (key);
1559           free (version);
1560           goto out;
1561         }
1562         fs->minor_version = parse_unsigned_int (g, minor);
1563         free (minor);
1564         if (fs->minor_version == -1) {
1565           free (key);
1566           free (version);
1567           goto out;
1568         }
1569       }
1570
1571       free (version);
1572     }
1573     else if (STRCASEEQ (key, "InstallationType")) {
1574       fs->product_variant = hivex_value_string (h, values[i]);
1575       if (!fs->product_variant) {
1576         perrorf (g, "hivex_value_string");
1577         free (key);
1578         goto out;
1579       }
1580     }
1581
1582     free (key);
1583   }
1584
1585   ret = 0;
1586
1587  out:
1588   if (h) hivex_close (h);
1589   free (values);
1590   free (software_path);
1591
1592   /* Free up the temporary file. */
1593   unlink (software_local);
1594 #undef software_local_len
1595
1596   return ret;
1597 }
1598
1599 static int
1600 check_windows_system_registry (guestfs_h *g, struct inspect_fs *fs)
1601 {
1602   TMP_TEMPLATE_ON_STACK (system_local);
1603
1604   size_t len = strlen (fs->windows_systemroot) + 64;
1605   char system[len];
1606   snprintf (system, len, "%s/system32/config/system",
1607             fs->windows_systemroot);
1608
1609   char *system_path = case_sensitive_path_silently (g, system);
1610   if (!system_path)
1611     /* If the system hive doesn't exist, just accept that we cannot
1612      * find hostname etc.
1613      */
1614     return 0;
1615
1616   int ret = -1;
1617   hive_h *h = NULL;
1618   hive_node_h root, node;
1619   hive_value_h value, *values = NULL;
1620   int32_t dword;
1621   size_t i, count;
1622
1623   if (download_to_tmp (g, system_path, system_local, MAX_REGISTRY_SIZE) == -1)
1624     goto out;
1625
1626   h = hivex_open (system_local, g->verbose ? HIVEX_OPEN_VERBOSE : 0);
1627   if (h == NULL) {
1628     perrorf (g, "hivex_open");
1629     goto out;
1630   }
1631
1632   root = hivex_root (h);
1633   if (root == 0) {
1634     perrorf (g, "hivex_root");
1635     goto out;
1636   }
1637
1638   /* Get the CurrentControlSet. */
1639   errno = 0;
1640   node = hivex_node_get_child (h, root, "Select");
1641   if (node == 0) {
1642     if (errno != 0)
1643       perrorf (g, "hivex_node_get_child");
1644     else
1645       error (g, "hivex: could not locate HKLM\\SYSTEM\\Select");
1646     goto out;
1647   }
1648
1649   errno = 0;
1650   value = hivex_node_get_value (h, node, "Current");
1651   if (value == 0) {
1652     if (errno != 0)
1653       perrorf (g, "hivex_node_get_value");
1654     else
1655       error (g, "hivex: HKLM\\System\\Select Default entry not found.");
1656     goto out;
1657   }
1658
1659   /* XXX Should check the type. */
1660   dword = hivex_value_dword (h, value);
1661   fs->windows_current_control_set = safe_asprintf (g, "ControlSet%03d", dword);
1662
1663   /* Get the drive mappings.
1664    * This page explains the contents of HKLM\System\MountedDevices:
1665    * http://www.goodells.net/multiboot/partsigs.shtml
1666    */
1667   errno = 0;
1668   node = hivex_node_get_child (h, root, "MountedDevices");
1669   if (node == 0) {
1670     if (errno != 0)
1671       perrorf (g, "hivex_node_get_child");
1672     else
1673       error (g, "hivex: could not locate HKLM\\SYSTEM\\MountedDevices");
1674     goto out;
1675   }
1676
1677   values = hivex_node_values (h, node);
1678
1679   /* Count how many DOS drive letter mappings there are.  This doesn't
1680    * ignore removable devices, so it overestimates, but that doesn't
1681    * matter because it just means we'll allocate a few bytes extra.
1682    */
1683   for (i = count = 0; values[i] != 0; ++i) {
1684     char *key = hivex_value_key (h, values[i]);
1685     if (key == NULL) {
1686       perrorf (g, "hivex_value_key");
1687       goto out;
1688     }
1689     if (STRCASEEQLEN (key, "\\DosDevices\\", 12) &&
1690         c_isalpha (key[12]) && key[13] == ':')
1691       count++;
1692   }
1693
1694   fs->drive_mappings = calloc (2*count + 1, sizeof (char *));
1695   if (fs->drive_mappings == NULL) {
1696     perrorf (g, "calloc");
1697     goto out;
1698   }
1699
1700   for (i = count = 0; values[i] != 0; ++i) {
1701     char *key = hivex_value_key (h, values[i]);
1702     if (key == NULL) {
1703       perrorf (g, "hivex_value_key");
1704       goto out;
1705     }
1706     if (STRCASEEQLEN (key, "\\DosDevices\\", 12) &&
1707         c_isalpha (key[12]) && key[13] == ':') {
1708       /* Get the binary value.  Is it a fixed disk? */
1709       char *blob, *device;
1710       size_t len;
1711       hive_type type;
1712
1713       blob = hivex_value_value (h, values[i], &type, &len);
1714       if (blob != NULL && type == 3 && len == 12) {
1715         /* Try to map the blob to a known disk and partition. */
1716         device = map_registry_disk_blob (g, blob);
1717         if (device != NULL) {
1718           fs->drive_mappings[count++] = safe_strndup (g, &key[12], 1);
1719           fs->drive_mappings[count++] = device;
1720         }
1721       }
1722       free (blob);
1723     }
1724   }
1725
1726   /* Get the hostname. */
1727   const char *hivepath[] =
1728     { fs->windows_current_control_set, "Services", "Tcpip", "Parameters" };
1729   for (node = root, i = 0;
1730        node != 0 && i < sizeof hivepath / sizeof hivepath[0];
1731        ++i) {
1732     node = hivex_node_get_child (h, node, hivepath[i]);
1733   }
1734
1735   if (node == 0) {
1736     perrorf (g, "hivex: cannot locate HKLM\\SYSTEM\\%s\\Services\\Tcpip\\Parameters",
1737              fs->windows_current_control_set);
1738     goto out;
1739   }
1740
1741   values = hivex_node_values (h, node);
1742
1743   for (i = 0; values[i] != 0; ++i) {
1744     char *key = hivex_value_key (h, values[i]);
1745     if (key == NULL) {
1746       perrorf (g, "hivex_value_key");
1747       goto out;
1748     }
1749
1750     if (STRCASEEQ (key, "Hostname")) {
1751       fs->hostname = hivex_value_string (h, values[i]);
1752       if (!fs->hostname) {
1753         perrorf (g, "hivex_value_string");
1754         free (key);
1755         goto out;
1756       }
1757     }
1758     /* many other interesting fields here ... */
1759
1760     free (key);
1761   }
1762
1763   ret = 0;
1764
1765  out:
1766   if (h) hivex_close (h);
1767   free (values);
1768   free (system_path);
1769
1770   /* Free up the temporary file. */
1771   unlink (system_local);
1772 #undef system_local_len
1773
1774   return ret;
1775 }
1776
1777 /* Windows Registry HKLM\SYSTEM\MountedDevices uses a blob of data
1778  * to store partitions.  This blob is described here:
1779  * http://www.goodells.net/multiboot/partsigs.shtml
1780  * The following function maps this blob to a libguestfs partition
1781  * name, if possible.
1782  */
1783 static char *
1784 map_registry_disk_blob (guestfs_h *g, const char *blob)
1785 {
1786   char **devices = NULL;
1787   struct guestfs_partition_list *partitions = NULL;
1788   char *diskid;
1789   size_t i, j, len;
1790   char *ret = NULL;
1791   uint64_t part_offset;
1792
1793   /* First 4 bytes are the disk ID.  Search all devices to find the
1794    * disk with this disk ID.
1795    */
1796   devices = guestfs_list_devices (g);
1797   if (devices == NULL)
1798     goto out;
1799
1800   for (i = 0; devices[i] != NULL; ++i) {
1801     /* Read the disk ID. */
1802     diskid = guestfs_pread_device (g, devices[i], 4, 0x01b8, &len);
1803     if (diskid == NULL)
1804       continue;
1805     if (len < 4) {
1806       free (diskid);
1807       continue;
1808     }
1809     if (memcmp (diskid, blob, 4) == 0) { /* found it */
1810       free (diskid);
1811       goto found_disk;
1812     }
1813     free (diskid);
1814   }
1815   goto out;
1816
1817  found_disk:
1818   /* Next 8 bytes are the offset of the partition in bytes(!) given as
1819    * a 64 bit little endian number.  Luckily it's easy to get the
1820    * partition byte offset from guestfs_part_list.
1821    */
1822   part_offset = le64toh (* (uint64_t *) &blob[4]);
1823
1824   partitions = guestfs_part_list (g, devices[i]);
1825   if (partitions == NULL)
1826     goto out;
1827
1828   for (j = 0; j < partitions->len; ++j) {
1829     if (partitions->val[j].part_start == part_offset) /* found it */
1830       goto found_partition;
1831   }
1832   goto out;
1833
1834  found_partition:
1835   /* Construct the full device name. */
1836   ret = safe_asprintf (g, "%s%d", devices[i], partitions->val[j].part_num);
1837
1838  out:
1839   if (devices)
1840     guestfs___free_string_list (devices);
1841   if (partitions)
1842     guestfs_free_partition_list (partitions);
1843   return ret;
1844 }
1845
1846 static char *
1847 case_sensitive_path_silently (guestfs_h *g, const char *path)
1848 {
1849   guestfs_error_handler_cb old_error_cb = g->error_cb;
1850   g->error_cb = NULL;
1851   char *ret = guestfs_case_sensitive_path (g, path);
1852   g->error_cb = old_error_cb;
1853   return ret;
1854 }
1855
1856 static int
1857 is_file_nocase (guestfs_h *g, const char *path)
1858 {
1859   char *p;
1860   int r;
1861
1862   p = case_sensitive_path_silently (g, path);
1863   if (!p)
1864     return 0;
1865   r = guestfs_is_file (g, p);
1866   free (p);
1867   return r > 0;
1868 }
1869
1870 static int
1871 is_dir_nocase (guestfs_h *g, const char *path)
1872 {
1873   char *p;
1874   int r;
1875
1876   p = case_sensitive_path_silently (g, path);
1877   if (!p)
1878     return 0;
1879   r = guestfs_is_dir (g, p);
1880   free (p);
1881   return r > 0;
1882 }
1883
1884 static int
1885 extend_fses (guestfs_h *g)
1886 {
1887   size_t n = g->nr_fses + 1;
1888   struct inspect_fs *p;
1889
1890   p = realloc (g->fses, n * sizeof (struct inspect_fs));
1891   if (p == NULL) {
1892     perrorf (g, "realloc");
1893     return -1;
1894   }
1895
1896   g->fses = p;
1897   g->nr_fses = n;
1898
1899   memset (&g->fses[n-1], 0, sizeof (struct inspect_fs));
1900
1901   return 0;
1902 }
1903
1904 /* Parse small, unsigned ints, as used in version numbers. */
1905 static int
1906 parse_unsigned_int (guestfs_h *g, const char *str)
1907 {
1908   long ret;
1909   int r = xstrtol (str, NULL, 10, &ret, "");
1910   if (r != LONGINT_OK) {
1911     error (g, _("could not parse integer in version number: %s"), str);
1912     return -1;
1913   }
1914   return ret;
1915 }
1916
1917 /* Like parse_unsigned_int, but ignore trailing stuff. */
1918 static int
1919 parse_unsigned_int_ignore_trailing (guestfs_h *g, const char *str)
1920 {
1921   long ret;
1922   int r = xstrtol (str, NULL, 10, &ret, NULL);
1923   if (r != LONGINT_OK) {
1924     error (g, _("could not parse integer in version number: %s"), str);
1925     return -1;
1926   }
1927   return ret;
1928 }
1929
1930 /* At the moment, package format and package management is just a
1931  * simple function of the distro and major_version fields, so these
1932  * can never return an error.  We might be cleverer in future.
1933  */
1934 static void
1935 check_package_format (guestfs_h *g, struct inspect_fs *fs)
1936 {
1937   switch (fs->distro) {
1938   case OS_DISTRO_FEDORA:
1939   case OS_DISTRO_MEEGO:
1940   case OS_DISTRO_REDHAT_BASED:
1941   case OS_DISTRO_RHEL:
1942   case OS_DISTRO_MANDRIVA:
1943     fs->package_format = OS_PACKAGE_FORMAT_RPM;
1944     break;
1945
1946   case OS_DISTRO_DEBIAN:
1947   case OS_DISTRO_UBUNTU:
1948   case OS_DISTRO_LINUX_MINT:
1949     fs->package_format = OS_PACKAGE_FORMAT_DEB;
1950     break;
1951
1952   case OS_DISTRO_ARCHLINUX:
1953     fs->package_format = OS_PACKAGE_FORMAT_PACMAN;
1954     break;
1955   case OS_DISTRO_GENTOO:
1956     fs->package_format = OS_PACKAGE_FORMAT_EBUILD;
1957     break;
1958   case OS_DISTRO_PARDUS:
1959     fs->package_format = OS_PACKAGE_FORMAT_PISI;
1960     break;
1961
1962   case OS_DISTRO_SLACKWARE:
1963   case OS_DISTRO_WINDOWS:
1964   case OS_DISTRO_UNKNOWN:
1965   default:
1966     fs->package_format = OS_PACKAGE_FORMAT_UNKNOWN;
1967     break;
1968   }
1969 }
1970
1971 static void
1972 check_package_management (guestfs_h *g, struct inspect_fs *fs)
1973 {
1974   switch (fs->distro) {
1975   case OS_DISTRO_FEDORA:
1976   case OS_DISTRO_MEEGO:
1977     fs->package_management = OS_PACKAGE_MANAGEMENT_YUM;
1978     break;
1979
1980   case OS_DISTRO_REDHAT_BASED:
1981   case OS_DISTRO_RHEL:
1982     if (fs->major_version >= 5)
1983       fs->package_management = OS_PACKAGE_MANAGEMENT_YUM;
1984     else
1985       fs->package_management = OS_PACKAGE_MANAGEMENT_UP2DATE;
1986     break;
1987
1988   case OS_DISTRO_DEBIAN:
1989   case OS_DISTRO_UBUNTU:
1990   case OS_DISTRO_LINUX_MINT:
1991     fs->package_management = OS_PACKAGE_MANAGEMENT_APT;
1992     break;
1993
1994   case OS_DISTRO_ARCHLINUX:
1995     fs->package_management = OS_PACKAGE_MANAGEMENT_PACMAN;
1996     break;
1997   case OS_DISTRO_GENTOO:
1998     fs->package_management = OS_PACKAGE_MANAGEMENT_PORTAGE;
1999     break;
2000   case OS_DISTRO_PARDUS:
2001     fs->package_management = OS_PACKAGE_MANAGEMENT_PISI;
2002     break;
2003   case OS_DISTRO_MANDRIVA:
2004     fs->package_management = OS_PACKAGE_MANAGEMENT_URPMI;
2005     break;
2006
2007   case OS_DISTRO_SLACKWARE:
2008   case OS_DISTRO_WINDOWS:
2009   case OS_DISTRO_UNKNOWN:
2010   default:
2011     fs->package_management = OS_PACKAGE_MANAGEMENT_UNKNOWN;
2012     break;
2013   }
2014 }
2015
2016 static struct inspect_fs *
2017 search_for_root (guestfs_h *g, const char *root)
2018 {
2019   if (g->nr_fses == 0) {
2020     error (g, _("no inspection data: call guestfs_inspect_os first"));
2021     return NULL;
2022   }
2023
2024   size_t i;
2025   struct inspect_fs *fs;
2026   for (i = 0; i < g->nr_fses; ++i) {
2027     fs = &g->fses[i];
2028     if (fs->is_root && STREQ (root, fs->device))
2029       return fs;
2030   }
2031
2032   error (g, _("%s: root device not found: only call this function with a root device previously returned by guestfs_inspect_os"),
2033          root);
2034   return NULL;
2035 }
2036
2037 char **
2038 guestfs__inspect_get_roots (guestfs_h *g)
2039 {
2040   /* NB. Doesn't matter if g->nr_fses == 0.  We just return an empty
2041    * list in this case.
2042    */
2043
2044   size_t i;
2045   size_t count = 0;
2046   for (i = 0; i < g->nr_fses; ++i)
2047     if (g->fses[i].is_root)
2048       count++;
2049
2050   char **ret = calloc (count+1, sizeof (char *));
2051   if (ret == NULL) {
2052     perrorf (g, "calloc");
2053     return NULL;
2054   }
2055
2056   count = 0;
2057   for (i = 0; i < g->nr_fses; ++i) {
2058     if (g->fses[i].is_root) {
2059       ret[count] = safe_strdup (g, g->fses[i].device);
2060       count++;
2061     }
2062   }
2063   ret[count] = NULL;
2064
2065   return ret;
2066 }
2067
2068 char *
2069 guestfs__inspect_get_type (guestfs_h *g, const char *root)
2070 {
2071   struct inspect_fs *fs = search_for_root (g, root);
2072   if (!fs)
2073     return NULL;
2074
2075   char *ret;
2076   switch (fs->type) {
2077   case OS_TYPE_LINUX: ret = safe_strdup (g, "linux"); break;
2078   case OS_TYPE_WINDOWS: ret = safe_strdup (g, "windows"); break;
2079   case OS_TYPE_FREEBSD: ret = safe_strdup (g, "freebsd"); break;
2080   case OS_TYPE_UNKNOWN: default: ret = safe_strdup (g, "unknown"); break;
2081   }
2082
2083   return ret;
2084 }
2085
2086 char *
2087 guestfs__inspect_get_arch (guestfs_h *g, const char *root)
2088 {
2089   struct inspect_fs *fs = search_for_root (g, root);
2090   if (!fs)
2091     return NULL;
2092
2093   return safe_strdup (g, fs->arch ? : "unknown");
2094 }
2095
2096 char *
2097 guestfs__inspect_get_distro (guestfs_h *g, const char *root)
2098 {
2099   struct inspect_fs *fs = search_for_root (g, root);
2100   if (!fs)
2101     return NULL;
2102
2103   char *ret;
2104   switch (fs->distro) {
2105   case OS_DISTRO_ARCHLINUX: ret = safe_strdup (g, "archlinux"); break;
2106   case OS_DISTRO_DEBIAN: ret = safe_strdup (g, "debian"); break;
2107   case OS_DISTRO_FEDORA: ret = safe_strdup (g, "fedora"); break;
2108   case OS_DISTRO_GENTOO: ret = safe_strdup (g, "gentoo"); break;
2109   case OS_DISTRO_LINUX_MINT: ret = safe_strdup (g, "linuxmint"); break;
2110   case OS_DISTRO_MANDRIVA: ret = safe_strdup (g, "mandriva"); break;
2111   case OS_DISTRO_MEEGO: ret = safe_strdup (g, "meego"); break;
2112   case OS_DISTRO_PARDUS: ret = safe_strdup (g, "pardus"); break;
2113   case OS_DISTRO_REDHAT_BASED: ret = safe_strdup (g, "redhat-based"); break;
2114   case OS_DISTRO_RHEL: ret = safe_strdup (g, "rhel"); break;
2115   case OS_DISTRO_SLACKWARE: ret = safe_strdup (g, "slackware"); break;
2116   case OS_DISTRO_WINDOWS: ret = safe_strdup (g, "windows"); break;
2117   case OS_DISTRO_UBUNTU: ret = safe_strdup (g, "ubuntu"); break;
2118   case OS_DISTRO_UNKNOWN: default: ret = safe_strdup (g, "unknown"); break;
2119   }
2120
2121   return ret;
2122 }
2123
2124 int
2125 guestfs__inspect_get_major_version (guestfs_h *g, const char *root)
2126 {
2127   struct inspect_fs *fs = search_for_root (g, root);
2128   if (!fs)
2129     return -1;
2130
2131   return fs->major_version;
2132 }
2133
2134 int
2135 guestfs__inspect_get_minor_version (guestfs_h *g, const char *root)
2136 {
2137   struct inspect_fs *fs = search_for_root (g, root);
2138   if (!fs)
2139     return -1;
2140
2141   return fs->minor_version;
2142 }
2143
2144 char *
2145 guestfs__inspect_get_product_name (guestfs_h *g, const char *root)
2146 {
2147   struct inspect_fs *fs = search_for_root (g, root);
2148   if (!fs)
2149     return NULL;
2150
2151   return safe_strdup (g, fs->product_name ? : "unknown");
2152 }
2153
2154 char *
2155 guestfs__inspect_get_product_variant (guestfs_h *g, const char *root)
2156 {
2157   struct inspect_fs *fs = search_for_root (g, root);
2158   if (!fs)
2159     return NULL;
2160
2161   return safe_strdup (g, fs->product_variant ? : "unknown");
2162 }
2163
2164 char *
2165 guestfs__inspect_get_windows_systemroot (guestfs_h *g, const char *root)
2166 {
2167   struct inspect_fs *fs = search_for_root (g, root);
2168   if (!fs)
2169     return NULL;
2170
2171   if (!fs->windows_systemroot) {
2172     error (g, _("not a Windows guest, or systemroot could not be determined"));
2173     return NULL;
2174   }
2175
2176   return safe_strdup (g, fs->windows_systemroot);
2177 }
2178
2179 char *
2180 guestfs__inspect_get_windows_current_control_set (guestfs_h *g,
2181                                                   const char *root)
2182 {
2183   struct inspect_fs *fs = search_for_root (g, root);
2184   if (!fs)
2185     return NULL;
2186
2187   if (!fs->windows_current_control_set) {
2188     error (g, _("not a Windows guest, or CurrentControlSet could not be determined"));
2189     return NULL;
2190   }
2191
2192   return safe_strdup (g, fs->windows_current_control_set);
2193 }
2194
2195 char *
2196 guestfs__inspect_get_format (guestfs_h *g, const char *root)
2197 {
2198   struct inspect_fs *fs = search_for_root (g, root);
2199   if (!fs)
2200     return NULL;
2201
2202   char *ret;
2203   switch (fs->format) {
2204   case OS_FORMAT_INSTALLED: ret = safe_strdup (g, "installed"); break;
2205   case OS_FORMAT_INSTALLER: ret = safe_strdup (g, "installer"); break;
2206   case OS_FORMAT_UNKNOWN: default: ret = safe_strdup (g, "unknown"); break;
2207   }
2208
2209   return ret;
2210 }
2211
2212 int
2213 guestfs__inspect_is_live (guestfs_h *g, const char *root)
2214 {
2215   struct inspect_fs *fs = search_for_root (g, root);
2216   if (!fs)
2217     return -1;
2218
2219   return fs->is_live_disk;
2220 }
2221
2222 int
2223 guestfs__inspect_is_netinst (guestfs_h *g, const char *root)
2224 {
2225   struct inspect_fs *fs = search_for_root (g, root);
2226   if (!fs)
2227     return -1;
2228
2229   return fs->is_netinst_disk;
2230 }
2231
2232 int
2233 guestfs__inspect_is_multipart (guestfs_h *g, const char *root)
2234 {
2235   struct inspect_fs *fs = search_for_root (g, root);
2236   if (!fs)
2237     return -1;
2238
2239   return fs->is_multipart_disk;
2240 }
2241
2242 char **
2243 guestfs__inspect_get_mountpoints (guestfs_h *g, const char *root)
2244 {
2245   struct inspect_fs *fs = search_for_root (g, root);
2246   if (!fs)
2247     return NULL;
2248
2249   char **ret;
2250
2251   /* If no fstab information (Windows) return just the root. */
2252   if (fs->nr_fstab == 0) {
2253     ret = calloc (3, sizeof (char *));
2254     ret[0] = safe_strdup (g, "/");
2255     ret[1] = safe_strdup (g, root);
2256     ret[2] = NULL;
2257     return ret;
2258   }
2259
2260 #define CRITERION fs->fstab[i].mountpoint[0] == '/'
2261   size_t i, count = 0;
2262   for (i = 0; i < fs->nr_fstab; ++i)
2263     if (CRITERION)
2264       count++;
2265
2266   /* Hashtables have 2N+1 entries. */
2267   ret = calloc (2*count+1, sizeof (char *));
2268   if (ret == NULL) {
2269     perrorf (g, "calloc");
2270     return NULL;
2271   }
2272
2273   count = 0;
2274   for (i = 0; i < fs->nr_fstab; ++i)
2275     if (CRITERION) {
2276       ret[2*count] = safe_strdup (g, fs->fstab[i].mountpoint);
2277       ret[2*count+1] = safe_strdup (g, fs->fstab[i].device);
2278       count++;
2279     }
2280 #undef CRITERION
2281
2282   return ret;
2283 }
2284
2285 char **
2286 guestfs__inspect_get_filesystems (guestfs_h *g, const char *root)
2287 {
2288   struct inspect_fs *fs = search_for_root (g, root);
2289   if (!fs)
2290     return NULL;
2291
2292   char **ret;
2293
2294   /* If no fstab information (Windows) return just the root. */
2295   if (fs->nr_fstab == 0) {
2296     ret = calloc (2, sizeof (char *));
2297     ret[0] = safe_strdup (g, root);
2298     ret[1] = NULL;
2299     return ret;
2300   }
2301
2302   ret = calloc (fs->nr_fstab + 1, sizeof (char *));
2303   if (ret == NULL) {
2304     perrorf (g, "calloc");
2305     return NULL;
2306   }
2307
2308   size_t i;
2309   for (i = 0; i < fs->nr_fstab; ++i)
2310     ret[i] = safe_strdup (g, fs->fstab[i].device);
2311
2312   return ret;
2313 }
2314
2315 char **
2316 guestfs__inspect_get_drive_mappings (guestfs_h *g, const char *root)
2317 {
2318   char **ret;
2319   size_t i, count;
2320   struct inspect_fs *fs;
2321
2322   fs = search_for_root (g, root);
2323   if (!fs)
2324     return NULL;
2325
2326   /* If no drive mappings, return an empty hashtable. */
2327   if (!fs->drive_mappings)
2328     count = 0;
2329   else {
2330     for (count = 0; fs->drive_mappings[count] != NULL; count++)
2331       ;
2332   }
2333
2334   ret = calloc (count+1, sizeof (char *));
2335   if (ret == NULL) {
2336     perrorf (g, "calloc");
2337     return NULL;
2338   }
2339
2340   /* We need to make a deep copy of the hashtable since the caller
2341    * will free it.
2342    */
2343   for (i = 0; i < count; ++i)
2344     ret[i] = safe_strdup (g, fs->drive_mappings[i]);
2345
2346   ret[count] = NULL;
2347
2348   return ret;
2349 }
2350
2351 char *
2352 guestfs__inspect_get_package_format (guestfs_h *g, const char *root)
2353 {
2354   struct inspect_fs *fs = search_for_root (g, root);
2355   if (!fs)
2356     return NULL;
2357
2358   char *ret;
2359   switch (fs->package_format) {
2360   case OS_PACKAGE_FORMAT_RPM: ret = safe_strdup (g, "rpm"); break;
2361   case OS_PACKAGE_FORMAT_DEB: ret = safe_strdup (g, "deb"); break;
2362   case OS_PACKAGE_FORMAT_PACMAN: ret = safe_strdup (g, "pacman"); break;
2363   case OS_PACKAGE_FORMAT_EBUILD: ret = safe_strdup (g, "ebuild"); break;
2364   case OS_PACKAGE_FORMAT_PISI: ret = safe_strdup (g, "pisi"); break;
2365   case OS_PACKAGE_FORMAT_UNKNOWN:
2366   default:
2367     ret = safe_strdup (g, "unknown");
2368     break;
2369   }
2370
2371   return ret;
2372 }
2373
2374 char *
2375 guestfs__inspect_get_package_management (guestfs_h *g, const char *root)
2376 {
2377   struct inspect_fs *fs = search_for_root (g, root);
2378   if (!fs)
2379     return NULL;
2380
2381   char *ret;
2382   switch (fs->package_management) {
2383   case OS_PACKAGE_MANAGEMENT_YUM: ret = safe_strdup (g, "yum"); break;
2384   case OS_PACKAGE_MANAGEMENT_UP2DATE: ret = safe_strdup (g, "up2date"); break;
2385   case OS_PACKAGE_MANAGEMENT_APT: ret = safe_strdup (g, "apt"); break;
2386   case OS_PACKAGE_MANAGEMENT_PACMAN: ret = safe_strdup (g, "pacman"); break;
2387   case OS_PACKAGE_MANAGEMENT_PORTAGE: ret = safe_strdup (g, "portage"); break;
2388   case OS_PACKAGE_MANAGEMENT_PISI: ret = safe_strdup (g, "pisi"); break;
2389   case OS_PACKAGE_MANAGEMENT_URPMI: ret = safe_strdup (g, "urpmi"); break;
2390   case OS_PACKAGE_MANAGEMENT_UNKNOWN:
2391   default:
2392     ret = safe_strdup (g, "unknown");
2393     break;
2394   }
2395
2396   return ret;
2397 }
2398
2399 char *
2400 guestfs__inspect_get_hostname (guestfs_h *g, const char *root)
2401 {
2402   struct inspect_fs *fs = search_for_root (g, root);
2403   if (!fs)
2404     return NULL;
2405
2406   return safe_strdup (g, fs->hostname ? : "unknown");
2407 }
2408
2409 #ifdef DB_DUMP
2410 static struct guestfs_application_list *list_applications_rpm (guestfs_h *g, struct inspect_fs *fs);
2411 #endif
2412 static struct guestfs_application_list *list_applications_deb (guestfs_h *g, struct inspect_fs *fs);
2413 static struct guestfs_application_list *list_applications_windows (guestfs_h *g, struct inspect_fs *fs);
2414 static void add_application (guestfs_h *g, struct guestfs_application_list *, const char *name, const char *display_name, int32_t epoch, const char *version, const char *release, const char *install_path, const char *publisher, const char *url, const char *description);
2415 static void sort_applications (struct guestfs_application_list *);
2416
2417 /* Unlike the simple inspect-get-* calls, this one assumes that the
2418  * disks are mounted up, and reads files from the mounted disks.
2419  */
2420 struct guestfs_application_list *
2421 guestfs__inspect_list_applications (guestfs_h *g, const char *root)
2422 {
2423   struct inspect_fs *fs = search_for_root (g, root);
2424   if (!fs)
2425     return NULL;
2426
2427   struct guestfs_application_list *ret = NULL;
2428
2429   /* Presently we can only list applications for installed disks.  It
2430    * is possible in future to get lists of packages from installers.
2431    */
2432   if (fs->format == OS_FORMAT_INSTALLED) {
2433     switch (fs->type) {
2434     case OS_TYPE_LINUX:
2435       switch (fs->package_format) {
2436       case OS_PACKAGE_FORMAT_RPM:
2437 #ifdef DB_DUMP
2438         ret = list_applications_rpm (g, fs);
2439         if (ret == NULL)
2440           return NULL;
2441 #endif
2442         break;
2443
2444       case OS_PACKAGE_FORMAT_DEB:
2445         ret = list_applications_deb (g, fs);
2446         if (ret == NULL)
2447           return NULL;
2448         break;
2449
2450       case OS_PACKAGE_FORMAT_PACMAN:
2451       case OS_PACKAGE_FORMAT_EBUILD:
2452       case OS_PACKAGE_FORMAT_PISI:
2453       case OS_PACKAGE_FORMAT_UNKNOWN:
2454       default:
2455         /* nothing - keep GCC happy */;
2456       }
2457       break;
2458
2459     case OS_TYPE_WINDOWS:
2460       ret = list_applications_windows (g, fs);
2461       if (ret == NULL)
2462         return NULL;
2463       break;
2464
2465     case OS_TYPE_FREEBSD:
2466     case OS_TYPE_UNKNOWN:
2467     default:
2468       /* nothing - keep GCC happy */;
2469     }
2470   }
2471
2472   if (ret == NULL) {
2473     /* Don't know how to do inspection.  Not an error, return an
2474      * empty list.
2475      */
2476     ret = safe_malloc (g, sizeof *ret);
2477     ret->len = 0;
2478     ret->val = NULL;
2479   }
2480
2481   sort_applications (ret);
2482
2483   return ret;
2484 }
2485
2486 #ifdef DB_DUMP
2487 static struct guestfs_application_list *
2488 list_applications_rpm (guestfs_h *g, struct inspect_fs *fs)
2489 {
2490   TMP_TEMPLATE_ON_STACK (tmpfile);
2491
2492   if (download_to_tmp (g, "/var/lib/rpm/Name", tmpfile, MAX_PKG_DB_SIZE) == -1)
2493     return NULL;
2494
2495   struct guestfs_application_list *apps = NULL, *ret = NULL;
2496 #define cmd_len (strlen (tmpfile) + 64)
2497   char cmd[cmd_len];
2498   FILE *pp = NULL;
2499   char line[1024];
2500   size_t len;
2501
2502   snprintf (cmd, cmd_len, DB_DUMP " -p '%s'", tmpfile);
2503
2504   debug (g, "list_applications_rpm: %s", cmd);
2505
2506   pp = popen (cmd, "r");
2507   if (pp == NULL) {
2508     perrorf (g, "popen: %s", cmd);
2509     goto out;
2510   }
2511
2512   /* Ignore everything to end-of-header marker. */
2513   for (;;) {
2514     if (fgets (line, sizeof line, pp) == NULL) {
2515       error (g, _("unexpected end of output from db_dump command"));
2516       goto out;
2517     }
2518
2519     len = strlen (line);
2520     if (len > 0 && line[len-1] == '\n') {
2521       line[len-1] = '\0';
2522       len--;
2523     }
2524
2525     if (STREQ (line, "HEADER=END"))
2526       break;
2527   }
2528
2529   /* Allocate 'apps' list. */
2530   apps = safe_malloc (g, sizeof *apps);
2531   apps->len = 0;
2532   apps->val = NULL;
2533
2534   /* Read alternate lines until end of data marker. */
2535   for (;;) {
2536     if (fgets (line, sizeof line, pp) == NULL) {
2537       error (g, _("unexpected end of output from db_dump command"));
2538       goto out;
2539     }
2540
2541     len = strlen (line);
2542     if (len > 0 && line[len-1] == '\n') {
2543       line[len-1] = '\0';
2544       len--;
2545     }
2546
2547     if (STREQ (line, "DATA=END"))
2548       break;
2549
2550     char *p = line;
2551     if (len > 0 && line[0] == ' ')
2552       p = line+1;
2553     /* Ignore any application name that contains non-printable chars.
2554      * In the db_dump output these would be escaped with backslash, so
2555      * we can just ignore any such line.
2556      */
2557     if (strchr (p, '\\') == NULL)
2558       add_application (g, apps, p, "", 0, "", "", "", "", "", "");
2559
2560     /* Discard next line. */
2561     if (fgets (line, sizeof line, pp) == NULL) {
2562       error (g, _("unexpected end of output from db_dump command"));
2563       goto out;
2564     }
2565   }
2566
2567   /* Catch errors from the db_dump command. */
2568   if (pclose (pp) == -1) {
2569     perrorf (g, "pclose: %s", cmd);
2570     goto out;
2571   }
2572   pp = NULL;
2573
2574   ret = apps;
2575
2576  out:
2577   if (ret == NULL && apps != NULL)
2578     guestfs_free_application_list (apps);
2579   if (pp)
2580     pclose (pp);
2581   unlink (tmpfile);
2582 #undef cmd_len
2583
2584   return ret;
2585 }
2586 #endif /* defined DB_DUMP */
2587
2588 static struct guestfs_application_list *
2589 list_applications_deb (guestfs_h *g, struct inspect_fs *fs)
2590 {
2591   TMP_TEMPLATE_ON_STACK (tmpfile);
2592
2593   if (download_to_tmp (g, "/var/lib/dpkg/status", tmpfile,
2594                        MAX_PKG_DB_SIZE) == -1)
2595     return NULL;
2596
2597   struct guestfs_application_list *apps = NULL, *ret = NULL;
2598   FILE *fp = NULL;
2599   char line[1024];
2600   size_t len;
2601   char *name = NULL, *version = NULL, *release = NULL;
2602   int installed_flag = 0;
2603
2604   fp = fopen (tmpfile, "r");
2605   if (fp == NULL) {
2606     perrorf (g, "fopen: %s", tmpfile);
2607     goto out;
2608   }
2609
2610   /* Allocate 'apps' list. */
2611   apps = safe_malloc (g, sizeof *apps);
2612   apps->len = 0;
2613   apps->val = NULL;
2614
2615   /* Read the temporary file.  Each package entry is separated by
2616    * a blank line.
2617    * XXX Strictly speaking this is in mailbox header format, so it
2618    * would be possible for fields to spread across multiple lines,
2619    * although for the short fields that we are concerned about this is
2620    * unlikely and not seen in practice.
2621    */
2622   while (fgets (line, sizeof line, fp) != NULL) {
2623     len = strlen (line);
2624     if (len > 0 && line[len-1] == '\n') {
2625       line[len-1] = '\0';
2626       len--;
2627     }
2628
2629     if (STRPREFIX (line, "Package: ")) {
2630       free (name);
2631       name = safe_strdup (g, &line[9]);
2632     }
2633     else if (STRPREFIX (line, "Status: ")) {
2634       installed_flag = strstr (&line[8], "installed") != NULL;
2635     }
2636     else if (STRPREFIX (line, "Version: ")) {
2637       free (version);
2638       free (release);
2639       char *p = strchr (&line[9], '-');
2640       if (p) {
2641         *p = '\0';
2642         version = safe_strdup (g, &line[9]);
2643         release = safe_strdup (g, p+1);
2644       } else {
2645         version = safe_strdup (g, &line[9]);
2646         release = NULL;
2647       }
2648     }
2649     else if (STREQ (line, "")) {
2650       if (installed_flag && name && version)
2651         add_application (g, apps, name, "", 0, version, release ? : "",
2652                          "", "", "", "");
2653       free (name);
2654       free (version);
2655       free (release);
2656       name = version = release = NULL;
2657       installed_flag = 0;
2658     }
2659   }
2660
2661   if (fclose (fp) == -1) {
2662     perrorf (g, "fclose: %s", tmpfile);
2663     goto out;
2664   }
2665   fp = NULL;
2666
2667   ret = apps;
2668
2669  out:
2670   if (ret == NULL && apps != NULL)
2671     guestfs_free_application_list (apps);
2672   if (fp)
2673     fclose (fp);
2674   free (name);
2675   free (version);
2676   free (release);
2677   unlink (tmpfile);
2678   return ret;
2679 }
2680
2681 static void list_applications_windows_from_path (guestfs_h *g, hive_h *h, struct guestfs_application_list *apps, const char **path, size_t path_len);
2682
2683 static struct guestfs_application_list *
2684 list_applications_windows (guestfs_h *g, struct inspect_fs *fs)
2685 {
2686   TMP_TEMPLATE_ON_STACK (software_local);
2687
2688   /* XXX We already download the SOFTWARE hive when doing general
2689    * inspection.  We could avoid this second download of the same file
2690    * by caching these entries in the handle.
2691    */
2692   size_t len = strlen (fs->windows_systemroot) + 64;
2693   char software[len];
2694   snprintf (software, len, "%s/system32/config/software",
2695             fs->windows_systemroot);
2696
2697   char *software_path = case_sensitive_path_silently (g, software);
2698   if (!software_path)
2699     /* If the software hive doesn't exist, just accept that we cannot
2700      * find product_name etc.
2701      */
2702     return 0;
2703
2704   struct guestfs_application_list *ret = NULL;
2705   hive_h *h = NULL;
2706
2707   if (download_to_tmp (g, software_path, software_local,
2708                        MAX_REGISTRY_SIZE) == -1)
2709     goto out;
2710
2711   free (software_path);
2712   software_path = NULL;
2713
2714   h = hivex_open (software_local, g->verbose ? HIVEX_OPEN_VERBOSE : 0);
2715   if (h == NULL) {
2716     perrorf (g, "hivex_open");
2717     goto out;
2718   }
2719
2720   /* Allocate apps list. */
2721   ret = safe_malloc (g, sizeof *ret);
2722   ret->len = 0;
2723   ret->val = NULL;
2724
2725   /* Ordinary native applications. */
2726   const char *hivepath[] =
2727     { "Microsoft", "Windows", "CurrentVersion", "Uninstall" };
2728   list_applications_windows_from_path (g, h, ret, hivepath,
2729                                        sizeof hivepath / sizeof hivepath[0]);
2730
2731   /* 32-bit emulated Windows apps running on the WOW64 emulator.
2732    * http://support.microsoft.com/kb/896459 (RHBZ#692545).
2733    */
2734   const char *hivepath2[] =
2735     { "WOW6432node", "Microsoft", "Windows", "CurrentVersion", "Uninstall" };
2736   list_applications_windows_from_path (g, h, ret, hivepath2,
2737                                        sizeof hivepath2 / sizeof hivepath2[0]);
2738
2739  out:
2740   if (h) hivex_close (h);
2741   free (software_path);
2742
2743   /* Delete the temporary file. */
2744   unlink (software_local);
2745 #undef software_local_len
2746
2747   return ret;
2748 }
2749
2750 static void
2751 list_applications_windows_from_path (guestfs_h *g, hive_h *h,
2752                                      struct guestfs_application_list *apps,
2753                                      const char **path, size_t path_len)
2754 {
2755   hive_node_h *children = NULL;
2756   hive_node_h node;
2757   size_t i;
2758
2759   node = hivex_root (h);
2760
2761   for (i = 0; node != 0 && i < path_len; ++i)
2762     node = hivex_node_get_child (h, node, path[i]);
2763
2764   if (node == 0)
2765     return;
2766
2767   children = hivex_node_children (h, node);
2768   if (children == NULL)
2769     return;
2770
2771   /* Consider any child node that has a DisplayName key.
2772    * See also:
2773    * http://nsis.sourceforge.net/Add_uninstall_information_to_Add/Remove_Programs#Optional_values
2774    */
2775   for (i = 0; children[i] != 0; ++i) {
2776     hive_value_h value;
2777     char *name = NULL;
2778     char *display_name = NULL;
2779     char *version = NULL;
2780     char *install_path = NULL;
2781     char *publisher = NULL;
2782     char *url = NULL;
2783     char *comments = NULL;
2784
2785     /* Use the node name as a proxy for the package name in Linux.  The
2786      * display name is not language-independent, so it cannot be used.
2787      */
2788     name = hivex_node_name (h, children[i]);
2789     if (name == NULL)
2790       continue;
2791
2792     value = hivex_node_get_value (h, children[i], "DisplayName");
2793     if (value) {
2794       display_name = hivex_value_string (h, value);
2795       if (display_name) {
2796         value = hivex_node_get_value (h, children[i], "DisplayVersion");
2797         if (value)
2798           version = hivex_value_string (h, value);
2799         value = hivex_node_get_value (h, children[i], "InstallLocation");
2800         if (value)
2801           install_path = hivex_value_string (h, value);
2802         value = hivex_node_get_value (h, children[i], "Publisher");
2803         if (value)
2804           publisher = hivex_value_string (h, value);
2805         value = hivex_node_get_value (h, children[i], "URLInfoAbout");
2806         if (value)
2807           url = hivex_value_string (h, value);
2808         value = hivex_node_get_value (h, children[i], "Comments");
2809         if (value)
2810           comments = hivex_value_string (h, value);
2811
2812         add_application (g, apps, name, display_name, 0,
2813                          version ? : "",
2814                          "",
2815                          install_path ? : "",
2816                          publisher ? : "",
2817                          url ? : "",
2818                          comments ? : "");
2819       }
2820     }
2821
2822     free (name);
2823     free (display_name);
2824     free (version);
2825     free (install_path);
2826     free (publisher);
2827     free (url);
2828     free (comments);
2829   }
2830
2831   free (children);
2832 }
2833
2834 static void
2835 add_application (guestfs_h *g, struct guestfs_application_list *apps,
2836                  const char *name, const char *display_name, int32_t epoch,
2837                  const char *version, const char *release,
2838                  const char *install_path,
2839                  const char *publisher, const char *url,
2840                  const char *description)
2841 {
2842   apps->len++;
2843   apps->val = safe_realloc (g, apps->val,
2844                             apps->len * sizeof (struct guestfs_application));
2845   apps->val[apps->len-1].app_name = safe_strdup (g, name);
2846   apps->val[apps->len-1].app_display_name = safe_strdup (g, display_name);
2847   apps->val[apps->len-1].app_epoch = epoch;
2848   apps->val[apps->len-1].app_version = safe_strdup (g, version);
2849   apps->val[apps->len-1].app_release = safe_strdup (g, release);
2850   apps->val[apps->len-1].app_install_path = safe_strdup (g, install_path);
2851   /* XXX Translated path is not implemented yet. */
2852   apps->val[apps->len-1].app_trans_path = safe_strdup (g, "");
2853   apps->val[apps->len-1].app_publisher = safe_strdup (g, publisher);
2854   apps->val[apps->len-1].app_url = safe_strdup (g, url);
2855   /* XXX The next two are not yet implemented for any package
2856    * format, but we could easily support them for rpm and deb.
2857    */
2858   apps->val[apps->len-1].app_source_package = safe_strdup (g, "");
2859   apps->val[apps->len-1].app_summary = safe_strdup (g, "");
2860   apps->val[apps->len-1].app_description = safe_strdup (g, description);
2861 }
2862
2863 /* Sort applications by name before returning the list. */
2864 static int
2865 compare_applications (const void *vp1, const void *vp2)
2866 {
2867   const struct guestfs_application *v1 = vp1;
2868   const struct guestfs_application *v2 = vp2;
2869
2870   return strcmp (v1->app_name, v2->app_name);
2871 }
2872
2873 static void
2874 sort_applications (struct guestfs_application_list *apps)
2875 {
2876   if (apps && apps->val)
2877     qsort (apps->val, apps->len, sizeof (struct guestfs_application),
2878            compare_applications);
2879 }
2880
2881 /* Download to a guest file to a local temporary file.  Refuse to
2882  * download the guest file if it is larger than max_size.  The caller
2883  * is responsible for deleting the temporary file after use.
2884  */
2885 static int
2886 download_to_tmp (guestfs_h *g, const char *filename,
2887                  char *localtmp, int64_t max_size)
2888 {
2889   int fd;
2890   char buf[32];
2891   int64_t size;
2892
2893   size = guestfs_filesize (g, filename);
2894   if (size == -1)
2895     /* guestfs_filesize failed and has already set error in handle */
2896     return -1;
2897   if (size > max_size) {
2898     error (g, _("size of %s is unreasonably large (%" PRIi64 " bytes)"),
2899            filename, size);
2900     return -1;
2901   }
2902
2903   fd = mkstemp (localtmp);
2904   if (fd == -1) {
2905     perrorf (g, "mkstemp");
2906     return -1;
2907   }
2908
2909   snprintf (buf, sizeof buf, "/dev/fd/%d", fd);
2910
2911   if (guestfs_download (g, filename, buf) == -1) {
2912     close (fd);
2913     unlink (localtmp);
2914     return -1;
2915   }
2916
2917   if (close (fd) == -1) {
2918     perrorf (g, "close: %s", localtmp);
2919     unlink (localtmp);
2920     return -1;
2921   }
2922
2923   return 0;
2924 }
2925
2926 /* Call 'f' with Augeas opened and having parsed 'filename' (this file
2927  * must exist).  As a security measure, this bails if the file is too
2928  * large for a reasonable configuration file.  After the call to 'f'
2929  * Augeas is closed.
2930  */
2931 static int
2932 inspect_with_augeas (guestfs_h *g, struct inspect_fs *fs, const char *filename,
2933                      int (*f) (guestfs_h *, struct inspect_fs *))
2934 {
2935   /* Security: Refuse to do this if filename is too large. */
2936   int64_t size = guestfs_filesize (g, filename);
2937   if (size == -1)
2938     /* guestfs_filesize failed and has already set error in handle */
2939     return -1;
2940   if (size > MAX_AUGEAS_FILE_SIZE) {
2941     error (g, _("size of %s is unreasonably large (%" PRIi64 " bytes)"),
2942            filename, size);
2943     return -1;
2944   }
2945
2946   /* If !feature_available (g, "augeas") then the next call will fail.
2947    * Arguably we might want to fall back to a non-Augeas method in
2948    * this case.
2949    */
2950   if (guestfs_aug_init (g, "/", 16|32) == -1)
2951     return -1;
2952
2953   int r = -1;
2954
2955   /* Tell Augeas to only load one file (thanks Raphaël Pinson). */
2956   char buf[strlen (filename) + 64];
2957   snprintf (buf, strlen (filename) + 64, "/augeas/load//incl[. != \"%s\"]",
2958             filename);
2959   if (guestfs_aug_rm (g, buf) == -1)
2960     goto out;
2961
2962   if (guestfs_aug_load (g) == -1)
2963     goto out;
2964
2965   r = f (g, fs);
2966
2967  out:
2968   guestfs_aug_close (g);
2969
2970   return r;
2971 }
2972
2973 /* Get the first line of a small file, without any trailing newline
2974  * character.
2975  */
2976 static char *
2977 first_line_of_file (guestfs_h *g, const char *filename)
2978 {
2979   char **lines;
2980   int64_t size;
2981   char *ret;
2982
2983   /* Don't trust guestfs_head_n not to break with very large files.
2984    * Check the file size is something reasonable first.
2985    */
2986   size = guestfs_filesize (g, filename);
2987   if (size == -1)
2988     /* guestfs_filesize failed and has already set error in handle */
2989     return NULL;
2990   if (size > MAX_SMALL_FILE_SIZE) {
2991     error (g, _("size of %s is unreasonably large (%" PRIi64 " bytes)"),
2992            filename, size);
2993     return NULL;
2994   }
2995
2996   lines = guestfs_head_n (g, 1, filename);
2997   if (lines == NULL)
2998     return NULL;
2999   if (lines[0] == NULL) {
3000     error (g, _("%s: file is empty"), filename);
3001     guestfs___free_string_list (lines);
3002     return NULL;
3003   }
3004   /* lines[1] should be NULL because of '1' argument above ... */
3005
3006   ret = lines[0];               /* caller frees */
3007   free (lines);                 /* free the array */
3008
3009   return ret;
3010 }
3011
3012 /* Get the first matching line (using guestfs_egrep{,i}) of a small file,
3013  * without any trailing newline character.
3014  *
3015  * Returns: 1 = returned a line (in *ret)
3016  *          0 = no match
3017  *          -1 = error
3018  */
3019 static int
3020 first_egrep_of_file (guestfs_h *g, const char *filename,
3021                      const char *eregex, int iflag, char **ret)
3022 {
3023   char **lines;
3024   int64_t size;
3025   size_t i;
3026
3027   /* Don't trust guestfs_egrep not to break with very large files.
3028    * Check the file size is something reasonable first.
3029    */
3030   size = guestfs_filesize (g, filename);
3031   if (size == -1)
3032     /* guestfs_filesize failed and has already set error in handle */
3033     return -1;
3034   if (size > MAX_SMALL_FILE_SIZE) {
3035     error (g, _("size of %s is unreasonably large (%" PRIi64 " bytes)"),
3036            filename, size);
3037     return -1;
3038   }
3039
3040   lines = (!iflag ? guestfs_egrep : guestfs_egrepi) (g, eregex, filename);
3041   if (lines == NULL)
3042     return -1;
3043   if (lines[0] == NULL) {
3044     guestfs___free_string_list (lines);
3045     return 0;
3046   }
3047
3048   *ret = lines[0];              /* caller frees */
3049
3050   /* free up any other matches and the array itself */
3051   for (i = 1; lines[i] != NULL; ++i)
3052     free (lines[i]);
3053   free (lines);
3054
3055   return 1;
3056 }
3057
3058 #else /* no PCRE or hivex at compile time */
3059
3060 /* XXX These functions should be in an optgroup. */
3061
3062 #define NOT_IMPL(r)                                                     \
3063   error (g, _("inspection API not available since this version of libguestfs was compiled without PCRE or hivex libraries")); \
3064   return r
3065
3066 char **
3067 guestfs__inspect_os (guestfs_h *g)
3068 {
3069   NOT_IMPL(NULL);
3070 }
3071
3072 char **
3073 guestfs__inspect_get_roots (guestfs_h *g)
3074 {
3075   NOT_IMPL(NULL);
3076 }
3077
3078 char *
3079 guestfs__inspect_get_type (guestfs_h *g, const char *root)
3080 {
3081   NOT_IMPL(NULL);
3082 }
3083
3084 char *
3085 guestfs__inspect_get_arch (guestfs_h *g, const char *root)
3086 {
3087   NOT_IMPL(NULL);
3088 }
3089
3090 char *
3091 guestfs__inspect_get_distro (guestfs_h *g, const char *root)
3092 {
3093   NOT_IMPL(NULL);
3094 }
3095
3096 int
3097 guestfs__inspect_get_major_version (guestfs_h *g, const char *root)
3098 {
3099   NOT_IMPL(-1);
3100 }
3101
3102 int
3103 guestfs__inspect_get_minor_version (guestfs_h *g, const char *root)
3104 {
3105   NOT_IMPL(-1);
3106 }
3107
3108 char *
3109 guestfs__inspect_get_product_name (guestfs_h *g, const char *root)
3110 {
3111   NOT_IMPL(NULL);
3112 }
3113
3114 char *
3115 guestfs__inspect_get_product_variant (guestfs_h *g, const char *root)
3116 {
3117   NOT_IMPL(NULL);
3118 }
3119
3120 char *
3121 guestfs__inspect_get_windows_systemroot (guestfs_h *g, const char *root)
3122 {
3123   NOT_IMPL(NULL);
3124 }
3125
3126 char *
3127 guestfs__inspect_get_windows_current_control_set (guestfs_h *g,
3128                                                   const char *root)
3129 {
3130   NOT_IMPL(NULL);
3131 }
3132
3133 char **
3134 guestfs__inspect_get_mountpoints (guestfs_h *g, const char *root)
3135 {
3136   NOT_IMPL(NULL);
3137 }
3138
3139 char **
3140 guestfs__inspect_get_filesystems (guestfs_h *g, const char *root)
3141 {
3142   NOT_IMPL(NULL);
3143 }
3144
3145 char **
3146 guestfs__inspect_get_drive_mappings (guestfs_h *g, const char *root)
3147 {
3148   NOT_IMPL(NULL);
3149 }
3150
3151 char *
3152 guestfs__inspect_get_package_format (guestfs_h *g, const char *root)
3153 {
3154   NOT_IMPL(NULL);
3155 }
3156
3157 char *
3158 guestfs__inspect_get_package_management (guestfs_h *g, const char *root)
3159 {
3160   NOT_IMPL(NULL);
3161 }
3162
3163 char *
3164 guestfs__inspect_get_hostname (guestfs_h *g, const char *root)
3165 {
3166   NOT_IMPL(NULL);
3167 }
3168
3169 struct guestfs_application_list *
3170 guestfs__inspect_list_applications (guestfs_h *g, const char *root)
3171 {
3172   NOT_IMPL(NULL);
3173 }
3174
3175 char *
3176 guestfs__inspect_get_format (guestfs_h *g, const char *root)
3177 {
3178   NOT_IMPL(NULL);
3179 }
3180
3181 int
3182 guestfs__inspect_is_live (guestfs_h *g, const char *root)
3183 {
3184   NOT_IMPL(-1);
3185 }
3186
3187 int
3188 guestfs__inspect_is_netinst (guestfs_h *g, const char *root)
3189 {
3190   NOT_IMPL(-1);
3191 }
3192
3193 int
3194 guestfs__inspect_is_multipart (guestfs_h *g, const char *root)
3195 {
3196   NOT_IMPL(-1);
3197 }
3198
3199 #endif /* no PCRE or hivex at compile time */
3200
3201 void
3202 guestfs___free_inspect_info (guestfs_h *g)
3203 {
3204   size_t i;
3205   for (i = 0; i < g->nr_fses; ++i) {
3206     free (g->fses[i].device);
3207     free (g->fses[i].product_name);
3208     free (g->fses[i].product_variant);
3209     free (g->fses[i].arch);
3210     free (g->fses[i].hostname);
3211     free (g->fses[i].windows_systemroot);
3212     free (g->fses[i].windows_current_control_set);
3213     size_t j;
3214     for (j = 0; j < g->fses[i].nr_fstab; ++j) {
3215       free (g->fses[i].fstab[j].device);
3216       free (g->fses[i].fstab[j].mountpoint);
3217     }
3218     free (g->fses[i].fstab);
3219     if (g->fses[i].drive_mappings)
3220       guestfs___free_string_list (g->fses[i].drive_mappings);
3221   }
3222   free (g->fses);
3223   g->nr_fses = 0;
3224   g->fses = NULL;
3225 }
3226
3227 /* In the Perl code this is a public function. */
3228 int
3229 guestfs___feature_available (guestfs_h *g, const char *feature)
3230 {
3231   /* If there's an error we should ignore it, so to do that we have to
3232    * temporarily replace the error handler with a null one.
3233    */
3234   guestfs_error_handler_cb old_error_cb = g->error_cb;
3235   g->error_cb = NULL;
3236
3237   const char *groups[] = { feature, NULL };
3238   int r = guestfs_available (g, (char * const *) groups);
3239
3240   g->error_cb = old_error_cb;
3241
3242   return r == 0 ? 1 : 0;
3243 }
3244
3245 #ifdef HAVE_PCRE
3246
3247 /* Match a regular expression which contains no captures.  Returns
3248  * true if it matches or false if it doesn't.
3249  */
3250 int
3251 guestfs___match (guestfs_h *g, const char *str, const pcre *re)
3252 {
3253   size_t len = strlen (str);
3254   int vec[30], r;
3255
3256   r = pcre_exec (re, NULL, str, len, 0, 0, vec, sizeof vec / sizeof vec[0]);
3257   if (r == PCRE_ERROR_NOMATCH)
3258     return 0;
3259   if (r != 1) {
3260     /* Internal error -- should not happen. */
3261     warning (g, "%s: %s: pcre_exec returned unexpected error code %d when matching against the string \"%s\"\n",
3262              __FILE__, __func__, r, str);
3263     return 0;
3264   }
3265
3266   return 1;
3267 }
3268
3269 /* Match a regular expression which contains exactly one capture.  If
3270  * the string matches, return the capture, otherwise return NULL.  The
3271  * caller must free the result.
3272  */
3273 char *
3274 guestfs___match1 (guestfs_h *g, const char *str, const pcre *re)
3275 {
3276   size_t len = strlen (str);
3277   int vec[30], r;
3278
3279   r = pcre_exec (re, NULL, str, len, 0, 0, vec, sizeof vec / sizeof vec[0]);
3280   if (r == PCRE_ERROR_NOMATCH)
3281     return NULL;
3282   if (r != 2) {
3283     /* Internal error -- should not happen. */
3284     warning (g, "%s: %s: internal error: pcre_exec returned unexpected error code %d when matching against the string \"%s\"",
3285              __FILE__, __func__, r, str);
3286     return NULL;
3287   }
3288
3289   return safe_strndup (g, &str[vec[2]], vec[3]-vec[2]);
3290 }
3291
3292 /* Match a regular expression which contains exactly two captures. */
3293 int
3294 guestfs___match2 (guestfs_h *g, const char *str, const pcre *re,
3295                   char **ret1, char **ret2)
3296 {
3297   size_t len = strlen (str);
3298   int vec[30], r;
3299
3300   r = pcre_exec (re, NULL, str, len, 0, 0, vec, 30);
3301   if (r == PCRE_ERROR_NOMATCH)
3302     return 0;
3303   if (r != 3) {
3304     /* Internal error -- should not happen. */
3305     warning (g, "%s: %s: internal error: pcre_exec returned unexpected error code %d when matching against the string \"%s\"",
3306              __FILE__, __func__, r, str);
3307     return 0;
3308   }
3309
3310   *ret1 = safe_strndup (g, &str[vec[2]], vec[3]-vec[2]);
3311   *ret2 = safe_strndup (g, &str[vec[4]], vec[5]-vec[4]);
3312
3313   return 1;
3314 }
3315
3316 /* Match a regular expression which contains exactly three captures. */
3317 int
3318 guestfs___match3 (guestfs_h *g, const char *str, const pcre *re,
3319                   char **ret1, char **ret2, char **ret3)
3320 {
3321   size_t len = strlen (str);
3322   int vec[30], r;
3323
3324   r = pcre_exec (re, NULL, str, len, 0, 0, vec, 30);
3325   if (r == PCRE_ERROR_NOMATCH)
3326     return 0;
3327   if (r != 4) {
3328     /* Internal error -- should not happen. */
3329     warning (g, "%s: %s: internal error: pcre_exec returned unexpected error code %d when matching against the string \"%s\"",
3330              __FILE__, __func__, r, str);
3331     return 0;
3332   }
3333
3334   *ret1 = safe_strndup (g, &str[vec[2]], vec[3]-vec[2]);
3335   *ret2 = safe_strndup (g, &str[vec[4]], vec[5]-vec[4]);
3336   *ret3 = safe_strndup (g, &str[vec[6]], vec[7]-vec[6]);
3337
3338   return 1;
3339 }
3340
3341 #endif /* HAVE_PCRE */