helper: Add better error messages if files too big for appliance root.
[febootstrap.git] / helper / ext2.c
1 /* febootstrap-supermin-helper reimplementation in C.
2  * Copyright (C) 2009-2011 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 <fcntl.h>
25 #include <unistd.h>
26 #include <errno.h>
27 #include <limits.h>
28 #include <sys/stat.h>
29 #include <assert.h>
30
31 #include "error.h"
32 #include "fts_.h"
33 #include "xvasprintf.h"
34
35 #include "helper.h"
36 #include "ext2internal.h"
37
38 ext2_filsys fs;
39
40 /* The ext2 image that we build always has a fixed size, and we 'hope'
41  * that the files fit in (otherwise we'll get an error).  Note that
42  * the file is sparsely allocated.
43  *
44  * The downside of allocating a very large initial disk is that the
45  * fixed overhead of ext2 is larger (since ext2 calculates it based on
46  * the size of the disk).  For a 1GB disk the overhead is
47  * approximately 16MB.
48  *
49  * In future, make this configurable, or determine it from the input
50  * files (XXX).
51  */
52 #define APPLIANCE_SIZE (1024*1024*1024)
53
54 static void
55 ext2_start (const char *hostcpu, const char *appliance,
56             const char *modpath, const char *initrd)
57 {
58   initialize_ext2_error_table ();
59
60   /* Make the initrd. */
61   ext2_make_initrd (modpath, initrd);
62
63   /* Make the appliance sparse image. */
64   int fd = open (appliance, O_WRONLY | O_CREAT | O_TRUNC | O_NOCTTY, 0644);
65   if (fd == -1)
66     error (EXIT_FAILURE, errno, "open: %s", appliance);
67
68   if (lseek (fd, APPLIANCE_SIZE - 1, SEEK_SET) == -1)
69     error (EXIT_FAILURE, errno, "lseek");
70
71   char c = 0;
72   if (write (fd, &c, 1) != 1)
73     error (EXIT_FAILURE, errno, "write");
74
75   if (close (fd) == -1)
76     error (EXIT_FAILURE, errno, "close");
77
78   /* Run mke2fs on the file.
79    * XXX Quoting, but this string doesn't come from an untrusted source.
80    */
81   char *cmd = xasprintf ("%s -t ext2 -F%s '%s'",
82                          MKE2FS,
83                          verbose >= 2 ? "" : "q",
84                          appliance);
85   int r = system (cmd);
86   if (r == -1 || WEXITSTATUS (r) != 0)
87     error (EXIT_FAILURE, 0, "%s: failed", cmd);
88   free (cmd);
89
90   if (verbose)
91     print_timestamped_message ("finished mke2fs");
92
93   /* Open the filesystem. */
94   errcode_t err =
95     ext2fs_open (appliance, EXT2_FLAG_RW, 0, 0, unix_io_manager, &fs);
96   if (err != 0)
97     error (EXIT_FAILURE, 0, "ext2fs_open: %s", error_message (err));
98
99   /* Bitmaps are not loaded by default, so load them.  ext2fs_close will
100    * write out any changes.
101    */
102   err = ext2fs_read_bitmaps (fs);
103   if (err != 0)
104     error (EXIT_FAILURE, 0, "ext2fs_read_bitmaps: %s", error_message (err));
105 }
106
107 static void
108 ext2_end (void)
109 {
110   /* Write out changes and close. */
111   errcode_t err = ext2fs_close (fs);
112   if (err != 0)
113     error (EXIT_FAILURE, 0, "ext2fs_close: %s", error_message (err));
114 }
115
116 void
117 ext2_mkdir (ext2_ino_t dir_ino, const char *dirname, const char *basename,
118             mode_t mode, uid_t uid, gid_t gid,
119             time_t ctime, time_t atime, time_t mtime)
120 {
121   errcode_t err;
122
123   mode = LINUX_S_IFDIR | (mode & 0777);
124
125   /* Does the directory exist?  This is legitimate: we just skip
126    * this case.
127    */
128   ext2_ino_t ino;
129   err = ext2fs_namei (fs, EXT2_ROOT_INO, dir_ino, basename, &ino);
130   if (err == 0)
131     return; /* skip */
132
133   /* Otherwise, create it. */
134   err = ext2fs_new_inode (fs, dir_ino, mode, 0, &ino);
135   if (err != 0)
136     error (EXIT_FAILURE, 0, "ext2fs_new_inode: %s", error_message (err));
137
138  try_again:
139   err = ext2fs_mkdir (fs, dir_ino, ino, basename);
140   if (err != 0) {
141     /* See: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=217892 */
142     if (err == EXT2_ET_DIR_NO_SPACE) {
143       err = ext2fs_expand_dir (fs, dir_ino);
144       if (err)
145         error (EXIT_FAILURE, 0, "ext2fs_expand_dir: %s/%s: %s",
146                dirname, basename, error_message (err));
147       goto try_again;
148     } else
149       error (EXIT_FAILURE, 0, "ext2fs_mkdir: %s/%s: %s",
150              dirname, basename, error_message (err));
151   }
152
153   /* Copy the final permissions, UID etc. to the inode. */
154   struct ext2_inode inode;
155   err = ext2fs_read_inode (fs, ino, &inode);
156   if (err != 0)
157     error (EXIT_FAILURE, 0, "ext2fs_read_inode: %s", error_message (err));
158   inode.i_mode = mode;
159   inode.i_uid = uid;
160   inode.i_gid = gid;
161   inode.i_ctime = ctime;
162   inode.i_atime = atime;
163   inode.i_mtime = mtime;
164   err = ext2fs_write_inode (fs, ino, &inode);
165   if (err != 0)
166     error (EXIT_FAILURE, 0, "ext2fs_write_inode: %s", error_message (err));
167 }
168
169 void
170 ext2_empty_inode (ext2_ino_t dir_ino, const char *dirname, const char *basename,
171                   mode_t mode, uid_t uid, gid_t gid,
172                   time_t ctime, time_t atime, time_t mtime,
173                   int major, int minor, int dir_ft, ext2_ino_t *ino_ret)
174 {
175   errcode_t err;
176   struct ext2_inode inode;
177   ext2_ino_t ino;
178
179   err = ext2fs_new_inode (fs, dir_ino, mode, 0, &ino);
180   if (err != 0)
181     error (EXIT_FAILURE, 0, "ext2fs_new_inode: %s", error_message (err));
182
183   memset (&inode, 0, sizeof inode);
184   inode.i_mode = mode;
185   inode.i_uid = uid;
186   inode.i_gid = gid;
187   inode.i_blocks = 0;
188   inode.i_links_count = 1;
189   inode.i_ctime = ctime;
190   inode.i_atime = atime;
191   inode.i_mtime = mtime;
192   inode.i_size = 0;
193   inode.i_block[0] = (minor & 0xff) | (major << 8) | ((minor & ~0xff) << 12);
194
195   err = ext2fs_write_new_inode (fs, ino, &inode);
196   if (err != 0)
197     error (EXIT_FAILURE, 0, "ext2fs_write_inode: %s", error_message (err));
198
199   ext2_link (dir_ino, basename, ino, dir_ft);
200
201   ext2fs_inode_alloc_stats2 (fs, ino, 1, 0);
202
203   if (ino_ret)
204     *ino_ret = ino;
205 }
206
207 /* You must create the file first with ext2_empty_inode. */
208 void
209 ext2_write_file (ext2_ino_t ino, const char *buf, size_t size,
210                  const char *orig_filename)
211 {
212   errcode_t err;
213   ext2_file_t file;
214   err = ext2fs_file_open2 (fs, ino, NULL, EXT2_FILE_WRITE, &file);
215   if (err != 0)
216     error (EXIT_FAILURE, 0, "ext2fs_file_open2: %s: %s",
217            orig_filename, error_message (err));
218
219   /* ext2fs_file_write cannot deal with partial writes.  You have
220    * to write the entire file in a single call.
221    */
222   unsigned int written;
223   err = ext2fs_file_write (file, buf, size, &written);
224   if (err != 0)
225     error (EXIT_FAILURE, 0, "ext2fs_file_write: %s: %s\n"
226            "Block allocation failures can happen here for several reasons:\n"
227            " - /lib/modules contains modules with debug that makes the modules very large\n"
228            " - a file listed in 'hostfiles' is unexpectedly very large\n"
229            " - too many packages added to the supermin appliance",
230            orig_filename, error_message (err));
231   if ((size_t) written != size)
232     error (EXIT_FAILURE, 0,
233            "ext2fs_file_write: %s: size = %zu != written = %u\n",
234            orig_filename, size, written);
235
236   err = ext2fs_file_flush (file);
237   if (err != 0)
238     error (EXIT_FAILURE, 0, "ext2fs_file_flush: %s: %s",
239            orig_filename, error_message (err));
240   err = ext2fs_file_close (file);
241   if (err != 0)
242     error (EXIT_FAILURE, 0, "ext2fs_file_close: %s: %s",
243            orig_filename, error_message (err));
244
245   /* Update the true size in the inode. */
246   struct ext2_inode inode;
247   err = ext2fs_read_inode (fs, ino, &inode);
248   if (err != 0)
249     error (EXIT_FAILURE, 0, "ext2fs_read_inode: %s: %s",
250            orig_filename, error_message (err));
251   inode.i_size = size;
252   err = ext2fs_write_inode (fs, ino, &inode);
253   if (err != 0)
254     error (EXIT_FAILURE, 0, "ext2fs_write_inode: %s: %s",
255            orig_filename, error_message (err));
256 }
257
258 /* This is just a wrapper around ext2fs_link which calls
259  * ext2fs_expand_dir as necessary if the directory fills up.  See
260  * definition of expand_dir in the sources of debugfs.
261  */
262 void
263 ext2_link (ext2_ino_t dir_ino, const char *basename, ext2_ino_t ino, int dir_ft)
264 {
265   errcode_t err;
266
267  again:
268   err = ext2fs_link (fs, dir_ino, basename, ino, dir_ft);
269
270   if (err == EXT2_ET_DIR_NO_SPACE) {
271     err = ext2fs_expand_dir (fs, dir_ino);
272     if (err != 0)
273       error (EXIT_FAILURE, 0, "ext2_link: ext2fs_expand_dir: %s: %s",
274              basename, error_message (err));
275     goto again;
276   }
277
278   if (err != 0)
279     error (EXIT_FAILURE, 0, "ext2fs_link: %s: %s",
280              basename, error_message (err));
281 }
282
283 static int
284 release_block (ext2_filsys fs, blk_t *blocknr,
285                 int blockcnt, void *private)
286 {
287   blk_t block;
288
289   block = *blocknr;
290   ext2fs_block_alloc_stats (fs, block, -1);
291   return 0;
292 }
293
294 /* unlink or rmdir path, if it exists. */
295 void
296 ext2_clean_path (ext2_ino_t dir_ino,
297                  const char *dirname, const char *basename,
298                  int isdir)
299 {
300   errcode_t err;
301
302   ext2_ino_t ino;
303   err = ext2fs_lookup (fs, dir_ino, basename, strlen (basename),
304                        NULL, &ino);
305   if (err == EXT2_ET_FILE_NOT_FOUND)
306     return;
307
308   if (!isdir) {
309     struct ext2_inode inode;
310     err = ext2fs_read_inode (fs, ino, &inode);
311     if (err != 0)
312       error (EXIT_FAILURE, 0, "ext2fs_read_inode: %s", error_message (err));
313     inode.i_links_count--;
314     err = ext2fs_write_inode (fs, ino, &inode);
315     if (err != 0)
316       error (EXIT_FAILURE, 0, "ext2fs_write_inode: %s", error_message (err));
317
318     err = ext2fs_unlink (fs, dir_ino, basename, 0, 0);
319     if (err != 0)
320       error (EXIT_FAILURE, 0, "ext2fs_unlink_inode: %s", error_message (err));
321
322     if (inode.i_links_count == 0) {
323       inode.i_dtime = time (NULL);
324       err = ext2fs_write_inode (fs, ino, &inode);
325       if (err != 0)
326         error (EXIT_FAILURE, 0, "ext2fs_write_inode: %s", error_message (err));
327
328       if (ext2fs_inode_has_valid_blocks (&inode)) {
329         int flags = 0;
330         /* From the docs: "BLOCK_FLAG_READ_ONLY is a promise by the
331          * caller that it will not modify returned block number."
332          * RHEL 5 does not have this flag, so just omit it if it is
333          * not defined.
334          */
335 #ifdef BLOCK_FLAG_READ_ONLY
336         flags |= BLOCK_FLAG_READ_ONLY;
337 #endif
338         ext2fs_block_iterate (fs, ino, flags, NULL,
339                               release_block, NULL);
340       }
341
342       ext2fs_inode_alloc_stats2 (fs, ino, -1, isdir);
343     }
344   }
345   /* else it's a directory, what to do? XXX */
346 }
347
348 /* Read in the whole file into memory.  Check the size is still 'size'. */
349 static char *
350 read_whole_file (const char *filename, size_t size)
351 {
352   char *buf = malloc (size);
353   if (buf == NULL)
354     error (EXIT_FAILURE, errno, "malloc");
355
356   int fd = open (filename, O_RDONLY);
357   if (fd == -1)
358     error (EXIT_FAILURE, errno, "open: %s", filename);
359
360   size_t n = 0;
361   char *p = buf;
362
363   while (n < size) {
364     ssize_t r = read (fd, p, size - n);
365     if (r == -1)
366       error (EXIT_FAILURE, errno, "read: %s", filename);
367     if (r == 0)
368       error (EXIT_FAILURE, 0,
369              "error: file has changed size unexpectedly: %s", filename);
370     n += r;
371     p += r;
372   }
373
374   if (close (fd) == -1)
375     error (EXIT_FAILURE, errno, "close: %s", filename);
376
377   return buf;
378 }
379
380 /* Add a file (or directory etc) from the host. */
381 static void
382 ext2_file_stat (const char *orig_filename, const struct stat *statbuf)
383 {
384   errcode_t err;
385
386   if (verbose >= 2)
387     fprintf (stderr, "ext2_file_stat %s 0%o\n",
388              orig_filename, statbuf->st_mode);
389
390   /* Sanity check the path.  These rules are always true for the paths
391    * passed to us here from the appliance layer.  The assertions just
392    * verify that the rules haven't changed.
393    */
394   size_t n = strlen (orig_filename);
395   assert (n <= PATH_MAX);
396   assert (n > 0);
397   assert (orig_filename[0] == '/'); /* always absolute path */
398   assert (n == 1 || orig_filename[n-1] != '/'); /* no trailing slash */
399
400   /* Don't make the root directory, it always exists.  This simplifies
401    * the code that follows.
402    */
403   if (n == 1) return;
404
405   const char *dirname, *basename;
406   const char *p = strrchr (orig_filename, '/');
407   ext2_ino_t dir_ino;
408   if (orig_filename == p) {     /* "/foo" */
409     dirname = "/";
410     basename = orig_filename+1;
411     dir_ino = EXT2_ROOT_INO;
412   } else {                      /* "/foo/bar" */
413     dirname = strndup (orig_filename, p-orig_filename);
414     basename = p+1;
415
416     /* If the parent directory is a symlink to another directory, then
417      * we want to look up the target directory. (RHBZ#698089).
418      */
419     struct stat stat1, stat2;
420     if (lstat (dirname, &stat1) == 0 && S_ISLNK (stat1.st_mode) &&
421         stat (dirname, &stat2) == 0 && S_ISDIR (stat2.st_mode)) {
422       char *new_dirname = malloc (PATH_MAX+1);
423       ssize_t r = readlink (dirname, new_dirname, PATH_MAX+1);
424       if (r == -1)
425         error (EXIT_FAILURE, errno, "readlink: %s", orig_filename);
426       new_dirname[r] = '\0';
427       dirname = new_dirname;
428     }
429
430     /* Look up the parent directory. */
431     err = ext2fs_namei (fs, EXT2_ROOT_INO, EXT2_ROOT_INO, dirname, &dir_ino);
432     if (err != 0)
433       error (EXIT_FAILURE, 0, "ext2: parent directory not found: %s: %s",
434              dirname, error_message (err));
435   }
436
437   ext2_clean_path (dir_ino, dirname, basename, S_ISDIR (statbuf->st_mode));
438
439   int dir_ft;
440
441   /* Create regular file. */
442   if (S_ISREG (statbuf->st_mode)) {
443     /* XXX Hard links get duplicated here. */
444     ext2_ino_t ino;
445     ext2_empty_inode (dir_ino, dirname, basename,
446                       statbuf->st_mode, statbuf->st_uid, statbuf->st_gid,
447                       statbuf->st_ctime, statbuf->st_atime, statbuf->st_mtime,
448                       0, 0, EXT2_FT_REG_FILE, &ino);
449
450     if (statbuf->st_size > 0) {
451       char *buf = read_whole_file (orig_filename, statbuf->st_size);
452       ext2_write_file (ino, buf, statbuf->st_size, orig_filename);
453       free (buf);
454     }
455   }
456   /* Create a symlink. */
457   else if (S_ISLNK (statbuf->st_mode)) {
458     ext2_ino_t ino;
459     ext2_empty_inode (dir_ino, dirname, basename,
460                       statbuf->st_mode, statbuf->st_uid, statbuf->st_gid,
461                       statbuf->st_ctime, statbuf->st_atime, statbuf->st_mtime,
462                       0, 0, EXT2_FT_SYMLINK, &ino);
463
464     char buf[PATH_MAX+1];
465     ssize_t r = readlink (orig_filename, buf, sizeof buf);
466     if (r == -1)
467       error (EXIT_FAILURE, errno, "readlink: %s", orig_filename);
468     ext2_write_file (ino, buf, r, orig_filename);
469   }
470   /* Create directory. */
471   else if (S_ISDIR (statbuf->st_mode))
472     ext2_mkdir (dir_ino, dirname, basename,
473                 statbuf->st_mode, statbuf->st_uid, statbuf->st_gid,
474                 statbuf->st_ctime, statbuf->st_atime, statbuf->st_mtime);
475   /* Create a special file. */
476   else if (S_ISBLK (statbuf->st_mode)) {
477     dir_ft = EXT2_FT_BLKDEV;
478     goto make_special;
479   }
480   else if (S_ISCHR (statbuf->st_mode)) {
481     dir_ft = EXT2_FT_CHRDEV;
482     goto make_special;
483   } else if (S_ISFIFO (statbuf->st_mode)) {
484     dir_ft = EXT2_FT_FIFO;
485     goto make_special;
486   } else if (S_ISSOCK (statbuf->st_mode)) {
487     dir_ft = EXT2_FT_SOCK;
488   make_special:
489     ext2_empty_inode (dir_ino, dirname, basename,
490                       statbuf->st_mode, statbuf->st_uid, statbuf->st_gid,
491                       statbuf->st_ctime, statbuf->st_atime, statbuf->st_mtime,
492                       major (statbuf->st_rdev), minor (statbuf->st_rdev),
493                       dir_ft, NULL);
494   }
495 }
496
497 static void
498 ext2_file (const char *filename)
499 {
500   struct stat statbuf;
501
502   if (lstat (filename, &statbuf) == -1)
503     error (EXIT_FAILURE, errno, "lstat: %s", filename);
504   ext2_file_stat (filename, &statbuf);
505 }
506
507 /* In theory this could be optimized to avoid a namei lookup, but
508  * it probably wouldn't make much difference.
509  */
510 static void
511 ext2_fts_entry (FTSENT *entry)
512 {
513   if (entry->fts_info & FTS_NS || entry->fts_info & FTS_NSOK)
514     ext2_file (entry->fts_path);
515   else
516     ext2_file_stat (entry->fts_path, entry->fts_statp);
517 }
518
519 struct writer ext2_writer = {
520   .wr_start = ext2_start,
521   .wr_end = ext2_end,
522   .wr_file = ext2_file,
523   .wr_file_stat = ext2_file_stat,
524   .wr_fts_entry = ext2_fts_entry,
525   .wr_cpio_file = ext2_cpio_file,
526 };