8b4046edd83e52a686a7ee0b29768a4bffb1f36f
[petitboot] / discover / device-handler.c
1
2 #include <assert.h>
3 #include <stdlib.h>
4 #include <stdbool.h>
5 #include <unistd.h>
6 #include <string.h>
7 #include <errno.h>
8 #include <mntent.h>
9 #include <sys/stat.h>
10 #include <sys/wait.h>
11
12 #include <pb-config/pb-config.h>
13 #include <talloc/talloc.h>
14 #include <list/list.h>
15 #include <log/log.h>
16 #include <types/types.h>
17 #include <system/system.h>
18 #include <process/process.h>
19 #include <url/url.h>
20
21 #include "device-handler.h"
22 #include "discover-server.h"
23 #include "event.h"
24 #include "parser.h"
25 #include "resource.h"
26 #include "paths.h"
27 #include "boot.h"
28
29 struct device_handler {
30         struct discover_server  *server;
31         int                     dry_run;
32
33         struct discover_device  **devices;
34         unsigned int            n_devices;
35
36         struct waitset          *waitset;
37         struct waiter           *timeout_waiter;
38         bool                    autoboot_enabled;
39         unsigned int            sec_to_boot;
40
41         struct discover_boot_option *default_boot_option;
42         struct list             unresolved_boot_options;
43 };
44
45 static int mount_device(struct discover_device *dev);
46 static int umount_device(struct discover_device *dev);
47
48 void discover_context_add_boot_option(struct discover_context *ctx,
49                 struct discover_boot_option *boot_option)
50 {
51         boot_option->source = ctx->parser;
52         list_add_tail(&ctx->boot_options, &boot_option->list);
53         talloc_steal(ctx, boot_option);
54 }
55
56 /**
57  * device_handler_get_device_count - Get the count of current handler devices.
58  */
59
60 int device_handler_get_device_count(const struct device_handler *handler)
61 {
62         return handler->n_devices;
63 }
64
65 /**
66  * device_handler_get_device - Get a handler device by index.
67  */
68
69 const struct discover_device *device_handler_get_device(
70         const struct device_handler *handler, unsigned int index)
71 {
72         if (index >= handler->n_devices) {
73                 assert(0 && "bad index");
74                 return NULL;
75         }
76
77         return handler->devices[index];
78 }
79
80 struct discover_boot_option *discover_boot_option_create(
81                 struct discover_context *ctx,
82                 struct discover_device *device)
83 {
84         struct discover_boot_option *opt;
85
86         opt = talloc_zero(ctx, struct discover_boot_option);
87         opt->option = talloc_zero(opt, struct boot_option);
88         opt->device = device;
89
90         return opt;
91 }
92
93 static int device_match_uuid(struct discover_device *dev, const char *uuid)
94 {
95         return dev->uuid && !strcmp(dev->uuid, uuid);
96 }
97
98 static int device_match_label(struct discover_device *dev, const char *label)
99 {
100         return dev->label && !strcmp(dev->label, label);
101 }
102
103 static int device_match_id(struct discover_device *dev, const char *id)
104 {
105         return !strcmp(dev->device->id, id);
106 }
107
108 static int device_match_serial(struct discover_device *dev, const char *serial)
109 {
110         const char *val = discover_device_get_param(dev, "ID_SERIAL");
111         return val && !strcmp(val, serial);
112 }
113
114 static struct discover_device *device_lookup(
115                 struct device_handler *device_handler,
116                 int (match_fn)(struct discover_device *, const char *),
117                 const char *str)
118 {
119         struct discover_device *dev;
120         unsigned int i;
121
122         if (!str)
123                 return NULL;
124
125         for (i = 0; i < device_handler->n_devices; i++) {
126                 dev = device_handler->devices[i];
127
128                 if (match_fn(dev, str))
129                         return dev;
130         }
131
132         return NULL;
133 }
134
135 struct discover_device *device_lookup_by_name(struct device_handler *handler,
136                 const char *name)
137 {
138         if (!strncmp(name, "/dev/", strlen("/dev/")))
139                 name += strlen("/dev/");
140
141         return device_lookup_by_id(handler, name);
142 }
143
144 struct discover_device *device_lookup_by_uuid(
145                 struct device_handler *device_handler,
146                 const char *uuid)
147 {
148         return device_lookup(device_handler, device_match_uuid, uuid);
149 }
150
151 struct discover_device *device_lookup_by_label(
152                 struct device_handler *device_handler,
153                 const char *label)
154 {
155         return device_lookup(device_handler, device_match_label, label);
156 }
157
158 struct discover_device *device_lookup_by_id(
159                 struct device_handler *device_handler,
160                 const char *id)
161 {
162         return device_lookup(device_handler, device_match_id, id);
163 }
164
165 struct discover_device *device_lookup_by_serial(
166                 struct device_handler *device_handler,
167                 const char *serial)
168 {
169         return device_lookup(device_handler, device_match_serial, serial);
170 }
171
172 void device_handler_destroy(struct device_handler *handler)
173 {
174         talloc_free(handler);
175 }
176
177 static int destroy_device(void *arg)
178 {
179         struct discover_device *dev = arg;
180
181         umount_device(dev);
182
183         return 0;
184 }
185
186 struct discover_device *discover_device_create(struct device_handler *handler,
187                 const char *id)
188 {
189         struct discover_device *dev;
190
191         dev = device_lookup_by_id(handler, id);
192         if (dev)
193                 return dev;
194
195         dev = talloc_zero(handler, struct discover_device);
196         dev->device = talloc_zero(dev, struct device);
197         dev->device->id = talloc_strdup(dev->device, id);
198         list_init(&dev->params);
199         list_init(&dev->boot_options);
200
201         talloc_set_destructor(dev, destroy_device);
202
203         return dev;
204 }
205
206 struct discover_device_param {
207         char                    *name;
208         char                    *value;
209         struct list_item        list;
210 };
211
212 void discover_device_set_param(struct discover_device *device,
213                 const char *name, const char *value)
214 {
215         struct discover_device_param *param;
216         bool found = false;
217
218         list_for_each_entry(&device->params, param, list) {
219                 if (!strcmp(param->name, name)) {
220                         found = true;
221                         break;
222                 }
223         }
224
225         if (!found) {
226                 if (!value)
227                         return;
228                 param = talloc(device, struct discover_device_param);
229                 param->name = talloc_strdup(param, name);
230                 list_add(&device->params, &param->list);
231         } else {
232                 if (!value) {
233                         list_remove(&param->list);
234                         talloc_free(param);
235                         return;
236                 }
237                 talloc_free(param->value);
238         }
239
240         param->value = talloc_strdup(param, value);
241 }
242
243 const char *discover_device_get_param(struct discover_device *device,
244                 const char *name)
245 {
246         struct discover_device_param *param;
247
248         list_for_each_entry(&device->params, param, list) {
249                 if (!strcmp(param->name, name))
250                         return param->name;
251         }
252         return NULL;
253 }
254
255 struct device_handler *device_handler_init(struct discover_server *server,
256                 struct waitset *waitset, int dry_run)
257 {
258         struct device_handler *handler;
259
260         handler = talloc_zero(NULL, struct device_handler);
261         handler->server = server;
262         handler->waitset = waitset;
263         handler->dry_run = dry_run;
264         handler->autoboot_enabled = config_get()->autoboot_enabled;
265
266         list_init(&handler->unresolved_boot_options);
267
268         /* set up our mount point base */
269         pb_mkdir_recursive(mount_base());
270
271         parser_init();
272
273         return handler;
274 }
275
276 void device_handler_remove(struct device_handler *handler,
277                 struct discover_device *device)
278 {
279         unsigned int i;
280
281         for (i = 0; i < handler->n_devices; i++)
282                 if (handler->devices[i] == device)
283                         break;
284
285         if (i == handler->n_devices) {
286                 talloc_free(device);
287                 return;
288         }
289
290         handler->n_devices--;
291         memmove(&handler->devices[i], &handler->devices[i + 1],
292                 (handler->n_devices - i) * sizeof(handler->devices[0]));
293         handler->devices = talloc_realloc(handler, handler->devices,
294                 struct discover_device *, handler->n_devices);
295
296         if (device->notified)
297                 discover_server_notify_device_remove(handler->server,
298                                                         device->device);
299
300         talloc_free(device);
301 }
302
303 static void boot_status(void *arg, struct boot_status *status)
304 {
305         struct device_handler *handler = arg;
306
307         discover_server_notify_boot_status(handler->server, status);
308 }
309
310 static void countdown_status(struct device_handler *handler,
311                 struct discover_boot_option *opt, unsigned int sec)
312 {
313         struct boot_status status;
314
315         status.type = BOOT_STATUS_INFO;
316         status.progress = -1;
317         status.detail = NULL;
318         status.message = talloc_asprintf(handler,
319                         "Booting %s in %u sec", opt->option->name, sec);
320
321         discover_server_notify_boot_status(handler->server, &status);
322
323         talloc_free(status.message);
324 }
325
326 static int default_timeout(void *arg)
327 {
328         struct device_handler *handler = arg;
329         struct discover_boot_option *opt;
330
331         if (!handler->default_boot_option)
332                 return 0;
333
334         opt = handler->default_boot_option;
335
336         if (handler->sec_to_boot) {
337                 countdown_status(handler, opt, handler->sec_to_boot);
338                 handler->sec_to_boot--;
339                 handler->timeout_waiter = waiter_register_timeout(
340                                                 handler->waitset, 1000,
341                                                 default_timeout, handler);
342                 return 0;
343         }
344
345         handler->timeout_waiter = NULL;
346
347         pb_log("Timeout expired, booting default option %s\n", opt->option->id);
348
349         boot(handler, handler->default_boot_option, NULL,
350                         handler->dry_run, boot_status, handler);
351         return 0;
352 }
353
354 static bool priority_match(struct boot_priority *prio,
355                 struct discover_boot_option *opt)
356 {
357         return prio->type == opt->device->device->type;
358 }
359
360 static int default_option_priority(struct discover_boot_option *opt)
361 {
362         const struct config *config;
363         struct boot_priority *prio;
364         int i;
365
366         config = config_get();
367
368         for (i = 0; i < config->n_boot_priorities; i++) {
369                 prio = &config->boot_priorities[i];
370                 if (priority_match(prio, opt))
371                         break;
372         }
373
374         return i;
375 }
376
377 static void set_default(struct device_handler *handler,
378                 struct discover_boot_option *opt)
379 {
380         if (!handler->autoboot_enabled)
381                 return;
382
383         /* Resolve any conflicts: if we have a new default option, it only
384          * replaces the current if it has a higher priority. */
385         if (handler->default_boot_option) {
386                 int new_prio, cur_prio;
387
388                 new_prio = default_option_priority(opt);
389                 cur_prio = default_option_priority(
390                                         handler->default_boot_option);
391
392                 if (new_prio < cur_prio) {
393                         handler->default_boot_option = opt;
394                         /* extend the timeout a little, so the user sees some
395                          * indication of the change */
396                         handler->sec_to_boot += 2;
397                 }
398
399                 return;
400         }
401
402         handler->sec_to_boot = config_get()->autoboot_timeout_sec;
403         handler->default_boot_option = opt;
404
405         pb_log("Boot option %s set as default, timeout %u sec.\n",
406                opt->option->id, handler->sec_to_boot);
407
408         default_timeout(handler);
409 }
410
411 static bool resource_is_resolved(struct resource *res)
412 {
413         return !res || res->resolved;
414 }
415
416 /* We only use this in an assert, which will disappear if we're compiling
417  * with NDEBUG, so we need the 'used' attribute for these builds */
418 static bool __attribute__((used)) boot_option_is_resolved(
419                 struct discover_boot_option *opt)
420 {
421         return resource_is_resolved(opt->boot_image) &&
422                 resource_is_resolved(opt->initrd) &&
423                 resource_is_resolved(opt->dtb) &&
424                 resource_is_resolved(opt->icon);
425 }
426
427 static bool resource_resolve(struct resource *res, const char *name,
428                 struct discover_boot_option *opt,
429                 struct device_handler *handler)
430 {
431         struct parser *parser = opt->source;
432
433         if (resource_is_resolved(res))
434                 return true;
435
436         pb_log("Attempting to resolve resource %s->%s with parser %s\n",
437                         opt->option->id, name, parser->name);
438         parser->resolve_resource(handler, res);
439
440         return res->resolved;
441 }
442
443 static bool boot_option_resolve(struct discover_boot_option *opt,
444                 struct device_handler *handler)
445 {
446         return resource_resolve(opt->boot_image, "boot_image", opt, handler) &&
447                 resource_resolve(opt->initrd, "initrd", opt, handler) &&
448                 resource_resolve(opt->dtb, "dtb", opt, handler) &&
449                 resource_resolve(opt->icon, "icon", opt, handler);
450 }
451
452 static void boot_option_finalise(struct device_handler *handler,
453                 struct discover_boot_option *opt)
454 {
455         assert(boot_option_is_resolved(opt));
456
457         /* check that the parsers haven't set any of the final data */
458         assert(!opt->option->boot_image_file);
459         assert(!opt->option->initrd_file);
460         assert(!opt->option->dtb_file);
461         assert(!opt->option->icon_file);
462         assert(!opt->option->device_id);
463
464         if (opt->boot_image)
465                 opt->option->boot_image_file = opt->boot_image->url->full;
466         if (opt->initrd)
467                 opt->option->initrd_file = opt->initrd->url->full;
468         if (opt->dtb)
469                 opt->option->dtb_file = opt->dtb->url->full;
470         if (opt->icon)
471                 opt->option->icon_file = opt->icon->url->full;
472
473         opt->option->device_id = opt->device->device->id;
474
475         if (opt->option->is_default)
476                 set_default(handler, opt);
477 }
478
479 static void notify_boot_option(struct device_handler *handler,
480                 struct discover_boot_option *opt)
481 {
482         struct discover_device *dev = opt->device;
483
484         if (!dev->notified)
485                 discover_server_notify_device_add(handler->server,
486                                                   opt->device->device);
487         dev->notified = true;
488         discover_server_notify_boot_option_add(handler->server, opt->option);
489 }
490
491 static void process_boot_option_queue(struct device_handler *handler)
492 {
493         struct discover_boot_option *opt, *tmp;
494
495         list_for_each_entry_safe(&handler->unresolved_boot_options,
496                         opt, tmp, list) {
497
498                 pb_log("queue: attempting resolution for %s\n",
499                                 opt->option->id);
500
501                 if (!boot_option_resolve(opt, handler))
502                         continue;
503
504                 pb_log("\tresolved!\n");
505
506                 list_remove(&opt->list);
507                 list_add_tail(&opt->device->boot_options, &opt->list);
508                 talloc_steal(opt->device, opt);
509                 boot_option_finalise(handler, opt);
510                 notify_boot_option(handler, opt);
511         }
512 }
513
514 struct discover_context *device_handler_discover_context_create(
515                 struct device_handler *handler,
516                 struct discover_device *device)
517 {
518         struct discover_context *ctx;
519
520         ctx = talloc(handler, struct discover_context);
521         ctx->device = device;
522         ctx->conf_url = NULL;
523         list_init(&ctx->boot_options);
524
525         return ctx;
526 }
527
528 /**
529  * context_commit - Commit a temporary discovery context to the handler,
530  * and notify the clients about any new options / devices
531  */
532 void device_handler_discover_context_commit(struct device_handler *handler,
533                 struct discover_context *ctx)
534 {
535         struct discover_device *dev = ctx->device;
536         struct discover_boot_option *opt, *tmp;
537
538         if (!device_lookup_by_id(handler, dev->device->id))
539                 device_handler_add_device(handler, dev);
540
541         /* move boot options from the context to the device */
542         list_for_each_entry_safe(&ctx->boot_options, opt, tmp, list) {
543                 list_remove(&opt->list);
544
545                 if (boot_option_resolve(opt, handler)) {
546                         pb_log("boot option %s is resolved, "
547                                         "sending to clients\n",
548                                         opt->option->id);
549                         list_add_tail(&dev->boot_options, &opt->list);
550                         talloc_steal(dev, opt);
551                         boot_option_finalise(handler, opt);
552                         notify_boot_option(handler, opt);
553                 } else {
554                         if (!opt->source->resolve_resource) {
555                                 pb_log("parser %s gave us an unresolved "
556                                         "resource (%s), but no way to "
557                                         "resolve it\n",
558                                         opt->source->name, opt->option->id);
559                                 talloc_free(opt);
560                         } else {
561                                 pb_log("boot option %s is unresolved, "
562                                                 "adding to queue\n",
563                                                 opt->option->id);
564                                 list_add(&handler->unresolved_boot_options,
565                                                 &opt->list);
566                                 talloc_steal(handler, opt);
567                         }
568                 }
569         }
570 }
571
572 void device_handler_add_device(struct device_handler *handler,
573                 struct discover_device *device)
574 {
575         handler->n_devices++;
576         handler->devices = talloc_realloc(handler, handler->devices,
577                                 struct discover_device *, handler->n_devices);
578         handler->devices[handler->n_devices - 1] = device;
579
580 }
581
582 /* Start discovery on a hotplugged device. The device will be in our devices
583  * array, but has only just been initialised by the hotplug source.
584  */
585 int device_handler_discover(struct device_handler *handler,
586                 struct discover_device *dev, enum conf_method method)
587 {
588         struct discover_context *ctx;
589         int rc;
590
591         process_boot_option_queue(handler);
592
593         /* create our context */
594         ctx = device_handler_discover_context_create(handler, dev);
595
596         rc = mount_device(dev);
597         if (rc)
598                 goto out;
599
600         /* run the parsers. This will populate the ctx's boot_option list. */
601         iterate_parsers(ctx, method);
602
603         /* add discovered stuff to the handler */
604         device_handler_discover_context_commit(handler, ctx);
605
606 out:
607         talloc_free(ctx);
608
609         return 0;
610 }
611
612 /* incoming conf event */
613 int device_handler_conf(struct device_handler *handler,
614                 struct discover_device *dev, struct pb_url *url,
615                 enum conf_method method)
616 {
617         struct discover_context *ctx;
618
619         /* create our context */
620         ctx = device_handler_discover_context_create(handler, dev);
621         ctx->conf_url = url;
622
623         iterate_parsers(ctx, method);
624
625         device_handler_discover_context_commit(handler, ctx);
626
627         talloc_free(ctx);
628
629         return 0;
630 }
631
632 static struct discover_boot_option *find_boot_option_by_id(
633                 struct device_handler *handler, const char *id)
634 {
635         unsigned int i;
636
637         for (i = 0; i < handler->n_devices; i++) {
638                 struct discover_device *dev = handler->devices[i];
639                 struct discover_boot_option *opt;
640
641                 list_for_each_entry(&dev->boot_options, opt, list)
642                         if (!strcmp(opt->option->id, id))
643                                 return opt;
644         }
645
646         return NULL;
647 }
648
649 void device_handler_boot(struct device_handler *handler,
650                 struct boot_command *cmd)
651 {
652         struct discover_boot_option *opt;
653
654         opt = find_boot_option_by_id(handler, cmd->option_id);
655
656         boot(handler, opt, cmd, handler->dry_run, boot_status, handler);
657 }
658
659 void device_handler_cancel_default(struct device_handler *handler)
660 {
661         struct boot_status status;
662
663         if (handler->timeout_waiter)
664                 waiter_remove(handler->timeout_waiter);
665
666         handler->timeout_waiter = NULL;
667         handler->autoboot_enabled = false;
668
669         /* we only send status if we had a default boot option queued */
670         if (!handler->default_boot_option)
671                 return;
672
673         pb_log("Cancelling default boot option\n");
674
675         handler->default_boot_option = NULL;
676
677         status.type = BOOT_STATUS_INFO;
678         status.progress = -1;
679         status.detail = NULL;
680         status.message = "Default boot cancelled";
681
682         discover_server_notify_boot_status(handler->server, &status);
683 }
684
685 #ifndef PETITBOOT_TEST
686 static bool check_existing_mount(struct discover_device *dev)
687 {
688         struct stat devstat, mntstat;
689         struct mntent *mnt;
690         FILE *fp;
691         int rc;
692
693         rc = stat(dev->device_path, &devstat);
694         if (rc) {
695                 pb_debug("%s: stat failed: %s\n", __func__, strerror(errno));
696                 return false;
697         }
698
699         if (!S_ISBLK(devstat.st_mode)) {
700                 pb_debug("%s: %s isn't a block device?\n", __func__,
701                                 dev->device_path);
702                 return false;
703         }
704
705         fp = fopen("/proc/self/mounts", "r");
706
707         for (;;) {
708                 mnt = getmntent(fp);
709                 if (!mnt)
710                         break;
711
712                 if (!mnt->mnt_fsname || mnt->mnt_fsname[0] != '/')
713                         continue;
714
715                 rc = stat(mnt->mnt_fsname, &mntstat);
716                 if (rc)
717                         continue;
718
719                 if (!S_ISBLK(mntstat.st_mode))
720                         continue;
721
722                 if (mntstat.st_rdev == devstat.st_rdev) {
723                         pb_debug("%s: %s is already mounted at %s\n"
724                                         __func__, dev->device_path,
725                                         mnt->mnt_dir);
726                         dev->mount_path = talloc_strdup(dev, mnt->mnt_dir);
727                         dev->mounted = true;
728                         dev->unmount = false;
729                         break;
730                 }
731         }
732
733         fclose(fp);
734
735         return mnt != NULL;
736 }
737
738 static int mount_device(struct discover_device *dev)
739 {
740         int rc;
741
742         if (!dev->device_path)
743                 return -1;
744
745         if (dev->mounted)
746                 return 0;
747
748         if (check_existing_mount(dev))
749                 return 0;
750
751         dev->mount_path = join_paths(dev, mount_base(),
752                                         dev->device_path);
753
754         if (pb_mkdir_recursive(dev->mount_path)) {
755                 pb_log("couldn't create mount directory %s: %s\n",
756                                 dev->mount_path, strerror(errno));
757                 goto err_free;
758         }
759
760         rc = process_run_simple(dev, pb_system_apps.mount,
761                         dev->device_path, dev->mount_path,
762                         "-o", "ro", NULL);
763         if (!rc) {
764                 dev->mounted = true;
765                 dev->unmount = true;
766                 return 0;
767         }
768
769         /* Retry mount without ro option. */
770         rc = process_run_simple(dev, pb_system_apps.mount,
771                         dev->device_path, dev->mount_path, NULL);
772
773         if (!rc) {
774                 dev->mounted = true;
775                 dev->unmount = true;
776                 return 0;
777         }
778
779         pb_rmdir_recursive(mount_base(), dev->mount_path);
780 err_free:
781         talloc_free(dev->mount_path);
782         dev->mount_path = NULL;
783         return -1;
784 }
785
786 static int umount_device(struct discover_device *dev)
787 {
788         int status;
789
790         if (!dev->mounted || !dev->unmount)
791                 return 0;
792
793         status = process_run_simple(dev, pb_system_apps.umount,
794                         dev->mount_path, NULL);
795
796         if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
797                 return -1;
798
799         dev->mounted = false;
800         talloc_free(dev->mount_path);
801         dev->mount_path = NULL;
802
803         pb_rmdir_recursive(mount_base(), dev->mount_path);
804
805         return 0;
806 }
807 #else
808
809 static int umount_device(struct discover_device *dev __attribute__((unused)))
810 {
811         return 0;
812 }
813
814 static int __attribute__((unused)) mount_device(
815                 struct discover_device *dev __attribute__((unused)))
816 {
817         return 0;
818 }
819
820 #endif
821