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