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