cb888da63518ba3ed90665149b6d7718ea855908
[libguestfs.git] / src / inspect.c
1 /* libguestfs
2  * Copyright (C) 2010 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 /* Compile all the regular expressions once when the shared library is
49  * loaded.  PCRE is thread safe so we're supposedly OK here if
50  * multiple threads call into the libguestfs API functions below
51  * simultaneously.
52  */
53 static pcre *re_fedora;
54 static pcre *re_rhel_old;
55 static pcre *re_rhel;
56 static pcre *re_rhel_no_minor;
57 static pcre *re_major_minor;
58 static pcre *re_aug_seq;
59 static pcre *re_xdev;
60 static pcre *re_first_partition;
61 static pcre *re_freebsd;
62 static pcre *re_windows_version;
63
64 static void compile_regexps (void) __attribute__((constructor));
65 static void free_regexps (void) __attribute__((destructor));
66
67 static void
68 compile_regexps (void)
69 {
70   const char *err;
71   int offset;
72
73 #define COMPILE(re,pattern,options)                                     \
74   do {                                                                  \
75     re = pcre_compile ((pattern), (options), &err, &offset, NULL);      \
76     if (re == NULL) {                                                   \
77       ignore_value (write (2, err, strlen (err)));                      \
78       abort ();                                                         \
79     }                                                                   \
80   } while (0)
81
82   COMPILE (re_fedora, "Fedora release (\\d+)", 0);
83   COMPILE (re_rhel_old,
84            "(?:Red Hat Enterprise Linux|CentOS|Scientific Linux).*release (\\d+).*Update (\\d+)", 0);
85   COMPILE (re_rhel,
86            "(?:Red Hat Enterprise Linux|CentOS|Scientific Linux).*release (\\d+)\\.(\\d+)", 0);
87   COMPILE (re_rhel_no_minor,
88            "(?:Red Hat Enterprise Linux|CentOS|Scientific Linux).*release (\\d+)", 0);
89   COMPILE (re_major_minor, "(\\d+)\\.(\\d+)", 0);
90   COMPILE (re_aug_seq, "/\\d+$", 0);
91   COMPILE (re_xdev, "^/dev/(?:h|s|v|xv)d([a-z]\\d*)$", 0);
92   COMPILE (re_first_partition, "^/dev/(?:h|s|v)d.1$", 0);
93   COMPILE (re_freebsd, "^/dev/ad(\\d+)s(\\d+)([a-z])$", 0);
94   COMPILE (re_windows_version, "^(\\d+)\\.(\\d+)", 0);
95 }
96
97 static void
98 free_regexps (void)
99 {
100   pcre_free (re_fedora);
101   pcre_free (re_rhel_old);
102   pcre_free (re_rhel);
103   pcre_free (re_rhel_no_minor);
104   pcre_free (re_major_minor);
105   pcre_free (re_aug_seq);
106   pcre_free (re_xdev);
107   pcre_free (re_first_partition);
108   pcre_free (re_freebsd);
109   pcre_free (re_windows_version);
110 }
111
112 /* The main inspection code. */
113 static int check_for_filesystem_on (guestfs_h *g, const char *device);
114
115 char **
116 guestfs__inspect_os (guestfs_h *g)
117 {
118   /* Remove any information previously stored in the handle. */
119   guestfs___free_inspect_info (g);
120
121   if (guestfs_umount_all (g) == -1)
122     return NULL;
123
124   /* Iterate over all possible devices.  Try to mount each
125    * (read-only).  Examine ones which contain filesystems and add that
126    * information to the handle.
127    */
128   /* Look to see if any devices directly contain filesystems (RHBZ#590167). */
129   char **devices;
130   devices = guestfs_list_devices (g);
131   if (devices == NULL)
132     return NULL;
133
134   size_t i;
135   for (i = 0; devices[i] != NULL; ++i) {
136     if (check_for_filesystem_on (g, devices[i]) == -1) {
137       guestfs___free_string_list (devices);
138       guestfs___free_inspect_info (g);
139       return NULL;
140     }
141   }
142   guestfs___free_string_list (devices);
143
144   /* Look at all partitions. */
145   char **partitions;
146   partitions = guestfs_list_partitions (g);
147   if (partitions == NULL) {
148     guestfs___free_inspect_info (g);
149     return NULL;
150   }
151
152   for (i = 0; partitions[i] != NULL; ++i) {
153     if (check_for_filesystem_on (g, partitions[i]) == -1) {
154       guestfs___free_string_list (partitions);
155       guestfs___free_inspect_info (g);
156       return NULL;
157     }
158   }
159   guestfs___free_string_list (partitions);
160
161   /* Look at all LVs. */
162   if (guestfs___feature_available (g, "lvm2")) {
163     char **lvs;
164     lvs = guestfs_lvs (g);
165     if (lvs == NULL) {
166       guestfs___free_inspect_info (g);
167       return NULL;
168     }
169
170     for (i = 0; lvs[i] != NULL; ++i) {
171       if (check_for_filesystem_on (g, lvs[i]) == -1) {
172         guestfs___free_string_list (lvs);
173         guestfs___free_inspect_info (g);
174         return NULL;
175       }
176     }
177     guestfs___free_string_list (lvs);
178   }
179
180   /* At this point we have, in the handle, a list of all filesystems
181    * found and data about each one.  Now we assemble the list of
182    * filesystems which are root devices and return that to the user.
183    * Fall through to guestfs__inspect_get_roots to do that.
184    */
185   char **ret = guestfs__inspect_get_roots (g);
186   if (ret == NULL)
187     guestfs___free_inspect_info (g);
188   return ret;
189 }
190
191 /* Find out if 'device' contains a filesystem.  If it does, add
192  * another entry in g->fses.
193  */
194 static int check_filesystem (guestfs_h *g, const char *device);
195 static int check_linux_root (guestfs_h *g, struct inspect_fs *fs);
196 static int check_freebsd_root (guestfs_h *g, struct inspect_fs *fs);
197 static void check_architecture (guestfs_h *g, struct inspect_fs *fs);
198 static int check_fstab (guestfs_h *g, struct inspect_fs *fs);
199 static int check_windows_root (guestfs_h *g, struct inspect_fs *fs);
200 static int check_windows_arch (guestfs_h *g, struct inspect_fs *fs);
201 static int check_windows_registry (guestfs_h *g, struct inspect_fs *fs);
202 static char *resolve_windows_path_silently (guestfs_h *g, const char *);
203 static int extend_fses (guestfs_h *g);
204 static int parse_unsigned_int (guestfs_h *g, const char *str);
205 static int add_fstab_entry (guestfs_h *g, struct inspect_fs *fs,
206                             const char *spec, const char *mp);
207 static char *resolve_fstab_device (guestfs_h *g, const char *spec);
208 static void check_package_format (guestfs_h *g, struct inspect_fs *fs);
209 static void check_package_management (guestfs_h *g, struct inspect_fs *fs);
210 static int download_to_tmp (guestfs_h *g, const char *filename, char *localtmp, int64_t max_size);
211 static int inspect_with_augeas (guestfs_h *g, struct inspect_fs *fs, const char *filename, int (*f) (guestfs_h *, struct inspect_fs *));
212
213 static int
214 check_for_filesystem_on (guestfs_h *g, const char *device)
215 {
216   /* Get vfs-type in order to check if it's a Linux(?) swap device.
217    * If there's an error we should ignore it, so to do that we have to
218    * temporarily replace the error handler with a null one.
219    */
220   guestfs_error_handler_cb old_error_cb = g->error_cb;
221   g->error_cb = NULL;
222   char *vfs_type = guestfs_vfs_type (g, device);
223   g->error_cb = old_error_cb;
224
225   int is_swap = vfs_type && STREQ (vfs_type, "swap");
226
227   if (g->verbose)
228     fprintf (stderr, "check_for_filesystem_on: %s (%s)\n",
229              device, vfs_type ? vfs_type : "failed to get vfs type");
230
231   if (is_swap) {
232     free (vfs_type);
233     if (extend_fses (g) == -1)
234       return -1;
235     g->fses[g->nr_fses-1].is_swap = 1;
236     return 0;
237   }
238
239   /* Try mounting the device.  As above, ignore errors. */
240   g->error_cb = NULL;
241   int r = guestfs_mount_ro (g, device, "/");
242   if (r == -1 && vfs_type && STREQ (vfs_type, "ufs")) /* Hack for the *BSDs. */
243     r = guestfs_mount_vfs (g, "ro,ufstype=ufs2", "ufs", device, "/");
244   free (vfs_type);
245   g->error_cb = old_error_cb;
246   if (r == -1)
247     return 0;
248
249   /* Do the rest of the checks. */
250   r = check_filesystem (g, device);
251
252   /* Unmount the filesystem. */
253   if (guestfs_umount_all (g) == -1)
254     return -1;
255
256   return r;
257 }
258
259 static int
260 check_filesystem (guestfs_h *g, const char *device)
261 {
262   if (extend_fses (g) == -1)
263     return -1;
264
265   struct inspect_fs *fs = &g->fses[g->nr_fses-1];
266
267   fs->device = safe_strdup (g, device);
268   fs->is_mountable = 1;
269
270   /* Optimize some of the tests by avoiding multiple tests of the same thing. */
271   int is_dir_etc = guestfs_is_dir (g, "/etc") > 0;
272   int is_dir_bin = guestfs_is_dir (g, "/bin") > 0;
273   int is_dir_share = guestfs_is_dir (g, "/share") > 0;
274
275   /* Grub /boot? */
276   if (guestfs_is_file (g, "/grub/menu.lst") > 0 ||
277       guestfs_is_file (g, "/grub/grub.conf") > 0)
278     fs->content = FS_CONTENT_LINUX_BOOT;
279   /* FreeBSD root? */
280   else if (is_dir_etc &&
281            is_dir_bin &&
282            guestfs_is_file (g, "/etc/freebsd-update.conf") > 0 &&
283            guestfs_is_file (g, "/etc/fstab") > 0) {
284     /* Ignore /dev/sda1 which is a shadow of the real root filesystem
285      * that is probably /dev/sda5 (see:
286      * http://www.freebsd.org/doc/handbook/disk-organization.html)
287      */
288     if (match (g, device, re_first_partition))
289       return 0;
290
291     fs->is_root = 1;
292     fs->content = FS_CONTENT_FREEBSD_ROOT;
293     if (check_freebsd_root (g, fs) == -1)
294       return -1;
295   }
296   /* Linux root? */
297   else if (is_dir_etc &&
298            is_dir_bin &&
299            guestfs_is_file (g, "/etc/fstab") > 0) {
300     fs->is_root = 1;
301     fs->content = FS_CONTENT_LINUX_ROOT;
302     if (check_linux_root (g, fs) == -1)
303       return -1;
304   }
305   /* Linux /usr/local? */
306   else if (is_dir_etc &&
307            is_dir_bin &&
308            is_dir_share &&
309            guestfs_exists (g, "/local") == 0 &&
310            guestfs_is_file (g, "/etc/fstab") == 0)
311     fs->content = FS_CONTENT_LINUX_USR_LOCAL;
312   /* Linux /usr? */
313   else if (is_dir_etc &&
314            is_dir_bin &&
315            is_dir_share &&
316            guestfs_exists (g, "/local") > 0 &&
317            guestfs_is_file (g, "/etc/fstab") == 0)
318     fs->content = FS_CONTENT_LINUX_USR;
319   /* Linux /var? */
320   else if (guestfs_is_dir (g, "/log") > 0 &&
321            guestfs_is_dir (g, "/run") > 0 &&
322            guestfs_is_dir (g, "/spool") > 0)
323     fs->content = FS_CONTENT_LINUX_VAR;
324   /* Windows root? */
325   else if (guestfs_is_file (g, "/AUTOEXEC.BAT") > 0 ||
326            guestfs_is_file (g, "/autoexec.bat") > 0 ||
327            guestfs_is_dir (g, "/Program Files") > 0 ||
328            guestfs_is_dir (g, "/WINDOWS") > 0 ||
329            guestfs_is_dir (g, "/Windows") > 0 ||
330            guestfs_is_dir (g, "/windows") > 0 ||
331            guestfs_is_dir (g, "/WIN32") > 0 ||
332            guestfs_is_dir (g, "/Win32") > 0 ||
333            guestfs_is_dir (g, "/WINNT") > 0 ||
334            guestfs_is_file (g, "/boot.ini") > 0 ||
335            guestfs_is_file (g, "/ntldr") > 0) {
336     fs->is_root = 1;
337     fs->content = FS_CONTENT_WINDOWS_ROOT;
338     if (check_windows_root (g, fs) == -1)
339       return -1;
340   }
341
342   return 0;
343 }
344
345 /* Set fs->product_name to the first line of the release file. */
346 static int
347 parse_release_file (guestfs_h *g, struct inspect_fs *fs,
348                     const char *release_filename)
349 {
350   char **product_name = guestfs_head_n (g, 1, release_filename);
351   if (product_name == NULL)
352     return -1;
353   if (product_name[0] == NULL) {
354     error (g, _("%s: file is empty"), release_filename);
355     guestfs___free_string_list (product_name);
356     return -1;
357   }
358
359   /* Note that this string becomes owned by the handle and will
360    * be freed by guestfs___free_inspect_info.
361    */
362   fs->product_name = product_name[0];
363   free (product_name);
364
365   return 0;
366 }
367
368 /* Parse generic MAJOR.MINOR from the fs->product_name string. */
369 static int
370 parse_major_minor (guestfs_h *g, struct inspect_fs *fs)
371 {
372   char *major, *minor;
373
374   if (match2 (g, fs->product_name, re_major_minor, &major, &minor)) {
375     fs->major_version = parse_unsigned_int (g, major);
376     free (major);
377     if (fs->major_version == -1) {
378       free (minor);
379       return -1;
380     }
381     fs->minor_version = parse_unsigned_int (g, minor);
382     free (minor);
383     if (fs->minor_version == -1)
384       return -1;
385   }
386   return 0;
387 }
388
389 /* Ubuntu has /etc/lsb-release containing:
390  *   DISTRIB_ID=Ubuntu                                # Distro
391  *   DISTRIB_RELEASE=10.04                            # Version
392  *   DISTRIB_CODENAME=lucid
393  *   DISTRIB_DESCRIPTION="Ubuntu 10.04.1 LTS"         # Product name
394  *
395  * [Ubuntu-derived ...] Linux Mint was found to have this:
396  *   DISTRIB_ID=LinuxMint
397  *   DISTRIB_RELEASE=10
398  *   DISTRIB_CODENAME=julia
399  *   DISTRIB_DESCRIPTION="Linux Mint 10 Julia"
400  * Linux Mint also has /etc/linuxmint/info with more information,
401  * but we can use the LSB file.
402  *
403  * Mandriva has:
404  *   LSB_VERSION=lsb-4.0-amd64:lsb-4.0-noarch
405  *   DISTRIB_ID=MandrivaLinux
406  *   DISTRIB_RELEASE=2010.1
407  *   DISTRIB_CODENAME=Henry_Farman
408  *   DISTRIB_DESCRIPTION="Mandriva Linux 2010.1"
409  * Mandriva also has a normal release file called /etc/mandriva-release.
410  */
411 static int
412 parse_lsb_release (guestfs_h *g, struct inspect_fs *fs)
413 {
414   char **lines;
415   size_t i;
416   int r = 0;
417
418   lines = guestfs_head_n (g, 10, "/etc/lsb-release");
419   if (lines == NULL)
420     return -1;
421
422   for (i = 0; lines[i] != NULL; ++i) {
423     if (fs->distro == 0 &&
424         STREQ (lines[i], "DISTRIB_ID=Ubuntu")) {
425       fs->distro = OS_DISTRO_UBUNTU;
426       r = 1;
427     }
428     else if (fs->distro == 0 &&
429              STREQ (lines[i], "DISTRIB_ID=LinuxMint")) {
430       fs->distro = OS_DISTRO_LINUX_MINT;
431       r = 1;
432     }
433     else if (fs->distro == 0 &&
434              STREQ (lines[i], "DISTRIB_ID=MandrivaLinux")) {
435       fs->distro = OS_DISTRO_MANDRIVA;
436       r = 1;
437     }
438     else if (STRPREFIX (lines[i], "DISTRIB_RELEASE=")) {
439       char *major, *minor;
440       if (match2 (g, &lines[i][16], re_major_minor, &major, &minor)) {
441         fs->major_version = parse_unsigned_int (g, major);
442         free (major);
443         if (fs->major_version == -1) {
444           free (minor);
445           guestfs___free_string_list (lines);
446           return -1;
447         }
448         fs->minor_version = parse_unsigned_int (g, minor);
449         free (minor);
450         if (fs->minor_version == -1) {
451           guestfs___free_string_list (lines);
452           return -1;
453         }
454       }
455     }
456     else if (fs->product_name == NULL &&
457              (STRPREFIX (lines[i], "DISTRIB_DESCRIPTION=\"") ||
458               STRPREFIX (lines[i], "DISTRIB_DESCRIPTION='"))) {
459       size_t len = strlen (lines[i]) - 21 - 1;
460       fs->product_name = safe_strndup (g, &lines[i][21], len);
461       r = 1;
462     }
463     else if (fs->product_name == NULL &&
464              STRPREFIX (lines[i], "DISTRIB_DESCRIPTION=")) {
465       size_t len = strlen (lines[i]) - 20;
466       fs->product_name = safe_strndup (g, &lines[i][20], len);
467       r = 1;
468     }
469   }
470
471   guestfs___free_string_list (lines);
472   return r;
473 }
474
475 /* The currently mounted device is known to be a Linux root.  Try to
476  * determine from this the distro, version, etc.  Also parse
477  * /etc/fstab to determine the arrangement of mountpoints and
478  * associated devices.
479  */
480 static int
481 check_linux_root (guestfs_h *g, struct inspect_fs *fs)
482 {
483   int r;
484
485   fs->type = OS_TYPE_LINUX;
486
487   if (guestfs_exists (g, "/etc/lsb-release") > 0) {
488     r = parse_lsb_release (g, fs);
489     if (r == -1)        /* error */
490       return -1;
491     if (r == 1)         /* ok - detected the release from this file */
492       goto skip_release_checks;
493   }
494
495   if (guestfs_exists (g, "/etc/redhat-release") > 0) {
496     fs->distro = OS_DISTRO_REDHAT_BASED; /* Something generic Red Hat-like. */
497
498     if (parse_release_file (g, fs, "/etc/redhat-release") == -1)
499       return -1;
500
501     char *major, *minor;
502     if ((major = match1 (g, fs->product_name, re_fedora)) != NULL) {
503       fs->distro = OS_DISTRO_FEDORA;
504       fs->major_version = parse_unsigned_int (g, major);
505       free (major);
506       if (fs->major_version == -1)
507         return -1;
508     }
509     else if (match2 (g, fs->product_name, re_rhel_old, &major, &minor) ||
510              match2 (g, fs->product_name, re_rhel, &major, &minor)) {
511       fs->distro = OS_DISTRO_RHEL;
512       fs->major_version = parse_unsigned_int (g, major);
513       free (major);
514       if (fs->major_version == -1) {
515         free (minor);
516         return -1;
517       }
518       fs->minor_version = parse_unsigned_int (g, minor);
519       free (minor);
520       if (fs->minor_version == -1)
521         return -1;
522     }
523     else if ((major = match1 (g, fs->product_name, re_rhel_no_minor)) != NULL) {
524       fs->distro = OS_DISTRO_RHEL;
525       fs->major_version = parse_unsigned_int (g, major);
526       free (major);
527       if (fs->major_version == -1)
528         return -1;
529       fs->minor_version = 0;
530     }
531   }
532   else if (guestfs_exists (g, "/etc/debian_version") > 0) {
533     fs->distro = OS_DISTRO_DEBIAN;
534
535     if (parse_release_file (g, fs, "/etc/debian_version") == -1)
536       return -1;
537
538     if (parse_major_minor (g, fs) == -1)
539       return -1;
540   }
541   else if (guestfs_exists (g, "/etc/pardus-release") > 0) {
542     fs->distro = OS_DISTRO_PARDUS;
543
544     if (parse_release_file (g, fs, "/etc/pardus-release") == -1)
545       return -1;
546
547     if (parse_major_minor (g, fs) == -1)
548       return -1;
549   }
550   else if (guestfs_exists (g, "/etc/arch-release") > 0) {
551     fs->distro = OS_DISTRO_ARCHLINUX;
552
553     /* /etc/arch-release file is empty and I can't see a way to
554      * determine the actual release or product string.
555      */
556   }
557   else if (guestfs_exists (g, "/etc/gentoo-release") > 0) {
558     fs->distro = OS_DISTRO_GENTOO;
559
560     if (parse_release_file (g, fs, "/etc/gentoo-release") == -1)
561       return -1;
562
563     if (parse_major_minor (g, fs) == -1)
564       return -1;
565   }
566   else if (guestfs_exists (g, "/etc/meego-release") > 0) {
567     fs->distro = OS_DISTRO_MEEGO;
568
569     if (parse_release_file (g, fs, "/etc/meego-release") == -1)
570       return -1;
571
572     if (parse_major_minor (g, fs) == -1)
573       return -1;
574   }
575
576  skip_release_checks:;
577
578   /* If distro test above was successful, work out the package format. */
579   check_package_format (g, fs);
580   check_package_management (g, fs);
581
582   /* Determine the architecture. */
583   check_architecture (g, fs);
584
585   /* We already know /etc/fstab exists because it's part of the test
586    * for Linux root above.  We must now parse this file to determine
587    * which filesystems are used by the operating system and how they
588    * are mounted.
589    */
590   if (inspect_with_augeas (g, fs, "/etc/fstab", check_fstab) == -1)
591     return -1;
592
593   return 0;
594 }
595
596 /* The currently mounted device is known to be a FreeBSD root. */
597 static int
598 check_freebsd_root (guestfs_h *g, struct inspect_fs *fs)
599 {
600   int r;
601
602   fs->type = OS_TYPE_FREEBSD;
603
604   /* FreeBSD has no authoritative version file.  The version number is
605    * in /etc/motd, which the system administrator might edit, but
606    * we'll use that anyway.
607    */
608
609   if (guestfs_exists (g, "/etc/motd") > 0) {
610     if (parse_release_file (g, fs, "/etc/motd") == -1)
611       return -1;
612
613     if (parse_major_minor (g, fs) == -1)
614       return -1;
615   }
616
617   /* Determine the architecture. */
618   check_architecture (g, fs);
619
620   /* We already know /etc/fstab exists because it's part of the test above. */
621   if (inspect_with_augeas (g, fs, "/etc/fstab", check_fstab) == -1)
622     return -1;
623
624   return 0;
625 }
626
627 static void
628 check_architecture (guestfs_h *g, struct inspect_fs *fs)
629 {
630   const char *binaries[] =
631     { "/bin/bash", "/bin/ls", "/bin/echo", "/bin/rm", "/bin/sh" };
632   size_t i;
633
634   for (i = 0; i < sizeof binaries / sizeof binaries[0]; ++i) {
635     if (guestfs_is_file (g, binaries[i]) > 0) {
636       /* Ignore errors from file_architecture call. */
637       guestfs_error_handler_cb old_error_cb = g->error_cb;
638       g->error_cb = NULL;
639       char *arch = guestfs_file_architecture (g, binaries[i]);
640       g->error_cb = old_error_cb;
641
642       if (arch) {
643         /* String will be owned by handle, freed by
644          * guestfs___free_inspect_info.
645          */
646         fs->arch = arch;
647         break;
648       }
649     }
650   }
651 }
652
653 static int
654 check_fstab (guestfs_h *g, struct inspect_fs *fs)
655 {
656   char **lines = guestfs_aug_ls (g, "/files/etc/fstab");
657   if (lines == NULL)
658     return -1;
659
660   if (lines[0] == NULL) {
661     error (g, _("could not parse /etc/fstab or empty file"));
662     guestfs___free_string_list (lines);
663     return -1;
664   }
665
666   size_t i;
667   char augpath[256];
668   for (i = 0; lines[i] != NULL; ++i) {
669     /* Ignore comments.  Only care about sequence lines which
670      * match m{/\d+$}.
671      */
672     if (match (g, lines[i], re_aug_seq)) {
673       snprintf (augpath, sizeof augpath, "%s/spec", lines[i]);
674       char *spec = guestfs_aug_get (g, augpath);
675       if (spec == NULL) {
676         guestfs___free_string_list (lines);
677         return -1;
678       }
679
680       snprintf (augpath, sizeof augpath, "%s/file", lines[i]);
681       char *mp = guestfs_aug_get (g, augpath);
682       if (mp == NULL) {
683         guestfs___free_string_list (lines);
684         free (spec);
685         return -1;
686       }
687
688       int r = add_fstab_entry (g, fs, spec, mp);
689       free (spec);
690       free (mp);
691
692       if (r == -1) {
693         guestfs___free_string_list (lines);
694         return -1;
695       }
696     }
697   }
698
699   guestfs___free_string_list (lines);
700   return 0;
701 }
702
703 /* Add a filesystem and possibly a mountpoint entry for
704  * the root filesystem 'fs'.
705  *
706  * 'spec' is the fstab spec field, which might be a device name or a
707  * pseudodevice or 'UUID=...' or 'LABEL=...'.
708  *
709  * 'mp' is the mount point, which could also be 'swap' or 'none'.
710  */
711 static int
712 add_fstab_entry (guestfs_h *g, struct inspect_fs *fs,
713                  const char *spec, const char *mp)
714 {
715   /* Ignore certain mountpoints. */
716   if (STRPREFIX (mp, "/dev/") ||
717       STREQ (mp, "/dev") ||
718       STRPREFIX (mp, "/media/") ||
719       STRPREFIX (mp, "/proc/") ||
720       STREQ (mp, "/proc") ||
721       STRPREFIX (mp, "/selinux/") ||
722       STREQ (mp, "/selinux") ||
723       STRPREFIX (mp, "/sys/") ||
724       STREQ (mp, "/sys"))
725     return 0;
726
727   /* Ignore /dev/fd (floppy disks) (RHBZ#642929) and CD-ROM drives. */
728   if ((STRPREFIX (spec, "/dev/fd") && c_isdigit (spec[7])) ||
729       STREQ (spec, "/dev/floppy") ||
730       STREQ (spec, "/dev/cdrom"))
731     return 0;
732
733   /* Resolve UUID= and LABEL= to the actual device. */
734   char *device = NULL;
735   if (STRPREFIX (spec, "UUID="))
736     device = guestfs_findfs_uuid (g, &spec[5]);
737   else if (STRPREFIX (spec, "LABEL="))
738     device = guestfs_findfs_label (g, &spec[6]);
739   /* Ignore "/.swap" (Pardus) and pseudo-devices like "tmpfs". */
740   else if (STRPREFIX (spec, "/dev/"))
741     /* Resolve guest block device names. */
742     device = resolve_fstab_device (g, spec);
743
744   /* If we haven't resolved the device successfully by this point,
745    * we don't care, just ignore it.
746    */
747   if (device == NULL)
748     return 0;
749
750   char *mountpoint = safe_strdup (g, mp);
751
752   /* Add this to the fstab entry in 'fs'.
753    * Note these are further filtered by guestfs_inspect_get_mountpoints
754    * and guestfs_inspect_get_filesystems.
755    */
756   size_t n = fs->nr_fstab + 1;
757   struct inspect_fstab_entry *p;
758
759   p = realloc (fs->fstab, n * sizeof (struct inspect_fstab_entry));
760   if (p == NULL) {
761     perrorf (g, "realloc");
762     free (device);
763     free (mountpoint);
764     return -1;
765   }
766
767   fs->fstab = p;
768   fs->nr_fstab = n;
769
770   /* These are owned by the handle and freed by guestfs___free_inspect_info. */
771   fs->fstab[n-1].device = device;
772   fs->fstab[n-1].mountpoint = mountpoint;
773
774   if (g->verbose)
775     fprintf (stderr, "fstab: device=%s mountpoint=%s\n", device, mountpoint);
776
777   return 0;
778 }
779
780 /* Resolve block device name to the libguestfs device name, eg.
781  * /dev/xvdb1 => /dev/vdb1; and /dev/mapper/VG-LV => /dev/VG/LV.  This
782  * assumes that disks were added in the same order as they appear to
783  * the real VM, which is a reasonable assumption to make.  Return
784  * anything we don't recognize unchanged.
785  */
786 static char *
787 resolve_fstab_device (guestfs_h *g, const char *spec)
788 {
789   char *a1;
790   char *device = NULL;
791   char *bsddisk, *bsdslice, *bsdpart;
792
793   if (STRPREFIX (spec, "/dev/mapper/")) {
794     /* LVM2 does some strange munging on /dev/mapper paths for VGs and
795      * LVs which contain '-' character:
796      *
797      * ><fs> lvcreate LV--test VG--test 32
798      * ><fs> debug ls /dev/mapper
799      * VG----test-LV----test
800      *
801      * This makes it impossible to reverse those paths directly, so
802      * we have implemented lvm_canonical_lv_name in the daemon.
803      */
804     device = guestfs_lvm_canonical_lv_name (g, spec);
805   }
806   else if ((a1 = match1 (g, spec, re_xdev)) != NULL) {
807     char **devices = guestfs_list_devices (g);
808     if (devices == NULL)
809       return NULL;
810
811     size_t count;
812     for (count = 0; devices[count] != NULL; count++)
813       ;
814
815     size_t i = a1[0] - 'a'; /* a1[0] is always [a-z] because of regex. */
816     if (i < count) {
817       size_t len = strlen (devices[i]) + strlen (a1) + 16;
818       device = safe_malloc (g, len);
819       snprintf (device, len, "%s%s", devices[i], &a1[1]);
820     }
821
822     free (a1);
823     guestfs___free_string_list (devices);
824   }
825   else if (match3 (g, spec, re_freebsd, &bsddisk, &bsdslice, &bsdpart)) {
826     /* FreeBSD disks are organized quite differently.  See:
827      * http://www.freebsd.org/doc/handbook/disk-organization.html
828      * FreeBSD "partitions" are exposed as quasi-extended partitions
829      * numbered from 5 in Linux.  I have no idea what happens when you
830      * have multiple "slices" (the FreeBSD term for MBR partitions).
831      */
832     int disk = parse_unsigned_int (g, bsddisk);
833     int slice = parse_unsigned_int (g, bsdslice);
834     int part = bsdpart[0] - 'a' /* counting from 0 */;
835     free (bsddisk);
836     free (bsdslice);
837     free (bsdpart);
838
839     if (disk == -1 || disk > 26 ||
840         slice <= 0 || slice > 1 /* > 4 .. see comment above */ ||
841         part < 0 || part >= 26)
842       goto out;
843
844     device = safe_asprintf (g, "/dev/sd%c%d", disk + 'a', part + 5);
845   }
846
847  out:
848   /* Didn't match device pattern, return original spec unchanged. */
849   if (device == NULL)
850     device = safe_strdup (g, spec);
851
852   return device;
853 }
854
855 /* XXX Handling of boot.ini in the Perl version was pretty broken.  It
856  * essentially didn't do anything for modern Windows guests.
857  * Therefore I've omitted all that code.
858  */
859 static int
860 check_windows_root (guestfs_h *g, struct inspect_fs *fs)
861 {
862   fs->type = OS_TYPE_WINDOWS;
863   fs->distro = OS_DISTRO_WINDOWS;
864
865   /* Try to find Windows systemroot using some common locations. */
866   const char *systemroots[] =
867     { "/windows", "/winnt", "/win32", "/win" };
868   size_t i;
869   char *systemroot = NULL;
870   for (i = 0;
871        systemroot == NULL && i < sizeof systemroots / sizeof systemroots[0];
872        ++i) {
873     systemroot = resolve_windows_path_silently (g, systemroots[i]);
874   }
875
876   if (!systemroot) {
877     error (g, _("cannot resolve Windows %%SYSTEMROOT%%"));
878     return -1;
879   }
880
881   if (g->verbose)
882     fprintf (stderr, "windows %%SYSTEMROOT%% = %s", systemroot);
883
884   /* Freed by guestfs___free_inspect_info. */
885   fs->windows_systemroot = systemroot;
886
887   if (check_windows_arch (g, fs) == -1)
888     return -1;
889
890   if (check_windows_registry (g, fs) == -1)
891     return -1;
892
893   check_package_format (g, fs);
894   check_package_management (g, fs);
895
896   return 0;
897 }
898
899 static int
900 check_windows_arch (guestfs_h *g, struct inspect_fs *fs)
901 {
902   size_t len = strlen (fs->windows_systemroot) + 32;
903   char cmd_exe[len];
904   snprintf (cmd_exe, len, "%s/system32/cmd.exe", fs->windows_systemroot);
905
906   char *cmd_exe_path = resolve_windows_path_silently (g, cmd_exe);
907   if (!cmd_exe_path)
908     return 0;
909
910   char *arch = guestfs_file_architecture (g, cmd_exe_path);
911   free (cmd_exe_path);
912
913   if (arch)
914     fs->arch = arch;        /* freed by guestfs___free_inspect_info */
915
916   return 0;
917 }
918
919 /* At the moment, pull just the ProductName and version numbers from
920  * the registry.  In future there is a case for making many more
921  * registry fields available to callers.
922  */
923 static int
924 check_windows_registry (guestfs_h *g, struct inspect_fs *fs)
925 {
926   TMP_TEMPLATE_ON_STACK (software_local);
927
928   size_t len = strlen (fs->windows_systemroot) + 64;
929   char software[len];
930   snprintf (software, len, "%s/system32/config/software",
931             fs->windows_systemroot);
932
933   char *software_path = resolve_windows_path_silently (g, software);
934   if (!software_path)
935     /* If the software hive doesn't exist, just accept that we cannot
936      * find product_name etc.
937      */
938     return 0;
939
940   int ret = -1;
941   hive_h *h = NULL;
942   hive_value_h *values = NULL;
943
944   if (download_to_tmp (g, software_path, software_local, 100000000) == -1)
945     goto out;
946
947   h = hivex_open (software_local, g->verbose ? HIVEX_OPEN_VERBOSE : 0);
948   if (h == NULL) {
949     perrorf (g, "hivex_open");
950     goto out;
951   }
952
953   hive_node_h node = hivex_root (h);
954   const char *hivepath[] =
955     { "Microsoft", "Windows NT", "CurrentVersion" };
956   size_t i;
957   for (i = 0;
958        node != 0 && i < sizeof hivepath / sizeof hivepath[0];
959        ++i) {
960     node = hivex_node_get_child (h, node, hivepath[i]);
961   }
962
963   if (node == 0) {
964     perrorf (g, "hivex: cannot locate HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
965     goto out;
966   }
967
968   values = hivex_node_values (h, node);
969
970   for (i = 0; values[i] != 0; ++i) {
971     char *key = hivex_value_key (h, values[i]);
972     if (key == NULL) {
973       perrorf (g, "hivex_value_key");
974       goto out;
975     }
976
977     if (STRCASEEQ (key, "ProductName")) {
978       fs->product_name = hivex_value_string (h, values[i]);
979       if (!fs->product_name) {
980         perrorf (g, "hivex_value_string");
981         free (key);
982         goto out;
983       }
984     }
985     else if (STRCASEEQ (key, "CurrentVersion")) {
986       char *version = hivex_value_string (h, values[i]);
987       if (!version) {
988         perrorf (g, "hivex_value_string");
989         free (key);
990         goto out;
991       }
992       char *major, *minor;
993       if (match2 (g, version, re_windows_version, &major, &minor)) {
994         fs->major_version = parse_unsigned_int (g, major);
995         free (major);
996         if (fs->major_version == -1) {
997           free (minor);
998           free (key);
999           free (version);
1000           goto out;
1001         }
1002         fs->minor_version = parse_unsigned_int (g, minor);
1003         free (minor);
1004         if (fs->minor_version == -1) {
1005           free (key);
1006           free (version);
1007           goto out;
1008         }
1009       }
1010
1011       free (version);
1012     }
1013
1014     free (key);
1015   }
1016
1017   ret = 0;
1018
1019  out:
1020   if (h) hivex_close (h);
1021   free (values);
1022   free (software_path);
1023
1024   /* Free up the temporary file. */
1025   unlink (software_local);
1026 #undef software_local_len
1027
1028   return ret;
1029 }
1030
1031 static char *
1032 resolve_windows_path_silently (guestfs_h *g, const char *path)
1033 {
1034   guestfs_error_handler_cb old_error_cb = g->error_cb;
1035   g->error_cb = NULL;
1036   char *ret = guestfs_case_sensitive_path (g, path);
1037   g->error_cb = old_error_cb;
1038   return ret;
1039 }
1040
1041 static int
1042 extend_fses (guestfs_h *g)
1043 {
1044   size_t n = g->nr_fses + 1;
1045   struct inspect_fs *p;
1046
1047   p = realloc (g->fses, n * sizeof (struct inspect_fs));
1048   if (p == NULL) {
1049     perrorf (g, "realloc");
1050     return -1;
1051   }
1052
1053   g->fses = p;
1054   g->nr_fses = n;
1055
1056   memset (&g->fses[n-1], 0, sizeof (struct inspect_fs));
1057
1058   return 0;
1059 }
1060
1061 /* Parse small, unsigned ints, as used in version numbers. */
1062 static int
1063 parse_unsigned_int (guestfs_h *g, const char *str)
1064 {
1065   long ret;
1066   int r = xstrtol (str, NULL, 10, &ret, "");
1067   if (r != LONGINT_OK) {
1068     error (g, _("could not parse integer in version number: %s"), str);
1069     return -1;
1070   }
1071   return ret;
1072 }
1073
1074 /* At the moment, package format and package management is just a
1075  * simple function of the distro and major_version fields, so these
1076  * can never return an error.  We might be cleverer in future.
1077  */
1078 static void
1079 check_package_format (guestfs_h *g, struct inspect_fs *fs)
1080 {
1081   switch (fs->distro) {
1082   case OS_DISTRO_FEDORA:
1083   case OS_DISTRO_MEEGO:
1084   case OS_DISTRO_REDHAT_BASED:
1085   case OS_DISTRO_RHEL:
1086   case OS_DISTRO_MANDRIVA:
1087     fs->package_format = OS_PACKAGE_FORMAT_RPM;
1088     break;
1089
1090   case OS_DISTRO_DEBIAN:
1091   case OS_DISTRO_UBUNTU:
1092   case OS_DISTRO_LINUX_MINT:
1093     fs->package_format = OS_PACKAGE_FORMAT_DEB;
1094     break;
1095
1096   case OS_DISTRO_ARCHLINUX:
1097     fs->package_format = OS_PACKAGE_FORMAT_PACMAN;
1098     break;
1099   case OS_DISTRO_GENTOO:
1100     fs->package_format = OS_PACKAGE_FORMAT_EBUILD;
1101     break;
1102   case OS_DISTRO_PARDUS:
1103     fs->package_format = OS_PACKAGE_FORMAT_PISI;
1104     break;
1105
1106   case OS_DISTRO_WINDOWS:
1107   case OS_DISTRO_UNKNOWN:
1108   default:
1109     fs->package_format = OS_PACKAGE_FORMAT_UNKNOWN;
1110     break;
1111   }
1112 }
1113
1114 static void
1115 check_package_management (guestfs_h *g, struct inspect_fs *fs)
1116 {
1117   switch (fs->distro) {
1118   case OS_DISTRO_FEDORA:
1119   case OS_DISTRO_MEEGO:
1120     fs->package_management = OS_PACKAGE_MANAGEMENT_YUM;
1121     break;
1122
1123   case OS_DISTRO_REDHAT_BASED:
1124   case OS_DISTRO_RHEL:
1125     if (fs->major_version >= 5)
1126       fs->package_management = OS_PACKAGE_MANAGEMENT_YUM;
1127     else
1128       fs->package_management = OS_PACKAGE_MANAGEMENT_UP2DATE;
1129     break;
1130
1131   case OS_DISTRO_DEBIAN:
1132   case OS_DISTRO_UBUNTU:
1133   case OS_DISTRO_LINUX_MINT:
1134     fs->package_management = OS_PACKAGE_MANAGEMENT_APT;
1135     break;
1136
1137   case OS_DISTRO_ARCHLINUX:
1138     fs->package_management = OS_PACKAGE_MANAGEMENT_PACMAN;
1139     break;
1140   case OS_DISTRO_GENTOO:
1141     fs->package_management = OS_PACKAGE_MANAGEMENT_PORTAGE;
1142     break;
1143   case OS_DISTRO_PARDUS:
1144     fs->package_management = OS_PACKAGE_MANAGEMENT_PISI;
1145     break;
1146   case OS_DISTRO_MANDRIVA:
1147     fs->package_management = OS_PACKAGE_MANAGEMENT_URPMI;
1148     break;
1149
1150   case OS_DISTRO_WINDOWS:
1151   case OS_DISTRO_UNKNOWN:
1152   default:
1153     fs->package_management = OS_PACKAGE_MANAGEMENT_UNKNOWN;
1154     break;
1155   }
1156 }
1157
1158 static struct inspect_fs *
1159 search_for_root (guestfs_h *g, const char *root)
1160 {
1161   if (g->nr_fses == 0) {
1162     error (g, _("no inspection data: call guestfs_inspect_os first"));
1163     return NULL;
1164   }
1165
1166   size_t i;
1167   struct inspect_fs *fs;
1168   for (i = 0; i < g->nr_fses; ++i) {
1169     fs = &g->fses[i];
1170     if (fs->is_root && STREQ (root, fs->device))
1171       return fs;
1172   }
1173
1174   error (g, _("%s: root device not found: only call this function with a root device previously returned by guestfs_inspect_os"),
1175          root);
1176   return NULL;
1177 }
1178
1179 char **
1180 guestfs__inspect_get_roots (guestfs_h *g)
1181 {
1182   /* NB. Doesn't matter if g->nr_fses == 0.  We just return an empty
1183    * list in this case.
1184    */
1185
1186   size_t i;
1187   size_t count = 0;
1188   for (i = 0; i < g->nr_fses; ++i)
1189     if (g->fses[i].is_root)
1190       count++;
1191
1192   char **ret = calloc (count+1, sizeof (char *));
1193   if (ret == NULL) {
1194     perrorf (g, "calloc");
1195     return NULL;
1196   }
1197
1198   count = 0;
1199   for (i = 0; i < g->nr_fses; ++i) {
1200     if (g->fses[i].is_root) {
1201       ret[count] = safe_strdup (g, g->fses[i].device);
1202       count++;
1203     }
1204   }
1205   ret[count] = NULL;
1206
1207   return ret;
1208 }
1209
1210 char *
1211 guestfs__inspect_get_type (guestfs_h *g, const char *root)
1212 {
1213   struct inspect_fs *fs = search_for_root (g, root);
1214   if (!fs)
1215     return NULL;
1216
1217   char *ret;
1218   switch (fs->type) {
1219   case OS_TYPE_LINUX: ret = safe_strdup (g, "linux"); break;
1220   case OS_TYPE_WINDOWS: ret = safe_strdup (g, "windows"); break;
1221   case OS_TYPE_FREEBSD: ret = safe_strdup (g, "freebsd"); break;
1222   case OS_TYPE_UNKNOWN: default: ret = safe_strdup (g, "unknown"); break;
1223   }
1224
1225   return ret;
1226 }
1227
1228 char *
1229 guestfs__inspect_get_arch (guestfs_h *g, const char *root)
1230 {
1231   struct inspect_fs *fs = search_for_root (g, root);
1232   if (!fs)
1233     return NULL;
1234
1235   return safe_strdup (g, fs->arch ? : "unknown");
1236 }
1237
1238 char *
1239 guestfs__inspect_get_distro (guestfs_h *g, const char *root)
1240 {
1241   struct inspect_fs *fs = search_for_root (g, root);
1242   if (!fs)
1243     return NULL;
1244
1245   char *ret;
1246   switch (fs->distro) {
1247   case OS_DISTRO_ARCHLINUX: ret = safe_strdup (g, "archlinux"); break;
1248   case OS_DISTRO_DEBIAN: ret = safe_strdup (g, "debian"); break;
1249   case OS_DISTRO_FEDORA: ret = safe_strdup (g, "fedora"); break;
1250   case OS_DISTRO_GENTOO: ret = safe_strdup (g, "gentoo"); break;
1251   case OS_DISTRO_LINUX_MINT: ret = safe_strdup (g, "linuxmint"); break;
1252   case OS_DISTRO_MANDRIVA: ret = safe_strdup (g, "mandriva"); break;
1253   case OS_DISTRO_MEEGO: ret = safe_strdup (g, "meego"); break;
1254   case OS_DISTRO_PARDUS: ret = safe_strdup (g, "pardus"); break;
1255   case OS_DISTRO_REDHAT_BASED: ret = safe_strdup (g, "redhat-based"); break;
1256   case OS_DISTRO_RHEL: ret = safe_strdup (g, "rhel"); break;
1257   case OS_DISTRO_WINDOWS: ret = safe_strdup (g, "windows"); break;
1258   case OS_DISTRO_UBUNTU: ret = safe_strdup (g, "ubuntu"); break;
1259   case OS_DISTRO_UNKNOWN: default: ret = safe_strdup (g, "unknown"); break;
1260   }
1261
1262   return ret;
1263 }
1264
1265 int
1266 guestfs__inspect_get_major_version (guestfs_h *g, const char *root)
1267 {
1268   struct inspect_fs *fs = search_for_root (g, root);
1269   if (!fs)
1270     return -1;
1271
1272   return fs->major_version;
1273 }
1274
1275 int
1276 guestfs__inspect_get_minor_version (guestfs_h *g, const char *root)
1277 {
1278   struct inspect_fs *fs = search_for_root (g, root);
1279   if (!fs)
1280     return -1;
1281
1282   return fs->minor_version;
1283 }
1284
1285 char *
1286 guestfs__inspect_get_product_name (guestfs_h *g, const char *root)
1287 {
1288   struct inspect_fs *fs = search_for_root (g, root);
1289   if (!fs)
1290     return NULL;
1291
1292   return safe_strdup (g, fs->product_name ? : "unknown");
1293 }
1294
1295 char *
1296 guestfs__inspect_get_windows_systemroot (guestfs_h *g, const char *root)
1297 {
1298   struct inspect_fs *fs = search_for_root (g, root);
1299   if (!fs)
1300     return NULL;
1301
1302   if (!fs->windows_systemroot) {
1303     error (g, _("not a Windows guest, or systemroot could not be determined"));
1304     return NULL;
1305   }
1306
1307   return safe_strdup (g, fs->windows_systemroot);
1308 }
1309
1310 char **
1311 guestfs__inspect_get_mountpoints (guestfs_h *g, const char *root)
1312 {
1313   struct inspect_fs *fs = search_for_root (g, root);
1314   if (!fs)
1315     return NULL;
1316
1317   char **ret;
1318
1319   /* If no fstab information (Windows) return just the root. */
1320   if (fs->nr_fstab == 0) {
1321     ret = calloc (3, sizeof (char *));
1322     ret[0] = safe_strdup (g, "/");
1323     ret[1] = safe_strdup (g, root);
1324     ret[2] = NULL;
1325     return ret;
1326   }
1327
1328 #define CRITERION fs->fstab[i].mountpoint[0] == '/'
1329   size_t i, count = 0;
1330   for (i = 0; i < fs->nr_fstab; ++i)
1331     if (CRITERION)
1332       count++;
1333
1334   /* Hashtables have 2N+1 entries. */
1335   ret = calloc (2*count+1, sizeof (char *));
1336   if (ret == NULL) {
1337     perrorf (g, "calloc");
1338     return NULL;
1339   }
1340
1341   count = 0;
1342   for (i = 0; i < fs->nr_fstab; ++i)
1343     if (CRITERION) {
1344       ret[2*count] = safe_strdup (g, fs->fstab[i].mountpoint);
1345       ret[2*count+1] = safe_strdup (g, fs->fstab[i].device);
1346       count++;
1347     }
1348 #undef CRITERION
1349
1350   return ret;
1351 }
1352
1353 char **
1354 guestfs__inspect_get_filesystems (guestfs_h *g, const char *root)
1355 {
1356   struct inspect_fs *fs = search_for_root (g, root);
1357   if (!fs)
1358     return NULL;
1359
1360   char **ret;
1361
1362   /* If no fstab information (Windows) return just the root. */
1363   if (fs->nr_fstab == 0) {
1364     ret = calloc (2, sizeof (char *));
1365     ret[0] = safe_strdup (g, root);
1366     ret[1] = NULL;
1367     return ret;
1368   }
1369
1370   ret = calloc (fs->nr_fstab + 1, sizeof (char *));
1371   if (ret == NULL) {
1372     perrorf (g, "calloc");
1373     return NULL;
1374   }
1375
1376   size_t i;
1377   for (i = 0; i < fs->nr_fstab; ++i)
1378     ret[i] = safe_strdup (g, fs->fstab[i].device);
1379
1380   return ret;
1381 }
1382
1383 char *
1384 guestfs__inspect_get_package_format (guestfs_h *g, const char *root)
1385 {
1386   struct inspect_fs *fs = search_for_root (g, root);
1387   if (!fs)
1388     return NULL;
1389
1390   char *ret;
1391   switch (fs->package_format) {
1392   case OS_PACKAGE_FORMAT_RPM: ret = safe_strdup (g, "rpm"); break;
1393   case OS_PACKAGE_FORMAT_DEB: ret = safe_strdup (g, "deb"); break;
1394   case OS_PACKAGE_FORMAT_PACMAN: ret = safe_strdup (g, "pacman"); break;
1395   case OS_PACKAGE_FORMAT_EBUILD: ret = safe_strdup (g, "ebuild"); break;
1396   case OS_PACKAGE_FORMAT_PISI: ret = safe_strdup (g, "pisi"); break;
1397   case OS_PACKAGE_FORMAT_UNKNOWN:
1398   default:
1399     ret = safe_strdup (g, "unknown");
1400     break;
1401   }
1402
1403   return ret;
1404 }
1405
1406 char *
1407 guestfs__inspect_get_package_management (guestfs_h *g, const char *root)
1408 {
1409   struct inspect_fs *fs = search_for_root (g, root);
1410   if (!fs)
1411     return NULL;
1412
1413   char *ret;
1414   switch (fs->package_management) {
1415   case OS_PACKAGE_MANAGEMENT_YUM: ret = safe_strdup (g, "yum"); break;
1416   case OS_PACKAGE_MANAGEMENT_UP2DATE: ret = safe_strdup (g, "up2date"); break;
1417   case OS_PACKAGE_MANAGEMENT_APT: ret = safe_strdup (g, "apt"); break;
1418   case OS_PACKAGE_MANAGEMENT_PACMAN: ret = safe_strdup (g, "pacman"); break;
1419   case OS_PACKAGE_MANAGEMENT_PORTAGE: ret = safe_strdup (g, "portage"); break;
1420   case OS_PACKAGE_MANAGEMENT_PISI: ret = safe_strdup (g, "pisi"); break;
1421   case OS_PACKAGE_MANAGEMENT_URPMI: ret = safe_strdup (g, "urpmi"); break;
1422   case OS_PACKAGE_MANAGEMENT_UNKNOWN:
1423   default:
1424     ret = safe_strdup (g, "unknown");
1425     break;
1426   }
1427
1428   return ret;
1429 }
1430
1431 static struct guestfs_application_list *list_applications_rpm (guestfs_h *g, struct inspect_fs *fs);
1432 static struct guestfs_application_list *list_applications_deb (guestfs_h *g, struct inspect_fs *fs);
1433 static struct guestfs_application_list *list_applications_windows (guestfs_h *g, struct inspect_fs *fs);
1434 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);
1435 static void sort_applications (struct guestfs_application_list *);
1436
1437 /* Unlike the simple inspect-get-* calls, this one assumes that the
1438  * disks are mounted up, and reads files from the mounted disks.
1439  */
1440 struct guestfs_application_list *
1441 guestfs__inspect_list_applications (guestfs_h *g, const char *root)
1442 {
1443   struct inspect_fs *fs = search_for_root (g, root);
1444   if (!fs)
1445     return NULL;
1446
1447   struct guestfs_application_list *ret = NULL;
1448
1449   switch (fs->type) {
1450   case OS_TYPE_LINUX:
1451     switch (fs->package_format) {
1452     case OS_PACKAGE_FORMAT_RPM:
1453       ret = list_applications_rpm (g, fs);
1454       if (ret == NULL)
1455         return NULL;
1456       break;
1457
1458     case OS_PACKAGE_FORMAT_DEB:
1459       ret = list_applications_deb (g, fs);
1460       if (ret == NULL)
1461         return NULL;
1462       break;
1463
1464     case OS_PACKAGE_FORMAT_PACMAN:
1465     case OS_PACKAGE_FORMAT_EBUILD:
1466     case OS_PACKAGE_FORMAT_PISI:
1467     case OS_PACKAGE_FORMAT_UNKNOWN:
1468     default:
1469       /* nothing - keep GCC happy */;
1470     }
1471     break;
1472
1473   case OS_TYPE_WINDOWS:
1474     ret = list_applications_windows (g, fs);
1475     if (ret == NULL)
1476       return NULL;
1477     break;
1478
1479   case OS_TYPE_FREEBSD:
1480   case OS_TYPE_UNKNOWN:
1481   default:
1482       /* nothing - keep GCC happy */;
1483   }
1484
1485   if (ret == NULL) {
1486     /* Don't know how to do inspection.  Not an error, return an
1487      * empty list.
1488      */
1489     ret = safe_malloc (g, sizeof *ret);
1490     ret->len = 0;
1491     ret->val = NULL;
1492   }
1493
1494   sort_applications (ret);
1495
1496   return ret;
1497 }
1498
1499 static struct guestfs_application_list *
1500 list_applications_rpm (guestfs_h *g, struct inspect_fs *fs)
1501 {
1502   TMP_TEMPLATE_ON_STACK (tmpfile);
1503
1504   if (download_to_tmp (g, "/var/lib/rpm/Name", tmpfile, 10000000) == -1)
1505     return NULL;
1506
1507   struct guestfs_application_list *apps = NULL, *ret = NULL;
1508 #define cmd_len (strlen (tmpfile) + 64)
1509   char cmd[cmd_len];
1510   FILE *pp = NULL;
1511   char line[1024];
1512   size_t len;
1513
1514   snprintf (cmd, cmd_len, "db_dump -p '%s'", tmpfile);
1515
1516   if (g->verbose)
1517     fprintf (stderr, "list_applications_rpm: %s\n", cmd);
1518
1519   pp = popen (cmd, "r");
1520   if (pp == NULL) {
1521     perrorf (g, "popen: %s", cmd);
1522     goto out;
1523   }
1524
1525   /* Ignore everything to end-of-header marker. */
1526   for (;;) {
1527     if (fgets (line, sizeof line, pp) == NULL) {
1528       error (g, _("unexpected end of output from db_dump command"));
1529       goto out;
1530     }
1531
1532     len = strlen (line);
1533     if (len > 0 && line[len-1] == '\n') {
1534       line[len-1] = '\0';
1535       len--;
1536     }
1537
1538     if (STREQ (line, "HEADER=END"))
1539       break;
1540   }
1541
1542   /* Allocate 'apps' list. */
1543   apps = safe_malloc (g, sizeof *apps);
1544   apps->len = 0;
1545   apps->val = NULL;
1546
1547   /* Read alternate lines until end of data marker. */
1548   for (;;) {
1549     if (fgets (line, sizeof line, pp) == NULL) {
1550       error (g, _("unexpected end of output from db_dump command"));
1551       goto out;
1552     }
1553
1554     len = strlen (line);
1555     if (len > 0 && line[len-1] == '\n') {
1556       line[len-1] = '\0';
1557       len--;
1558     }
1559
1560     if (STREQ (line, "DATA=END"))
1561       break;
1562
1563     char *p = line;
1564     if (len > 0 && line[0] == ' ')
1565       p = line+1;
1566     /* Ignore any application name that contains non-printable chars.
1567      * In the db_dump output these would be escaped with backslash, so
1568      * we can just ignore any such line.
1569      */
1570     if (strchr (p, '\\') == NULL)
1571       add_application (g, apps, p, "", 0, "", "", "", "", "", "");
1572
1573     /* Discard next line. */
1574     if (fgets (line, sizeof line, pp) == NULL) {
1575       error (g, _("unexpected end of output from db_dump command"));
1576       goto out;
1577     }
1578   }
1579
1580   /* Catch errors from the db_dump command. */
1581   if (pclose (pp) == -1) {
1582     perrorf (g, "pclose: %s", cmd);
1583     goto out;
1584   }
1585   pp = NULL;
1586
1587   ret = apps;
1588
1589  out:
1590   if (ret == NULL && apps != NULL)
1591     guestfs_free_application_list (apps);
1592   if (pp)
1593     pclose (pp);
1594   unlink (tmpfile);
1595 #undef cmd_len
1596
1597   return ret;
1598 }
1599
1600 static struct guestfs_application_list *
1601 list_applications_deb (guestfs_h *g, struct inspect_fs *fs)
1602 {
1603   TMP_TEMPLATE_ON_STACK (tmpfile);
1604
1605   if (download_to_tmp (g, "/var/lib/dpkg/status", tmpfile, 10000000) == -1)
1606     return NULL;
1607
1608   struct guestfs_application_list *apps = NULL, *ret = NULL;
1609   FILE *fp = NULL;
1610   char line[1024];
1611   size_t len;
1612   char *name = NULL, *version = NULL, *release = NULL;
1613   int installed_flag = 0;
1614
1615   fp = fopen (tmpfile, "r");
1616   if (fp == NULL) {
1617     perrorf (g, "fopen: %s", tmpfile);
1618     goto out;
1619   }
1620
1621   /* Allocate 'apps' list. */
1622   apps = safe_malloc (g, sizeof *apps);
1623   apps->len = 0;
1624   apps->val = NULL;
1625
1626   /* Read the temporary file.  Each package entry is separated by
1627    * a blank line.
1628    * XXX Strictly speaking this is in mailbox header format, so it
1629    * would be possible for fields to spread across multiple lines,
1630    * although for the short fields that we are concerned about this is
1631    * unlikely and not seen in practice.
1632    */
1633   while (fgets (line, sizeof line, fp) != NULL) {
1634     len = strlen (line);
1635     if (len > 0 && line[len-1] == '\n') {
1636       line[len-1] = '\0';
1637       len--;
1638     }
1639
1640     if (STRPREFIX (line, "Package: ")) {
1641       free (name);
1642       name = safe_strdup (g, &line[9]);
1643     }
1644     else if (STRPREFIX (line, "Status: ")) {
1645       installed_flag = strstr (&line[8], "installed") != NULL;
1646     }
1647     else if (STRPREFIX (line, "Version: ")) {
1648       free (version);
1649       free (release);
1650       char *p = strchr (&line[9], '-');
1651       if (p) {
1652         *p = '\0';
1653         version = safe_strdup (g, &line[9]);
1654         release = safe_strdup (g, p+1);
1655       } else {
1656         version = safe_strdup (g, &line[9]);
1657         release = NULL;
1658       }
1659     }
1660     else if (STREQ (line, "")) {
1661       if (installed_flag && name && version)
1662         add_application (g, apps, name, "", 0, version, release ? : "",
1663                          "", "", "", "");
1664       free (name);
1665       free (version);
1666       free (release);
1667       name = version = release = NULL;
1668       installed_flag = 0;
1669     }
1670   }
1671
1672   if (fclose (fp) == -1) {
1673     perrorf (g, "fclose: %s", tmpfile);
1674     goto out;
1675   }
1676   fp = NULL;
1677
1678   ret = apps;
1679
1680  out:
1681   if (ret == NULL && apps != NULL)
1682     guestfs_free_application_list (apps);
1683   if (fp)
1684     fclose (fp);
1685   free (name);
1686   free (version);
1687   free (release);
1688   unlink (tmpfile);
1689   return ret;
1690 }
1691
1692 /* XXX We already download the SOFTWARE hive when doing general
1693  * inspection.  We could avoid this second download of the same file
1694  * by caching these entries in the handle.
1695  */
1696 static struct guestfs_application_list *
1697 list_applications_windows (guestfs_h *g, struct inspect_fs *fs)
1698 {
1699   TMP_TEMPLATE_ON_STACK (software_local);
1700
1701   size_t len = strlen (fs->windows_systemroot) + 64;
1702   char software[len];
1703   snprintf (software, len, "%s/system32/config/software",
1704             fs->windows_systemroot);
1705
1706   char *software_path = resolve_windows_path_silently (g, software);
1707   if (!software_path)
1708     /* If the software hive doesn't exist, just accept that we cannot
1709      * find product_name etc.
1710      */
1711     return 0;
1712
1713   struct guestfs_application_list *apps = NULL, *ret = NULL;
1714   hive_h *h = NULL;
1715   hive_node_h *children = NULL;
1716
1717   if (download_to_tmp (g, software_path, software_local, 100000000) == -1)
1718     goto out;
1719
1720   h = hivex_open (software_local, g->verbose ? HIVEX_OPEN_VERBOSE : 0);
1721   if (h == NULL) {
1722     perrorf (g, "hivex_open");
1723     goto out;
1724   }
1725
1726   hive_node_h node = hivex_root (h);
1727   const char *hivepath[] =
1728     { "Microsoft", "Windows", "CurrentVersion", "Uninstall" };
1729   size_t i;
1730   for (i = 0;
1731        node != 0 && i < sizeof hivepath / sizeof hivepath[0];
1732        ++i) {
1733     node = hivex_node_get_child (h, node, hivepath[i]);
1734   }
1735
1736   if (node == 0) {
1737     perrorf (g, "hivex: cannot locate HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall");
1738     goto out;
1739   }
1740
1741   children = hivex_node_children (h, node);
1742   if (children == NULL) {
1743     perrorf (g, "hivex_node_children");
1744     goto out;
1745   }
1746
1747   /* Allocate 'apps' list. */
1748   apps = safe_malloc (g, sizeof *apps);
1749   apps->len = 0;
1750   apps->val = NULL;
1751
1752   /* Consider any child node that has a DisplayName key.
1753    * See also:
1754    * http://nsis.sourceforge.net/Add_uninstall_information_to_Add/Remove_Programs#Optional_values
1755    */
1756   for (i = 0; children[i] != 0; ++i) {
1757     hive_value_h value;
1758     char *name = NULL;
1759     char *display_name = NULL;
1760     char *version = NULL;
1761     char *install_path = NULL;
1762     char *publisher = NULL;
1763     char *url = NULL;
1764     char *comments = NULL;
1765
1766     /* Use the node name as a proxy for the package name in Linux.  The
1767      * display name is not language-independent, so it cannot be used.
1768      */
1769     name = hivex_node_name (h, children[i]);
1770     if (name == NULL) {
1771       perrorf (g, "hivex_node_get_name");
1772       goto out;
1773     }
1774
1775     value = hivex_node_get_value (h, children[i], "DisplayName");
1776     if (value) {
1777       display_name = hivex_value_string (h, value);
1778       if (display_name) {
1779         value = hivex_node_get_value (h, children[i], "DisplayVersion");
1780         if (value)
1781           version = hivex_value_string (h, value);
1782         value = hivex_node_get_value (h, children[i], "InstallLocation");
1783         if (value)
1784           install_path = hivex_value_string (h, value);
1785         value = hivex_node_get_value (h, children[i], "Publisher");
1786         if (value)
1787           publisher = hivex_value_string (h, value);
1788         value = hivex_node_get_value (h, children[i], "URLInfoAbout");
1789         if (value)
1790           url = hivex_value_string (h, value);
1791         value = hivex_node_get_value (h, children[i], "Comments");
1792         if (value)
1793           comments = hivex_value_string (h, value);
1794
1795         add_application (g, apps, name, display_name, 0,
1796                          version ? : "",
1797                          "",
1798                          install_path ? : "",
1799                          publisher ? : "",
1800                          url ? : "",
1801                          comments ? : "");
1802       }
1803     }
1804
1805     free (name);
1806     free (display_name);
1807     free (version);
1808     free (install_path);
1809     free (publisher);
1810     free (url);
1811     free (comments);
1812   }
1813
1814   ret = apps;
1815
1816  out:
1817   if (ret == NULL && apps != NULL)
1818     guestfs_free_application_list (apps);
1819   if (h) hivex_close (h);
1820   free (children);
1821   free (software_path);
1822
1823   /* Free up the temporary file. */
1824   unlink (software_local);
1825 #undef software_local_len
1826
1827   return ret;
1828 }
1829
1830 static void
1831 add_application (guestfs_h *g, struct guestfs_application_list *apps,
1832                  const char *name, const char *display_name, int32_t epoch,
1833                  const char *version, const char *release,
1834                  const char *install_path,
1835                  const char *publisher, const char *url,
1836                  const char *description)
1837 {
1838   apps->len++;
1839   apps->val = safe_realloc (g, apps->val,
1840                             apps->len * sizeof (struct guestfs_application));
1841   apps->val[apps->len-1].app_name = safe_strdup (g, name);
1842   apps->val[apps->len-1].app_display_name = safe_strdup (g, display_name);
1843   apps->val[apps->len-1].app_epoch = epoch;
1844   apps->val[apps->len-1].app_version = safe_strdup (g, version);
1845   apps->val[apps->len-1].app_release = safe_strdup (g, release);
1846   apps->val[apps->len-1].app_install_path = safe_strdup (g, install_path);
1847   /* XXX Translated path is not implemented yet. */
1848   apps->val[apps->len-1].app_trans_path = safe_strdup (g, "");
1849   apps->val[apps->len-1].app_publisher = safe_strdup (g, publisher);
1850   apps->val[apps->len-1].app_url = safe_strdup (g, url);
1851   /* XXX The next two are not yet implemented for any package
1852    * format, but we could easily support them for rpm and deb.
1853    */
1854   apps->val[apps->len-1].app_source_package = safe_strdup (g, "");
1855   apps->val[apps->len-1].app_summary = safe_strdup (g, "");
1856   apps->val[apps->len-1].app_description = safe_strdup (g, description);
1857 }
1858
1859 /* Sort applications by name before returning the list. */
1860 static int
1861 compare_applications (const void *vp1, const void *vp2)
1862 {
1863   const struct guestfs_application *v1 = vp1;
1864   const struct guestfs_application *v2 = vp2;
1865
1866   return strcmp (v1->app_name, v2->app_name);
1867 }
1868
1869 static void
1870 sort_applications (struct guestfs_application_list *apps)
1871 {
1872   if (apps && apps->val)
1873     qsort (apps->val, apps->len, sizeof (struct guestfs_application),
1874            compare_applications);
1875 }
1876
1877 /* Download to a guest file to a local temporary file.  Refuse to
1878  * download the guest file if it is larger than max_size.  The caller
1879  * is responsible for deleting the temporary file after use.
1880  */
1881 static int
1882 download_to_tmp (guestfs_h *g, const char *filename,
1883                  char *localtmp, int64_t max_size)
1884 {
1885   int fd;
1886   char buf[32];
1887   int64_t size;
1888
1889   size = guestfs_filesize (g, filename);
1890   if (size == -1)
1891     /* guestfs_filesize failed and has already set error in handle */
1892     return -1;
1893   if (size > max_size) {
1894     error (g, _("size of %s is unreasonably large (%" PRIi64 " bytes)"),
1895            filename, size);
1896     return -1;
1897   }
1898
1899   fd = mkstemp (localtmp);
1900   if (fd == -1) {
1901     perrorf (g, "mkstemp");
1902     return -1;
1903   }
1904
1905   snprintf (buf, sizeof buf, "/dev/fd/%d", fd);
1906
1907   if (guestfs_download (g, filename, buf) == -1) {
1908     close (fd);
1909     unlink (localtmp);
1910     return -1;
1911   }
1912
1913   if (close (fd) == -1) {
1914     perrorf (g, "close: %s", localtmp);
1915     unlink (localtmp);
1916     return -1;
1917   }
1918
1919   return 0;
1920 }
1921
1922 /* Call 'f' with Augeas opened and having parsed 'filename' (this file
1923  * must exist).  As a security measure, this bails if the file is too
1924  * large for a reasonable configuration file.  After the call to 'f'
1925  * Augeas is closed.
1926  */
1927 static int
1928 inspect_with_augeas (guestfs_h *g, struct inspect_fs *fs, const char *filename,
1929                      int (*f) (guestfs_h *, struct inspect_fs *))
1930 {
1931   /* Security: Refuse to do this if filename is too large. */
1932   int64_t size = guestfs_filesize (g, filename);
1933   if (size == -1)
1934     /* guestfs_filesize failed and has already set error in handle */
1935     return -1;
1936   if (size > 100000) {
1937     error (g, _("size of %s is unreasonably large (%" PRIi64 " bytes)"),
1938            filename, size);
1939     return -1;
1940   }
1941
1942   /* If !feature_available (g, "augeas") then the next call will fail.
1943    * Arguably we might want to fall back to a non-Augeas method in
1944    * this case.
1945    */
1946   if (guestfs_aug_init (g, "/", 16|32) == -1)
1947     return -1;
1948
1949   int r = -1;
1950
1951   /* Tell Augeas to only load one file (thanks RaphaĆ«l Pinson). */
1952   char buf[strlen (filename) + 64];
1953   snprintf (buf, strlen (filename) + 64, "/augeas/load//incl[. != \"%s\"]",
1954             filename);
1955   if (guestfs_aug_rm (g, buf) == -1)
1956     goto out;
1957
1958   if (guestfs_aug_load (g) == -1)
1959     goto out;
1960
1961   r = f (g, fs);
1962
1963  out:
1964   guestfs_aug_close (g);
1965
1966   return r;
1967 }
1968
1969 #else /* no PCRE or hivex at compile time */
1970
1971 /* XXX These functions should be in an optgroup. */
1972
1973 #define NOT_IMPL(r)                                                     \
1974   error (g, _("inspection API not available since this version of libguestfs was compiled without PCRE or hivex libraries")); \
1975   return r
1976
1977 char **
1978 guestfs__inspect_os (guestfs_h *g)
1979 {
1980   NOT_IMPL(NULL);
1981 }
1982
1983 char **
1984 guestfs__inspect_get_roots (guestfs_h *g)
1985 {
1986   NOT_IMPL(NULL);
1987 }
1988
1989 char *
1990 guestfs__inspect_get_type (guestfs_h *g, const char *root)
1991 {
1992   NOT_IMPL(NULL);
1993 }
1994
1995 char *
1996 guestfs__inspect_get_arch (guestfs_h *g, const char *root)
1997 {
1998   NOT_IMPL(NULL);
1999 }
2000
2001 char *
2002 guestfs__inspect_get_distro (guestfs_h *g, const char *root)
2003 {
2004   NOT_IMPL(NULL);
2005 }
2006
2007 int
2008 guestfs__inspect_get_major_version (guestfs_h *g, const char *root)
2009 {
2010   NOT_IMPL(-1);
2011 }
2012
2013 int
2014 guestfs__inspect_get_minor_version (guestfs_h *g, const char *root)
2015 {
2016   NOT_IMPL(-1);
2017 }
2018
2019 char *
2020 guestfs__inspect_get_product_name (guestfs_h *g, const char *root)
2021 {
2022   NOT_IMPL(NULL);
2023 }
2024
2025 char *
2026 guestfs__inspect_get_windows_systemroot (guestfs_h *g, const char *root)
2027 {
2028   NOT_IMPL(NULL);
2029 }
2030
2031 char **
2032 guestfs__inspect_get_mountpoints (guestfs_h *g, const char *root)
2033 {
2034   NOT_IMPL(NULL);
2035 }
2036
2037 char **
2038 guestfs__inspect_get_filesystems (guestfs_h *g, const char *root)
2039 {
2040   NOT_IMPL(NULL);
2041 }
2042
2043 char *
2044 guestfs__inspect_get_package_format (guestfs_h *g, const char *root)
2045 {
2046   NOT_IMPL(NULL);
2047 }
2048
2049 char *
2050 guestfs__inspect_get_package_management (guestfs_h *g, const char *root)
2051 {
2052   NOT_IMPL(NULL);
2053 }
2054
2055 struct guestfs_application_list *
2056 guestfs__inspect_list_applications (guestfs_h *g, const char *root)
2057 {
2058   NOT_IMPL(NULL);
2059 }
2060
2061 #endif /* no PCRE or hivex at compile time */
2062
2063 void
2064 guestfs___free_inspect_info (guestfs_h *g)
2065 {
2066   size_t i;
2067   for (i = 0; i < g->nr_fses; ++i) {
2068     free (g->fses[i].device);
2069     free (g->fses[i].product_name);
2070     free (g->fses[i].arch);
2071     free (g->fses[i].windows_systemroot);
2072     size_t j;
2073     for (j = 0; j < g->fses[i].nr_fstab; ++j) {
2074       free (g->fses[i].fstab[j].device);
2075       free (g->fses[i].fstab[j].mountpoint);
2076     }
2077     free (g->fses[i].fstab);
2078   }
2079   free (g->fses);
2080   g->nr_fses = 0;
2081   g->fses = NULL;
2082 }
2083
2084 /* In the Perl code this is a public function. */
2085 int
2086 guestfs___feature_available (guestfs_h *g, const char *feature)
2087 {
2088   /* If there's an error we should ignore it, so to do that we have to
2089    * temporarily replace the error handler with a null one.
2090    */
2091   guestfs_error_handler_cb old_error_cb = g->error_cb;
2092   g->error_cb = NULL;
2093
2094   const char *groups[] = { feature, NULL };
2095   int r = guestfs_available (g, (char * const *) groups);
2096
2097   g->error_cb = old_error_cb;
2098
2099   return r == 0 ? 1 : 0;
2100 }
2101
2102 #ifdef HAVE_PCRE
2103
2104 /* Match a regular expression which contains no captures.  Returns
2105  * true if it matches or false if it doesn't.
2106  */
2107 int
2108 guestfs___match (guestfs_h *g, const char *str, const pcre *re)
2109 {
2110   size_t len = strlen (str);
2111   int vec[30], r;
2112
2113   r = pcre_exec (re, NULL, str, len, 0, 0, vec, sizeof vec / sizeof vec[0]);
2114   if (r == PCRE_ERROR_NOMATCH)
2115     return 0;
2116   if (r != 1) {
2117     /* Internal error -- should not happen. */
2118     fprintf (stderr, "libguestfs: %s: %s: internal error: pcre_exec returned unexpected error code %d when matching against the string \"%s\"\n",
2119              __FILE__, __func__, r, str);
2120     return 0;
2121   }
2122
2123   return 1;
2124 }
2125
2126 /* Match a regular expression which contains exactly one capture.  If
2127  * the string matches, return the capture, otherwise return NULL.  The
2128  * caller must free the result.
2129  */
2130 char *
2131 guestfs___match1 (guestfs_h *g, const char *str, const pcre *re)
2132 {
2133   size_t len = strlen (str);
2134   int vec[30], r;
2135
2136   r = pcre_exec (re, NULL, str, len, 0, 0, vec, sizeof vec / sizeof vec[0]);
2137   if (r == PCRE_ERROR_NOMATCH)
2138     return NULL;
2139   if (r != 2) {
2140     /* Internal error -- should not happen. */
2141     fprintf (stderr, "libguestfs: %s: %s: internal error: pcre_exec returned unexpected error code %d when matching against the string \"%s\"\n",
2142              __FILE__, __func__, r, str);
2143     return NULL;
2144   }
2145
2146   return safe_strndup (g, &str[vec[2]], vec[3]-vec[2]);
2147 }
2148
2149 /* Match a regular expression which contains exactly two captures. */
2150 int
2151 guestfs___match2 (guestfs_h *g, const char *str, const pcre *re,
2152                   char **ret1, char **ret2)
2153 {
2154   size_t len = strlen (str);
2155   int vec[30], r;
2156
2157   r = pcre_exec (re, NULL, str, len, 0, 0, vec, 30);
2158   if (r == PCRE_ERROR_NOMATCH)
2159     return 0;
2160   if (r != 3) {
2161     /* Internal error -- should not happen. */
2162     fprintf (stderr, "libguestfs: %s: %s: internal error: pcre_exec returned unexpected error code %d when matching against the string \"%s\"\n",
2163              __FILE__, __func__, r, str);
2164     return 0;
2165   }
2166
2167   *ret1 = safe_strndup (g, &str[vec[2]], vec[3]-vec[2]);
2168   *ret2 = safe_strndup (g, &str[vec[4]], vec[5]-vec[4]);
2169
2170   return 1;
2171 }
2172
2173 /* Match a regular expression which contains exactly three captures. */
2174 int
2175 guestfs___match3 (guestfs_h *g, const char *str, const pcre *re,
2176                   char **ret1, char **ret2, char **ret3)
2177 {
2178   size_t len = strlen (str);
2179   int vec[30], r;
2180
2181   r = pcre_exec (re, NULL, str, len, 0, 0, vec, 30);
2182   if (r == PCRE_ERROR_NOMATCH)
2183     return 0;
2184   if (r != 4) {
2185     /* Internal error -- should not happen. */
2186     fprintf (stderr, "libguestfs: %s: %s: internal error: pcre_exec returned unexpected error code %d when matching against the string \"%s\"\n",
2187              __FILE__, __func__, r, str);
2188     return 0;
2189   }
2190
2191   *ret1 = safe_strndup (g, &str[vec[2]], vec[3]-vec[2]);
2192   *ret2 = safe_strndup (g, &str[vec[4]], vec[5]-vec[4]);
2193   *ret3 = safe_strndup (g, &str[vec[6]], vec[7]-vec[6]);
2194
2195   return 1;
2196 }
2197
2198 #endif /* HAVE_PCRE */