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