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