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