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