0732a50aea0318fce5f2fc5225716b50c8350776
[petitboot] / discover / boot.c
1
2 #if defined(HAVE_CONFIG_H)
3 #include "config.h"
4 #endif
5
6 #include <stdbool.h>
7 #include <stdlib.h>
8 #include <assert.h>
9 #include <dirent.h>
10 #include <string.h>
11 #include <fcntl.h>
12 #include <sys/types.h>
13
14 #include <log/log.h>
15 #include <pb-protocol/pb-protocol.h>
16 #include <process/process.h>
17 #include <system/system.h>
18 #include <talloc/talloc.h>
19 #include <url/url.h>
20 #include <util/util.h>
21 #include <i18n/i18n.h>
22
23 #include "device-handler.h"
24 #include "boot.h"
25 #include "paths.h"
26 #include "resource.h"
27 #include "platform.h"
28
29 #include <security/gpg.h>
30
31 static const char *boot_hook_dir = PKG_SYSCONF_DIR "/boot.d";
32 enum {
33         BOOT_HOOK_EXIT_OK       = 0,
34         BOOT_HOOK_EXIT_UPDATE   = 2,
35 };
36
37 /**
38  * kexec_load - kexec load helper.
39  */
40 static int kexec_load(struct boot_task *boot_task)
41 {
42         int result;
43         const char *argv[7];
44         const char **p;
45         char *s_initrd = NULL;
46         char *s_dtb = NULL;
47         char *s_args = NULL;
48
49         boot_task->local_initrd_override = NULL;
50         boot_task->local_dtb_override = NULL;
51         boot_task->local_image_override = NULL;
52
53         if ((result = gpg_validate_boot_files(boot_task))) {
54                 if (result == KEXEC_LOAD_DECRYPTION_FALURE) {
55                         pb_log("%s: Aborting kexec due to"
56                                 " decryption failure\n", __func__);
57                         goto abort_kexec;
58                 }
59                 if (result == KEXEC_LOAD_SIGNATURE_FAILURE) {
60                         pb_log("%s: Aborting kexec due to signature"
61                                 " verification failure\n", __func__);
62                         goto abort_kexec;
63                 }
64         }
65
66         const char* local_initrd = (boot_task->local_initrd_override) ?
67                 boot_task->local_initrd_override : boot_task->local_initrd;
68         const char* local_dtb = (boot_task->local_dtb_override) ?
69                 boot_task->local_dtb_override : boot_task->local_dtb;
70         const char* local_image = (boot_task->local_image_override) ?
71                 boot_task->local_image_override : boot_task->local_image;
72
73         p = argv;
74         *p++ = pb_system_apps.kexec;    /* 1 */
75         *p++ = "-l";                    /* 2 */
76
77         if (local_initrd) {
78                 s_initrd = talloc_asprintf(boot_task, "--initrd=%s",
79                                 local_initrd);
80                 assert(s_initrd);
81                 *p++ = s_initrd;         /* 3 */
82         }
83
84         if (local_dtb) {
85                 s_dtb = talloc_asprintf(boot_task, "--dtb=%s",
86                                                 local_dtb);
87                 assert(s_dtb);
88                 *p++ = s_dtb;            /* 4 */
89         }
90
91         s_args = talloc_asprintf(boot_task, "--append=%s",
92                                 boot_task->args ?: "\"\"");
93         assert(s_args);
94         *p++ = s_args;          /* 5 */
95
96         *p++ = local_image;             /* 6 */
97         *p++ = NULL;                    /* 7 */
98
99         result = process_run_simple_argv(boot_task, argv);
100
101         if (result)
102                 pb_log("%s: failed: (%d)\n", __func__, result);
103
104 abort_kexec:
105         gpg_validate_boot_files_cleanup(boot_task);
106
107         return result;
108 }
109
110 /**
111  * kexec_reboot - Helper to boot the new kernel.
112  *
113  * Must only be called after a successful call to kexec_load().
114  */
115
116 static int kexec_reboot(struct boot_task *task)
117 {
118         int result;
119
120         /* First try running shutdown.  Init scripts should run 'exec -e' */
121         result = process_run_simple(task, pb_system_apps.shutdown, "-r",
122                         "now", NULL);
123
124         /* On error, force a kexec with the -e option */
125         if (result) {
126                 result = process_run_simple(task, pb_system_apps.kexec,
127                                                 "-e", NULL);
128         }
129
130         if (result)
131                 pb_log("%s: failed: (%d)\n", __func__, result);
132
133         /* okay, kexec -e -f */
134         if (result) {
135                 result = process_run_simple(task, pb_system_apps.kexec,
136                                                 "-e", "-f", NULL);
137         }
138
139         if (result)
140                 pb_log("%s: failed: (%d)\n", __func__, result);
141
142
143         return result;
144 }
145
146 static void __attribute__((format(__printf__, 4, 5))) update_status(
147                 boot_status_fn fn, void *arg, int type, char *fmt, ...)
148 {
149         struct boot_status status;
150         va_list ap;
151
152         va_start(ap, fmt);
153         status.message = talloc_vasprintf(NULL, fmt, ap);
154         va_end(ap);
155
156         status.type = type;
157         status.progress = -1;
158         status.detail = NULL;
159
160         pb_debug("boot status: [%d] %s\n", type, status.message);
161
162         fn(arg, &status);
163
164         talloc_free(status.message);
165 }
166
167 static void boot_hook_update_param(void *ctx, struct boot_task *task,
168                 const char *name, const char *value)
169 {
170         struct p {
171                 const char *name;
172                 const char **p;
173         } *param, params[] = {
174                 { "boot_image",         &task->local_image },
175                 { "boot_initrd",        &task->local_initrd },
176                 { "boot_dtb",           &task->local_dtb },
177                 { "boot_args",          &task->args },
178                 { NULL, NULL },
179         };
180
181         for (param = params; param->name; param++) {
182                 if (strcmp(param->name, name))
183                         continue;
184
185                 *param->p = talloc_strdup(ctx, value);
186                 return;
187         }
188 }
189
190 static void boot_hook_update(struct boot_task *task, const char *hookname,
191                 char *buf)
192 {
193         char *line, *name, *val, *sep;
194         char *saveptr = NULL;
195
196         for (;; buf = NULL) {
197
198                 line = strtok_r(buf, "\n", &saveptr);
199                 if (!line)
200                         break;
201
202                 sep = strchr(line, '=');
203                 if (!sep)
204                         continue;
205
206                 *sep = '\0';
207                 name = line;
208                 val = sep + 1;
209
210                 boot_hook_update_param(task, task, name, val);
211
212                 pb_log("boot hook %s specified %s=%s\n",
213                                 hookname, name, val);
214         }
215 }
216
217 static void boot_hook_setenv(struct boot_task *task)
218 {
219         unsetenv("boot_image");
220         unsetenv("boot_initrd");
221         unsetenv("boot_dtb");
222         unsetenv("boot_args");
223         unsetenv("boot_console");
224
225         setenv("boot_image", task->local_image, 1);
226         if (task->local_initrd)
227                 setenv("boot_initrd", task->local_initrd, 1);
228         if (task->local_dtb)
229                 setenv("boot_dtb", task->local_dtb, 1);
230         if (task->args)
231                 setenv("boot_args", task->args, 1);
232         if (task->boot_console)
233                 setenv("boot_console", task->boot_console, 1);
234 }
235
236 static int hook_filter(const struct dirent *dirent)
237 {
238         return dirent->d_type == DT_REG || dirent->d_type == DT_LNK;
239 }
240
241 static int hook_cmp(const struct dirent **a, const struct dirent **b)
242 {
243         return strcmp((*a)->d_name, (*b)->d_name);
244 }
245
246 static void run_boot_hooks(struct boot_task *task)
247 {
248         struct dirent **hooks;
249         int i, n;
250
251         n = scandir(boot_hook_dir, &hooks, hook_filter, hook_cmp);
252         if (n < 1)
253                 return;
254
255         update_status(task->status_fn, task->status_arg, BOOT_STATUS_INFO,
256                         _("running boot hooks"));
257
258         boot_hook_setenv(task);
259
260         for (i = 0; i < n; i++) {
261                 const char *argv[2] = { NULL, NULL };
262                 struct process *process;
263                 char *path;
264                 int rc;
265
266                 path = join_paths(task, boot_hook_dir, hooks[i]->d_name);
267
268                 if (access(path, X_OK)) {
269                         talloc_free(path);
270                         continue;
271                 }
272
273                 process = process_create(task);
274
275                 argv[0] = path;
276                 process->path = path;
277                 process->argv = argv;
278                 process->keep_stdout = true;
279
280                 pb_log("running boot hook %s\n", hooks[i]->d_name);
281
282                 rc = process_run_sync(process);
283                 if (rc) {
284                         pb_log("boot hook exec failed!\n");
285
286                 } else if (WIFEXITED(process->exit_status) &&
287                            WEXITSTATUS(process->exit_status)
288                                 == BOOT_HOOK_EXIT_UPDATE) {
289                         /* if the hook returned with BOOT_HOOK_EXIT_UPDATE,
290                          * then we process stdout to look for updated params
291                          */
292                         boot_hook_update(task, hooks[i]->d_name,
293                                         process->stdout_buf);
294                         boot_hook_setenv(task);
295                 }
296
297                 process_release(process);
298                 talloc_free(path);
299         }
300
301         free(hooks);
302 }
303
304 static bool load_pending(struct load_url_result *result)
305 {
306         return result && result->status == LOAD_ASYNC;
307 }
308
309 static int check_load(struct boot_task *task, const char *name,
310                 struct load_url_result *result)
311 {
312         if (!result)
313                 return 0;
314         if (result->status != LOAD_ERROR)
315                 return 0;
316
317         update_status(task->status_fn, task->status_arg,
318                         BOOT_STATUS_ERROR,
319                         _("Couldn't load %s"), name);
320         return -1;
321 }
322
323 static void cleanup_load(struct load_url_result *result)
324 {
325         if (!result)
326                 return;
327         if (result->status != LOAD_OK)
328                 return;
329         if (!result->cleanup_local)
330                 return;
331         unlink(result->local);
332 }
333
334 static void cleanup_cancellations(struct boot_task *task,
335                 struct load_url_result *cur_result)
336 {
337         struct load_url_result *result, **results[] = {
338                 &task->image, &task->initrd, &task->dtb,
339         };
340         bool pending = false;
341         unsigned int i;
342
343         for (i = 0; i < ARRAY_SIZE(results); i++) {
344                 result = *results[i];
345
346                 if (!result)
347                         continue;
348
349                 /* We need to cleanup and free any completed loads */
350                 if (result == cur_result || result->status == LOAD_OK
351                                 || result->status == LOAD_ERROR) {
352                         cleanup_load(result);
353                         talloc_free(result);
354                         *results[i] = NULL;
355
356                 /* ... and cancel any pending loads, which we'll free in
357                  * the completion callback */
358                 } else if (result->status == LOAD_ASYNC) {
359                         load_url_async_cancel(result);
360                         pending = true;
361
362                 /* if we're waiting for a cancellation, we still need to
363                  * wait for the completion before freeing the boot task */
364                 } else if (result->status == LOAD_CANCELLED) {
365                         pending = true;
366                 }
367         }
368
369         if (!pending)
370                 talloc_free(task);
371 }
372
373 static void boot_process(struct load_url_result *result, void *data)
374 {
375         struct boot_task *task = data;
376         int rc = -1;
377
378         if (task->cancelled) {
379                 cleanup_cancellations(task, result);
380                 return;
381         }
382
383         if (load_pending(task->image) ||
384                         load_pending(task->initrd) ||
385                         load_pending(task->dtb))
386                 return;
387
388         if (check_load(task, "kernel image", task->image) ||
389                         check_load(task, "initrd", task->initrd) ||
390                         check_load(task, "dtb", task->dtb))
391                 goto no_load;
392
393         if (task->verify_signature) {
394                 if (load_pending(task->image_signature) ||
395                                 load_pending(task->initrd_signature) ||
396                                 load_pending(task->dtb_signature) ||
397                                 load_pending(task->cmdline_signature))
398                         return;
399         }
400         if (task->decrypt_files) {
401                 if (load_pending(task->cmdline_signature))
402                         return;
403         }
404
405         if (task->verify_signature) {
406                 if (check_load(task, "kernel image signature",
407                                         task->image_signature) ||
408                                 check_load(task, "initrd signature",
409                                         task->initrd_signature) ||
410                                 check_load(task, "dtb signature",
411                                         task->dtb_signature) ||
412                                 check_load(task, "command line signature",
413                                         task->cmdline_signature))
414                         goto no_sig_load;
415         }
416         if (task->decrypt_files) {
417                 if (load_pending(task->cmdline_signature))
418                         return;
419
420                 if (check_load(task, "command line signature",
421                                         task->cmdline_signature))
422                         goto no_decrypt_sig_load;
423         }
424
425         /* we make a copy of the local paths, as the boot hooks might update
426          * and/or create these */
427         task->local_image = task->image ? task->image->local : NULL;
428         task->local_initrd = task->initrd ? task->initrd->local : NULL;
429         task->local_dtb = task->dtb ? task->dtb->local : NULL;
430
431         if (task->verify_signature) {
432                 task->local_image_signature = task->image_signature ?
433                         task->image_signature->local : NULL;
434                 task->local_initrd_signature = task->initrd_signature ?
435                         task->initrd_signature->local : NULL;
436                 task->local_dtb_signature = task->dtb_signature ?
437                         task->dtb_signature->local : NULL;
438         }
439         if (task->verify_signature || task->decrypt_files) {
440                 task->local_cmdline_signature = task->cmdline_signature ?
441                         task->cmdline_signature->local : NULL;
442         }
443
444         run_boot_hooks(task);
445
446         update_status(task->status_fn, task->status_arg, BOOT_STATUS_INFO,
447                         _("performing kexec_load"));
448
449         rc = kexec_load(task);
450         if (rc == KEXEC_LOAD_DECRYPTION_FALURE) {
451                 update_status(task->status_fn, task->status_arg,
452                                 BOOT_STATUS_ERROR, _("decryption failed"));
453         }
454         else if (rc == KEXEC_LOAD_SIGNATURE_FAILURE) {
455                 update_status(task->status_fn, task->status_arg,
456                                 BOOT_STATUS_ERROR,
457                                 _("signature verification failed"));
458         }
459         else if (rc == KEXEC_LOAD_SIG_SETUP_INVALID) {
460                 update_status(task->status_fn, task->status_arg,
461                                 BOOT_STATUS_ERROR,
462                                 _("invalid signature configuration"));
463         }
464         else if (rc) {
465                 update_status(task->status_fn, task->status_arg,
466                                 BOOT_STATUS_ERROR,
467                                 _("kexec load failed"));
468         }
469
470 no_sig_load:
471         cleanup_load(task->image_signature);
472         cleanup_load(task->initrd_signature);
473         cleanup_load(task->dtb_signature);
474
475 no_decrypt_sig_load:
476         cleanup_load(task->cmdline_signature);
477
478 no_load:
479         cleanup_load(task->image);
480         cleanup_load(task->initrd);
481         cleanup_load(task->dtb);
482
483         if (!rc) {
484                 update_status(task->status_fn, task->status_arg,
485                                 BOOT_STATUS_INFO,
486                                 _("performing kexec reboot"));
487
488                 rc = kexec_reboot(task);
489                 if (rc) {
490                         update_status(task->status_fn, task->status_arg,
491                                         BOOT_STATUS_ERROR,
492                                         _("kexec reboot failed"));
493                 }
494         }
495 }
496
497 static int start_url_load(struct boot_task *task, const char *name,
498                 struct pb_url *url, struct load_url_result **result)
499 {
500         if (!url)
501                 return 0;
502
503         *result = load_url_async(task, url, boot_process, task);
504         if (!*result) {
505                 update_status(task->status_fn, task->status_arg,
506                                 BOOT_STATUS_ERROR,
507                                 _("Error loading %s"), name);
508                 return -1;
509         }
510         return 0;
511 }
512
513 struct boot_task *boot(void *ctx, struct discover_boot_option *opt,
514                 struct boot_command *cmd, int dry_run,
515                 boot_status_fn status_fn, void *status_arg)
516 {
517         struct pb_url *image = NULL, *initrd = NULL, *dtb = NULL;
518         struct pb_url *image_sig = NULL, *initrd_sig = NULL, *dtb_sig = NULL,
519                 *cmdline_sig = NULL;
520         const struct config *config;
521         struct boot_task *boot_task;
522         const char *boot_desc;
523         int rc;
524         int lockdown_type;
525
526         if (opt && opt->option->name)
527                 boot_desc = opt->option->name;
528         else if (cmd && cmd->boot_image_file)
529                 boot_desc = cmd->boot_image_file;
530         else
531                 boot_desc = _("(unknown)");
532
533         update_status(status_fn, status_arg, BOOT_STATUS_INFO,
534                         _("Booting %s."), boot_desc);
535
536         if (cmd && cmd->boot_image_file) {
537                 image = pb_url_parse(opt, cmd->boot_image_file);
538         } else if (opt && opt->boot_image) {
539                 image = opt->boot_image->url;
540         } else {
541                 pb_log("%s: no image specified\n", __func__);
542                 update_status(status_fn, status_arg, BOOT_STATUS_INFO,
543                                 _("Boot failed: no image specified"));
544                 return NULL;
545         }
546
547         if (cmd && cmd->initrd_file) {
548                 initrd = pb_url_parse(opt, cmd->initrd_file);
549         } else if (opt && opt->initrd) {
550                 initrd = opt->initrd->url;
551         }
552
553         if (cmd && cmd->dtb_file) {
554                 dtb = pb_url_parse(opt, cmd->dtb_file);
555         } else if (opt && opt->dtb) {
556                 dtb = opt->dtb->url;
557         }
558
559         boot_task = talloc_zero(ctx, struct boot_task);
560         boot_task->dry_run = dry_run;
561         boot_task->status_fn = status_fn;
562         boot_task->status_arg = status_arg;
563
564         lockdown_type = lockdown_status();
565         boot_task->verify_signature = (lockdown_type == PB_LOCKDOWN_SIGN);
566         boot_task->decrypt_files = (lockdown_type == PB_LOCKDOWN_DECRYPT);
567
568         if (cmd && cmd->boot_args) {
569                 boot_task->args = talloc_strdup(boot_task, cmd->boot_args);
570         } else if (opt && opt->option->boot_args) {
571                 boot_task->args = talloc_strdup(boot_task,
572                                                 opt->option->boot_args);
573         } else {
574                 boot_task->args = NULL;
575         }
576
577         if (cmd && cmd->console)
578                 boot_task->boot_console = talloc_strdup(boot_task, cmd->console);
579         else {
580                 config = config_get();
581                 boot_task->boot_console = config ? config->boot_console : NULL;
582         }
583
584         if (boot_task->verify_signature || boot_task->decrypt_files) {
585                 if (cmd && cmd->args_sig_file) {
586                         cmdline_sig = pb_url_parse(opt, cmd->args_sig_file);
587                 } else if (opt && opt->args_sig_file) {
588                         cmdline_sig = opt->args_sig_file->url;
589                 } else {
590                         pb_log("%s: no command line signature file"
591                                 " specified\n", __func__);
592                         update_status(status_fn, status_arg, BOOT_STATUS_INFO,
593                                         _("Boot failed: no command line"
594                                                 " signature file specified"));
595                         talloc_free(boot_task);
596                         return NULL;
597                 }
598         }
599
600         /* start async loads for boot resources */
601         rc = start_url_load(boot_task, "kernel image", image, &boot_task->image)
602           || start_url_load(boot_task, "initrd", initrd, &boot_task->initrd)
603           || start_url_load(boot_task, "dtb", dtb, &boot_task->dtb);
604
605         if (boot_task->verify_signature) {
606                 /* Generate names of associated signature files and load */
607                 if (image) {
608                         image_sig = gpg_get_signature_url(ctx, image);
609                         rc |= start_url_load(boot_task,
610                                 "kernel image signature", image_sig,
611                                 &boot_task->image_signature);
612                 }
613                 if (initrd) {
614                         initrd_sig = gpg_get_signature_url(ctx, initrd);
615                         rc |= start_url_load(boot_task, "initrd signature",
616                                 initrd_sig, &boot_task->initrd_signature);
617                 }
618                 if (dtb) {
619                         dtb_sig = gpg_get_signature_url(ctx, dtb);
620                         rc |= start_url_load(boot_task, "dtb signature",
621                                 dtb_sig, &boot_task->dtb_signature);
622                 }
623         }
624
625         if (boot_task->verify_signature || boot_task->decrypt_files) {
626                 rc |= start_url_load(boot_task,
627                         "kernel command line signature", cmdline_sig,
628                         &boot_task->cmdline_signature);
629         }
630
631         /* If all URLs are local, we may be done. */
632         if (rc) {
633                 /* Don't call boot_cancel() to preserve the status update */
634                 boot_task->cancelled = true;
635                 cleanup_cancellations(boot_task, NULL);
636                 return NULL;
637         }
638
639         boot_process(NULL, boot_task);
640
641         return boot_task;
642 }
643
644 void boot_cancel(struct boot_task *task)
645 {
646         task->cancelled = true;
647
648         update_status(task->status_fn, task->status_arg, BOOT_STATUS_INFO,
649                         _("Boot cancelled"));
650
651         cleanup_cancellations(task, NULL);
652 }