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