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