fc280af186fb9d8e400bd59ef6a5b42b9118a39b
[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         ctx->test_data = NULL;
524         list_init(&ctx->boot_options);
525
526         return ctx;
527 }
528
529 /**
530  * context_commit - Commit a temporary discovery context to the handler,
531  * and notify the clients about any new options / devices
532  */
533 void device_handler_discover_context_commit(struct device_handler *handler,
534                 struct discover_context *ctx)
535 {
536         struct discover_device *dev = ctx->device;
537         struct discover_boot_option *opt, *tmp;
538
539         if (!device_lookup_by_id(handler, dev->device->id))
540                 device_handler_add_device(handler, dev);
541
542         /* move boot options from the context to the device */
543         list_for_each_entry_safe(&ctx->boot_options, opt, tmp, list) {
544                 list_remove(&opt->list);
545
546                 if (boot_option_resolve(opt, handler)) {
547                         pb_log("boot option %s is resolved, "
548                                         "sending to clients\n",
549                                         opt->option->id);
550                         list_add_tail(&dev->boot_options, &opt->list);
551                         talloc_steal(dev, opt);
552                         boot_option_finalise(handler, opt);
553                         notify_boot_option(handler, opt);
554                 } else {
555                         if (!opt->source->resolve_resource) {
556                                 pb_log("parser %s gave us an unresolved "
557                                         "resource (%s), but no way to "
558                                         "resolve it\n",
559                                         opt->source->name, opt->option->id);
560                                 talloc_free(opt);
561                         } else {
562                                 pb_log("boot option %s is unresolved, "
563                                                 "adding to queue\n",
564                                                 opt->option->id);
565                                 list_add(&handler->unresolved_boot_options,
566                                                 &opt->list);
567                                 talloc_steal(handler, opt);
568                         }
569                 }
570         }
571 }
572
573 void device_handler_add_device(struct device_handler *handler,
574                 struct discover_device *device)
575 {
576         handler->n_devices++;
577         handler->devices = talloc_realloc(handler, handler->devices,
578                                 struct discover_device *, handler->n_devices);
579         handler->devices[handler->n_devices - 1] = device;
580
581 }
582
583 /* Start discovery on a hotplugged device. The device will be in our devices
584  * array, but has only just been initialised by the hotplug source.
585  */
586 int device_handler_discover(struct device_handler *handler,
587                 struct discover_device *dev, enum conf_method method)
588 {
589         struct discover_context *ctx;
590         int rc;
591
592         process_boot_option_queue(handler);
593
594         /* create our context */
595         ctx = device_handler_discover_context_create(handler, dev);
596
597         rc = mount_device(dev);
598         if (rc)
599                 goto out;
600
601         /* run the parsers. This will populate the ctx's boot_option list. */
602         iterate_parsers(ctx, method);
603
604         /* add discovered stuff to the handler */
605         device_handler_discover_context_commit(handler, ctx);
606
607 out:
608         talloc_free(ctx);
609
610         return 0;
611 }
612
613 /* incoming conf event */
614 int device_handler_conf(struct device_handler *handler,
615                 struct discover_device *dev, struct pb_url *url,
616                 enum conf_method method)
617 {
618         struct discover_context *ctx;
619
620         /* create our context */
621         ctx = device_handler_discover_context_create(handler, dev);
622         ctx->conf_url = url;
623
624         iterate_parsers(ctx, method);
625
626         device_handler_discover_context_commit(handler, ctx);
627
628         talloc_free(ctx);
629
630         return 0;
631 }
632
633 static struct discover_boot_option *find_boot_option_by_id(
634                 struct device_handler *handler, const char *id)
635 {
636         unsigned int i;
637
638         for (i = 0; i < handler->n_devices; i++) {
639                 struct discover_device *dev = handler->devices[i];
640                 struct discover_boot_option *opt;
641
642                 list_for_each_entry(&dev->boot_options, opt, list)
643                         if (!strcmp(opt->option->id, id))
644                                 return opt;
645         }
646
647         return NULL;
648 }
649
650 void device_handler_boot(struct device_handler *handler,
651                 struct boot_command *cmd)
652 {
653         struct discover_boot_option *opt;
654
655         opt = find_boot_option_by_id(handler, cmd->option_id);
656
657         boot(handler, opt, cmd, handler->dry_run, boot_status, handler);
658 }
659
660 void device_handler_cancel_default(struct device_handler *handler)
661 {
662         struct boot_status status;
663
664         if (handler->timeout_waiter)
665                 waiter_remove(handler->timeout_waiter);
666
667         handler->timeout_waiter = NULL;
668         handler->autoboot_enabled = false;
669
670         /* we only send status if we had a default boot option queued */
671         if (!handler->default_boot_option)
672                 return;
673
674         pb_log("Cancelling default boot option\n");
675
676         handler->default_boot_option = NULL;
677
678         status.type = BOOT_STATUS_INFO;
679         status.progress = -1;
680         status.detail = NULL;
681         status.message = "Default boot cancelled";
682
683         discover_server_notify_boot_status(handler->server, &status);
684 }
685
686 #ifndef PETITBOOT_TEST
687 static bool check_existing_mount(struct discover_device *dev)
688 {
689         struct stat devstat, mntstat;
690         struct mntent *mnt;
691         FILE *fp;
692         int rc;
693
694         rc = stat(dev->device_path, &devstat);
695         if (rc) {
696                 pb_debug("%s: stat failed: %s\n", __func__, strerror(errno));
697                 return false;
698         }
699
700         if (!S_ISBLK(devstat.st_mode)) {
701                 pb_debug("%s: %s isn't a block device?\n", __func__,
702                                 dev->device_path);
703                 return false;
704         }
705
706         fp = fopen("/proc/self/mounts", "r");
707
708         for (;;) {
709                 mnt = getmntent(fp);
710                 if (!mnt)
711                         break;
712
713                 if (!mnt->mnt_fsname || mnt->mnt_fsname[0] != '/')
714                         continue;
715
716                 rc = stat(mnt->mnt_fsname, &mntstat);
717                 if (rc)
718                         continue;
719
720                 if (!S_ISBLK(mntstat.st_mode))
721                         continue;
722
723                 if (mntstat.st_rdev == devstat.st_rdev) {
724                         pb_debug("%s: %s is already mounted at %s\n"
725                                         __func__, dev->device_path,
726                                         mnt->mnt_dir);
727                         dev->mount_path = talloc_strdup(dev, mnt->mnt_dir);
728                         dev->mounted = true;
729                         dev->unmount = false;
730                         break;
731                 }
732         }
733
734         fclose(fp);
735
736         return mnt != NULL;
737 }
738
739 static int mount_device(struct discover_device *dev)
740 {
741         int rc;
742
743         if (!dev->device_path)
744                 return -1;
745
746         if (dev->mounted)
747                 return 0;
748
749         if (check_existing_mount(dev))
750                 return 0;
751
752         dev->mount_path = join_paths(dev, mount_base(),
753                                         dev->device_path);
754
755         if (pb_mkdir_recursive(dev->mount_path)) {
756                 pb_log("couldn't create mount directory %s: %s\n",
757                                 dev->mount_path, strerror(errno));
758                 goto err_free;
759         }
760
761         rc = process_run_simple(dev, pb_system_apps.mount,
762                         dev->device_path, dev->mount_path,
763                         "-o", "ro", NULL);
764         if (!rc) {
765                 dev->mounted = true;
766                 dev->unmount = true;
767                 return 0;
768         }
769
770         /* Retry mount without ro option. */
771         rc = process_run_simple(dev, pb_system_apps.mount,
772                         dev->device_path, dev->mount_path, NULL);
773
774         if (!rc) {
775                 dev->mounted = true;
776                 dev->unmount = true;
777                 return 0;
778         }
779
780         pb_rmdir_recursive(mount_base(), dev->mount_path);
781 err_free:
782         talloc_free(dev->mount_path);
783         dev->mount_path = NULL;
784         return -1;
785 }
786
787 static int umount_device(struct discover_device *dev)
788 {
789         int status;
790
791         if (!dev->mounted || !dev->unmount)
792                 return 0;
793
794         status = process_run_simple(dev, pb_system_apps.umount,
795                         dev->mount_path, NULL);
796
797         if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
798                 return -1;
799
800         dev->mounted = false;
801         talloc_free(dev->mount_path);
802         dev->mount_path = NULL;
803
804         pb_rmdir_recursive(mount_base(), dev->mount_path);
805
806         return 0;
807 }
808 #else
809
810 static int umount_device(struct discover_device *dev __attribute__((unused)))
811 {
812         return 0;
813 }
814
815 static int __attribute__((unused)) mount_device(
816                 struct discover_device *dev __attribute__((unused)))
817 {
818         return 0;
819 }
820
821 #endif
822