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