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