16baf0b2311d0922fb58c8b1342f6dbb69442bb8
[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     free (key);
1693   }
1694
1695   fs->drive_mappings = calloc (2*count + 1, sizeof (char *));
1696   if (fs->drive_mappings == NULL) {
1697     perrorf (g, "calloc");
1698     goto out;
1699   }
1700
1701   for (i = count = 0; values[i] != 0; ++i) {
1702     char *key = hivex_value_key (h, values[i]);
1703     if (key == NULL) {
1704       perrorf (g, "hivex_value_key");
1705       goto out;
1706     }
1707     if (STRCASEEQLEN (key, "\\DosDevices\\", 12) &&
1708         c_isalpha (key[12]) && key[13] == ':') {
1709       /* Get the binary value.  Is it a fixed disk? */
1710       char *blob, *device;
1711       size_t len;
1712       hive_type type;
1713
1714       blob = hivex_value_value (h, values[i], &type, &len);
1715       if (blob != NULL && type == 3 && len == 12) {
1716         /* Try to map the blob to a known disk and partition. */
1717         device = map_registry_disk_blob (g, blob);
1718         if (device != NULL) {
1719           fs->drive_mappings[count++] = safe_strndup (g, &key[12], 1);
1720           fs->drive_mappings[count++] = device;
1721         }
1722       }
1723       free (blob);
1724     }
1725     free (key);
1726   }
1727
1728   /* Get the hostname. */
1729   const char *hivepath[] =
1730     { fs->windows_current_control_set, "Services", "Tcpip", "Parameters" };
1731   for (node = root, i = 0;
1732        node != 0 && i < sizeof hivepath / sizeof hivepath[0];
1733        ++i) {
1734     node = hivex_node_get_child (h, node, hivepath[i]);
1735   }
1736
1737   if (node == 0) {
1738     perrorf (g, "hivex: cannot locate HKLM\\SYSTEM\\%s\\Services\\Tcpip\\Parameters",
1739              fs->windows_current_control_set);
1740     goto out;
1741   }
1742
1743   free (values);
1744   values = hivex_node_values (h, node);
1745
1746   for (i = 0; values[i] != 0; ++i) {
1747     char *key = hivex_value_key (h, values[i]);
1748     if (key == NULL) {
1749       perrorf (g, "hivex_value_key");
1750       goto out;
1751     }
1752
1753     if (STRCASEEQ (key, "Hostname")) {
1754       fs->hostname = hivex_value_string (h, values[i]);
1755       if (!fs->hostname) {
1756         perrorf (g, "hivex_value_string");
1757         free (key);
1758         goto out;
1759       }
1760     }
1761     /* many other interesting fields here ... */
1762
1763     free (key);
1764   }
1765
1766   ret = 0;
1767
1768  out:
1769   if (h) hivex_close (h);
1770   free (values);
1771   free (system_path);
1772
1773   /* Free up the temporary file. */
1774   unlink (system_local);
1775 #undef system_local_len
1776
1777   return ret;
1778 }
1779
1780 /* Windows Registry HKLM\SYSTEM\MountedDevices uses a blob of data
1781  * to store partitions.  This blob is described here:
1782  * http://www.goodells.net/multiboot/partsigs.shtml
1783  * The following function maps this blob to a libguestfs partition
1784  * name, if possible.
1785  */
1786 static char *
1787 map_registry_disk_blob (guestfs_h *g, const char *blob)
1788 {
1789   char **devices = NULL;
1790   struct guestfs_partition_list *partitions = NULL;
1791   char *diskid;
1792   size_t i, j, len;
1793   char *ret = NULL;
1794   uint64_t part_offset;
1795
1796   /* First 4 bytes are the disk ID.  Search all devices to find the
1797    * disk with this disk ID.
1798    */
1799   devices = guestfs_list_devices (g);
1800   if (devices == NULL)
1801     goto out;
1802
1803   for (i = 0; devices[i] != NULL; ++i) {
1804     /* Read the disk ID. */
1805     diskid = guestfs_pread_device (g, devices[i], 4, 0x01b8, &len);
1806     if (diskid == NULL)
1807       continue;
1808     if (len < 4) {
1809       free (diskid);
1810       continue;
1811     }
1812     if (memcmp (diskid, blob, 4) == 0) { /* found it */
1813       free (diskid);
1814       goto found_disk;
1815     }
1816     free (diskid);
1817   }
1818   goto out;
1819
1820  found_disk:
1821   /* Next 8 bytes are the offset of the partition in bytes(!) given as
1822    * a 64 bit little endian number.  Luckily it's easy to get the
1823    * partition byte offset from guestfs_part_list.
1824    */
1825   part_offset = le64toh (* (uint64_t *) &blob[4]);
1826
1827   partitions = guestfs_part_list (g, devices[i]);
1828   if (partitions == NULL)
1829     goto out;
1830
1831   for (j = 0; j < partitions->len; ++j) {
1832     if (partitions->val[j].part_start == part_offset) /* found it */
1833       goto found_partition;
1834   }
1835   goto out;
1836
1837  found_partition:
1838   /* Construct the full device name. */
1839   ret = safe_asprintf (g, "%s%d", devices[i], partitions->val[j].part_num);
1840
1841  out:
1842   if (devices)
1843     guestfs___free_string_list (devices);
1844   if (partitions)
1845     guestfs_free_partition_list (partitions);
1846   return ret;
1847 }
1848
1849 static char *
1850 case_sensitive_path_silently (guestfs_h *g, const char *path)
1851 {
1852   guestfs_error_handler_cb old_error_cb = g->error_cb;
1853   g->error_cb = NULL;
1854   char *ret = guestfs_case_sensitive_path (g, path);
1855   g->error_cb = old_error_cb;
1856   return ret;
1857 }
1858
1859 static int
1860 is_file_nocase (guestfs_h *g, const char *path)
1861 {
1862   char *p;
1863   int r;
1864
1865   p = case_sensitive_path_silently (g, path);
1866   if (!p)
1867     return 0;
1868   r = guestfs_is_file (g, p);
1869   free (p);
1870   return r > 0;
1871 }
1872
1873 static int
1874 is_dir_nocase (guestfs_h *g, const char *path)
1875 {
1876   char *p;
1877   int r;
1878
1879   p = case_sensitive_path_silently (g, path);
1880   if (!p)
1881     return 0;
1882   r = guestfs_is_dir (g, p);
1883   free (p);
1884   return r > 0;
1885 }
1886
1887 static int
1888 extend_fses (guestfs_h *g)
1889 {
1890   size_t n = g->nr_fses + 1;
1891   struct inspect_fs *p;
1892
1893   p = realloc (g->fses, n * sizeof (struct inspect_fs));
1894   if (p == NULL) {
1895     perrorf (g, "realloc");
1896     return -1;
1897   }
1898
1899   g->fses = p;
1900   g->nr_fses = n;
1901
1902   memset (&g->fses[n-1], 0, sizeof (struct inspect_fs));
1903
1904   return 0;
1905 }
1906
1907 /* Parse small, unsigned ints, as used in version numbers. */
1908 static int
1909 parse_unsigned_int (guestfs_h *g, const char *str)
1910 {
1911   long ret;
1912   int r = xstrtol (str, NULL, 10, &ret, "");
1913   if (r != LONGINT_OK) {
1914     error (g, _("could not parse integer in version number: %s"), str);
1915     return -1;
1916   }
1917   return ret;
1918 }
1919
1920 /* Like parse_unsigned_int, but ignore trailing stuff. */
1921 static int
1922 parse_unsigned_int_ignore_trailing (guestfs_h *g, const char *str)
1923 {
1924   long ret;
1925   int r = xstrtol (str, NULL, 10, &ret, NULL);
1926   if (r != LONGINT_OK) {
1927     error (g, _("could not parse integer in version number: %s"), str);
1928     return -1;
1929   }
1930   return ret;
1931 }
1932
1933 /* At the moment, package format and package management is just a
1934  * simple function of the distro and major_version fields, so these
1935  * can never return an error.  We might be cleverer in future.
1936  */
1937 static void
1938 check_package_format (guestfs_h *g, struct inspect_fs *fs)
1939 {
1940   switch (fs->distro) {
1941   case OS_DISTRO_FEDORA:
1942   case OS_DISTRO_MEEGO:
1943   case OS_DISTRO_REDHAT_BASED:
1944   case OS_DISTRO_RHEL:
1945   case OS_DISTRO_MANDRIVA:
1946     fs->package_format = OS_PACKAGE_FORMAT_RPM;
1947     break;
1948
1949   case OS_DISTRO_DEBIAN:
1950   case OS_DISTRO_UBUNTU:
1951   case OS_DISTRO_LINUX_MINT:
1952     fs->package_format = OS_PACKAGE_FORMAT_DEB;
1953     break;
1954
1955   case OS_DISTRO_ARCHLINUX:
1956     fs->package_format = OS_PACKAGE_FORMAT_PACMAN;
1957     break;
1958   case OS_DISTRO_GENTOO:
1959     fs->package_format = OS_PACKAGE_FORMAT_EBUILD;
1960     break;
1961   case OS_DISTRO_PARDUS:
1962     fs->package_format = OS_PACKAGE_FORMAT_PISI;
1963     break;
1964
1965   case OS_DISTRO_SLACKWARE:
1966   case OS_DISTRO_WINDOWS:
1967   case OS_DISTRO_UNKNOWN:
1968   default:
1969     fs->package_format = OS_PACKAGE_FORMAT_UNKNOWN;
1970     break;
1971   }
1972 }
1973
1974 static void
1975 check_package_management (guestfs_h *g, struct inspect_fs *fs)
1976 {
1977   switch (fs->distro) {
1978   case OS_DISTRO_FEDORA:
1979   case OS_DISTRO_MEEGO:
1980     fs->package_management = OS_PACKAGE_MANAGEMENT_YUM;
1981     break;
1982
1983   case OS_DISTRO_REDHAT_BASED:
1984   case OS_DISTRO_RHEL:
1985     if (fs->major_version >= 5)
1986       fs->package_management = OS_PACKAGE_MANAGEMENT_YUM;
1987     else
1988       fs->package_management = OS_PACKAGE_MANAGEMENT_UP2DATE;
1989     break;
1990
1991   case OS_DISTRO_DEBIAN:
1992   case OS_DISTRO_UBUNTU:
1993   case OS_DISTRO_LINUX_MINT:
1994     fs->package_management = OS_PACKAGE_MANAGEMENT_APT;
1995     break;
1996
1997   case OS_DISTRO_ARCHLINUX:
1998     fs->package_management = OS_PACKAGE_MANAGEMENT_PACMAN;
1999     break;
2000   case OS_DISTRO_GENTOO:
2001     fs->package_management = OS_PACKAGE_MANAGEMENT_PORTAGE;
2002     break;
2003   case OS_DISTRO_PARDUS:
2004     fs->package_management = OS_PACKAGE_MANAGEMENT_PISI;
2005     break;
2006   case OS_DISTRO_MANDRIVA:
2007     fs->package_management = OS_PACKAGE_MANAGEMENT_URPMI;
2008     break;
2009
2010   case OS_DISTRO_SLACKWARE:
2011   case OS_DISTRO_WINDOWS:
2012   case OS_DISTRO_UNKNOWN:
2013   default:
2014     fs->package_management = OS_PACKAGE_MANAGEMENT_UNKNOWN;
2015     break;
2016   }
2017 }
2018
2019 static struct inspect_fs *
2020 search_for_root (guestfs_h *g, const char *root)
2021 {
2022   if (g->nr_fses == 0) {
2023     error (g, _("no inspection data: call guestfs_inspect_os first"));
2024     return NULL;
2025   }
2026
2027   size_t i;
2028   struct inspect_fs *fs;
2029   for (i = 0; i < g->nr_fses; ++i) {
2030     fs = &g->fses[i];
2031     if (fs->is_root && STREQ (root, fs->device))
2032       return fs;
2033   }
2034
2035   error (g, _("%s: root device not found: only call this function with a root device previously returned by guestfs_inspect_os"),
2036          root);
2037   return NULL;
2038 }
2039
2040 char **
2041 guestfs__inspect_get_roots (guestfs_h *g)
2042 {
2043   /* NB. Doesn't matter if g->nr_fses == 0.  We just return an empty
2044    * list in this case.
2045    */
2046
2047   size_t i;
2048   size_t count = 0;
2049   for (i = 0; i < g->nr_fses; ++i)
2050     if (g->fses[i].is_root)
2051       count++;
2052
2053   char **ret = calloc (count+1, sizeof (char *));
2054   if (ret == NULL) {
2055     perrorf (g, "calloc");
2056     return NULL;
2057   }
2058
2059   count = 0;
2060   for (i = 0; i < g->nr_fses; ++i) {
2061     if (g->fses[i].is_root) {
2062       ret[count] = safe_strdup (g, g->fses[i].device);
2063       count++;
2064     }
2065   }
2066   ret[count] = NULL;
2067
2068   return ret;
2069 }
2070
2071 char *
2072 guestfs__inspect_get_type (guestfs_h *g, const char *root)
2073 {
2074   struct inspect_fs *fs = search_for_root (g, root);
2075   if (!fs)
2076     return NULL;
2077
2078   char *ret;
2079   switch (fs->type) {
2080   case OS_TYPE_LINUX: ret = safe_strdup (g, "linux"); break;
2081   case OS_TYPE_WINDOWS: ret = safe_strdup (g, "windows"); break;
2082   case OS_TYPE_FREEBSD: ret = safe_strdup (g, "freebsd"); break;
2083   case OS_TYPE_UNKNOWN: default: ret = safe_strdup (g, "unknown"); break;
2084   }
2085
2086   return ret;
2087 }
2088
2089 char *
2090 guestfs__inspect_get_arch (guestfs_h *g, const char *root)
2091 {
2092   struct inspect_fs *fs = search_for_root (g, root);
2093   if (!fs)
2094     return NULL;
2095
2096   return safe_strdup (g, fs->arch ? : "unknown");
2097 }
2098
2099 char *
2100 guestfs__inspect_get_distro (guestfs_h *g, const char *root)
2101 {
2102   struct inspect_fs *fs = search_for_root (g, root);
2103   if (!fs)
2104     return NULL;
2105
2106   char *ret;
2107   switch (fs->distro) {
2108   case OS_DISTRO_ARCHLINUX: ret = safe_strdup (g, "archlinux"); break;
2109   case OS_DISTRO_DEBIAN: ret = safe_strdup (g, "debian"); break;
2110   case OS_DISTRO_FEDORA: ret = safe_strdup (g, "fedora"); break;
2111   case OS_DISTRO_GENTOO: ret = safe_strdup (g, "gentoo"); break;
2112   case OS_DISTRO_LINUX_MINT: ret = safe_strdup (g, "linuxmint"); break;
2113   case OS_DISTRO_MANDRIVA: ret = safe_strdup (g, "mandriva"); break;
2114   case OS_DISTRO_MEEGO: ret = safe_strdup (g, "meego"); break;
2115   case OS_DISTRO_PARDUS: ret = safe_strdup (g, "pardus"); break;
2116   case OS_DISTRO_REDHAT_BASED: ret = safe_strdup (g, "redhat-based"); break;
2117   case OS_DISTRO_RHEL: ret = safe_strdup (g, "rhel"); break;
2118   case OS_DISTRO_SLACKWARE: ret = safe_strdup (g, "slackware"); break;
2119   case OS_DISTRO_WINDOWS: ret = safe_strdup (g, "windows"); break;
2120   case OS_DISTRO_UBUNTU: ret = safe_strdup (g, "ubuntu"); break;
2121   case OS_DISTRO_UNKNOWN: default: ret = safe_strdup (g, "unknown"); break;
2122   }
2123
2124   return ret;
2125 }
2126
2127 int
2128 guestfs__inspect_get_major_version (guestfs_h *g, const char *root)
2129 {
2130   struct inspect_fs *fs = search_for_root (g, root);
2131   if (!fs)
2132     return -1;
2133
2134   return fs->major_version;
2135 }
2136
2137 int
2138 guestfs__inspect_get_minor_version (guestfs_h *g, const char *root)
2139 {
2140   struct inspect_fs *fs = search_for_root (g, root);
2141   if (!fs)
2142     return -1;
2143
2144   return fs->minor_version;
2145 }
2146
2147 char *
2148 guestfs__inspect_get_product_name (guestfs_h *g, const char *root)
2149 {
2150   struct inspect_fs *fs = search_for_root (g, root);
2151   if (!fs)
2152     return NULL;
2153
2154   return safe_strdup (g, fs->product_name ? : "unknown");
2155 }
2156
2157 char *
2158 guestfs__inspect_get_product_variant (guestfs_h *g, const char *root)
2159 {
2160   struct inspect_fs *fs = search_for_root (g, root);
2161   if (!fs)
2162     return NULL;
2163
2164   return safe_strdup (g, fs->product_variant ? : "unknown");
2165 }
2166
2167 char *
2168 guestfs__inspect_get_windows_systemroot (guestfs_h *g, const char *root)
2169 {
2170   struct inspect_fs *fs = search_for_root (g, root);
2171   if (!fs)
2172     return NULL;
2173
2174   if (!fs->windows_systemroot) {
2175     error (g, _("not a Windows guest, or systemroot could not be determined"));
2176     return NULL;
2177   }
2178
2179   return safe_strdup (g, fs->windows_systemroot);
2180 }
2181
2182 char *
2183 guestfs__inspect_get_windows_current_control_set (guestfs_h *g,
2184                                                   const char *root)
2185 {
2186   struct inspect_fs *fs = search_for_root (g, root);
2187   if (!fs)
2188     return NULL;
2189
2190   if (!fs->windows_current_control_set) {
2191     error (g, _("not a Windows guest, or CurrentControlSet could not be determined"));
2192     return NULL;
2193   }
2194
2195   return safe_strdup (g, fs->windows_current_control_set);
2196 }
2197
2198 char *
2199 guestfs__inspect_get_format (guestfs_h *g, const char *root)
2200 {
2201   struct inspect_fs *fs = search_for_root (g, root);
2202   if (!fs)
2203     return NULL;
2204
2205   char *ret;
2206   switch (fs->format) {
2207   case OS_FORMAT_INSTALLED: ret = safe_strdup (g, "installed"); break;
2208   case OS_FORMAT_INSTALLER: ret = safe_strdup (g, "installer"); break;
2209   case OS_FORMAT_UNKNOWN: default: ret = safe_strdup (g, "unknown"); break;
2210   }
2211
2212   return ret;
2213 }
2214
2215 int
2216 guestfs__inspect_is_live (guestfs_h *g, const char *root)
2217 {
2218   struct inspect_fs *fs = search_for_root (g, root);
2219   if (!fs)
2220     return -1;
2221
2222   return fs->is_live_disk;
2223 }
2224
2225 int
2226 guestfs__inspect_is_netinst (guestfs_h *g, const char *root)
2227 {
2228   struct inspect_fs *fs = search_for_root (g, root);
2229   if (!fs)
2230     return -1;
2231
2232   return fs->is_netinst_disk;
2233 }
2234
2235 int
2236 guestfs__inspect_is_multipart (guestfs_h *g, const char *root)
2237 {
2238   struct inspect_fs *fs = search_for_root (g, root);
2239   if (!fs)
2240     return -1;
2241
2242   return fs->is_multipart_disk;
2243 }
2244
2245 char **
2246 guestfs__inspect_get_mountpoints (guestfs_h *g, const char *root)
2247 {
2248   struct inspect_fs *fs = search_for_root (g, root);
2249   if (!fs)
2250     return NULL;
2251
2252   char **ret;
2253
2254   /* If no fstab information (Windows) return just the root. */
2255   if (fs->nr_fstab == 0) {
2256     ret = calloc (3, sizeof (char *));
2257     ret[0] = safe_strdup (g, "/");
2258     ret[1] = safe_strdup (g, root);
2259     ret[2] = NULL;
2260     return ret;
2261   }
2262
2263 #define CRITERION fs->fstab[i].mountpoint[0] == '/'
2264   size_t i, count = 0;
2265   for (i = 0; i < fs->nr_fstab; ++i)
2266     if (CRITERION)
2267       count++;
2268
2269   /* Hashtables have 2N+1 entries. */
2270   ret = calloc (2*count+1, sizeof (char *));
2271   if (ret == NULL) {
2272     perrorf (g, "calloc");
2273     return NULL;
2274   }
2275
2276   count = 0;
2277   for (i = 0; i < fs->nr_fstab; ++i)
2278     if (CRITERION) {
2279       ret[2*count] = safe_strdup (g, fs->fstab[i].mountpoint);
2280       ret[2*count+1] = safe_strdup (g, fs->fstab[i].device);
2281       count++;
2282     }
2283 #undef CRITERION
2284
2285   return ret;
2286 }
2287
2288 char **
2289 guestfs__inspect_get_filesystems (guestfs_h *g, const char *root)
2290 {
2291   struct inspect_fs *fs = search_for_root (g, root);
2292   if (!fs)
2293     return NULL;
2294
2295   char **ret;
2296
2297   /* If no fstab information (Windows) return just the root. */
2298   if (fs->nr_fstab == 0) {
2299     ret = calloc (2, sizeof (char *));
2300     ret[0] = safe_strdup (g, root);
2301     ret[1] = NULL;
2302     return ret;
2303   }
2304
2305   ret = calloc (fs->nr_fstab + 1, sizeof (char *));
2306   if (ret == NULL) {
2307     perrorf (g, "calloc");
2308     return NULL;
2309   }
2310
2311   size_t i;
2312   for (i = 0; i < fs->nr_fstab; ++i)
2313     ret[i] = safe_strdup (g, fs->fstab[i].device);
2314
2315   return ret;
2316 }
2317
2318 char **
2319 guestfs__inspect_get_drive_mappings (guestfs_h *g, const char *root)
2320 {
2321   char **ret;
2322   size_t i, count;
2323   struct inspect_fs *fs;
2324
2325   fs = search_for_root (g, root);
2326   if (!fs)
2327     return NULL;
2328
2329   /* If no drive mappings, return an empty hashtable. */
2330   if (!fs->drive_mappings)
2331     count = 0;
2332   else {
2333     for (count = 0; fs->drive_mappings[count] != NULL; count++)
2334       ;
2335   }
2336
2337   ret = calloc (count+1, sizeof (char *));
2338   if (ret == NULL) {
2339     perrorf (g, "calloc");
2340     return NULL;
2341   }
2342
2343   /* We need to make a deep copy of the hashtable since the caller
2344    * will free it.
2345    */
2346   for (i = 0; i < count; ++i)
2347     ret[i] = safe_strdup (g, fs->drive_mappings[i]);
2348
2349   ret[count] = NULL;
2350
2351   return ret;
2352 }
2353
2354 char *
2355 guestfs__inspect_get_package_format (guestfs_h *g, const char *root)
2356 {
2357   struct inspect_fs *fs = search_for_root (g, root);
2358   if (!fs)
2359     return NULL;
2360
2361   char *ret;
2362   switch (fs->package_format) {
2363   case OS_PACKAGE_FORMAT_RPM: ret = safe_strdup (g, "rpm"); break;
2364   case OS_PACKAGE_FORMAT_DEB: ret = safe_strdup (g, "deb"); break;
2365   case OS_PACKAGE_FORMAT_PACMAN: ret = safe_strdup (g, "pacman"); break;
2366   case OS_PACKAGE_FORMAT_EBUILD: ret = safe_strdup (g, "ebuild"); break;
2367   case OS_PACKAGE_FORMAT_PISI: ret = safe_strdup (g, "pisi"); break;
2368   case OS_PACKAGE_FORMAT_UNKNOWN:
2369   default:
2370     ret = safe_strdup (g, "unknown");
2371     break;
2372   }
2373
2374   return ret;
2375 }
2376
2377 char *
2378 guestfs__inspect_get_package_management (guestfs_h *g, const char *root)
2379 {
2380   struct inspect_fs *fs = search_for_root (g, root);
2381   if (!fs)
2382     return NULL;
2383
2384   char *ret;
2385   switch (fs->package_management) {
2386   case OS_PACKAGE_MANAGEMENT_YUM: ret = safe_strdup (g, "yum"); break;
2387   case OS_PACKAGE_MANAGEMENT_UP2DATE: ret = safe_strdup (g, "up2date"); break;
2388   case OS_PACKAGE_MANAGEMENT_APT: ret = safe_strdup (g, "apt"); break;
2389   case OS_PACKAGE_MANAGEMENT_PACMAN: ret = safe_strdup (g, "pacman"); break;
2390   case OS_PACKAGE_MANAGEMENT_PORTAGE: ret = safe_strdup (g, "portage"); break;
2391   case OS_PACKAGE_MANAGEMENT_PISI: ret = safe_strdup (g, "pisi"); break;
2392   case OS_PACKAGE_MANAGEMENT_URPMI: ret = safe_strdup (g, "urpmi"); break;
2393   case OS_PACKAGE_MANAGEMENT_UNKNOWN:
2394   default:
2395     ret = safe_strdup (g, "unknown");
2396     break;
2397   }
2398
2399   return ret;
2400 }
2401
2402 char *
2403 guestfs__inspect_get_hostname (guestfs_h *g, const char *root)
2404 {
2405   struct inspect_fs *fs = search_for_root (g, root);
2406   if (!fs)
2407     return NULL;
2408
2409   return safe_strdup (g, fs->hostname ? : "unknown");
2410 }
2411
2412 #ifdef DB_DUMP
2413 static struct guestfs_application_list *list_applications_rpm (guestfs_h *g, struct inspect_fs *fs);
2414 #endif
2415 static struct guestfs_application_list *list_applications_deb (guestfs_h *g, struct inspect_fs *fs);
2416 static struct guestfs_application_list *list_applications_windows (guestfs_h *g, struct inspect_fs *fs);
2417 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);
2418 static void sort_applications (struct guestfs_application_list *);
2419
2420 /* Unlike the simple inspect-get-* calls, this one assumes that the
2421  * disks are mounted up, and reads files from the mounted disks.
2422  */
2423 struct guestfs_application_list *
2424 guestfs__inspect_list_applications (guestfs_h *g, const char *root)
2425 {
2426   struct inspect_fs *fs = search_for_root (g, root);
2427   if (!fs)
2428     return NULL;
2429
2430   struct guestfs_application_list *ret = NULL;
2431
2432   /* Presently we can only list applications for installed disks.  It
2433    * is possible in future to get lists of packages from installers.
2434    */
2435   if (fs->format == OS_FORMAT_INSTALLED) {
2436     switch (fs->type) {
2437     case OS_TYPE_LINUX:
2438       switch (fs->package_format) {
2439       case OS_PACKAGE_FORMAT_RPM:
2440 #ifdef DB_DUMP
2441         ret = list_applications_rpm (g, fs);
2442         if (ret == NULL)
2443           return NULL;
2444 #endif
2445         break;
2446
2447       case OS_PACKAGE_FORMAT_DEB:
2448         ret = list_applications_deb (g, fs);
2449         if (ret == NULL)
2450           return NULL;
2451         break;
2452
2453       case OS_PACKAGE_FORMAT_PACMAN:
2454       case OS_PACKAGE_FORMAT_EBUILD:
2455       case OS_PACKAGE_FORMAT_PISI:
2456       case OS_PACKAGE_FORMAT_UNKNOWN:
2457       default:
2458         /* nothing - keep GCC happy */;
2459       }
2460       break;
2461
2462     case OS_TYPE_WINDOWS:
2463       ret = list_applications_windows (g, fs);
2464       if (ret == NULL)
2465         return NULL;
2466       break;
2467
2468     case OS_TYPE_FREEBSD:
2469     case OS_TYPE_UNKNOWN:
2470     default:
2471       /* nothing - keep GCC happy */;
2472     }
2473   }
2474
2475   if (ret == NULL) {
2476     /* Don't know how to do inspection.  Not an error, return an
2477      * empty list.
2478      */
2479     ret = safe_malloc (g, sizeof *ret);
2480     ret->len = 0;
2481     ret->val = NULL;
2482   }
2483
2484   sort_applications (ret);
2485
2486   return ret;
2487 }
2488
2489 #ifdef DB_DUMP
2490 static struct guestfs_application_list *
2491 list_applications_rpm (guestfs_h *g, struct inspect_fs *fs)
2492 {
2493   TMP_TEMPLATE_ON_STACK (tmpfile);
2494
2495   if (download_to_tmp (g, "/var/lib/rpm/Name", tmpfile, MAX_PKG_DB_SIZE) == -1)
2496     return NULL;
2497
2498   struct guestfs_application_list *apps = NULL, *ret = NULL;
2499 #define cmd_len (strlen (tmpfile) + 64)
2500   char cmd[cmd_len];
2501   FILE *pp = NULL;
2502   char line[1024];
2503   size_t len;
2504
2505   snprintf (cmd, cmd_len, DB_DUMP " -p '%s'", tmpfile);
2506
2507   debug (g, "list_applications_rpm: %s", cmd);
2508
2509   pp = popen (cmd, "r");
2510   if (pp == NULL) {
2511     perrorf (g, "popen: %s", cmd);
2512     goto out;
2513   }
2514
2515   /* Ignore everything to end-of-header marker. */
2516   for (;;) {
2517     if (fgets (line, sizeof line, pp) == NULL) {
2518       error (g, _("unexpected end of output from db_dump command"));
2519       goto out;
2520     }
2521
2522     len = strlen (line);
2523     if (len > 0 && line[len-1] == '\n') {
2524       line[len-1] = '\0';
2525       len--;
2526     }
2527
2528     if (STREQ (line, "HEADER=END"))
2529       break;
2530   }
2531
2532   /* Allocate 'apps' list. */
2533   apps = safe_malloc (g, sizeof *apps);
2534   apps->len = 0;
2535   apps->val = NULL;
2536
2537   /* Read alternate lines until end of data marker. */
2538   for (;;) {
2539     if (fgets (line, sizeof line, pp) == NULL) {
2540       error (g, _("unexpected end of output from db_dump command"));
2541       goto out;
2542     }
2543
2544     len = strlen (line);
2545     if (len > 0 && line[len-1] == '\n') {
2546       line[len-1] = '\0';
2547       len--;
2548     }
2549
2550     if (STREQ (line, "DATA=END"))
2551       break;
2552
2553     char *p = line;
2554     if (len > 0 && line[0] == ' ')
2555       p = line+1;
2556     /* Ignore any application name that contains non-printable chars.
2557      * In the db_dump output these would be escaped with backslash, so
2558      * we can just ignore any such line.
2559      */
2560     if (strchr (p, '\\') == NULL)
2561       add_application (g, apps, p, "", 0, "", "", "", "", "", "");
2562
2563     /* Discard next line. */
2564     if (fgets (line, sizeof line, pp) == NULL) {
2565       error (g, _("unexpected end of output from db_dump command"));
2566       goto out;
2567     }
2568   }
2569
2570   /* Catch errors from the db_dump command. */
2571   if (pclose (pp) == -1) {
2572     perrorf (g, "pclose: %s", cmd);
2573     goto out;
2574   }
2575   pp = NULL;
2576
2577   ret = apps;
2578
2579  out:
2580   if (ret == NULL && apps != NULL)
2581     guestfs_free_application_list (apps);
2582   if (pp)
2583     pclose (pp);
2584   unlink (tmpfile);
2585 #undef cmd_len
2586
2587   return ret;
2588 }
2589 #endif /* defined DB_DUMP */
2590
2591 static struct guestfs_application_list *
2592 list_applications_deb (guestfs_h *g, struct inspect_fs *fs)
2593 {
2594   TMP_TEMPLATE_ON_STACK (tmpfile);
2595
2596   if (download_to_tmp (g, "/var/lib/dpkg/status", tmpfile,
2597                        MAX_PKG_DB_SIZE) == -1)
2598     return NULL;
2599
2600   struct guestfs_application_list *apps = NULL, *ret = NULL;
2601   FILE *fp = NULL;
2602   char line[1024];
2603   size_t len;
2604   char *name = NULL, *version = NULL, *release = NULL;
2605   int installed_flag = 0;
2606
2607   fp = fopen (tmpfile, "r");
2608   if (fp == NULL) {
2609     perrorf (g, "fopen: %s", tmpfile);
2610     goto out;
2611   }
2612
2613   /* Allocate 'apps' list. */
2614   apps = safe_malloc (g, sizeof *apps);
2615   apps->len = 0;
2616   apps->val = NULL;
2617
2618   /* Read the temporary file.  Each package entry is separated by
2619    * a blank line.
2620    * XXX Strictly speaking this is in mailbox header format, so it
2621    * would be possible for fields to spread across multiple lines,
2622    * although for the short fields that we are concerned about this is
2623    * unlikely and not seen in practice.
2624    */
2625   while (fgets (line, sizeof line, fp) != NULL) {
2626     len = strlen (line);
2627     if (len > 0 && line[len-1] == '\n') {
2628       line[len-1] = '\0';
2629       len--;
2630     }
2631
2632     if (STRPREFIX (line, "Package: ")) {
2633       free (name);
2634       name = safe_strdup (g, &line[9]);
2635     }
2636     else if (STRPREFIX (line, "Status: ")) {
2637       installed_flag = strstr (&line[8], "installed") != NULL;
2638     }
2639     else if (STRPREFIX (line, "Version: ")) {
2640       free (version);
2641       free (release);
2642       char *p = strchr (&line[9], '-');
2643       if (p) {
2644         *p = '\0';
2645         version = safe_strdup (g, &line[9]);
2646         release = safe_strdup (g, p+1);
2647       } else {
2648         version = safe_strdup (g, &line[9]);
2649         release = NULL;
2650       }
2651     }
2652     else if (STREQ (line, "")) {
2653       if (installed_flag && name && version)
2654         add_application (g, apps, name, "", 0, version, release ? : "",
2655                          "", "", "", "");
2656       free (name);
2657       free (version);
2658       free (release);
2659       name = version = release = NULL;
2660       installed_flag = 0;
2661     }
2662   }
2663
2664   if (fclose (fp) == -1) {
2665     perrorf (g, "fclose: %s", tmpfile);
2666     goto out;
2667   }
2668   fp = NULL;
2669
2670   ret = apps;
2671
2672  out:
2673   if (ret == NULL && apps != NULL)
2674     guestfs_free_application_list (apps);
2675   if (fp)
2676     fclose (fp);
2677   free (name);
2678   free (version);
2679   free (release);
2680   unlink (tmpfile);
2681   return ret;
2682 }
2683
2684 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);
2685
2686 static struct guestfs_application_list *
2687 list_applications_windows (guestfs_h *g, struct inspect_fs *fs)
2688 {
2689   TMP_TEMPLATE_ON_STACK (software_local);
2690
2691   /* XXX We already download the SOFTWARE hive when doing general
2692    * inspection.  We could avoid this second download of the same file
2693    * by caching these entries in the handle.
2694    */
2695   size_t len = strlen (fs->windows_systemroot) + 64;
2696   char software[len];
2697   snprintf (software, len, "%s/system32/config/software",
2698             fs->windows_systemroot);
2699
2700   char *software_path = case_sensitive_path_silently (g, software);
2701   if (!software_path)
2702     /* If the software hive doesn't exist, just accept that we cannot
2703      * find product_name etc.
2704      */
2705     return 0;
2706
2707   struct guestfs_application_list *ret = NULL;
2708   hive_h *h = NULL;
2709
2710   if (download_to_tmp (g, software_path, software_local,
2711                        MAX_REGISTRY_SIZE) == -1)
2712     goto out;
2713
2714   free (software_path);
2715   software_path = NULL;
2716
2717   h = hivex_open (software_local, g->verbose ? HIVEX_OPEN_VERBOSE : 0);
2718   if (h == NULL) {
2719     perrorf (g, "hivex_open");
2720     goto out;
2721   }
2722
2723   /* Allocate apps list. */
2724   ret = safe_malloc (g, sizeof *ret);
2725   ret->len = 0;
2726   ret->val = NULL;
2727
2728   /* Ordinary native applications. */
2729   const char *hivepath[] =
2730     { "Microsoft", "Windows", "CurrentVersion", "Uninstall" };
2731   list_applications_windows_from_path (g, h, ret, hivepath,
2732                                        sizeof hivepath / sizeof hivepath[0]);
2733
2734   /* 32-bit emulated Windows apps running on the WOW64 emulator.
2735    * http://support.microsoft.com/kb/896459 (RHBZ#692545).
2736    */
2737   const char *hivepath2[] =
2738     { "WOW6432node", "Microsoft", "Windows", "CurrentVersion", "Uninstall" };
2739   list_applications_windows_from_path (g, h, ret, hivepath2,
2740                                        sizeof hivepath2 / sizeof hivepath2[0]);
2741
2742  out:
2743   if (h) hivex_close (h);
2744   free (software_path);
2745
2746   /* Delete the temporary file. */
2747   unlink (software_local);
2748 #undef software_local_len
2749
2750   return ret;
2751 }
2752
2753 static void
2754 list_applications_windows_from_path (guestfs_h *g, hive_h *h,
2755                                      struct guestfs_application_list *apps,
2756                                      const char **path, size_t path_len)
2757 {
2758   hive_node_h *children = NULL;
2759   hive_node_h node;
2760   size_t i;
2761
2762   node = hivex_root (h);
2763
2764   for (i = 0; node != 0 && i < path_len; ++i)
2765     node = hivex_node_get_child (h, node, path[i]);
2766
2767   if (node == 0)
2768     return;
2769
2770   children = hivex_node_children (h, node);
2771   if (children == NULL)
2772     return;
2773
2774   /* Consider any child node that has a DisplayName key.
2775    * See also:
2776    * http://nsis.sourceforge.net/Add_uninstall_information_to_Add/Remove_Programs#Optional_values
2777    */
2778   for (i = 0; children[i] != 0; ++i) {
2779     hive_value_h value;
2780     char *name = NULL;
2781     char *display_name = NULL;
2782     char *version = NULL;
2783     char *install_path = NULL;
2784     char *publisher = NULL;
2785     char *url = NULL;
2786     char *comments = NULL;
2787
2788     /* Use the node name as a proxy for the package name in Linux.  The
2789      * display name is not language-independent, so it cannot be used.
2790      */
2791     name = hivex_node_name (h, children[i]);
2792     if (name == NULL)
2793       continue;
2794
2795     value = hivex_node_get_value (h, children[i], "DisplayName");
2796     if (value) {
2797       display_name = hivex_value_string (h, value);
2798       if (display_name) {
2799         value = hivex_node_get_value (h, children[i], "DisplayVersion");
2800         if (value)
2801           version = hivex_value_string (h, value);
2802         value = hivex_node_get_value (h, children[i], "InstallLocation");
2803         if (value)
2804           install_path = hivex_value_string (h, value);
2805         value = hivex_node_get_value (h, children[i], "Publisher");
2806         if (value)
2807           publisher = hivex_value_string (h, value);
2808         value = hivex_node_get_value (h, children[i], "URLInfoAbout");
2809         if (value)
2810           url = hivex_value_string (h, value);
2811         value = hivex_node_get_value (h, children[i], "Comments");
2812         if (value)
2813           comments = hivex_value_string (h, value);
2814
2815         add_application (g, apps, name, display_name, 0,
2816                          version ? : "",
2817                          "",
2818                          install_path ? : "",
2819                          publisher ? : "",
2820                          url ? : "",
2821                          comments ? : "");
2822       }
2823     }
2824
2825     free (name);
2826     free (display_name);
2827     free (version);
2828     free (install_path);
2829     free (publisher);
2830     free (url);
2831     free (comments);
2832   }
2833
2834   free (children);
2835 }
2836
2837 static void
2838 add_application (guestfs_h *g, struct guestfs_application_list *apps,
2839                  const char *name, const char *display_name, int32_t epoch,
2840                  const char *version, const char *release,
2841                  const char *install_path,
2842                  const char *publisher, const char *url,
2843                  const char *description)
2844 {
2845   apps->len++;
2846   apps->val = safe_realloc (g, apps->val,
2847                             apps->len * sizeof (struct guestfs_application));
2848   apps->val[apps->len-1].app_name = safe_strdup (g, name);
2849   apps->val[apps->len-1].app_display_name = safe_strdup (g, display_name);
2850   apps->val[apps->len-1].app_epoch = epoch;
2851   apps->val[apps->len-1].app_version = safe_strdup (g, version);
2852   apps->val[apps->len-1].app_release = safe_strdup (g, release);
2853   apps->val[apps->len-1].app_install_path = safe_strdup (g, install_path);
2854   /* XXX Translated path is not implemented yet. */
2855   apps->val[apps->len-1].app_trans_path = safe_strdup (g, "");
2856   apps->val[apps->len-1].app_publisher = safe_strdup (g, publisher);
2857   apps->val[apps->len-1].app_url = safe_strdup (g, url);
2858   /* XXX The next two are not yet implemented for any package
2859    * format, but we could easily support them for rpm and deb.
2860    */
2861   apps->val[apps->len-1].app_source_package = safe_strdup (g, "");
2862   apps->val[apps->len-1].app_summary = safe_strdup (g, "");
2863   apps->val[apps->len-1].app_description = safe_strdup (g, description);
2864 }
2865
2866 /* Sort applications by name before returning the list. */
2867 static int
2868 compare_applications (const void *vp1, const void *vp2)
2869 {
2870   const struct guestfs_application *v1 = vp1;
2871   const struct guestfs_application *v2 = vp2;
2872
2873   return strcmp (v1->app_name, v2->app_name);
2874 }
2875
2876 static void
2877 sort_applications (struct guestfs_application_list *apps)
2878 {
2879   if (apps && apps->val)
2880     qsort (apps->val, apps->len, sizeof (struct guestfs_application),
2881            compare_applications);
2882 }
2883
2884 /* Download to a guest file to a local temporary file.  Refuse to
2885  * download the guest file if it is larger than max_size.  The caller
2886  * is responsible for deleting the temporary file after use.
2887  */
2888 static int
2889 download_to_tmp (guestfs_h *g, const char *filename,
2890                  char *localtmp, int64_t max_size)
2891 {
2892   int fd;
2893   char buf[32];
2894   int64_t size;
2895
2896   size = guestfs_filesize (g, filename);
2897   if (size == -1)
2898     /* guestfs_filesize failed and has already set error in handle */
2899     return -1;
2900   if (size > max_size) {
2901     error (g, _("size of %s is unreasonably large (%" PRIi64 " bytes)"),
2902            filename, size);
2903     return -1;
2904   }
2905
2906   fd = mkstemp (localtmp);
2907   if (fd == -1) {
2908     perrorf (g, "mkstemp");
2909     return -1;
2910   }
2911
2912   snprintf (buf, sizeof buf, "/dev/fd/%d", fd);
2913
2914   if (guestfs_download (g, filename, buf) == -1) {
2915     close (fd);
2916     unlink (localtmp);
2917     return -1;
2918   }
2919
2920   if (close (fd) == -1) {
2921     perrorf (g, "close: %s", localtmp);
2922     unlink (localtmp);
2923     return -1;
2924   }
2925
2926   return 0;
2927 }
2928
2929 /* Call 'f' with Augeas opened and having parsed 'filename' (this file
2930  * must exist).  As a security measure, this bails if the file is too
2931  * large for a reasonable configuration file.  After the call to 'f'
2932  * Augeas is closed.
2933  */
2934 static int
2935 inspect_with_augeas (guestfs_h *g, struct inspect_fs *fs, const char *filename,
2936                      int (*f) (guestfs_h *, struct inspect_fs *))
2937 {
2938   /* Security: Refuse to do this if filename is too large. */
2939   int64_t size = guestfs_filesize (g, filename);
2940   if (size == -1)
2941     /* guestfs_filesize failed and has already set error in handle */
2942     return -1;
2943   if (size > MAX_AUGEAS_FILE_SIZE) {
2944     error (g, _("size of %s is unreasonably large (%" PRIi64 " bytes)"),
2945            filename, size);
2946     return -1;
2947   }
2948
2949   /* If !feature_available (g, "augeas") then the next call will fail.
2950    * Arguably we might want to fall back to a non-Augeas method in
2951    * this case.
2952    */
2953   if (guestfs_aug_init (g, "/", 16|32) == -1)
2954     return -1;
2955
2956   int r = -1;
2957
2958   /* Tell Augeas to only load one file (thanks Raphaël Pinson). */
2959   char buf[strlen (filename) + 64];
2960   snprintf (buf, strlen (filename) + 64, "/augeas/load//incl[. != \"%s\"]",
2961             filename);
2962   if (guestfs_aug_rm (g, buf) == -1)
2963     goto out;
2964
2965   if (guestfs_aug_load (g) == -1)
2966     goto out;
2967
2968   r = f (g, fs);
2969
2970  out:
2971   guestfs_aug_close (g);
2972
2973   return r;
2974 }
2975
2976 /* Get the first line of a small file, without any trailing newline
2977  * character.
2978  */
2979 static char *
2980 first_line_of_file (guestfs_h *g, const char *filename)
2981 {
2982   char **lines;
2983   int64_t size;
2984   char *ret;
2985
2986   /* Don't trust guestfs_head_n not to break with very large files.
2987    * Check the file size is something reasonable first.
2988    */
2989   size = guestfs_filesize (g, filename);
2990   if (size == -1)
2991     /* guestfs_filesize failed and has already set error in handle */
2992     return NULL;
2993   if (size > MAX_SMALL_FILE_SIZE) {
2994     error (g, _("size of %s is unreasonably large (%" PRIi64 " bytes)"),
2995            filename, size);
2996     return NULL;
2997   }
2998
2999   lines = guestfs_head_n (g, 1, filename);
3000   if (lines == NULL)
3001     return NULL;
3002   if (lines[0] == NULL) {
3003     error (g, _("%s: file is empty"), filename);
3004     guestfs___free_string_list (lines);
3005     return NULL;
3006   }
3007   /* lines[1] should be NULL because of '1' argument above ... */
3008
3009   ret = lines[0];               /* caller frees */
3010   free (lines);                 /* free the array */
3011
3012   return ret;
3013 }
3014
3015 /* Get the first matching line (using guestfs_egrep{,i}) of a small file,
3016  * without any trailing newline character.
3017  *
3018  * Returns: 1 = returned a line (in *ret)
3019  *          0 = no match
3020  *          -1 = error
3021  */
3022 static int
3023 first_egrep_of_file (guestfs_h *g, const char *filename,
3024                      const char *eregex, int iflag, char **ret)
3025 {
3026   char **lines;
3027   int64_t size;
3028   size_t i;
3029
3030   /* Don't trust guestfs_egrep not to break with very large files.
3031    * Check the file size is something reasonable first.
3032    */
3033   size = guestfs_filesize (g, filename);
3034   if (size == -1)
3035     /* guestfs_filesize failed and has already set error in handle */
3036     return -1;
3037   if (size > MAX_SMALL_FILE_SIZE) {
3038     error (g, _("size of %s is unreasonably large (%" PRIi64 " bytes)"),
3039            filename, size);
3040     return -1;
3041   }
3042
3043   lines = (!iflag ? guestfs_egrep : guestfs_egrepi) (g, eregex, filename);
3044   if (lines == NULL)
3045     return -1;
3046   if (lines[0] == NULL) {
3047     guestfs___free_string_list (lines);
3048     return 0;
3049   }
3050
3051   *ret = lines[0];              /* caller frees */
3052
3053   /* free up any other matches and the array itself */
3054   for (i = 1; lines[i] != NULL; ++i)
3055     free (lines[i]);
3056   free (lines);
3057
3058   return 1;
3059 }
3060
3061 #else /* no PCRE or hivex at compile time */
3062
3063 /* XXX These functions should be in an optgroup. */
3064
3065 #define NOT_IMPL(r)                                                     \
3066   error (g, _("inspection API not available since this version of libguestfs was compiled without PCRE or hivex libraries")); \
3067   return r
3068
3069 char **
3070 guestfs__inspect_os (guestfs_h *g)
3071 {
3072   NOT_IMPL(NULL);
3073 }
3074
3075 char **
3076 guestfs__inspect_get_roots (guestfs_h *g)
3077 {
3078   NOT_IMPL(NULL);
3079 }
3080
3081 char *
3082 guestfs__inspect_get_type (guestfs_h *g, const char *root)
3083 {
3084   NOT_IMPL(NULL);
3085 }
3086
3087 char *
3088 guestfs__inspect_get_arch (guestfs_h *g, const char *root)
3089 {
3090   NOT_IMPL(NULL);
3091 }
3092
3093 char *
3094 guestfs__inspect_get_distro (guestfs_h *g, const char *root)
3095 {
3096   NOT_IMPL(NULL);
3097 }
3098
3099 int
3100 guestfs__inspect_get_major_version (guestfs_h *g, const char *root)
3101 {
3102   NOT_IMPL(-1);
3103 }
3104
3105 int
3106 guestfs__inspect_get_minor_version (guestfs_h *g, const char *root)
3107 {
3108   NOT_IMPL(-1);
3109 }
3110
3111 char *
3112 guestfs__inspect_get_product_name (guestfs_h *g, const char *root)
3113 {
3114   NOT_IMPL(NULL);
3115 }
3116
3117 char *
3118 guestfs__inspect_get_product_variant (guestfs_h *g, const char *root)
3119 {
3120   NOT_IMPL(NULL);
3121 }
3122
3123 char *
3124 guestfs__inspect_get_windows_systemroot (guestfs_h *g, const char *root)
3125 {
3126   NOT_IMPL(NULL);
3127 }
3128
3129 char *
3130 guestfs__inspect_get_windows_current_control_set (guestfs_h *g,
3131                                                   const char *root)
3132 {
3133   NOT_IMPL(NULL);
3134 }
3135
3136 char **
3137 guestfs__inspect_get_mountpoints (guestfs_h *g, const char *root)
3138 {
3139   NOT_IMPL(NULL);
3140 }
3141
3142 char **
3143 guestfs__inspect_get_filesystems (guestfs_h *g, const char *root)
3144 {
3145   NOT_IMPL(NULL);
3146 }
3147
3148 char **
3149 guestfs__inspect_get_drive_mappings (guestfs_h *g, const char *root)
3150 {
3151   NOT_IMPL(NULL);
3152 }
3153
3154 char *
3155 guestfs__inspect_get_package_format (guestfs_h *g, const char *root)
3156 {
3157   NOT_IMPL(NULL);
3158 }
3159
3160 char *
3161 guestfs__inspect_get_package_management (guestfs_h *g, const char *root)
3162 {
3163   NOT_IMPL(NULL);
3164 }
3165
3166 char *
3167 guestfs__inspect_get_hostname (guestfs_h *g, const char *root)
3168 {
3169   NOT_IMPL(NULL);
3170 }
3171
3172 struct guestfs_application_list *
3173 guestfs__inspect_list_applications (guestfs_h *g, const char *root)
3174 {
3175   NOT_IMPL(NULL);
3176 }
3177
3178 char *
3179 guestfs__inspect_get_format (guestfs_h *g, const char *root)
3180 {
3181   NOT_IMPL(NULL);
3182 }
3183
3184 int
3185 guestfs__inspect_is_live (guestfs_h *g, const char *root)
3186 {
3187   NOT_IMPL(-1);
3188 }
3189
3190 int
3191 guestfs__inspect_is_netinst (guestfs_h *g, const char *root)
3192 {
3193   NOT_IMPL(-1);
3194 }
3195
3196 int
3197 guestfs__inspect_is_multipart (guestfs_h *g, const char *root)
3198 {
3199   NOT_IMPL(-1);
3200 }
3201
3202 #endif /* no PCRE or hivex at compile time */
3203
3204 void
3205 guestfs___free_inspect_info (guestfs_h *g)
3206 {
3207   size_t i;
3208   for (i = 0; i < g->nr_fses; ++i) {
3209     free (g->fses[i].device);
3210     free (g->fses[i].product_name);
3211     free (g->fses[i].product_variant);
3212     free (g->fses[i].arch);
3213     free (g->fses[i].hostname);
3214     free (g->fses[i].windows_systemroot);
3215     free (g->fses[i].windows_current_control_set);
3216     size_t j;
3217     for (j = 0; j < g->fses[i].nr_fstab; ++j) {
3218       free (g->fses[i].fstab[j].device);
3219       free (g->fses[i].fstab[j].mountpoint);
3220     }
3221     free (g->fses[i].fstab);
3222     if (g->fses[i].drive_mappings)
3223       guestfs___free_string_list (g->fses[i].drive_mappings);
3224   }
3225   free (g->fses);
3226   g->nr_fses = 0;
3227   g->fses = NULL;
3228 }
3229
3230 /* In the Perl code this is a public function. */
3231 int
3232 guestfs___feature_available (guestfs_h *g, const char *feature)
3233 {
3234   /* If there's an error we should ignore it, so to do that we have to
3235    * temporarily replace the error handler with a null one.
3236    */
3237   guestfs_error_handler_cb old_error_cb = g->error_cb;
3238   g->error_cb = NULL;
3239
3240   const char *groups[] = { feature, NULL };
3241   int r = guestfs_available (g, (char * const *) groups);
3242
3243   g->error_cb = old_error_cb;
3244
3245   return r == 0 ? 1 : 0;
3246 }
3247
3248 #ifdef HAVE_PCRE
3249
3250 /* Match a regular expression which contains no captures.  Returns
3251  * true if it matches or false if it doesn't.
3252  */
3253 int
3254 guestfs___match (guestfs_h *g, const char *str, const pcre *re)
3255 {
3256   size_t len = strlen (str);
3257   int vec[30], r;
3258
3259   r = pcre_exec (re, NULL, str, len, 0, 0, vec, sizeof vec / sizeof vec[0]);
3260   if (r == PCRE_ERROR_NOMATCH)
3261     return 0;
3262   if (r != 1) {
3263     /* Internal error -- should not happen. */
3264     warning (g, "%s: %s: pcre_exec returned unexpected error code %d when matching against the string \"%s\"\n",
3265              __FILE__, __func__, r, str);
3266     return 0;
3267   }
3268
3269   return 1;
3270 }
3271
3272 /* Match a regular expression which contains exactly one capture.  If
3273  * the string matches, return the capture, otherwise return NULL.  The
3274  * caller must free the result.
3275  */
3276 char *
3277 guestfs___match1 (guestfs_h *g, const char *str, const pcre *re)
3278 {
3279   size_t len = strlen (str);
3280   int vec[30], r;
3281
3282   r = pcre_exec (re, NULL, str, len, 0, 0, vec, sizeof vec / sizeof vec[0]);
3283   if (r == PCRE_ERROR_NOMATCH)
3284     return NULL;
3285   if (r != 2) {
3286     /* Internal error -- should not happen. */
3287     warning (g, "%s: %s: internal error: pcre_exec returned unexpected error code %d when matching against the string \"%s\"",
3288              __FILE__, __func__, r, str);
3289     return NULL;
3290   }
3291
3292   return safe_strndup (g, &str[vec[2]], vec[3]-vec[2]);
3293 }
3294
3295 /* Match a regular expression which contains exactly two captures. */
3296 int
3297 guestfs___match2 (guestfs_h *g, const char *str, const pcre *re,
3298                   char **ret1, char **ret2)
3299 {
3300   size_t len = strlen (str);
3301   int vec[30], r;
3302
3303   r = pcre_exec (re, NULL, str, len, 0, 0, vec, 30);
3304   if (r == PCRE_ERROR_NOMATCH)
3305     return 0;
3306   if (r != 3) {
3307     /* Internal error -- should not happen. */
3308     warning (g, "%s: %s: internal error: pcre_exec returned unexpected error code %d when matching against the string \"%s\"",
3309              __FILE__, __func__, r, str);
3310     return 0;
3311   }
3312
3313   *ret1 = safe_strndup (g, &str[vec[2]], vec[3]-vec[2]);
3314   *ret2 = safe_strndup (g, &str[vec[4]], vec[5]-vec[4]);
3315
3316   return 1;
3317 }
3318
3319 /* Match a regular expression which contains exactly three captures. */
3320 int
3321 guestfs___match3 (guestfs_h *g, const char *str, const pcre *re,
3322                   char **ret1, char **ret2, char **ret3)
3323 {
3324   size_t len = strlen (str);
3325   int vec[30], r;
3326
3327   r = pcre_exec (re, NULL, str, len, 0, 0, vec, 30);
3328   if (r == PCRE_ERROR_NOMATCH)
3329     return 0;
3330   if (r != 4) {
3331     /* Internal error -- should not happen. */
3332     warning (g, "%s: %s: internal error: pcre_exec returned unexpected error code %d when matching against the string \"%s\"",
3333              __FILE__, __func__, r, str);
3334     return 0;
3335   }
3336
3337   *ret1 = safe_strndup (g, &str[vec[2]], vec[3]-vec[2]);
3338   *ret2 = safe_strndup (g, &str[vec[4]], vec[5]-vec[4]);
3339   *ret3 = safe_strndup (g, &str[vec[6]], vec[7]-vec[6]);
3340
3341   return 1;
3342 }
3343
3344 #endif /* HAVE_PCRE */