inspection: Cleanup iteration over fstab entries in inspect_fs_unix.c
[libguestfs.git] / src / inspect_fs_unix.c
1 /* libguestfs
2  * Copyright (C) 2010-2011 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 <fcntl.h>
27 #include <string.h>
28 #include <sys/stat.h>
29 #include <errno.h>
30 #include <endian.h>
31
32 #include <pcre.h>
33
34 #ifdef HAVE_HIVEX
35 #include <hivex.h>
36 #endif
37
38 #include "c-ctype.h"
39 #include "ignore-value.h"
40 #include "xstrtol.h"
41
42 #include "guestfs.h"
43 #include "guestfs-internal.h"
44 #include "guestfs-internal-actions.h"
45 #include "guestfs_protocol.h"
46
47 #if defined(HAVE_HIVEX)
48
49 /* Compile all the regular expressions once when the shared library is
50  * loaded.  PCRE is thread safe so we're supposedly OK here if
51  * multiple threads call into the libguestfs API functions below
52  * simultaneously.
53  */
54 static pcre *re_fedora;
55 static pcre *re_rhel_old;
56 static pcre *re_rhel;
57 static pcre *re_rhel_no_minor;
58 static pcre *re_centos_old;
59 static pcre *re_centos;
60 static pcre *re_centos_no_minor;
61 static pcre *re_scientific_linux_old;
62 static pcre *re_scientific_linux;
63 static pcre *re_scientific_linux_no_minor;
64 static pcre *re_major_minor;
65 static pcre *re_aug_seq;
66 static pcre *re_xdev;
67 static pcre *re_cciss;
68 static pcre *re_first_partition;
69 static pcre *re_freebsd;
70 static pcre *re_netbsd;
71
72 static void compile_regexps (void) __attribute__((constructor));
73 static void free_regexps (void) __attribute__((destructor));
74
75 static void
76 compile_regexps (void)
77 {
78   const char *err;
79   int offset;
80
81 #define COMPILE(re,pattern,options)                                     \
82   do {                                                                  \
83     re = pcre_compile ((pattern), (options), &err, &offset, NULL);      \
84     if (re == NULL) {                                                   \
85       ignore_value (write (2, err, strlen (err)));                      \
86       abort ();                                                         \
87     }                                                                   \
88   } while (0)
89
90   COMPILE (re_fedora, "Fedora release (\\d+)", 0);
91   COMPILE (re_rhel_old,
92            "Red Hat.*release (\\d+).*Update (\\d+)", 0);
93   COMPILE (re_rhel,
94            "Red Hat.*release (\\d+)\\.(\\d+)", 0);
95   COMPILE (re_rhel_no_minor,
96            "Red Hat.*release (\\d+)", 0);
97   COMPILE (re_centos_old,
98            "CentOS.*release (\\d+).*Update (\\d+)", 0);
99   COMPILE (re_centos,
100            "CentOS.*release (\\d+)\\.(\\d+)", 0);
101   COMPILE (re_centos_no_minor,
102            "CentOS.*release (\\d+)", 0);
103   COMPILE (re_scientific_linux_old,
104            "Scientific Linux.*release (\\d+).*Update (\\d+)", 0);
105   COMPILE (re_scientific_linux,
106            "Scientific Linux.*release (\\d+)\\.(\\d+)", 0);
107   COMPILE (re_scientific_linux_no_minor,
108            "Scientific Linux.*release (\\d+)", 0);
109   COMPILE (re_major_minor, "(\\d+)\\.(\\d+)", 0);
110   COMPILE (re_xdev, "^/dev/(h|s|v|xv)d([a-z]+)(\\d*)$", 0);
111   COMPILE (re_cciss, "^/dev/(cciss/c\\d+d\\d+)(?:p(\\d+))?$", 0);
112   COMPILE (re_freebsd, "^/dev/ad(\\d+)s(\\d+)([a-z])$", 0);
113   COMPILE (re_netbsd, "^NetBSD (\\d+)\\.(\\d+)", 0);
114 }
115
116 static void
117 free_regexps (void)
118 {
119   pcre_free (re_fedora);
120   pcre_free (re_rhel_old);
121   pcre_free (re_rhel);
122   pcre_free (re_rhel_no_minor);
123   pcre_free (re_centos_old);
124   pcre_free (re_centos);
125   pcre_free (re_centos_no_minor);
126   pcre_free (re_scientific_linux_old);
127   pcre_free (re_scientific_linux);
128   pcre_free (re_scientific_linux_no_minor);
129   pcre_free (re_major_minor);
130   pcre_free (re_xdev);
131   pcre_free (re_cciss);
132   pcre_free (re_freebsd);
133   pcre_free (re_netbsd);
134 }
135
136 static void check_architecture (guestfs_h *g, struct inspect_fs *fs);
137 static int check_hostname_unix (guestfs_h *g, struct inspect_fs *fs);
138 static int check_hostname_redhat (guestfs_h *g, struct inspect_fs *fs);
139 static int check_hostname_freebsd (guestfs_h *g, struct inspect_fs *fs);
140 static int check_fstab (guestfs_h *g, struct inspect_fs *fs);
141 static int add_fstab_entry (guestfs_h *g, struct inspect_fs *fs,
142                             const char *spec, const char *mp);
143 static char *resolve_fstab_device (guestfs_h *g, const char *spec);
144 static int inspect_with_augeas (guestfs_h *g, struct inspect_fs *fs, const char **configfiles, int (*f) (guestfs_h *, struct inspect_fs *));
145
146 /* Set fs->product_name to the first line of the release file. */
147 static int
148 parse_release_file (guestfs_h *g, struct inspect_fs *fs,
149                     const char *release_filename)
150 {
151   fs->product_name = guestfs___first_line_of_file (g, release_filename);
152   if (fs->product_name == NULL)
153     return -1;
154   return 0;
155 }
156
157 /* Ubuntu has /etc/lsb-release containing:
158  *   DISTRIB_ID=Ubuntu                                # Distro
159  *   DISTRIB_RELEASE=10.04                            # Version
160  *   DISTRIB_CODENAME=lucid
161  *   DISTRIB_DESCRIPTION="Ubuntu 10.04.1 LTS"         # Product name
162  *
163  * [Ubuntu-derived ...] Linux Mint was found to have this:
164  *   DISTRIB_ID=LinuxMint
165  *   DISTRIB_RELEASE=10
166  *   DISTRIB_CODENAME=julia
167  *   DISTRIB_DESCRIPTION="Linux Mint 10 Julia"
168  * Linux Mint also has /etc/linuxmint/info with more information,
169  * but we can use the LSB file.
170  *
171  * Mandriva has:
172  *   LSB_VERSION=lsb-4.0-amd64:lsb-4.0-noarch
173  *   DISTRIB_ID=MandrivaLinux
174  *   DISTRIB_RELEASE=2010.1
175  *   DISTRIB_CODENAME=Henry_Farman
176  *   DISTRIB_DESCRIPTION="Mandriva Linux 2010.1"
177  * Mandriva also has a normal release file called /etc/mandriva-release.
178  */
179 static int
180 parse_lsb_release (guestfs_h *g, struct inspect_fs *fs)
181 {
182   const char *filename = "/etc/lsb-release";
183   int64_t size;
184   char **lines;
185   size_t i;
186   int r = 0;
187
188   /* Don't trust guestfs_head_n not to break with very large files.
189    * Check the file size is something reasonable first.
190    */
191   size = guestfs_filesize (g, filename);
192   if (size == -1)
193     /* guestfs_filesize failed and has already set error in handle */
194     return -1;
195   if (size > MAX_SMALL_FILE_SIZE) {
196     error (g, _("size of %s is unreasonably large (%" PRIi64 " bytes)"),
197            filename, size);
198     return -1;
199   }
200
201   lines = guestfs_head_n (g, 10, filename);
202   if (lines == NULL)
203     return -1;
204
205   for (i = 0; lines[i] != NULL; ++i) {
206     if (fs->distro == 0 &&
207         STREQ (lines[i], "DISTRIB_ID=Ubuntu")) {
208       fs->distro = OS_DISTRO_UBUNTU;
209       r = 1;
210     }
211     else if (fs->distro == 0 &&
212              STREQ (lines[i], "DISTRIB_ID=LinuxMint")) {
213       fs->distro = OS_DISTRO_LINUX_MINT;
214       r = 1;
215     }
216     else if (fs->distro == 0 &&
217              STREQ (lines[i], "DISTRIB_ID=MandrivaLinux")) {
218       fs->distro = OS_DISTRO_MANDRIVA;
219       r = 1;
220     }
221     else if (fs->distro == 0 &&
222              STREQ (lines[i], "DISTRIB_ID=\"Mageia\"")) {
223       fs->distro = OS_DISTRO_MAGEIA;
224       r = 1;
225     }
226     else if (STRPREFIX (lines[i], "DISTRIB_RELEASE=")) {
227       char *major, *minor;
228       if (match2 (g, &lines[i][16], re_major_minor, &major, &minor)) {
229         fs->major_version = guestfs___parse_unsigned_int (g, major);
230         free (major);
231         if (fs->major_version == -1) {
232           free (minor);
233           guestfs___free_string_list (lines);
234           return -1;
235         }
236         fs->minor_version = guestfs___parse_unsigned_int (g, minor);
237         free (minor);
238         if (fs->minor_version == -1) {
239           guestfs___free_string_list (lines);
240           return -1;
241         }
242       }
243     }
244     else if (fs->product_name == NULL &&
245              (STRPREFIX (lines[i], "DISTRIB_DESCRIPTION=\"") ||
246               STRPREFIX (lines[i], "DISTRIB_DESCRIPTION='"))) {
247       size_t len = strlen (lines[i]) - 21 - 1;
248       fs->product_name = safe_strndup (g, &lines[i][21], len);
249       r = 1;
250     }
251     else if (fs->product_name == NULL &&
252              STRPREFIX (lines[i], "DISTRIB_DESCRIPTION=")) {
253       size_t len = strlen (lines[i]) - 20;
254       fs->product_name = safe_strndup (g, &lines[i][20], len);
255       r = 1;
256     }
257   }
258
259   guestfs___free_string_list (lines);
260   return r;
261 }
262
263 /* The currently mounted device is known to be a Linux root.  Try to
264  * determine from this the distro, version, etc.  Also parse
265  * /etc/fstab to determine the arrangement of mountpoints and
266  * associated devices.
267  */
268 int
269 guestfs___check_linux_root (guestfs_h *g, struct inspect_fs *fs)
270 {
271   int r;
272
273   fs->type = OS_TYPE_LINUX;
274
275   if (guestfs_exists (g, "/etc/lsb-release") > 0) {
276     r = parse_lsb_release (g, fs);
277     if (r == -1)        /* error */
278       return -1;
279     if (r == 1)         /* ok - detected the release from this file */
280       goto skip_release_checks;
281   }
282
283   if (guestfs_exists (g, "/etc/redhat-release") > 0) {
284     fs->distro = OS_DISTRO_REDHAT_BASED; /* Something generic Red Hat-like. */
285
286     if (parse_release_file (g, fs, "/etc/redhat-release") == -1)
287       return -1;
288
289     char *major, *minor;
290     if ((major = match1 (g, fs->product_name, re_fedora)) != NULL) {
291       fs->distro = OS_DISTRO_FEDORA;
292       fs->major_version = guestfs___parse_unsigned_int (g, major);
293       free (major);
294       if (fs->major_version == -1)
295         return -1;
296     }
297     else if (match2 (g, fs->product_name, re_rhel_old, &major, &minor) ||
298              match2 (g, fs->product_name, re_rhel, &major, &minor)) {
299       fs->distro = OS_DISTRO_RHEL;
300       fs->major_version = guestfs___parse_unsigned_int (g, major);
301       free (major);
302       if (fs->major_version == -1) {
303         free (minor);
304         return -1;
305       }
306       fs->minor_version = guestfs___parse_unsigned_int (g, minor);
307       free (minor);
308       if (fs->minor_version == -1)
309         return -1;
310     }
311     else if ((major = match1 (g, fs->product_name, re_rhel_no_minor)) != NULL) {
312       fs->distro = OS_DISTRO_RHEL;
313       fs->major_version = guestfs___parse_unsigned_int (g, major);
314       free (major);
315       if (fs->major_version == -1)
316         return -1;
317       fs->minor_version = 0;
318     }
319     else if (match2 (g, fs->product_name, re_centos_old, &major, &minor) ||
320              match2 (g, fs->product_name, re_centos, &major, &minor)) {
321       fs->distro = OS_DISTRO_CENTOS;
322       fs->major_version = guestfs___parse_unsigned_int (g, major);
323       free (major);
324       if (fs->major_version == -1) {
325         free (minor);
326         return -1;
327       }
328       fs->minor_version = guestfs___parse_unsigned_int (g, minor);
329       free (minor);
330       if (fs->minor_version == -1)
331         return -1;
332     }
333     else if ((major = match1 (g, fs->product_name, re_centos_no_minor)) != NULL) {
334       fs->distro = OS_DISTRO_CENTOS;
335       fs->major_version = guestfs___parse_unsigned_int (g, major);
336       free (major);
337       if (fs->major_version == -1)
338         return -1;
339       fs->minor_version = 0;
340     }
341     else if (match2 (g, fs->product_name, re_scientific_linux_old, &major, &minor) ||
342              match2 (g, fs->product_name, re_scientific_linux, &major, &minor)) {
343       fs->distro = OS_DISTRO_SCIENTIFIC_LINUX;
344       fs->major_version = guestfs___parse_unsigned_int (g, major);
345       free (major);
346       if (fs->major_version == -1) {
347         free (minor);
348         return -1;
349       }
350       fs->minor_version = guestfs___parse_unsigned_int (g, minor);
351       free (minor);
352       if (fs->minor_version == -1)
353         return -1;
354     }
355     else if ((major = match1 (g, fs->product_name, re_scientific_linux_no_minor)) != NULL) {
356       fs->distro = OS_DISTRO_SCIENTIFIC_LINUX;
357       fs->major_version = guestfs___parse_unsigned_int (g, major);
358       free (major);
359       if (fs->major_version == -1)
360         return -1;
361       fs->minor_version = 0;
362     }
363   }
364   else if (guestfs_exists (g, "/etc/debian_version") > 0) {
365     fs->distro = OS_DISTRO_DEBIAN;
366
367     if (parse_release_file (g, fs, "/etc/debian_version") == -1)
368       return -1;
369
370     if (guestfs___parse_major_minor (g, fs) == -1)
371       return -1;
372   }
373   else if (guestfs_exists (g, "/etc/pardus-release") > 0) {
374     fs->distro = OS_DISTRO_PARDUS;
375
376     if (parse_release_file (g, fs, "/etc/pardus-release") == -1)
377       return -1;
378
379     if (guestfs___parse_major_minor (g, fs) == -1)
380       return -1;
381   }
382   else if (guestfs_exists (g, "/etc/arch-release") > 0) {
383     fs->distro = OS_DISTRO_ARCHLINUX;
384
385     /* /etc/arch-release file is empty and I can't see a way to
386      * determine the actual release or product string.
387      */
388   }
389   else if (guestfs_exists (g, "/etc/gentoo-release") > 0) {
390     fs->distro = OS_DISTRO_GENTOO;
391
392     if (parse_release_file (g, fs, "/etc/gentoo-release") == -1)
393       return -1;
394
395     if (guestfs___parse_major_minor (g, fs) == -1)
396       return -1;
397   }
398   else if (guestfs_exists (g, "/etc/meego-release") > 0) {
399     fs->distro = OS_DISTRO_MEEGO;
400
401     if (parse_release_file (g, fs, "/etc/meego-release") == -1)
402       return -1;
403
404     if (guestfs___parse_major_minor (g, fs) == -1)
405       return -1;
406   }
407   else if (guestfs_exists (g, "/etc/slackware-version") > 0) {
408     fs->distro = OS_DISTRO_SLACKWARE;
409
410     if (parse_release_file (g, fs, "/etc/slackware-version") == -1)
411       return -1;
412
413     if (guestfs___parse_major_minor (g, fs) == -1)
414       return -1;
415   }
416   else if (guestfs_exists (g, "/etc/ttylinux-target") > 0) {
417     fs->distro = OS_DISTRO_TTYLINUX;
418
419     fs->product_name = guestfs___first_line_of_file (g, "/etc/ttylinux-target");
420     if (fs->product_name == NULL)
421       return -1;
422
423     if (guestfs___parse_major_minor (g, fs) == -1)
424       return -1;
425   }
426   else if (guestfs_exists (g, "/etc/SuSE-release") > 0) {
427     fs->distro = OS_DISTRO_OPENSUSE;
428
429     if (parse_release_file (g, fs, "/etc/SuSE-release") == -1)
430       return -1;
431
432     if (guestfs___parse_major_minor (g, fs) == -1)
433       return -1;
434   }
435
436
437  skip_release_checks:;
438
439   /* Determine the architecture. */
440   check_architecture (g, fs);
441
442   /* We already know /etc/fstab exists because it's part of the test
443    * for Linux root above.  We must now parse this file to determine
444    * which filesystems are used by the operating system and how they
445    * are mounted.
446    */
447   const char *configfiles[] = { "/etc/fstab", NULL };
448   if (inspect_with_augeas (g, fs, configfiles, check_fstab) == -1)
449     return -1;
450
451   /* Determine hostname. */
452   if (check_hostname_unix (g, fs) == -1)
453     return -1;
454
455   return 0;
456 }
457
458 /* The currently mounted device is known to be a FreeBSD root. */
459 int
460 guestfs___check_freebsd_root (guestfs_h *g, struct inspect_fs *fs)
461 {
462   fs->type = OS_TYPE_FREEBSD;
463
464   /* FreeBSD has no authoritative version file.  The version number is
465    * in /etc/motd, which the system administrator might edit, but
466    * we'll use that anyway.
467    */
468
469   if (guestfs_exists (g, "/etc/motd") > 0) {
470     if (parse_release_file (g, fs, "/etc/motd") == -1)
471       return -1;
472
473     if (guestfs___parse_major_minor (g, fs) == -1)
474       return -1;
475   }
476
477   /* Determine the architecture. */
478   check_architecture (g, fs);
479
480   /* We already know /etc/fstab exists because it's part of the test above. */
481   const char *configfiles[] = { "/etc/fstab", NULL };
482   if (inspect_with_augeas (g, fs, configfiles, check_fstab) == -1)
483     return -1;
484
485   /* Determine hostname. */
486   if (check_hostname_unix (g, fs) == -1)
487     return -1;
488
489   return 0;
490 }
491
492 /* The currently mounted device is maybe to be a *BSD root. */
493 int
494 guestfs___check_netbsd_root (guestfs_h *g, struct inspect_fs *fs)
495 {
496
497   if (guestfs_exists (g, "/etc/release") > 0) {
498     char *major, *minor;
499     if (parse_release_file (g, fs, "/etc/release") == -1)
500       return -1;
501
502     if (match2 (g, fs->product_name, re_netbsd, &major, &minor)) {
503       fs->type = OS_TYPE_NETBSD;
504       fs->major_version = guestfs___parse_unsigned_int (g, major);
505       free (major);
506       if (fs->major_version == -1) {
507         free (minor);
508         return -1;
509       }
510       fs->minor_version = guestfs___parse_unsigned_int (g, minor);
511       free (minor);
512       if (fs->minor_version == -1)
513         return -1;
514     }
515   } else {
516     return -1;
517   }
518
519   /* Determine the architecture. */
520   check_architecture (g, fs);
521
522   /* We already know /etc/fstab exists because it's part of the test above. */
523   const char *configfiles[] = { "/etc/fstab", NULL };
524   if (inspect_with_augeas (g, fs, configfiles, check_fstab) == -1)
525     return -1;
526
527   /* Determine hostname. */
528   if (check_hostname_unix (g, fs) == -1)
529     return -1;
530
531   return 0;
532 }
533
534 /* The currently mounted device may be a Hurd root.  Hurd has distros
535  * just like Linux.
536  */
537 int
538 guestfs___check_hurd_root (guestfs_h *g, struct inspect_fs *fs)
539 {
540   int r;
541
542   fs->type = OS_TYPE_HURD;
543
544   if (guestfs_exists (g, "/etc/debian_version") > 0) {
545     fs->distro = OS_DISTRO_DEBIAN;
546
547     if (parse_release_file (g, fs, "/etc/debian_version") == -1)
548       return -1;
549
550     if (guestfs___parse_major_minor (g, fs) == -1)
551       return -1;
552   }
553
554   /* Arch Hurd also exists, but inconveniently it doesn't have
555    * the normal /etc/arch-release file.  XXX
556    */
557
558   /* Determine the architecture. */
559   check_architecture (g, fs);
560
561   /* XXX Check for /etc/fstab. */
562
563   /* Determine hostname. */
564   if (check_hostname_unix (g, fs) == -1)
565     return -1;
566
567   return 0;
568 }
569
570 static void
571 check_architecture (guestfs_h *g, struct inspect_fs *fs)
572 {
573   const char *binaries[] =
574     { "/bin/bash", "/bin/ls", "/bin/echo", "/bin/rm", "/bin/sh" };
575   size_t i;
576
577   for (i = 0; i < sizeof binaries / sizeof binaries[0]; ++i) {
578     if (guestfs_is_file (g, binaries[i]) > 0) {
579       /* Ignore errors from file_architecture call. */
580       guestfs_error_handler_cb old_error_cb = g->error_cb;
581       g->error_cb = NULL;
582       char *arch = guestfs_file_architecture (g, binaries[i]);
583       g->error_cb = old_error_cb;
584
585       if (arch) {
586         /* String will be owned by handle, freed by
587          * guestfs___free_inspect_info.
588          */
589         fs->arch = arch;
590         break;
591       }
592     }
593   }
594 }
595
596 /* Try several methods to determine the hostname from a Linux or
597  * FreeBSD guest.  Note that type and distro have been set, so we can
598  * use that information to direct the search.
599  */
600 static int
601 check_hostname_unix (guestfs_h *g, struct inspect_fs *fs)
602 {
603   switch (fs->type) {
604   case OS_TYPE_LINUX:
605   case OS_TYPE_HURD:
606     /* Red Hat-derived would be in /etc/sysconfig/network, and
607      * Debian-derived in the file /etc/hostname.  Very old Debian and
608      * SUSE use /etc/HOSTNAME.  It's best to just look for each of
609      * these files in turn, rather than try anything clever based on
610      * distro.
611      */
612     if (guestfs_is_file (g, "/etc/HOSTNAME")) {
613       fs->hostname = guestfs___first_line_of_file (g, "/etc/HOSTNAME");
614       if (fs->hostname == NULL)
615         return -1;
616     }
617     else if (guestfs_is_file (g, "/etc/hostname")) {
618       fs->hostname = guestfs___first_line_of_file (g, "/etc/hostname");
619       if (fs->hostname == NULL)
620         return -1;
621     }
622     else if (guestfs_is_file (g, "/etc/sysconfig/network")) {
623       const char *configfiles[] = { "/etc/sysconfig/network", NULL };
624       if (inspect_with_augeas (g, fs, configfiles,
625                                check_hostname_redhat) == -1)
626         return -1;
627     }
628     break;
629
630   case OS_TYPE_FREEBSD:
631   case OS_TYPE_NETBSD:
632     /* /etc/rc.conf contains the hostname, but there is no Augeas lens
633      * for this file.
634      */
635     if (guestfs_is_file (g, "/etc/rc.conf")) {
636       if (check_hostname_freebsd (g, fs) == -1)
637         return -1;
638     }
639     break;
640
641   case OS_TYPE_WINDOWS: /* not here, see check_windows_system_registry */
642   case OS_TYPE_UNKNOWN:
643   default:
644     /* nothing, keep GCC warnings happy */;
645   }
646
647   return 0;
648 }
649
650 /* Parse the hostname from /etc/sysconfig/network.  This must be called
651  * from the inspect_with_augeas wrapper.
652  */
653 static int
654 check_hostname_redhat (guestfs_h *g, struct inspect_fs *fs)
655 {
656   char *hostname;
657
658   /* Errors here are not fatal (RHBZ#726739), since it could be
659    * just missing HOSTNAME field in the file.
660    */
661   guestfs_error_handler_cb old_error_cb = g->error_cb;
662   g->error_cb = NULL;
663   hostname = guestfs_aug_get (g, "/files/etc/sysconfig/network/HOSTNAME");
664   g->error_cb = old_error_cb;
665
666   /* This is freed by guestfs___free_inspect_info.  Note that hostname
667    * could be NULL because we ignored errors above.
668    */
669   fs->hostname = hostname;
670   return 0;
671 }
672
673 /* Parse the hostname from /etc/rc.conf.  On FreeBSD this file
674  * contains comments, blank lines and:
675  *   hostname="freebsd8.example.com"
676  *   ifconfig_re0="DHCP"
677  *   keymap="uk.iso"
678  *   sshd_enable="YES"
679  */
680 static int
681 check_hostname_freebsd (guestfs_h *g, struct inspect_fs *fs)
682 {
683   const char *filename = "/etc/rc.conf";
684   int64_t size;
685   char **lines;
686   size_t i;
687
688   /* Don't trust guestfs_read_lines not to break with very large files.
689    * Check the file size is something reasonable first.
690    */
691   size = guestfs_filesize (g, filename);
692   if (size == -1)
693     /* guestfs_filesize failed and has already set error in handle */
694     return -1;
695   if (size > MAX_SMALL_FILE_SIZE) {
696     error (g, _("size of %s is unreasonably large (%" PRIi64 " bytes)"),
697            filename, size);
698     return -1;
699   }
700
701   lines = guestfs_read_lines (g, filename);
702   if (lines == NULL)
703     return -1;
704
705   for (i = 0; lines[i] != NULL; ++i) {
706     if (STRPREFIX (lines[i], "hostname=\"") ||
707         STRPREFIX (lines[i], "hostname='")) {
708       size_t len = strlen (lines[i]) - 10 - 1;
709       fs->hostname = safe_strndup (g, &lines[i][10], len);
710       break;
711     } else if (STRPREFIX (lines[i], "hostname=")) {
712       size_t len = strlen (lines[i]) - 9;
713       fs->hostname = safe_strndup (g, &lines[i][9], len);
714       break;
715     }
716   }
717
718   guestfs___free_string_list (lines);
719   return 0;
720 }
721
722 static int
723 check_fstab (guestfs_h *g, struct inspect_fs *fs)
724 {
725   char **entries, **entry;
726   char augpath[256];
727   char *spec, *mp;
728   int r;
729
730   entries = guestfs_aug_match (g, "/files/etc/fstab/*[label() != '#comment']");
731   if (entries == NULL) goto error;
732
733   if (entries[0] == NULL) {
734     error (g, _("could not parse /etc/fstab or empty file"));
735     goto error;
736   }
737
738   for (entry = entries; *entry != NULL; entry++) {
739     snprintf (augpath, sizeof augpath, "%s/spec", *entry);
740     spec = guestfs_aug_get (g, augpath);
741     if (spec == NULL) goto error;
742
743     snprintf (augpath, sizeof augpath, "%s/file", *entry);
744     mp = guestfs_aug_get (g, augpath);
745     if (mp == NULL) {
746       free (spec);
747       goto error;
748     }
749
750     r = add_fstab_entry (g, fs, spec, mp);
751     free (spec);
752     free (mp);
753
754     if (r == -1) goto error;
755   }
756
757   guestfs___free_string_list (entries);
758   return 0;
759
760 error:
761   if (entries) guestfs___free_string_list (entries);
762   return -1;
763 }
764
765 /* Add a filesystem and possibly a mountpoint entry for
766  * the root filesystem 'fs'.
767  *
768  * 'spec' is the fstab spec field, which might be a device name or a
769  * pseudodevice or 'UUID=...' or 'LABEL=...'.
770  *
771  * 'mp' is the mount point, which could also be 'swap' or 'none'.
772  */
773 static int
774 add_fstab_entry (guestfs_h *g, struct inspect_fs *fs,
775                  const char *spec, const char *mp)
776 {
777   /* Ignore certain mountpoints. */
778   if (STRPREFIX (mp, "/dev/") ||
779       STREQ (mp, "/dev") ||
780       STRPREFIX (mp, "/media/") ||
781       STRPREFIX (mp, "/proc/") ||
782       STREQ (mp, "/proc") ||
783       STRPREFIX (mp, "/selinux/") ||
784       STREQ (mp, "/selinux") ||
785       STRPREFIX (mp, "/sys/") ||
786       STREQ (mp, "/sys"))
787     return 0;
788
789   /* Ignore /dev/fd (floppy disks) (RHBZ#642929) and CD-ROM drives. */
790   if ((STRPREFIX (spec, "/dev/fd") && c_isdigit (spec[7])) ||
791       STREQ (spec, "/dev/floppy") ||
792       STREQ (spec, "/dev/cdrom"))
793     return 0;
794
795   /* Resolve UUID= and LABEL= to the actual device. */
796   char *device = NULL;
797   if (STRPREFIX (spec, "UUID="))
798     device = guestfs_findfs_uuid (g, &spec[5]);
799   else if (STRPREFIX (spec, "LABEL="))
800     device = guestfs_findfs_label (g, &spec[6]);
801   /* Ignore "/.swap" (Pardus) and pseudo-devices like "tmpfs". */
802   else if (STREQ (spec, "/dev/root"))
803     /* Resolve /dev/root to the current device. */
804     device = safe_strdup (g, fs->device);
805   else if (STRPREFIX (spec, "/dev/"))
806     /* Resolve guest block device names. */
807     device = resolve_fstab_device (g, spec);
808
809   /* If we haven't resolved the device successfully by this point,
810    * we don't care, just ignore it.
811    */
812   if (device == NULL)
813     return 0;
814
815   char *mountpoint = safe_strdup (g, mp);
816
817   /* Add this to the fstab entry in 'fs'.
818    * Note these are further filtered by guestfs_inspect_get_mountpoints
819    * and guestfs_inspect_get_filesystems.
820    */
821   size_t n = fs->nr_fstab + 1;
822   struct inspect_fstab_entry *p;
823
824   p = realloc (fs->fstab, n * sizeof (struct inspect_fstab_entry));
825   if (p == NULL) {
826     perrorf (g, "realloc");
827     free (device);
828     free (mountpoint);
829     return -1;
830   }
831
832   fs->fstab = p;
833   fs->nr_fstab = n;
834
835   /* These are owned by the handle and freed by guestfs___free_inspect_info. */
836   fs->fstab[n-1].device = device;
837   fs->fstab[n-1].mountpoint = mountpoint;
838
839   debug (g, "fstab: device=%s mountpoint=%s", device, mountpoint);
840
841   return 0;
842 }
843
844 /* Resolve block device name to the libguestfs device name, eg.
845  * /dev/xvdb1 => /dev/vdb1; and /dev/mapper/VG-LV => /dev/VG/LV.  This
846  * assumes that disks were added in the same order as they appear to
847  * the real VM, which is a reasonable assumption to make.  Return
848  * anything we don't recognize unchanged.
849  */
850 static char *
851 resolve_fstab_device (guestfs_h *g, const char *spec)
852 {
853   char *device = NULL;
854   char *type, *slice, *disk, *part;
855
856   if (STRPREFIX (spec, "/dev/mapper/")) {
857     /* LVM2 does some strange munging on /dev/mapper paths for VGs and
858      * LVs which contain '-' character:
859      *
860      * ><fs> lvcreate LV--test VG--test 32
861      * ><fs> debug ls /dev/mapper
862      * VG----test-LV----test
863      *
864      * This makes it impossible to reverse those paths directly, so
865      * we have implemented lvm_canonical_lv_name in the daemon.
866      */
867     device = guestfs_lvm_canonical_lv_name (g, spec);
868   }
869   else if (match3 (g, spec, re_xdev, &type, &disk, &part)) {
870     /* type: (h|s|v|xv)
871      * disk: ([a-z]+)
872      * part: (\d*) */
873     char **devices = guestfs_list_devices (g);
874     if (devices == NULL)
875       return NULL;
876
877     /* Check any hints we were passed for a non-heuristic mapping */
878     char *name = safe_asprintf (g, "%sd%s", type, disk);
879     size_t i = 0;
880     struct drive *drive = g->drives;
881     while (drive) {
882       if (drive->name && STREQ(drive->name, name)) {
883         device = safe_asprintf (g, "%s%s", devices[i], part);
884         break;
885       }
886
887       i++; drive = drive->next;
888     }
889     free (name);
890
891     /* Guess the appliance device name if we didn't find a matching hint */
892     if (!device) {
893       /* Count how many disks the libguestfs appliance has */
894       size_t count;
895       for (count = 0; devices[count] != NULL; count++)
896         ;
897
898       /* Calculate the numerical index of the disk */
899       i = disk[0] - 'a';
900       for (char *p = disk + 1; *p != '\0'; p++) {
901         i += 1; i *= 26;
902         i += *p - 'a';
903       }
904
905       /* Check the index makes sense wrt the number of disks the appliance has.
906        * If it does, map it to an appliance disk. */
907       if (i < count) {
908         device = safe_asprintf (g, "%s%s", devices[i], part);
909       }
910     }
911
912     free (type);
913     free (disk);
914     free (part);
915     guestfs___free_string_list (devices);
916   }
917   else if (match2 (g, spec, re_cciss, &disk, &part)) {
918     /* disk: (cciss/c\d+d\d+)
919      * part: (\d+)? */
920     char **devices = guestfs_list_devices (g);
921     if (devices == NULL)
922       return NULL;
923
924     /* Check any hints we were passed for a non-heuristic mapping */
925     size_t i = 0;
926     struct drive *drive = g->drives;
927     while (drive) {
928       if (drive->name && STREQ(drive->name, disk)) {
929         if (part) {
930           device = safe_asprintf (g, "%s%s", devices[i], part);
931         } else {
932           device = safe_strdup (g, devices[i]);
933         }
934         break;
935       }
936
937       i++; drive = drive->next;
938     }
939
940     /* We don't try to guess mappings for cciss devices */
941
942     free (disk);
943     free (part);
944     guestfs___free_string_list (devices);
945   }
946   else if (match3 (g, spec, re_freebsd, &disk, &slice, &part)) {
947     /* FreeBSD disks are organized quite differently.  See:
948      * http://www.freebsd.org/doc/handbook/disk-organization.html
949      * FreeBSD "partitions" are exposed as quasi-extended partitions
950      * numbered from 5 in Linux.  I have no idea what happens when you
951      * have multiple "slices" (the FreeBSD term for MBR partitions).
952      */
953     int disk_i = guestfs___parse_unsigned_int (g, disk);
954     int slice_i = guestfs___parse_unsigned_int (g, slice);
955     int part_i = part[0] - 'a' /* counting from 0 */;
956     free (disk);
957     free (slice);
958     free (part);
959
960     if (disk_i != -1 && disk_i <= 26 &&
961         slice_i > 0 && slice_i <= 1 /* > 4 .. see comment above */ &&
962         part_i >= 0 && part_i < 26) {
963       device = safe_asprintf (g, "/dev/sd%c%d", disk_i + 'a', part_i + 5);
964     }
965   }
966
967   /* Didn't match device pattern, return original spec unchanged. */
968   if (device == NULL)
969     device = safe_strdup (g, spec);
970
971   return device;
972 }
973
974 /* Call 'f' with Augeas opened and having parsed 'filename' (this file
975  * must exist).  As a security measure, this bails if the file is too
976  * large for a reasonable configuration file.  After the call to 'f'
977  * Augeas is closed.
978  */
979 static int
980 inspect_with_augeas (guestfs_h *g, struct inspect_fs *fs,
981                      const char **configfiles,
982                      int (*f) (guestfs_h *, struct inspect_fs *))
983 {
984   /* Security: Refuse to do this if a config file is too large. */
985   for (const char **i = configfiles; *i != NULL; i++) {
986     if (guestfs_exists(g, *i) == 0) continue;
987
988     int64_t size = guestfs_filesize (g, *i);
989     if (size == -1)
990       /* guestfs_filesize failed and has already set error in handle */
991       return -1;
992     if (size > MAX_AUGEAS_FILE_SIZE) {
993       error (g, _("size of %s is unreasonably large (%" PRIi64 " bytes)"),
994              *i, size);
995       return -1;
996     }
997   }
998
999   /* If !feature_available (g, "augeas") then the next call will fail.
1000    * Arguably we might want to fall back to a non-Augeas method in
1001    * this case.
1002    */
1003   if (guestfs_aug_init (g, "/", 16|32) == -1)
1004     return -1;
1005
1006   int r = -1;
1007
1008   /* Tell Augeas to only load one file (thanks RaphaĆ«l Pinson). */
1009 #define AUGEAS_LOAD "/augeas/load//incl[. != \""
1010 #define AUGEAS_LOAD_LEN (strlen(AUGEAS_LOAD))
1011   size_t conflen = strlen(configfiles[0]);
1012   size_t buflen = AUGEAS_LOAD_LEN + conflen + 1 /* Closing " */;
1013   char *buf = safe_malloc(g, buflen + 2 /* Closing ] + null terminator */);
1014
1015   memcpy(buf, AUGEAS_LOAD, AUGEAS_LOAD_LEN);
1016   memcpy(buf + AUGEAS_LOAD_LEN, configfiles[0], conflen);
1017   buf[buflen - 1] = '"';
1018 #undef AUGEAS_LOAD_LEN
1019 #undef AUGEAS_LOAD
1020
1021 #define EXCL " and . != \""
1022 #define EXCL_LEN (strlen(EXCL))
1023   for (const char **i = &configfiles[1]; *i != NULL; i++) {
1024     size_t orig_buflen = buflen;
1025     conflen = strlen(*i);
1026     buflen += EXCL_LEN + conflen + 1 /* Closing " */;
1027     buf = safe_realloc(g, buf, buflen + 2 /* Closing ] + null terminator */);
1028     char *s = buf + orig_buflen;
1029
1030     memcpy(s, EXCL, EXCL_LEN);
1031     memcpy(s + EXCL_LEN, *i, conflen);
1032     buf[buflen - 1] = '"';
1033   }
1034 #undef EXCL_LEN
1035 #undef EXCL
1036
1037   buf[buflen] = ']';
1038   buf[buflen + 1] = '\0';
1039
1040   if (guestfs_aug_rm (g, buf) == -1) {
1041     free(buf);
1042     goto out;
1043   }
1044   free(buf);
1045
1046   if (guestfs_aug_load (g) == -1)
1047     goto out;
1048
1049   r = f (g, fs);
1050
1051  out:
1052   guestfs_aug_close (g);
1053
1054   return r;
1055 }
1056
1057 #endif /* defined(HAVE_HIVEX) */