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