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