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