ba6ce25928180cf02847e1bcfe5fda4a8d4636e4
[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 static const char *boot_hook_dir = PKG_SYSCONF_DIR "/boot.d";
30 enum {
31         BOOT_HOOK_EXIT_OK       = 0,
32         BOOT_HOOK_EXIT_UPDATE   = 2,
33 };
34
35 struct boot_task {
36         struct load_url_result *image;
37         struct load_url_result *initrd;
38         struct load_url_result *dtb;
39         const char *local_image;
40         const char *local_initrd;
41         const char *local_dtb;
42         const char *args;
43         const char *boot_tty;
44         boot_status_fn status_fn;
45         void *status_arg;
46         bool dry_run;
47         bool cancelled;
48 };
49
50 /**
51  * kexec_load - kexec load helper.
52  */
53 static int kexec_load(struct boot_task *boot_task)
54 {
55         int result;
56         const char *argv[7];
57         const char **p;
58         char *s_initrd = NULL;
59         char *s_dtb = NULL;
60         char *s_args = NULL;
61
62         p = argv;
63         *p++ = pb_system_apps.kexec;    /* 1 */
64         *p++ = "-l";                    /* 2 */
65
66         if (boot_task->local_initrd) {
67                 s_initrd = talloc_asprintf(boot_task, "--initrd=%s",
68                                 boot_task->local_initrd);
69                 assert(s_initrd);
70                 *p++ = s_initrd;         /* 3 */
71         }
72
73         if (boot_task->local_dtb) {
74                 s_dtb = talloc_asprintf(boot_task, "--dtb=%s",
75                                                 boot_task->local_dtb);
76                 assert(s_dtb);
77                 *p++ = s_dtb;            /* 4 */
78         }
79
80         if (boot_task->args) {
81                 s_args = talloc_asprintf(boot_task, "--append=%s",
82                                                 boot_task->args);
83                 assert(s_args);
84                 *p++ = s_args;          /* 5 */
85         }
86
87         *p++ = boot_task->local_image;  /* 6 */
88         *p++ = NULL;                    /* 7 */
89
90         result = process_run_simple_argv(boot_task, argv);
91
92         if (result)
93                 pb_log("%s: failed: (%d)\n", __func__, result);
94
95         return result;
96 }
97
98 /**
99  * kexec_reboot - Helper to boot the new kernel.
100  *
101  * Must only be called after a successful call to kexec_load().
102  */
103
104 static int kexec_reboot(struct boot_task *task)
105 {
106         int result;
107
108         /* First try running shutdown.  Init scripts should run 'exec -e' */
109         result = process_run_simple(task, pb_system_apps.shutdown, "-r",
110                         "now", NULL);
111
112         /* On error, force a kexec with the -e option */
113         if (result) {
114                 result = process_run_simple(task, pb_system_apps.kexec,
115                                                 "-e", NULL);
116         }
117
118         if (result)
119                 pb_log("%s: failed: (%d)\n", __func__, result);
120
121         /* okay, kexec -e -f */
122         if (result) {
123                 result = process_run_simple(task, pb_system_apps.kexec,
124                                                 "-e", "-f", NULL);
125         }
126
127         if (result)
128                 pb_log("%s: failed: (%d)\n", __func__, result);
129
130
131         return result;
132 }
133
134 static void __attribute__((format(__printf__, 4, 5))) update_status(
135                 boot_status_fn fn, void *arg, int type, char *fmt, ...)
136 {
137         struct boot_status status;
138         va_list ap;
139
140         va_start(ap, fmt);
141         status.message = talloc_vasprintf(NULL, fmt, ap);
142         va_end(ap);
143
144         status.type = type;
145         status.progress = -1;
146         status.detail = NULL;
147
148         pb_debug("boot status: [%d] %s\n", type, status.message);
149
150         fn(arg, &status);
151
152         talloc_free(status.message);
153 }
154
155 static void boot_hook_update_param(void *ctx, struct boot_task *task,
156                 const char *name, const char *value)
157 {
158         struct p {
159                 const char *name;
160                 const char **p;
161         } *param, params[] = {
162                 { "boot_image",         &task->local_image },
163                 { "boot_initrd",        &task->local_initrd },
164                 { "boot_dtb",           &task->local_dtb },
165                 { "boot_args",          &task->args },
166                 { NULL, NULL },
167         };
168
169         for (param = params; param->name; param++) {
170                 if (strcmp(param->name, name))
171                         continue;
172
173                 *param->p = talloc_strdup(ctx, value);
174                 return;
175         }
176 }
177
178 static void boot_hook_update(struct boot_task *task, const char *hookname,
179                 char *buf)
180 {
181         char *line, *name, *val, *sep;
182         char *saveptr = NULL;
183
184         for (;; buf = NULL) {
185
186                 line = strtok_r(buf, "\n", &saveptr);
187                 if (!line)
188                         break;
189
190                 sep = strchr(line, '=');
191                 if (!sep)
192                         continue;
193
194                 *sep = '\0';
195                 name = line;
196                 val = sep + 1;
197
198                 boot_hook_update_param(task, task, name, val);
199
200                 pb_log("boot hook %s specified %s=%s\n",
201                                 hookname, name, val);
202         }
203 }
204
205 static void boot_hook_setenv(struct boot_task *task)
206 {
207         unsetenv("boot_image");
208         unsetenv("boot_initrd");
209         unsetenv("boot_dtb");
210         unsetenv("boot_args");
211         unsetenv("boot_tty");
212
213         setenv("boot_image", task->local_image, 1);
214         if (task->local_initrd)
215                 setenv("boot_initrd", task->local_initrd, 1);
216         if (task->local_dtb)
217                 setenv("boot_dtb", task->local_dtb, 1);
218         if (task->args)
219                 setenv("boot_args", task->args, 1);
220         if (task->boot_tty)
221                 setenv("boot_tty", task->boot_tty, 1);
222 }
223
224 static int hook_filter(const struct dirent *dirent)
225 {
226         return dirent->d_type == DT_REG || dirent->d_type == DT_LNK;
227 }
228
229 static int hook_cmp(const struct dirent **a, const struct dirent **b)
230 {
231         return strcmp((*a)->d_name, (*b)->d_name);
232 }
233
234 static void run_boot_hooks(struct boot_task *task)
235 {
236         struct dirent **hooks;
237         int i, n;
238
239         n = scandir(boot_hook_dir, &hooks, hook_filter, hook_cmp);
240         if (n < 1)
241                 return;
242
243         update_status(task->status_fn, task->status_arg, BOOT_STATUS_INFO,
244                         _("running boot hooks"));
245
246         boot_hook_setenv(task);
247
248         for (i = 0; i < n; i++) {
249                 const char *argv[2] = { NULL, NULL };
250                 struct process *process;
251                 char *path;
252                 int rc;
253
254                 path = join_paths(task, boot_hook_dir, hooks[i]->d_name);
255
256                 if (access(path, X_OK)) {
257                         talloc_free(path);
258                         continue;
259                 }
260
261                 process = process_create(task);
262
263                 argv[0] = path;
264                 process->path = path;
265                 process->argv = argv;
266                 process->keep_stdout = true;
267
268                 pb_log("running boot hook %s\n", hooks[i]->d_name);
269
270                 rc = process_run_sync(process);
271                 if (rc) {
272                         pb_log("boot hook exec failed!\n");
273
274                 } else if (WIFEXITED(process->exit_status) &&
275                            WEXITSTATUS(process->exit_status)
276                                 == BOOT_HOOK_EXIT_UPDATE) {
277                         /* if the hook returned with BOOT_HOOK_EXIT_UPDATE,
278                          * then we process stdout to look for updated params
279                          */
280                         boot_hook_update(task, hooks[i]->d_name,
281                                         process->stdout_buf);
282                         boot_hook_setenv(task);
283                 }
284
285                 process_release(process);
286                 talloc_free(path);
287         }
288
289         free(hooks);
290 }
291
292 static bool load_pending(struct load_url_result *result)
293 {
294         return result && result->status == LOAD_ASYNC;
295 }
296
297 static int check_load(struct boot_task *task, const char *name,
298                 struct load_url_result *result)
299 {
300         if (!result)
301                 return 0;
302         if (result->status != LOAD_ERROR)
303                 return 0;
304
305         update_status(task->status_fn, task->status_arg,
306                         BOOT_STATUS_ERROR,
307                         _("Couldn't load %s"), name);
308         return -1;
309 }
310
311 static void cleanup_load(struct load_url_result *result)
312 {
313         if (!result)
314                 return;
315         if (result->status != LOAD_OK)
316                 return;
317         if (!result->cleanup_local)
318                 return;
319         unlink(result->local);
320 }
321
322 static void cleanup_cancellations(struct boot_task *task,
323                 struct load_url_result *cur_result)
324 {
325         struct load_url_result *result, **results[] = {
326                 &task->image, &task->initrd, &task->dtb,
327         };
328         bool pending = false;
329         unsigned int i;
330
331         for (i = 0; i < ARRAY_SIZE(results); i++) {
332                 result = *results[i];
333
334                 if (!result)
335                         continue;
336
337                 /* We need to cleanup and free any completed loads */
338                 if (result == cur_result || result->status == LOAD_OK
339                                 || result->status == LOAD_ERROR) {
340                         cleanup_load(result);
341                         talloc_free(result);
342                         *results[i] = NULL;
343
344                 /* ... and cancel any pending loads, which we'll free in
345                  * the completion callback */
346                 } else if (result->status == LOAD_ASYNC) {
347                         load_url_async_cancel(result);
348                         pending = true;
349
350                 /* if we're waiting for a cancellation, we still need to
351                  * wait for the completion before freeing the boot task */
352                 } else if (result->status == LOAD_CANCELLED) {
353                         pending = true;
354                 }
355         }
356
357         if (!pending)
358                 talloc_free(task);
359 }
360
361 static void boot_process(struct load_url_result *result, void *data)
362 {
363         struct boot_task *task = data;
364         int rc = -1;
365
366         if (task->cancelled) {
367                 cleanup_cancellations(task, result);
368                 return;
369         }
370
371         if (load_pending(task->image) ||
372                         load_pending(task->initrd) ||
373                         load_pending(task->dtb))
374                 return;
375
376         if (check_load(task, "kernel image", task->image) ||
377                         check_load(task, "initrd", task->initrd) ||
378                         check_load(task, "dtb", task->dtb))
379                 goto no_load;
380
381         /* we make a copy of the local paths, as the boot hooks might update
382          * and/or create these */
383         task->local_image = task->image ? task->image->local : NULL;
384         task->local_initrd = task->initrd ? task->initrd->local : NULL;
385         task->local_dtb = task->dtb ? task->dtb->local : NULL;
386
387         run_boot_hooks(task);
388
389         update_status(task->status_fn, task->status_arg, BOOT_STATUS_INFO,
390                         _("performing kexec_load"));
391
392         rc = kexec_load(task);
393         if (rc) {
394                 update_status(task->status_fn, task->status_arg,
395                                 BOOT_STATUS_ERROR, _("kexec load failed"));
396         }
397
398 no_load:
399         cleanup_load(task->image);
400         cleanup_load(task->initrd);
401         cleanup_load(task->dtb);
402
403         if (!rc) {
404                 update_status(task->status_fn, task->status_arg,
405                                 BOOT_STATUS_INFO,
406                                 _("performing kexec reboot"));
407
408                 rc = kexec_reboot(task);
409                 if (rc) {
410                         update_status(task->status_fn, task->status_arg,
411                                         BOOT_STATUS_ERROR,
412                                         _("kexec reboot failed"));
413                 }
414         }
415 }
416
417 static int start_url_load(struct boot_task *task, const char *name,
418                 struct pb_url *url, struct load_url_result **result)
419 {
420         if (!url)
421                 return 0;
422
423         *result = load_url_async(task, url, boot_process, task);
424         if (!*result) {
425                 update_status(task->status_fn, task->status_arg,
426                                 BOOT_STATUS_ERROR,
427                                 _("Error loading %s"), name);
428                 return -1;
429         }
430         return 0;
431 }
432
433 struct boot_task *boot(void *ctx, struct discover_boot_option *opt,
434                 struct boot_command *cmd, int dry_run,
435                 boot_status_fn status_fn, void *status_arg)
436 {
437         struct pb_url *image = NULL, *initrd = NULL, *dtb = NULL;
438         const struct config *config;
439         struct boot_task *boot_task;
440         const char *boot_desc;
441         int rc;
442
443         if (opt && opt->option->name)
444                 boot_desc = opt->option->name;
445         else if (cmd && cmd->boot_image_file)
446                 boot_desc = cmd->boot_image_file;
447         else
448                 boot_desc = _("(unknown)");
449
450         update_status(status_fn, status_arg, BOOT_STATUS_INFO,
451                         _("Booting %s."), boot_desc);
452
453         if (cmd && cmd->boot_image_file) {
454                 image = pb_url_parse(opt, cmd->boot_image_file);
455         } else if (opt && opt->boot_image) {
456                 image = opt->boot_image->url;
457         } else {
458                 pb_log("%s: no image specified\n", __func__);
459                 update_status(status_fn, status_arg, BOOT_STATUS_INFO,
460                                 _("Boot failed: no image specified"));
461                 return NULL;
462         }
463
464         if (cmd && cmd->initrd_file) {
465                 initrd = pb_url_parse(opt, cmd->initrd_file);
466         } else if (opt && opt->initrd) {
467                 initrd = opt->initrd->url;
468         }
469
470         if (cmd && cmd->dtb_file) {
471                 dtb = pb_url_parse(opt, cmd->dtb_file);
472         } else if (opt && opt->dtb) {
473                 dtb = opt->dtb->url;
474         }
475
476         boot_task = talloc_zero(ctx, struct boot_task);
477         boot_task->dry_run = dry_run;
478         boot_task->status_fn = status_fn;
479         boot_task->status_arg = status_arg;
480
481         if (cmd && cmd->boot_args) {
482                 boot_task->args = talloc_strdup(boot_task, cmd->boot_args);
483         } else if (opt && opt->option->boot_args) {
484                 boot_task->args = talloc_strdup(boot_task,
485                                                 opt->option->boot_args);
486         } else {
487                 boot_task->args = NULL;
488         }
489
490         if (cmd && cmd->tty)
491                 boot_task->boot_tty = talloc_strdup(boot_task, cmd->tty);
492         else {
493                 config = config_get();
494                 boot_task->boot_tty = config ? config->boot_tty : NULL;
495         }
496
497         /* start async loads for boot resources */
498         rc = start_url_load(boot_task, "kernel image", image, &boot_task->image)
499           || start_url_load(boot_task, "initrd", initrd, &boot_task->initrd)
500           || start_url_load(boot_task, "dtb", dtb, &boot_task->dtb);
501
502         if (rc) {
503                 /* Don't call boot_cancel() to preserve the status update */
504                 boot_task->cancelled = true;
505                 cleanup_cancellations(boot_task, NULL);
506                 return NULL;
507         }
508
509         boot_process(NULL, boot_task);
510
511         return boot_task;
512 }
513
514 void boot_cancel(struct boot_task *task)
515 {
516         task->cancelled = true;
517
518         update_status(task->status_fn, task->status_arg, BOOT_STATUS_INFO,
519                         _("Boot cancelled"));
520
521         cleanup_cancellations(task, NULL);
522 }