Refactor cpio code into separate file.
[febootstrap.git] / helper / appliance.c
1 /* febootstrap-supermin-helper reimplementation in C.
2  * Copyright (C) 2009-2010 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program 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
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  */
18
19 #include <config.h>
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <errno.h>
27 #include <dirent.h>
28 #include <fnmatch.h>
29 #include <sys/stat.h>
30 #include <assert.h>
31
32 #include "error.h"
33 #include "fts_.h"
34 #include "xalloc.h"
35 #include "xvasprintf.h"
36
37 #include "helper.h"
38
39 static void iterate_inputs (char **inputs, int nr_inputs, struct writer *);
40 static void iterate_input_directory (const char *dirname, int dirfd, struct writer *);
41 static void add_kernel_modules (const char *whitelist, const char *modpath, struct writer *);
42 static void add_hostfiles (const char *hostfiles_file, struct writer *);
43
44 /* Create the appliance.
45  *
46  * The initrd consists of these components concatenated together:
47  *
48  * (1) The base skeleton appliance that we constructed at build time.
49  *     format = plain cpio
50  * (2) The host files which match wildcards in *.supermin.hostfiles.
51  *     input format = plain text, output format = plain cpio
52  * (3) The modules from modpath which are on the module whitelist.
53  *     output format = plain cpio
54  *
55  * The original shell script used the external cpio program to create
56  * parts (2) and (3), but we have decided it's going to be faster if
57  * we just write out the data outselves.  The reasons are that
58  * external cpio is slow (particularly when used with SELinux because
59  * it does 512 byte reads), and the format that we're writing is
60  * narrow and well understood, because we only care that the Linux
61  * kernel can read it.
62  *
63  * This version contains some improvements over the C version written
64  * for libguestfs, in that we can have multiple base images (or
65  * hostfiles) or use a directory to store these files.
66  */
67 void
68 create_appliance (char **inputs, int nr_inputs,
69                   const char *whitelist,
70                   const char *modpath,
71                   const char *appliance,
72                   struct writer *writer)
73 {
74   writer->wr_start (appliance);
75
76   iterate_inputs (inputs, nr_inputs, writer);
77
78   /* Kernel modules (3). */
79   add_kernel_modules (whitelist, modpath, writer);
80
81   writer->wr_end ();
82 }
83
84 /* Iterate over the inputs to find out what they are, visiting
85  * directories if specified.
86  */
87 static void
88 iterate_inputs (char **inputs, int nr_inputs, struct writer *writer)
89 {
90   int i;
91   for (i = 0; i < nr_inputs; ++i) {
92     if (verbose)
93       print_timestamped_message ("visiting %s", inputs[i]);
94
95     int fd = open (inputs[i], O_RDONLY);
96     if (fd == -1)
97       error (EXIT_FAILURE, errno, "open: %s", inputs[i]);
98
99     struct stat statbuf;
100     if (fstat (fd, &statbuf) == -1)
101       error (EXIT_FAILURE, errno, "fstat: %s", inputs[i]);
102
103     /* Directory? */
104     if (S_ISDIR (statbuf.st_mode))
105       iterate_input_directory (inputs[i], fd, writer);
106     else if (S_ISREG (statbuf.st_mode)) {
107       /* Is it a cpio file? */
108       char buf[6];
109       if (read (fd, buf, 6) == 6 && memcmp (buf, "070701", 6) == 0)
110         /* Yes, a cpio file.  This is a skeleton appliance, case (1). */
111         writer->wr_cpio_file (inputs[i]);
112       else
113         /* No, must be hostfiles, case (2). */
114         add_hostfiles (inputs[i], writer);
115     }
116     else
117       error (EXIT_FAILURE, 0, "%s: input is not a regular file or directory",
118              inputs[i]);
119
120     close (fd);
121   }
122 }
123
124 static void
125 iterate_input_directory (const char *dirname, int dirfd, struct writer *writer)
126 {
127   char path[PATH_MAX];
128   strcpy (path, dirname);
129   size_t len = strlen (dirname);
130   path[len++] = '/';
131
132   char *inputs[] = { path };
133
134   DIR *dir = fdopendir (dirfd);
135   if (dir == NULL)
136     error (EXIT_FAILURE, errno, "fdopendir: %s", dirname);
137
138   struct dirent *d;
139   while ((errno = 0, d = readdir (dir)) != NULL) {
140     if (d->d_name[0] == '.') /* ignore ., .. and any hidden files. */
141       continue;
142
143     strcpy (&path[len], d->d_name);
144     iterate_inputs (inputs, 1, writer);
145   }
146
147   if (errno != 0)
148     error (EXIT_FAILURE, errno, "readdir: %s", dirname);
149
150   if (closedir (dir) == -1)
151     error (EXIT_FAILURE, errno, "closedir: %s", dirname);
152 }
153
154 /* Copy kernel modules.
155  *
156  * Find every file under modpath.
157  *
158  * Exclude all *.ko files, *except* ones which match names in
159  * the whitelist (which may contain wildcards).  Include all
160  * other files.
161  *
162  * Add chosen files to the output.
163  *
164  * whitelist_file may be NULL, to include ALL kernel modules.
165  */
166 static void
167 add_kernel_modules (const char *whitelist_file, const char *modpath,
168                     struct writer *writer)
169 {
170   char **whitelist = NULL;
171   if (whitelist_file != NULL)
172     whitelist = load_file (whitelist_file);
173
174   char *paths[2] = { (char *) modpath, NULL };
175   FTS *fts = fts_open (paths, FTS_COMFOLLOW|FTS_PHYSICAL, NULL);
176   if (fts == NULL)
177     error (EXIT_FAILURE, errno, "add_kernel_modules: fts_open: %s", modpath);
178
179   for (;;) {
180     errno = 0;
181     FTSENT *entry = fts_read (fts);
182     if (entry == NULL && errno != 0)
183       error (EXIT_FAILURE, errno, "add_kernel_modules: fts_read: %s", modpath);
184     if (entry == NULL)
185       break;
186
187     /* Ignore directories being visited in post-order. */
188     if (entry->fts_info & FTS_DP)
189       continue;
190
191     /* Is it a *.ko file? */
192     if (entry->fts_namelen >= 3 &&
193         entry->fts_name[entry->fts_namelen-3] == '.' &&
194         entry->fts_name[entry->fts_namelen-2] == 'k' &&
195         entry->fts_name[entry->fts_namelen-1] == 'o') {
196       if (whitelist) {
197         /* Is it a *.ko file which is on the whitelist? */
198         size_t j;
199         for (j = 0; whitelist[j] != NULL; ++j) {
200           int r;
201           r = fnmatch (whitelist[j], entry->fts_name, 0);
202           if (r == 0) {
203             /* It's on the whitelist, so include it. */
204             if (verbose >= 2)
205               fprintf (stderr, "including kernel module %s (matches whitelist entry %s)\n",
206                        entry->fts_name, whitelist[j]);
207             writer->wr_fts_entry (entry);
208             break;
209           } else if (r != FNM_NOMATCH)
210             error (EXIT_FAILURE, 0, "internal error: fnmatch ('%s', '%s', %d) returned unexpected non-zero value %d\n",
211                    whitelist[j], entry->fts_name, 0, r);
212         } /* for (j) */
213       } else { /* whitelist == NULL, always include */
214         if (verbose >= 2)
215           fprintf (stderr, "including kernel module %s\n", entry->fts_name);
216         writer->wr_fts_entry (entry);
217       }
218     } else
219       /* It's some other sort of file, or a directory, always include. */
220       writer->wr_fts_entry (entry);
221   }
222
223   if (fts_close (fts) == -1)
224     error (EXIT_FAILURE, errno, "add_kernel_modules: fts_close: %s", modpath);
225 }
226
227 /* Copy the host files.
228  *
229  * Read the list of entries in hostfiles (which may contain
230  * wildcards).  Look them up in the filesystem, and add those files
231  * that exist.  Ignore any files that don't exist or are not readable.
232  */
233 static void
234 add_hostfiles (const char *hostfiles_file, struct writer *writer)
235 {
236   char **hostfiles = load_file (hostfiles_file);
237
238   /* Hostfiles list can contain "." before each path - ignore it.
239    * It also contains each directory name before we enter it.  But
240    * we don't read that until we see a wildcard for that directory.
241    */
242   size_t i, j;
243   for (i = 0; hostfiles[i] != NULL; ++i) {
244     char *hostfile = hostfiles[i];
245     if (hostfile[0] == '.')
246       hostfile++;
247
248     struct stat statbuf;
249
250     /* Is it a wildcard? */
251     if (strchr (hostfile, '*') || strchr (hostfile, '?')) {
252       char *dirname = xstrdup (hostfile);
253       char *patt = strrchr (dirname, '/');
254       assert (patt);
255       *patt++ = '\0';
256
257       char **files = read_dir (dirname);
258       files = filter_fnmatch (files, patt, FNM_NOESCAPE);
259
260       /* Add matching files. */
261       for (j = 0; files[j] != NULL; ++j) {
262         char *tmp = xasprintf ("%s/%s", dirname, files[j]);
263
264         if (verbose >= 2)
265           fprintf (stderr, "including host file %s (matches %s)\n", tmp, patt);
266
267         writer->wr_file (tmp);
268
269         free (tmp);
270       }
271     }
272     /* Else does this file/directory/whatever exist? */
273     else if (lstat (hostfile, &statbuf) == 0) {
274       if (verbose >= 2)
275         fprintf (stderr, "including host file %s (directly referenced)\n",
276                  hostfile);
277
278       writer->wr_file_stat (hostfile, &statbuf);
279     } /* Ignore files that don't exist. */
280   }
281 }