lib: Make pcre, libmagic and hivex libraries optional.
[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_windows_version;
61
62 static void compile_regexps (void) __attribute__((constructor));
63 static void free_regexps (void) __attribute__((destructor));
64
65 static void
66 compile_regexps (void)
67 {
68   const char *err;
69   int offset;
70
71 #define COMPILE(re,pattern,options)                                     \
72   do {                                                                  \
73     re = pcre_compile ((pattern), (options), &err, &offset, NULL);      \
74     if (re == NULL) {                                                   \
75       ignore_value (write (2, err, strlen (err)));                      \
76       abort ();                                                         \
77     }                                                                   \
78   } while (0)
79
80   COMPILE (re_fedora, "Fedora release (\\d+)", 0);
81   COMPILE (re_rhel_old,
82            "(?:Red Hat Enterprise Linux|CentOS|Scientific Linux).*release (\\d+).*Update (\\d+)", 0);
83   COMPILE (re_rhel,
84            "(?:Red Hat Enterprise Linux|CentOS|Scientific Linux).*release (\\d+)\\.(\\d+)", 0);
85   COMPILE (re_rhel_no_minor,
86            "(?:Red Hat Enterprise Linux|CentOS|Scientific Linux).*release (\\d+)", 0);
87   COMPILE (re_major_minor, "(\\d+)\\.(\\d+)", 0);
88   COMPILE (re_aug_seq, "/\\d+$", 0);
89   COMPILE (re_xdev, "^/dev/(?:h|s|v|xv)d([a-z]\\d*)$", 0);
90   COMPILE (re_windows_version, "^(\\d+)\\.(\\d+)", 0);
91 }
92
93 static void
94 free_regexps (void)
95 {
96   pcre_free (re_fedora);
97   pcre_free (re_rhel_old);
98   pcre_free (re_rhel);
99   pcre_free (re_rhel_no_minor);
100   pcre_free (re_major_minor);
101   pcre_free (re_aug_seq);
102   pcre_free (re_xdev);
103   pcre_free (re_windows_version);
104 }
105
106 /* The main inspection code. */
107 static int check_for_filesystem_on (guestfs_h *g, const char *device);
108
109 char **
110 guestfs__inspect_os (guestfs_h *g)
111 {
112   /* Remove any information previously stored in the handle. */
113   guestfs___free_inspect_info (g);
114
115   if (guestfs_umount_all (g) == -1)
116     return NULL;
117
118   /* Iterate over all possible devices.  Try to mount each
119    * (read-only).  Examine ones which contain filesystems and add that
120    * information to the handle.
121    */
122   /* Look to see if any devices directly contain filesystems (RHBZ#590167). */
123   char **devices;
124   devices = guestfs_list_devices (g);
125   if (devices == NULL)
126     return NULL;
127
128   size_t i;
129   for (i = 0; devices[i] != NULL; ++i) {
130     if (check_for_filesystem_on (g, devices[i]) == -1) {
131       guestfs___free_string_list (devices);
132       guestfs___free_inspect_info (g);
133       return NULL;
134     }
135   }
136   guestfs___free_string_list (devices);
137
138   /* Look at all partitions. */
139   char **partitions;
140   partitions = guestfs_list_partitions (g);
141   if (partitions == NULL) {
142     guestfs___free_inspect_info (g);
143     return NULL;
144   }
145
146   for (i = 0; partitions[i] != NULL; ++i) {
147     if (check_for_filesystem_on (g, partitions[i]) == -1) {
148       guestfs___free_string_list (partitions);
149       guestfs___free_inspect_info (g);
150       return NULL;
151     }
152   }
153   guestfs___free_string_list (partitions);
154
155   /* Look at all LVs. */
156   if (guestfs___feature_available (g, "lvm2")) {
157     char **lvs;
158     lvs = guestfs_lvs (g);
159     if (lvs == NULL) {
160       guestfs___free_inspect_info (g);
161       return NULL;
162     }
163
164     for (i = 0; lvs[i] != NULL; ++i) {
165       if (check_for_filesystem_on (g, lvs[i]) == -1) {
166         guestfs___free_string_list (lvs);
167         guestfs___free_inspect_info (g);
168         return NULL;
169       }
170     }
171     guestfs___free_string_list (lvs);
172   }
173
174   /* At this point we have, in the handle, a list of all filesystems
175    * found and data about each one.  Now we assemble the list of
176    * filesystems which are root devices and return that to the user.
177    */
178   size_t count = 0;
179   for (i = 0; i < g->nr_fses; ++i)
180     if (g->fses[i].is_root)
181       count++;
182
183   char **ret = calloc (count+1, sizeof (char *));
184   if (ret == NULL) {
185     perrorf (g, "calloc");
186     guestfs___free_inspect_info (g);
187     return NULL;
188   }
189
190   count = 0;
191   for (i = 0; i < g->nr_fses; ++i) {
192     if (g->fses[i].is_root) {
193       ret[count] = safe_strdup (g, g->fses[i].device);
194       count++;
195     }
196   }
197   ret[count] = NULL;
198
199   return ret;
200 }
201
202 /* Find out if 'device' contains a filesystem.  If it does, add
203  * another entry in g->fses.
204  */
205 static int check_filesystem (guestfs_h *g, const char *device);
206 static int check_linux_root (guestfs_h *g, struct inspect_fs *fs);
207 static int check_fstab (guestfs_h *g, struct inspect_fs *fs);
208 static int check_windows_root (guestfs_h *g, struct inspect_fs *fs);
209 static int check_windows_arch (guestfs_h *g, struct inspect_fs *fs);
210 static int check_windows_registry (guestfs_h *g, struct inspect_fs *fs);
211 static char *resolve_windows_path_silently (guestfs_h *g, const char *);
212 static int extend_fses (guestfs_h *g);
213 static int parse_unsigned_int (guestfs_h *g, const char *str);
214 static int add_fstab_entry (guestfs_h *g, struct inspect_fs *fs,
215                             const char *spec, const char *mp);
216 static char *resolve_fstab_device (guestfs_h *g, const char *spec);
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   /* 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   /* Linux root? */
280   else if (guestfs_is_dir (g, "/etc") > 0 &&
281            guestfs_is_dir (g, "/bin") > 0 &&
282            guestfs_is_file (g, "/etc/fstab") > 0) {
283     fs->is_root = 1;
284     fs->content = FS_CONTENT_LINUX_ROOT;
285     if (check_linux_root (g, fs) == -1)
286       return -1;
287   }
288   /* Linux /usr/local? */
289   else if (guestfs_is_dir (g, "/etc") > 0 &&
290            guestfs_is_dir (g, "/bin") > 0 &&
291            guestfs_is_dir (g, "/share") > 0 &&
292            guestfs_exists (g, "/local") == 0 &&
293            guestfs_is_file (g, "/etc/fstab") == 0)
294     fs->content = FS_CONTENT_LINUX_USR_LOCAL;
295   /* Linux /usr? */
296   else if (guestfs_is_dir (g, "/etc") > 0 &&
297            guestfs_is_dir (g, "/bin") > 0 &&
298            guestfs_is_dir (g, "/share") > 0 &&
299            guestfs_exists (g, "/local") > 0 &&
300            guestfs_is_file (g, "/etc/fstab") == 0)
301     fs->content = FS_CONTENT_LINUX_USR;
302   /* Linux /var? */
303   else if (guestfs_is_dir (g, "/log") > 0 &&
304            guestfs_is_dir (g, "/run") > 0 &&
305            guestfs_is_dir (g, "/spool") > 0)
306     fs->content = FS_CONTENT_LINUX_VAR;
307   /* Windows root? */
308   else if (guestfs_is_file (g, "/AUTOEXEC.BAT") > 0 ||
309            guestfs_is_file (g, "/autoexec.bat") > 0 ||
310            guestfs_is_dir (g, "/Program Files") > 0 ||
311            guestfs_is_dir (g, "/WINDOWS") > 0 ||
312            guestfs_is_dir (g, "/Windows") > 0 ||
313            guestfs_is_dir (g, "/windows") > 0 ||
314            guestfs_is_dir (g, "/WIN32") > 0 ||
315            guestfs_is_dir (g, "/Win32") > 0 ||
316            guestfs_is_dir (g, "/WINNT") > 0 ||
317            guestfs_is_file (g, "/boot.ini") > 0 ||
318            guestfs_is_file (g, "/ntldr") > 0) {
319     fs->is_root = 1;
320     fs->content = FS_CONTENT_WINDOWS_ROOT;
321     if (check_windows_root (g, fs) == -1)
322       return -1;
323   }
324
325   return 0;
326 }
327
328 /* Set fs->product_name to the first line of the release file. */
329 static int
330 parse_release_file (guestfs_h *g, struct inspect_fs *fs,
331                     const char *release_filename)
332 {
333   char **product_name = guestfs_head_n (g, 1, release_filename);
334   if (product_name == NULL)
335     return -1;
336   if (product_name[0] == NULL) {
337     error (g, "%s: file is empty", release_filename);
338     guestfs___free_string_list (product_name);
339     return -1;
340   }
341
342   /* Note that this string becomes owned by the handle and will
343    * be freed by guestfs___free_inspect_info.
344    */
345   fs->product_name = product_name[0];
346   free (product_name);
347
348   return 0;
349 }
350
351 /* Parse generic MAJOR.MINOR from the fs->product_name string. */
352 static int
353 parse_major_minor (guestfs_h *g, struct inspect_fs *fs)
354 {
355   char *major, *minor;
356
357   if (match2 (g, fs->product_name, re_major_minor, &major, &minor)) {
358     fs->major_version = parse_unsigned_int (g, major);
359     free (major);
360     if (fs->major_version == -1) {
361       free (minor);
362       return -1;
363     }
364     fs->minor_version = parse_unsigned_int (g, minor);
365     free (minor);
366     if (fs->minor_version == -1)
367       return -1;
368   }
369   return 0;
370 }
371
372 /* Ubuntu has /etc/lsb-release containing:
373  *   DISTRIB_ID=Ubuntu                                # Distro
374  *   DISTRIB_RELEASE=10.04                            # Version
375  *   DISTRIB_CODENAME=lucid
376  *   DISTRIB_DESCRIPTION="Ubuntu 10.04.1 LTS"         # Product name
377  * In theory other distros could have this LSB file, but none do.
378  */
379 static int
380 parse_lsb_release (guestfs_h *g, struct inspect_fs *fs)
381 {
382   char **lines;
383   size_t i;
384   int r = 0;
385
386   lines = guestfs_head_n (g, 10, "/etc/lsb-release");
387   if (lines == NULL)
388     return -1;
389
390   for (i = 0; lines[i] != NULL; ++i) {
391     if (fs->distro == 0 &&
392         STREQ (lines[i], "DISTRIB_ID=Ubuntu")) {
393       fs->distro = OS_DISTRO_UBUNTU;
394       r = 1;
395     }
396     else if (STRPREFIX (lines[i], "DISTRIB_RELEASE=")) {
397       char *major, *minor;
398       if (match2 (g, &lines[i][16], re_major_minor, &major, &minor)) {
399         fs->major_version = parse_unsigned_int (g, major);
400         free (major);
401         if (fs->major_version == -1) {
402           free (minor);
403           guestfs___free_string_list (lines);
404           return -1;
405         }
406         fs->minor_version = parse_unsigned_int (g, minor);
407         free (minor);
408         if (fs->minor_version == -1) {
409           guestfs___free_string_list (lines);
410           return -1;
411         }
412       }
413     }
414     else if (fs->product_name == NULL &&
415              (STRPREFIX (lines[i], "DISTRIB_DESCRIPTION=\"") ||
416               STRPREFIX (lines[i], "DISTRIB_DESCRIPTION='"))) {
417       size_t len = strlen (lines[i]) - 21 - 1;
418       fs->product_name = safe_strndup (g, &lines[i][21], len);
419       r = 1;
420     }
421     else if (fs->product_name == NULL &&
422              STRPREFIX (lines[i], "DISTRIB_DESCRIPTION=")) {
423       size_t len = strlen (lines[i]) - 20;
424       fs->product_name = safe_strndup (g, &lines[i][20], len);
425       r = 1;
426     }
427   }
428
429   guestfs___free_string_list (lines);
430   return r;
431 }
432
433 /* The currently mounted device is known to be a Linux root.  Try to
434  * determine from this the distro, version, etc.  Also parse
435  * /etc/fstab to determine the arrangement of mountpoints and
436  * associated devices.
437  */
438 static int
439 check_linux_root (guestfs_h *g, struct inspect_fs *fs)
440 {
441   int r;
442
443   fs->type = OS_TYPE_LINUX;
444
445   if (guestfs_exists (g, "/etc/lsb-release") > 0) {
446     r = parse_lsb_release (g, fs);
447     if (r == -1)        /* error */
448       return -1;
449     if (r == 1)         /* ok - detected the release from this file */
450       goto skip_release_checks;
451   }
452
453   if (guestfs_exists (g, "/etc/redhat-release") > 0) {
454     fs->distro = OS_DISTRO_REDHAT_BASED; /* Something generic Red Hat-like. */
455
456     if (parse_release_file (g, fs, "/etc/redhat-release") == -1)
457       return -1;
458
459     char *major, *minor;
460     if ((major = match1 (g, fs->product_name, re_fedora)) != NULL) {
461       fs->distro = OS_DISTRO_FEDORA;
462       fs->major_version = parse_unsigned_int (g, major);
463       free (major);
464       if (fs->major_version == -1)
465         return -1;
466     }
467     else if (match2 (g, fs->product_name, re_rhel_old, &major, &minor) ||
468              match2 (g, fs->product_name, re_rhel, &major, &minor)) {
469       fs->distro = OS_DISTRO_RHEL;
470       fs->major_version = parse_unsigned_int (g, major);
471       free (major);
472       if (fs->major_version == -1) {
473         free (minor);
474         return -1;
475       }
476       fs->minor_version = parse_unsigned_int (g, minor);
477       free (minor);
478       if (fs->minor_version == -1)
479         return -1;
480     }
481     else if ((major = match1 (g, fs->product_name, re_rhel_no_minor)) != NULL) {
482       fs->distro = OS_DISTRO_RHEL;
483       fs->major_version = parse_unsigned_int (g, major);
484       free (major);
485       if (fs->major_version == -1)
486         return -1;
487       fs->minor_version = 0;
488     }
489   }
490   else if (guestfs_exists (g, "/etc/debian_version") > 0) {
491     fs->distro = OS_DISTRO_DEBIAN;
492
493     if (parse_release_file (g, fs, "/etc/debian_version") == -1)
494       return -1;
495
496     if (parse_major_minor (g, fs) == -1)
497       return -1;
498   }
499   else if (guestfs_exists (g, "/etc/pardus-release") > 0) {
500     fs->distro = OS_DISTRO_PARDUS;
501
502     if (parse_release_file (g, fs, "/etc/pardus-release") == -1)
503       return -1;
504
505     if (parse_major_minor (g, fs) == -1)
506       return -1;
507   }
508   else if (guestfs_exists (g, "/etc/arch-release") > 0) {
509     fs->distro = OS_DISTRO_ARCHLINUX;
510
511     /* /etc/arch-release file is empty and I can't see a way to
512      * determine the actual release or product string.
513      */
514   }
515   else if (guestfs_exists (g, "/etc/gentoo-release") > 0) {
516     fs->distro = OS_DISTRO_GENTOO;
517
518     if (parse_release_file (g, fs, "/etc/gentoo-release") == -1)
519       return -1;
520
521     if (parse_major_minor (g, fs) == -1)
522       return -1;
523   }
524   else if (guestfs_exists (g, "/etc/meego-release") > 0) {
525     fs->distro = OS_DISTRO_MEEGO;
526
527     if (parse_release_file (g, fs, "/etc/meego-release") == -1)
528       return -1;
529
530     if (parse_major_minor (g, fs) == -1)
531       return -1;
532   }
533
534  skip_release_checks:;
535
536   /* Determine the architecture. */
537   const char *binaries[] =
538     { "/bin/bash", "/bin/ls", "/bin/echo", "/bin/rm", "/bin/sh" };
539   size_t i;
540   for (i = 0; i < sizeof binaries / sizeof binaries[0]; ++i) {
541     if (guestfs_is_file (g, binaries[i]) > 0) {
542       /* Ignore errors from file_architecture call. */
543       guestfs_error_handler_cb old_error_cb = g->error_cb;
544       g->error_cb = NULL;
545       char *arch = guestfs_file_architecture (g, binaries[i]);
546       g->error_cb = old_error_cb;
547
548       if (arch) {
549         /* String will be owned by handle, freed by
550          * guestfs___free_inspect_info.
551          */
552         fs->arch = arch;
553         break;
554       }
555     }
556   }
557
558   /* We already know /etc/fstab exists because it's part of the test
559    * for Linux root above.  We must now parse this file to determine
560    * which filesystems are used by the operating system and how they
561    * are mounted.
562    * XXX What if !feature_available (g, "augeas")?
563    */
564   if (guestfs_aug_init (g, "/", 16|32) == -1)
565     return -1;
566
567   /* Tell Augeas to only load /etc/fstab (thanks Raphaël Pinson). */
568   guestfs_aug_rm (g, "/augeas/load//incl[. != \"/etc/fstab\"]");
569   guestfs_aug_load (g);
570
571   r = check_fstab (g, fs);
572   guestfs_aug_close (g);
573   if (r == -1)
574     return -1;
575
576   return 0;
577 }
578
579 static int
580 check_fstab (guestfs_h *g, struct inspect_fs *fs)
581 {
582   char **lines = guestfs_aug_ls (g, "/files/etc/fstab");
583   if (lines == NULL)
584     return -1;
585
586   if (lines[0] == NULL) {
587     error (g, "could not parse /etc/fstab or empty file");
588     guestfs___free_string_list (lines);
589     return -1;
590   }
591
592   size_t i;
593   char augpath[256];
594   for (i = 0; lines[i] != NULL; ++i) {
595     /* Ignore comments.  Only care about sequence lines which
596      * match m{/\d+$}.
597      */
598     if (match (g, lines[i], re_aug_seq)) {
599       snprintf (augpath, sizeof augpath, "%s/spec", lines[i]);
600       char *spec = guestfs_aug_get (g, augpath);
601       if (spec == NULL) {
602         guestfs___free_string_list (lines);
603         return -1;
604       }
605
606       snprintf (augpath, sizeof augpath, "%s/file", lines[i]);
607       char *mp = guestfs_aug_get (g, augpath);
608       if (mp == NULL) {
609         guestfs___free_string_list (lines);
610         free (spec);
611         return -1;
612       }
613
614       int r = add_fstab_entry (g, fs, spec, mp);
615       free (spec);
616       free (mp);
617
618       if (r == -1) {
619         guestfs___free_string_list (lines);
620         return -1;
621       }
622     }
623   }
624
625   guestfs___free_string_list (lines);
626   return 0;
627 }
628
629 /* Add a filesystem and possibly a mountpoint entry for
630  * the root filesystem 'fs'.
631  *
632  * 'spec' is the fstab spec field, which might be a device name or a
633  * pseudodevice or 'UUID=...' or 'LABEL=...'.
634  *
635  * 'mp' is the mount point, which could also be 'swap' or 'none'.
636  */
637 static int
638 add_fstab_entry (guestfs_h *g, struct inspect_fs *fs,
639                  const char *spec, const char *mp)
640 {
641   /* Ignore certain mountpoints. */
642   if (STRPREFIX (mp, "/dev/") ||
643       STREQ (mp, "/dev") ||
644       STRPREFIX (mp, "/media/") ||
645       STRPREFIX (mp, "/proc/") ||
646       STREQ (mp, "/proc") ||
647       STRPREFIX (mp, "/selinux/") ||
648       STREQ (mp, "/selinux") ||
649       STRPREFIX (mp, "/sys/") ||
650       STREQ (mp, "/sys"))
651     return 0;
652
653   /* Ignore /dev/fd (floppy disks) (RHBZ#642929) and CD-ROM drives. */
654   if ((STRPREFIX (spec, "/dev/fd") && c_isdigit (spec[7])) ||
655       STREQ (spec, "/dev/floppy") ||
656       STREQ (spec, "/dev/cdrom"))
657     return 0;
658
659   /* Resolve UUID= and LABEL= to the actual device. */
660   char *device = NULL;
661   if (STRPREFIX (spec, "UUID="))
662     device = guestfs_findfs_uuid (g, &spec[5]);
663   else if (STRPREFIX (spec, "LABEL="))
664     device = guestfs_findfs_label (g, &spec[6]);
665   /* Ignore "/.swap" (Pardus) and pseudo-devices like "tmpfs". */
666   else if (STRPREFIX (spec, "/dev/"))
667     /* Resolve guest block device names. */
668     device = resolve_fstab_device (g, spec);
669
670   /* If we haven't resolved the device successfully by this point,
671    * we don't care, just ignore it.
672    */
673   if (device == NULL)
674     return 0;
675
676   char *mountpoint = safe_strdup (g, mp);
677
678   /* Add this to the fstab entry in 'fs'.
679    * Note these are further filtered by guestfs_inspect_get_mountpoints
680    * and guestfs_inspect_get_filesystems.
681    */
682   size_t n = fs->nr_fstab + 1;
683   struct inspect_fstab_entry *p;
684
685   p = realloc (fs->fstab, n * sizeof (struct inspect_fstab_entry));
686   if (p == NULL) {
687     perrorf (g, "realloc");
688     free (device);
689     free (mountpoint);
690     return -1;
691   }
692
693   fs->fstab = p;
694   fs->nr_fstab = n;
695
696   /* These are owned by the handle and freed by guestfs___free_inspect_info. */
697   fs->fstab[n-1].device = device;
698   fs->fstab[n-1].mountpoint = mountpoint;
699
700   if (g->verbose)
701     fprintf (stderr, "fstab: device=%s mountpoint=%s\n", device, mountpoint);
702
703   return 0;
704 }
705
706 /* Resolve block device name to the libguestfs device name, eg.
707  * /dev/xvdb1 => /dev/vdb1; and /dev/mapper/VG-LV => /dev/VG/LV.  This
708  * assumes that disks were added in the same order as they appear to
709  * the real VM, which is a reasonable assumption to make.  Return
710  * anything we don't recognize unchanged.
711  */
712 static char *
713 resolve_fstab_device (guestfs_h *g, const char *spec)
714 {
715   char *a1;
716   char *device = NULL;
717
718   if (STRPREFIX (spec, "/dev/mapper/")) {
719     /* LVM2 does some strange munging on /dev/mapper paths for VGs and
720      * LVs which contain '-' character:
721      *
722      * ><fs> lvcreate LV--test VG--test 32
723      * ><fs> debug ls /dev/mapper
724      * VG----test-LV----test
725      *
726      * This makes it impossible to reverse those paths directly, so
727      * we have implemented lvm_canonical_lv_name in the daemon.
728      */
729     device = guestfs_lvm_canonical_lv_name (g, spec);
730   }
731   else if ((a1 = match1 (g, spec, re_xdev)) != NULL) {
732     char **devices = guestfs_list_devices (g);
733     if (devices == NULL)
734       return NULL;
735
736     size_t count;
737     for (count = 0; devices[count] != NULL; count++)
738       ;
739
740     size_t i = a1[0] - 'a'; /* a1[0] is always [a-z] because of regex. */
741     if (i < count) {
742       size_t len = strlen (devices[i]) + strlen (a1) + 16;
743       device = safe_malloc (g, len);
744       snprintf (device, len, "%s%s", devices[i], &a1[1]);
745     }
746
747     free (a1);
748     guestfs___free_string_list (devices);
749   }
750   else {
751     /* Didn't match device pattern, return original spec unchanged. */
752     device = safe_strdup (g, spec);
753   }
754
755   return device;
756 }
757
758 /* XXX Handling of boot.ini in the Perl version was pretty broken.  It
759  * essentially didn't do anything for modern Windows guests.
760  * Therefore I've omitted all that code.
761  */
762 static int
763 check_windows_root (guestfs_h *g, struct inspect_fs *fs)
764 {
765   fs->type = OS_TYPE_WINDOWS;
766   fs->distro = OS_DISTRO_WINDOWS;
767
768   /* Try to find Windows systemroot using some common locations. */
769   const char *systemroots[] =
770     { "/windows", "/winnt", "/win32", "/win" };
771   size_t i;
772   char *systemroot = NULL;
773   for (i = 0;
774        systemroot == NULL && i < sizeof systemroots / sizeof systemroots[0];
775        ++i) {
776     systemroot = resolve_windows_path_silently (g, systemroots[i]);
777   }
778
779   if (!systemroot) {
780     error (g, _("cannot resolve Windows %%SYSTEMROOT%%"));
781     return -1;
782   }
783
784   if (g->verbose)
785     fprintf (stderr, "windows %%SYSTEMROOT%% = %s", systemroot);
786
787   /* Freed by guestfs___free_inspect_info. */
788   fs->windows_systemroot = systemroot;
789
790   if (check_windows_arch (g, fs) == -1)
791     return -1;
792
793   if (check_windows_registry (g, fs) == -1)
794     return -1;
795
796   return 0;
797 }
798
799 static int
800 check_windows_arch (guestfs_h *g, struct inspect_fs *fs)
801 {
802   size_t len = strlen (fs->windows_systemroot) + 32;
803   char cmd_exe[len];
804   snprintf (cmd_exe, len, "%s/system32/cmd.exe", fs->windows_systemroot);
805
806   char *cmd_exe_path = resolve_windows_path_silently (g, cmd_exe);
807   if (!cmd_exe_path)
808     return 0;
809
810   char *arch = guestfs_file_architecture (g, cmd_exe_path);
811   free (cmd_exe_path);
812
813   if (arch)
814     fs->arch = arch;        /* freed by guestfs___free_inspect_info */
815
816   return 0;
817 }
818
819 /* At the moment, pull just the ProductName and version numbers from
820  * the registry.  In future there is a case for making many more
821  * registry fields available to callers.
822  */
823 static int
824 check_windows_registry (guestfs_h *g, struct inspect_fs *fs)
825 {
826   TMP_TEMPLATE_ON_STACK (dir);
827 #define dir_len (strlen (dir))
828 #define software_hive_len (dir_len + 16)
829   char software_hive[software_hive_len];
830 #define cmd_len (dir_len + 16)
831   char cmd[cmd_len];
832
833   size_t len = strlen (fs->windows_systemroot) + 64;
834   char software[len];
835   snprintf (software, len, "%s/system32/config/software",
836             fs->windows_systemroot);
837
838   char *software_path = resolve_windows_path_silently (g, software);
839   if (!software_path)
840     /* If the software hive doesn't exist, just accept that we cannot
841      * find product_name etc.
842      */
843     return 0;
844
845   int ret = -1;
846   hive_h *h = NULL;
847   hive_value_h *values = NULL;
848
849   if (mkdtemp (dir) == NULL) {
850     perrorf (g, "mkdtemp");
851     goto out;
852   }
853
854   snprintf (software_hive, software_hive_len, "%s/software", dir);
855
856   if (guestfs_download (g, software_path, software_hive) == -1)
857     goto out;
858
859   h = hivex_open (software_hive, g->verbose ? HIVEX_OPEN_VERBOSE : 0);
860   if (h == NULL) {
861     perrorf (g, "hivex_open");
862     goto out;
863   }
864
865   hive_node_h node = hivex_root (h);
866   const char *hivepath[] =
867     { "Microsoft", "Windows NT", "CurrentVersion" };
868   size_t i;
869   for (i = 0;
870        node != 0 && i < sizeof hivepath / sizeof hivepath[0];
871        ++i) {
872     node = hivex_node_get_child (h, node, hivepath[i]);
873   }
874
875   if (node == 0) {
876     perrorf (g, "hivex: cannot locate HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
877     goto out;
878   }
879
880   values = hivex_node_values (h, node);
881
882   for (i = 0; values[i] != 0; ++i) {
883     char *key = hivex_value_key (h, values[i]);
884     if (key == NULL) {
885       perrorf (g, "hivex_value_key");
886       goto out;
887     }
888
889     if (STRCASEEQ (key, "ProductName")) {
890       fs->product_name = hivex_value_string (h, values[i]);
891       if (!fs->product_name) {
892         perrorf (g, "hivex_value_string");
893         free (key);
894         goto out;
895       }
896     }
897     else if (STRCASEEQ (key, "CurrentVersion")) {
898       char *version = hivex_value_string (h, values[i]);
899       if (!version) {
900         perrorf (g, "hivex_value_string");
901         free (key);
902         goto out;
903       }
904       char *major, *minor;
905       if (match2 (g, version, re_windows_version, &major, &minor)) {
906         fs->major_version = parse_unsigned_int (g, major);
907         free (major);
908         if (fs->major_version == -1) {
909           free (minor);
910           free (key);
911           free (version);
912           goto out;
913         }
914         fs->minor_version = parse_unsigned_int (g, minor);
915         free (minor);
916         if (fs->minor_version == -1) {
917           free (key);
918           free (version);
919           return -1;
920         }
921       }
922
923       free (version);
924     }
925
926     free (key);
927   }
928
929   ret = 0;
930
931  out:
932   if (h) hivex_close (h);
933   free (values);
934   free (software_path);
935
936   /* Free up the temporary directory.  Note the directory name cannot
937    * contain shell meta-characters because of the way it was
938    * constructed above.
939    */
940   snprintf (cmd, cmd_len, "rm -rf %s", dir);
941   ignore_value (system (cmd));
942 #undef dir_len
943 #undef software_hive_len
944 #undef cmd_len
945
946   return ret;
947 }
948
949 static char *
950 resolve_windows_path_silently (guestfs_h *g, const char *path)
951 {
952   guestfs_error_handler_cb old_error_cb = g->error_cb;
953   g->error_cb = NULL;
954   char *ret = guestfs_case_sensitive_path (g, path);
955   g->error_cb = old_error_cb;
956   return ret;
957 }
958
959 static int
960 extend_fses (guestfs_h *g)
961 {
962   size_t n = g->nr_fses + 1;
963   struct inspect_fs *p;
964
965   p = realloc (g->fses, n * sizeof (struct inspect_fs));
966   if (p == NULL) {
967     perrorf (g, "realloc");
968     return -1;
969   }
970
971   g->fses = p;
972   g->nr_fses = n;
973
974   memset (&g->fses[n-1], 0, sizeof (struct inspect_fs));
975
976   return 0;
977 }
978
979 /* Parse small, unsigned ints, as used in version numbers. */
980 static int
981 parse_unsigned_int (guestfs_h *g, const char *str)
982 {
983   long ret;
984   int r = xstrtol (str, NULL, 10, &ret, "");
985   if (r != LONGINT_OK) {
986     error (g, "could not parse integer in version number: %s", str);
987     return -1;
988   }
989   return ret;
990 }
991
992 static struct inspect_fs *
993 search_for_root (guestfs_h *g, const char *root)
994 {
995   if (g->nr_fses == 0) {
996     error (g, _("no inspection data: call guestfs_inspect_os first"));
997     return NULL;
998   }
999
1000   size_t i;
1001   struct inspect_fs *fs;
1002   for (i = 0; i < g->nr_fses; ++i) {
1003     fs = &g->fses[i];
1004     if (fs->is_root && STREQ (root, fs->device))
1005       return fs;
1006   }
1007
1008   error (g, _("%s: root device not found: only call this function with a root device previously returned by guestfs_inspect_os"),
1009          root);
1010   return NULL;
1011 }
1012
1013 char *
1014 guestfs__inspect_get_type (guestfs_h *g, const char *root)
1015 {
1016   struct inspect_fs *fs = search_for_root (g, root);
1017   if (!fs)
1018     return NULL;
1019
1020   char *ret;
1021   switch (fs->type) {
1022   case OS_TYPE_LINUX: ret = safe_strdup (g, "linux"); break;
1023   case OS_TYPE_WINDOWS: ret = safe_strdup (g, "windows"); break;
1024   case OS_TYPE_UNKNOWN: default: ret = safe_strdup (g, "unknown"); break;
1025   }
1026
1027   return ret;
1028 }
1029
1030 char *
1031 guestfs__inspect_get_arch (guestfs_h *g, const char *root)
1032 {
1033   struct inspect_fs *fs = search_for_root (g, root);
1034   if (!fs)
1035     return NULL;
1036
1037   return safe_strdup (g, fs->arch ? : "unknown");
1038 }
1039
1040 char *
1041 guestfs__inspect_get_distro (guestfs_h *g, const char *root)
1042 {
1043   struct inspect_fs *fs = search_for_root (g, root);
1044   if (!fs)
1045     return NULL;
1046
1047   char *ret;
1048   switch (fs->distro) {
1049   case OS_DISTRO_ARCHLINUX: ret = safe_strdup (g, "archlinux"); break;
1050   case OS_DISTRO_DEBIAN: ret = safe_strdup (g, "debian"); break;
1051   case OS_DISTRO_FEDORA: ret = safe_strdup (g, "fedora"); break;
1052   case OS_DISTRO_GENTOO: ret = safe_strdup (g, "gentoo"); break;
1053   case OS_DISTRO_MEEGO: ret = safe_strdup (g, "meego"); break;
1054   case OS_DISTRO_PARDUS: ret = safe_strdup (g, "pardus"); break;
1055   case OS_DISTRO_REDHAT_BASED: ret = safe_strdup (g, "redhat-based"); break;
1056   case OS_DISTRO_RHEL: ret = safe_strdup (g, "rhel"); break;
1057   case OS_DISTRO_WINDOWS: ret = safe_strdup (g, "windows"); break;
1058   case OS_DISTRO_UBUNTU: ret = safe_strdup (g, "ubuntu"); break;
1059   case OS_DISTRO_UNKNOWN: default: ret = safe_strdup (g, "unknown"); break;
1060   }
1061
1062   return ret;
1063 }
1064
1065 int
1066 guestfs__inspect_get_major_version (guestfs_h *g, const char *root)
1067 {
1068   struct inspect_fs *fs = search_for_root (g, root);
1069   if (!fs)
1070     return -1;
1071
1072   return fs->major_version;
1073 }
1074
1075 int
1076 guestfs__inspect_get_minor_version (guestfs_h *g, const char *root)
1077 {
1078   struct inspect_fs *fs = search_for_root (g, root);
1079   if (!fs)
1080     return -1;
1081
1082   return fs->minor_version;
1083 }
1084
1085 char *
1086 guestfs__inspect_get_product_name (guestfs_h *g, const char *root)
1087 {
1088   struct inspect_fs *fs = search_for_root (g, root);
1089   if (!fs)
1090     return NULL;
1091
1092   return safe_strdup (g, fs->product_name ? : "unknown");
1093 }
1094
1095 char *
1096 guestfs__inspect_get_windows_systemroot (guestfs_h *g, const char *root)
1097 {
1098   struct inspect_fs *fs = search_for_root (g, root);
1099   if (!fs)
1100     return NULL;
1101
1102   if (!fs->windows_systemroot) {
1103     error (g, _("not a Windows guest, or systemroot could not be determined"));
1104     return NULL;
1105   }
1106
1107   return safe_strdup (g, fs->windows_systemroot);
1108 }
1109
1110 char **
1111 guestfs__inspect_get_mountpoints (guestfs_h *g, const char *root)
1112 {
1113   struct inspect_fs *fs = search_for_root (g, root);
1114   if (!fs)
1115     return NULL;
1116
1117   char **ret;
1118
1119   /* If no fstab information (Windows) return just the root. */
1120   if (fs->nr_fstab == 0) {
1121     ret = calloc (3, sizeof (char *));
1122     ret[0] = safe_strdup (g, "/");
1123     ret[1] = safe_strdup (g, root);
1124     ret[2] = NULL;
1125     return ret;
1126   }
1127
1128 #define CRITERION fs->fstab[i].mountpoint[0] == '/'
1129   size_t i, count = 0;
1130   for (i = 0; i < fs->nr_fstab; ++i)
1131     if (CRITERION)
1132       count++;
1133
1134   /* Hashtables have 2N+1 entries. */
1135   ret = calloc (2*count+1, sizeof (char *));
1136   if (ret == NULL) {
1137     perrorf (g, "calloc");
1138     return NULL;
1139   }
1140
1141   count = 0;
1142   for (i = 0; i < fs->nr_fstab; ++i)
1143     if (CRITERION) {
1144       ret[2*count] = safe_strdup (g, fs->fstab[i].mountpoint);
1145       ret[2*count+1] = safe_strdup (g, fs->fstab[i].device);
1146       count++;
1147     }
1148 #undef CRITERION
1149
1150   return ret;
1151 }
1152
1153 char **
1154 guestfs__inspect_get_filesystems (guestfs_h *g, const char *root)
1155 {
1156   struct inspect_fs *fs = search_for_root (g, root);
1157   if (!fs)
1158     return NULL;
1159
1160   char **ret;
1161
1162   /* If no fstab information (Windows) return just the root. */
1163   if (fs->nr_fstab == 0) {
1164     ret = calloc (2, sizeof (char *));
1165     ret[0] = safe_strdup (g, root);
1166     ret[1] = NULL;
1167     return ret;
1168   }
1169
1170   ret = calloc (fs->nr_fstab + 1, sizeof (char *));
1171   if (ret == NULL) {
1172     perrorf (g, "calloc");
1173     return NULL;
1174   }
1175
1176   size_t i;
1177   for (i = 0; i < fs->nr_fstab; ++i)
1178     ret[i] = safe_strdup (g, fs->fstab[i].device);
1179
1180   return ret;
1181 }
1182
1183 #else /* no PCRE or hivex at compile time */
1184
1185 /* XXX These functions should be in an optgroup. */
1186
1187 #define NOT_IMPL(r)                                                     \
1188   error (g, _("inspection API not available since this version of libguestfs was compiled without PCRE or hivex libraries")); \
1189   return r
1190
1191 char **
1192 guestfs__inspect_os (guestfs_h *g)
1193 {
1194   NOT_IMPL(NULL);
1195 }
1196
1197 char **
1198 guestfs__inspect_get_roots (guestfs_h *g)
1199 {
1200   NOT_IMPL(NULL);
1201 }
1202
1203 char *
1204 guestfs__inspect_get_type (guestfs_h *g, const char *root)
1205 {
1206   NOT_IMPL(NULL);
1207 }
1208
1209 char *
1210 guestfs__inspect_get_arch (guestfs_h *g, const char *root)
1211 {
1212   NOT_IMPL(NULL);
1213 }
1214
1215 char *
1216 guestfs__inspect_get_distro (guestfs_h *g, const char *root)
1217 {
1218   NOT_IMPL(NULL);
1219 }
1220
1221 int
1222 guestfs__inspect_get_major_version (guestfs_h *g, const char *root)
1223 {
1224   NOT_IMPL(-1);
1225 }
1226
1227 int
1228 guestfs__inspect_get_minor_version (guestfs_h *g, const char *root)
1229 {
1230   NOT_IMPL(-1);
1231 }
1232
1233 char *
1234 guestfs__inspect_get_product_name (guestfs_h *g, const char *root)
1235 {
1236   NOT_IMPL(NULL);
1237 }
1238
1239 char *
1240 guestfs__inspect_get_windows_systemroot (guestfs_h *g, const char *root)
1241 {
1242   NOT_IMPL(NULL);
1243 }
1244
1245 char **
1246 guestfs__inspect_get_mountpoints (guestfs_h *g, const char *root)
1247 {
1248   NOT_IMPL(NULL);
1249 }
1250
1251 char **
1252 guestfs__inspect_get_filesystems (guestfs_h *g, const char *root)
1253 {
1254   NOT_IMPL(NULL);
1255 }
1256
1257 #endif /* no PCRE or hivex at compile time */
1258
1259 void
1260 guestfs___free_inspect_info (guestfs_h *g)
1261 {
1262   size_t i;
1263   for (i = 0; i < g->nr_fses; ++i) {
1264     free (g->fses[i].device);
1265     free (g->fses[i].product_name);
1266     free (g->fses[i].arch);
1267     free (g->fses[i].windows_systemroot);
1268     size_t j;
1269     for (j = 0; j < g->fses[i].nr_fstab; ++j) {
1270       free (g->fses[i].fstab[j].device);
1271       free (g->fses[i].fstab[j].mountpoint);
1272     }
1273     free (g->fses[i].fstab);
1274   }
1275   free (g->fses);
1276   g->nr_fses = 0;
1277   g->fses = NULL;
1278 }
1279
1280 /* In the Perl code this is a public function. */
1281 int
1282 guestfs___feature_available (guestfs_h *g, const char *feature)
1283 {
1284   /* If there's an error we should ignore it, so to do that we have to
1285    * temporarily replace the error handler with a null one.
1286    */
1287   guestfs_error_handler_cb old_error_cb = g->error_cb;
1288   g->error_cb = NULL;
1289
1290   const char *groups[] = { feature, NULL };
1291   int r = guestfs_available (g, (char * const *) groups);
1292
1293   g->error_cb = old_error_cb;
1294
1295   return r == 0 ? 1 : 0;
1296 }
1297
1298 #ifdef HAVE_PCRE
1299
1300 /* Match a regular expression which contains no captures.  Returns
1301  * true if it matches or false if it doesn't.
1302  */
1303 int
1304 guestfs___match (guestfs_h *g, const char *str, const pcre *re)
1305 {
1306   size_t len = strlen (str);
1307   int vec[30], r;
1308
1309   r = pcre_exec (re, NULL, str, len, 0, 0, vec, sizeof vec / sizeof vec[0]);
1310   if (r == PCRE_ERROR_NOMATCH)
1311     return 0;
1312   if (r != 1) {
1313     /* Internal error -- should not happen. */
1314     fprintf (stderr, "libguestfs: %s: %s: internal error: pcre_exec returned unexpected error code %d when matching against the string \"%s\"\n",
1315              __FILE__, __func__, r, str);
1316     return 0;
1317   }
1318
1319   return 1;
1320 }
1321
1322 /* Match a regular expression which contains exactly one capture.  If
1323  * the string matches, return the capture, otherwise return NULL.  The
1324  * caller must free the result.
1325  */
1326 char *
1327 guestfs___match1 (guestfs_h *g, const char *str, const pcre *re)
1328 {
1329   size_t len = strlen (str);
1330   int vec[30], r;
1331
1332   r = pcre_exec (re, NULL, str, len, 0, 0, vec, sizeof vec / sizeof vec[0]);
1333   if (r == PCRE_ERROR_NOMATCH)
1334     return NULL;
1335   if (r != 2) {
1336     /* Internal error -- should not happen. */
1337     fprintf (stderr, "libguestfs: %s: %s: internal error: pcre_exec returned unexpected error code %d when matching against the string \"%s\"\n",
1338              __FILE__, __func__, r, str);
1339     return NULL;
1340   }
1341
1342   return safe_strndup (g, &str[vec[2]], vec[3]-vec[2]);
1343 }
1344
1345 /* Match a regular expression which contains exactly two captures. */
1346 int
1347 guestfs___match2 (guestfs_h *g, const char *str, const pcre *re,
1348                   char **ret1, char **ret2)
1349 {
1350   size_t len = strlen (str);
1351   int vec[30], r;
1352
1353   r = pcre_exec (re, NULL, str, len, 0, 0, vec, 30);
1354   if (r == PCRE_ERROR_NOMATCH)
1355     return 0;
1356   if (r != 3) {
1357     /* Internal error -- should not happen. */
1358     fprintf (stderr, "libguestfs: %s: %s: internal error: pcre_exec returned unexpected error code %d when matching against the string \"%s\"\n",
1359              __FILE__, __func__, r, str);
1360     return 0;
1361   }
1362
1363   *ret1 = safe_strndup (g, &str[vec[2]], vec[3]-vec[2]);
1364   *ret2 = safe_strndup (g, &str[vec[4]], vec[5]-vec[4]);
1365
1366   return 1;
1367 }
1368
1369 #endif /* HAVE_PCRE */