febootstrap/helper/init: Mount /proc if not already present.
[febootstrap.git] / febootstrap.ml
1 (* febootstrap 3
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  *)
18
19 open Unix
20 open Printf
21
22 open Febootstrap_package_handlers
23 open Febootstrap_utils
24 open Febootstrap_cmdline
25
26 (* Create a temporary directory for use by all the functions in this file. *)
27 let tmpdir = tmpdir ()
28
29 let () =
30   debug "%s %s" Config.package_name Config.package_version;
31
32   (* Instead of printing out warnings as we go along, accumulate them
33    * in lists and print them all out at the end.
34    *)
35   let warn_unreadable = ref [] in
36
37   (* Determine which package manager this system uses. *)
38   check_system ();
39   let ph = get_package_handler () in
40
41   debug "selected package handler: %s" (get_package_handler_name ());
42
43   (* Not --names: check files exist. *)
44   if not names_mode then (
45     List.iter (
46       fun pkg ->
47         if not (file_exists pkg) then (
48           eprintf "febootstrap: %s: no such file (did you miss out the --names option?)\n" pkg;
49           exit 1
50         )
51     ) packages
52   );
53
54   (* --names: resolve the package list to a full list of package names
55    * (including dependencies).
56    *)
57   let packages =
58     if names_mode then (
59       let packages = ph.ph_resolve_dependencies_and_download packages in
60       debug "resolved packages: %s" (String.concat " " packages);
61       packages
62     )
63     else packages in
64
65   (* Get the list of files. *)
66   let files =
67     List.flatten (
68       List.map (
69         fun pkg ->
70           let files = ph.ph_list_files pkg in
71           List.map (fun (filename, ft) -> filename, ft, pkg) files
72       ) packages
73     ) in
74
75   (* Sort and combine duplicate files. *)
76   let files =
77     let files = List.sort compare files in
78
79     let combine (name1, ft1, pkg1) (name2, ft2, pkg2) =
80       (* Rules for combining files. *)
81       if ft1.ft_config || ft2.ft_config then (
82         (* It's a fairly frequent bug in Fedora for two packages to
83          * incorrectly list the same config file.  Allow this, provided
84          * the size of both files is 0.
85          *)
86         if ft1.ft_size = 0 && ft2.ft_size = 0 then
87           (name1, ft1, pkg1)
88         else (
89           eprintf "febootstrap: error: %s is a config file which is listed in two packages (%s, %s)\n"
90             name1 pkg1 pkg2;
91           exit 1
92         )
93       )
94       else if (ft1.ft_dir || ft2.ft_dir) && (not (ft1.ft_dir && ft2.ft_dir)) then (
95         eprintf "febootstrap: error: %s appears as both directory and ordinary file (%s, %s)\n"
96           name1 pkg1 pkg2;
97         exit 1
98       )
99       else if ft1.ft_ghost then
100         (name2, ft2, pkg2)
101       else
102         (name1, ft1, pkg1)
103     in
104
105     let rec loop = function
106       | [] -> []
107       | (name1, _, _ as f1) :: (name2, _, _ as f2) :: fs when name1 = name2 ->
108           let f = combine f1 f2 in loop (f :: fs)
109       | f :: fs -> f :: loop fs
110     in
111     loop files in
112
113   (* Because we may have excluded some packages, and also because of
114    * distribution packaging errors, it's not necessarily true that a
115    * directory is created before each file in that directory.
116    * Determine those missing directories and add them now.
117    *)
118   let files =
119     let insert_dir, dir_seen =
120       let h = Hashtbl.create (List.length files) in
121       let insert_dir dir = Hashtbl.replace h dir true in
122       let dir_seen dir = Hashtbl.mem h dir in
123       insert_dir, dir_seen
124     in
125     let files =
126       List.map (
127         fun (path, { ft_dir = is_dir }, _ as f) ->
128           if is_dir then
129             insert_dir path;
130
131           let rec loop path =
132             let parent = Filename.dirname path in
133             if dir_seen parent then []
134             else (
135               insert_dir parent;
136               let newdir = (parent, { ft_dir = true; ft_config = false;
137                                       ft_ghost = false; ft_mode = 0o40755;
138                                       ft_size = 0 },
139                             "") in
140               newdir :: loop parent
141             )
142           in
143           List.rev (f :: loop path)
144       ) files in
145     List.flatten files in
146
147   (* Debugging. *)
148   debug "%d files and directories" (List.length files);
149   if false then (
150     List.iter (
151       fun (name, { ft_dir = dir; ft_ghost = ghost; ft_config = config;
152                    ft_mode = mode; ft_size = size }, pkg) ->
153         printf "%s [%s%s%s%o %d] from %s\n" name
154           (if dir then "dir " else "")
155           (if ghost then "ghost " else "")
156           (if config then "config " else "")
157           mode size
158           pkg
159     ) files
160   );
161
162   (* Split the list of files into ones for hostfiles and ones for base image. *)
163   let p_hmac = Str.regexp "^\\..*\\.hmac$" in
164
165   let hostfiles = ref []
166   and baseimgfiles = ref [] in
167   List.iter (
168     fun (path, {ft_dir = dir; ft_ghost = ghost; ft_config = config} ,_ as f) ->
169       let file = Filename.basename path in
170
171       (* Ignore boot files, kernel, kernel modules.  Supermin appliances
172        * are booted from external kernel and initrd, and
173        * febootstrap-supermin-helper copies the host kernel modules.
174        * Note we want to keep the /boot and /lib/modules directory entries.
175        *)
176       if string_prefix "/boot/" path then ()
177       else if string_prefix "/lib/modules/" path then ()
178
179       (* Always write directory names to both output files. *)
180       else if dir then (
181         hostfiles := f :: !hostfiles;
182         baseimgfiles := f :: !baseimgfiles;
183       )
184
185       (* Timezone configuration is config, but copy it from host system. *)
186       else if path = "/etc/localtime" then
187         hostfiles := f :: !hostfiles
188
189       (* Ignore FIPS files (.*.hmac) (RHBZ#654638). *)
190       else if Str.string_match p_hmac file 0 then ()
191
192       (* Ghost files are created empty in the base image. *)
193       else if ghost then
194         baseimgfiles := f :: !baseimgfiles
195
196       (* For config files we can't rely on the host-installed copy
197        * since the admin may have modified then.  We have to get the
198        * original file from the package and put it in the base image.
199        *)
200       else if config then
201         baseimgfiles := f :: !baseimgfiles
202
203       (* Anything else comes from the host. *)
204       else
205         hostfiles := f :: !hostfiles
206   ) files;
207   let hostfiles = List.rev !hostfiles
208   and baseimgfiles = List.rev !baseimgfiles in
209
210   (* Write hostfiles. *)
211
212   (* Regexps used below. *)
213   let p_ld_so = Str.regexp "^ld-[.0-9]+\\.so$" in
214   let p_libbfd = Str.regexp "^libbfd-.*\\.so$" in
215   let p_libgcc = Str.regexp "^libgcc_s-.*\\.so\\.\\([0-9]+\\)$" in
216   let p_libntfs3g = Str.regexp "^libntfs-3g\\.so\\..*$" in
217   let p_lib123so = Str.regexp "^lib\\(.*\\)-[-.0-9]+\\.so$" in
218   let p_lib123so123 =
219     Str.regexp "^lib\\(.*\\)-[-.0-9]+\\.so\\.\\([0-9]+\\)\\." in
220   let p_libso123 = Str.regexp "^lib\\(.*\\)\\.so\\.\\([0-9]+\\)\\." in
221   let ntfs3g_once = ref false in
222
223   let chan = open_out (tmpdir // "hostfiles") in
224   List.iter (
225     fun (path, {ft_dir = is_dir; ft_ghost = ghost; ft_config = config;
226                 ft_mode = mode }, _) ->
227       let dir = Filename.dirname path in
228       let file = Filename.basename path in
229
230       if is_dir then
231         fprintf chan "%s\n" path
232
233       (* Warn about hostfiles which are unreadable by non-root.  We
234        * won't be able to add those to the appliance at run time, but
235        * there's not much else we can do about it except get the
236        * distros to fix this nonsense.
237        *)
238       else if mode land 0o004 = 0 then
239         warn_unreadable := path :: !warn_unreadable
240
241       (* Replace fixed numbers in some library names by wildcards. *)
242       else if Str.string_match p_ld_so file 0 then
243         fprintf chan "%s/ld-*.so\n" dir
244
245       (* Special case for libbfd. *)
246       else if Str.string_match p_libbfd file 0 then
247         fprintf chan "%s/libbfd-*.so\n" dir
248
249       (* Special case for libgcc_s-<gccversion>-<date>.so.N *)
250       else if Str.string_match p_libgcc file 0 then
251         fprintf chan "%s/libgcc_s-*.so.%s\n" dir (Str.matched_group 1 file)
252
253       (* Special case for libntfs-3g.so.* *)
254       else if Str.string_match p_libntfs3g file 0 then (
255         if not !ntfs3g_once then (
256           fprintf chan "%s/libntfs-3g.so.*\n" dir;
257           ntfs3g_once := true
258         )
259       )
260
261       (* libfoo-1.2.3.so *)
262       else if Str.string_match p_lib123so file 0 then
263         fprintf chan "%s/lib%s-*.so\n" dir (Str.matched_group 1 file)
264
265       (* libfoo-1.2.3.so.123 (but NOT '*.so.N') *)
266       else if Str.string_match p_lib123so123 file 0 then
267         fprintf chan "%s/lib%s-*.so.%s.*\n" dir
268           (Str.matched_group 1 file) (Str.matched_group 2 file)
269
270       (* libfoo.so.1.2.3 (but NOT '*.so.N') *)
271       else if Str.string_match p_libso123 file 0 then
272         fprintf chan "%s/lib%s.so.%s.*\n" dir
273           (Str.matched_group 1 file) (Str.matched_group 2 file)
274
275       (* Anything else comes from the host. *)
276       else
277         fprintf chan "%s\n" path
278   ) hostfiles;
279   close_out chan;
280
281   (* Write base.img.
282    *
283    * We have to create directories and copy files to tmpdir/root
284    * and then call out to cpio to construct the initrd.
285    *)
286   let rootdir = tmpdir // "root" in
287   mkdir rootdir 0o755;
288   List.iter (
289     fun (path, { ft_dir = is_dir; ft_ghost = ghost; ft_config = config;
290                  ft_mode = mode }, pkg) ->
291       (* Always write directory names to both output files. *)
292       if is_dir then (
293         (* Directory permissions are fixed up below. *)
294         if path <> "/" then mkdir (rootdir // path) 0o755
295       )
296
297       (* Ghost files are just touched with the correct perms. *)
298       else if ghost then (
299         let chan = open_out (rootdir // path) in
300         close_out chan;
301         chmod (rootdir // path) (mode land 0o777 lor 0o400)
302       )
303
304       (* For config files we can't rely on the host-installed copy
305        * since the admin may have modified it.  We have to get the
306        * original file from the package.
307        *)
308       else if config then (
309         let outfile = ph.ph_get_file_from_package pkg path in
310
311         (* Note that the output config file might not be a regular file. *)
312         let statbuf = lstat outfile in
313
314         let destfile = rootdir // path in
315
316         (* Depending on the file type, copy it to destination. *)
317         match statbuf.st_kind with
318         | S_REG ->
319             (* Unreadable files (eg. /etc/gshadow).  Make readable. *)
320             if statbuf.st_perm = 0 then chmod outfile 0o400;
321             let cmd =
322               sprintf "cp %s %s"
323                 (Filename.quote outfile) (Filename.quote destfile) in
324             run_command cmd;
325             chmod destfile (mode land 0o777 lor 0o400)
326         | S_LNK ->
327             let link = readlink outfile in
328             symlink link destfile
329         | S_DIR -> assert false
330         | S_CHR
331         | S_BLK
332         | S_FIFO
333         | S_SOCK ->
334             eprintf "febootstrap: error: %s: don't know how to handle this type of file\n" path;
335             exit 1
336       )
337
338       else
339         assert false (* should not be reached *)
340   ) baseimgfiles;
341
342   (* Fix up directory permissions, in reverse order.  Since we don't
343    * want to have a read-only directory that we can't write into above.
344    *)
345   List.iter (
346     fun (path, { ft_dir = is_dir; ft_mode = mode }, _) ->
347       if is_dir then chmod (rootdir // path) (mode land 0o777 lor 0o700)
348   ) (List.rev baseimgfiles);
349
350   (* Construct the 'base.img' initramfs.  Feed in the list of filenames
351    * partly because we conveniently have them, and partly because
352    * this results in a nice alphabetical ordering in the cpio file.
353    *)
354   (*let cmd = sprintf "ls -lR %s" rootdir in
355   ignore (Sys.command cmd);*)
356   let cmd =
357     sprintf "(cd %s && cpio --quiet -o -0 -H newc) > %s"
358       rootdir (tmpdir // "base.img") in
359   let chan = open_process_out cmd in
360   List.iter (fun (path, _, _) -> fprintf chan ".%s\000" path) baseimgfiles;
361   let stat = close_process_out chan in
362   (match stat with
363    | WEXITED 0 -> ()
364    | WEXITED i ->
365        eprintf "febootstrap: command '%s' failed (returned %d), see earlier error messages\n" cmd i;
366        exit i
367    | WSIGNALED i ->
368        eprintf "febootstrap: command '%s' killed by signal %d" cmd i;
369        exit 1
370    | WSTOPPED i ->
371        eprintf "febootstrap: command '%s' stopped by signal %d" cmd i;
372        exit 1
373   );
374
375   (* Undo directory permissions, because rm -rf can't delete files in
376    * unreadable directories.
377    *)
378   List.iter (
379     fun (path, { ft_dir = is_dir; ft_mode = mode }, _) ->
380       if is_dir then chmod (rootdir // path) 0o755
381   ) (List.rev baseimgfiles);
382
383   (* Print warnings. *)
384   if warnings then (
385     (match !warn_unreadable with
386      | [] -> ()
387      | paths ->
388          eprintf "febootstrap: warning: some host files are unreadable by non-root\n";
389          eprintf "febootstrap: warning: get your distro to fix these files:\n";
390          List.iter
391            (fun path -> eprintf "\t%s\n%!" path)
392            (List.sort compare paths)
393     );
394   );
395
396   (* Near-atomically copy files to the final output directory. *)
397   debug "writing %s ..." (outputdir // "base.img");
398   let cmd =
399     sprintf "mv %s %s"
400       (Filename.quote (tmpdir // "base.img"))
401       (Filename.quote (outputdir // "base.img")) in
402   run_command cmd;
403   debug "writing %s ..." (outputdir // "hostfiles");
404   let cmd =
405     sprintf "mv %s %s"
406       (Filename.quote (tmpdir // "hostfiles"))
407       (Filename.quote (outputdir // "hostfiles")) in
408   run_command cmd