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