11 #include <sys/mount.h>
13 #include <talloc/talloc.h>
14 #include <list/list.h>
16 #include <types/types.h>
17 #include <system/system.h>
18 #include <process/process.h>
20 #include <i18n/i18n.h>
22 #include <sys/sysmacros.h>
23 #include <sys/types.h>
24 #include <sys/socket.h>
26 #include <arpa/inet.h>
28 #include "device-handler.h"
29 #include "discover-server.h"
30 #include "devmapper.h"
31 #include "user-event.h"
43 enum default_priority {
44 DEFAULT_PRIORITY_REMOTE = 1,
45 DEFAULT_PRIORITY_LOCAL_FIRST = 2,
46 DEFAULT_PRIORITY_LOCAL_LAST = 0xfe,
47 DEFAULT_PRIORITY_DISABLED = 0xff,
50 struct progress_info {
51 unsigned int percentage;
52 unsigned long size; /* size in bytes */
54 const struct process_info *procinfo;
55 struct list_item list;
58 struct device_handler {
59 struct discover_server *server;
63 struct network *network;
64 struct user_event *user_event;
66 struct discover_device **devices;
67 unsigned int n_devices;
69 struct ramdisk_device **ramdisks;
70 unsigned int n_ramdisks;
72 struct waitset *waitset;
73 struct waiter *timeout_waiter;
74 bool autoboot_enabled;
75 unsigned int sec_to_boot;
77 struct discover_boot_option *default_boot_option;
78 int default_boot_option_priority;
80 struct list unresolved_boot_options;
82 struct boot_task *pending_boot;
83 bool pending_boot_is_default;
86 unsigned int n_progress;
88 struct plugin_option **plugins;
89 unsigned int n_plugins;
90 bool plugin_installing;
93 static int mount_device(struct discover_device *dev);
94 static int umount_device(struct discover_device *dev);
96 static int device_handler_init_sources(struct device_handler *handler);
97 static void device_handler_reinit_sources(struct device_handler *handler);
99 static void device_handler_update_lang(const char *lang);
101 void discover_context_add_boot_option(struct discover_context *ctx,
102 struct discover_boot_option *boot_option)
104 boot_option->source = ctx->parser;
105 list_add_tail(&ctx->boot_options, &boot_option->list);
106 talloc_steal(ctx, boot_option);
110 * device_handler_get_device_count - Get the count of current handler devices.
113 int device_handler_get_device_count(const struct device_handler *handler)
115 return handler->n_devices;
119 * device_handler_get_device - Get a handler device by index.
122 const struct discover_device *device_handler_get_device(
123 const struct device_handler *handler, unsigned int index)
125 if (index >= handler->n_devices) {
126 assert(0 && "bad index");
130 return handler->devices[index];
134 * device_handler_get_plugin_count - Get the count of current handler plugins.
136 int device_handler_get_plugin_count(const struct device_handler *handler)
138 return handler->n_plugins;
142 * discover_handler_get_plugin - Get a handler plugin by index.
144 const struct plugin_option *device_handler_get_plugin(
145 const struct device_handler *handler, unsigned int index)
147 if (index >= handler->n_plugins) {
148 assert(0 && "bad index");
152 return handler->plugins[index];
155 struct network *device_handler_get_network(
156 const struct device_handler *handler)
158 return handler->network;
161 struct discover_boot_option *discover_boot_option_create(
162 struct discover_context *ctx,
163 struct discover_device *device)
165 struct discover_boot_option *opt;
167 opt = talloc_zero(ctx, struct discover_boot_option);
168 opt->option = talloc_zero(opt, struct boot_option);
169 opt->device = device;
174 static int device_match_uuid(struct discover_device *dev, const char *uuid)
176 return dev->uuid && !strcmp(dev->uuid, uuid);
179 static int device_match_label(struct discover_device *dev, const char *label)
181 return dev->label && !strcmp(dev->label, label);
184 static int device_match_id(struct discover_device *dev, const char *id)
186 return !strcmp(dev->device->id, id);
189 static int device_match_serial(struct discover_device *dev, const char *serial)
191 const char *val = discover_device_get_param(dev, "ID_SERIAL");
192 return val && !strcmp(val, serial);
195 static struct discover_device *device_lookup(
196 struct device_handler *device_handler,
197 int (match_fn)(struct discover_device *, const char *),
200 struct discover_device *dev;
206 for (i = 0; i < device_handler->n_devices; i++) {
207 dev = device_handler->devices[i];
209 if (match_fn(dev, str))
216 struct discover_device *device_lookup_by_name(struct device_handler *handler,
219 if (!strncmp(name, "/dev/", strlen("/dev/")))
220 name += strlen("/dev/");
222 return device_lookup_by_id(handler, name);
225 struct discover_device *device_lookup_by_uuid(
226 struct device_handler *device_handler,
229 return device_lookup(device_handler, device_match_uuid, uuid);
232 struct discover_device *device_lookup_by_label(
233 struct device_handler *device_handler,
236 return device_lookup(device_handler, device_match_label, label);
239 struct discover_device *device_lookup_by_id(
240 struct device_handler *device_handler,
243 return device_lookup(device_handler, device_match_id, id);
246 struct discover_device *device_lookup_by_serial(
247 struct device_handler *device_handler,
250 return device_lookup(device_handler, device_match_serial, serial);
253 void device_handler_destroy(struct device_handler *handler)
255 talloc_free(handler);
258 static int destroy_device(void *arg)
260 struct discover_device *dev = arg;
267 struct discover_device *discover_device_create(struct device_handler *handler,
268 const char *uuid, const char *id)
270 struct discover_device *dev;
273 dev = device_lookup_by_uuid(handler, uuid);
275 dev = device_lookup_by_id(handler, id);
280 dev = talloc_zero(handler, struct discover_device);
281 dev->device = talloc_zero(dev, struct device);
282 dev->device->id = talloc_strdup(dev->device, id);
283 dev->uuid = talloc_strdup(dev, uuid);
284 list_init(&dev->params);
285 list_init(&dev->boot_options);
287 talloc_set_destructor(dev, destroy_device);
292 struct discover_device_param {
295 struct list_item list;
298 void discover_device_set_param(struct discover_device *device,
299 const char *name, const char *value)
301 struct discover_device_param *param;
304 list_for_each_entry(&device->params, param, list) {
305 if (!strcmp(param->name, name)) {
314 param = talloc(device, struct discover_device_param);
315 param->name = talloc_strdup(param, name);
316 list_add(&device->params, ¶m->list);
319 list_remove(¶m->list);
323 talloc_free(param->value);
326 param->value = talloc_strdup(param, value);
329 const char *discover_device_get_param(struct discover_device *device,
332 struct discover_device_param *param;
334 list_for_each_entry(&device->params, param, list) {
335 if (!strcmp(param->name, name))
341 struct device_handler *device_handler_init(struct discover_server *server,
342 struct waitset *waitset, int dry_run)
344 struct device_handler *handler;
347 handler = talloc_zero(NULL, struct device_handler);
348 handler->server = server;
349 handler->waitset = waitset;
350 handler->dry_run = dry_run;
351 handler->autoboot_enabled = config_autoboot_active(config_get());
353 list_init(&handler->unresolved_boot_options);
355 list_init(&handler->progress);
357 /* set up our mount point base */
358 pb_mkdir_recursive(mount_base());
362 if (config_get()->safe_mode)
365 rc = device_handler_init_sources(handler);
367 talloc_free(handler);
374 void device_handler_reinit(struct device_handler *handler)
376 struct discover_boot_option *opt, *tmp;
377 struct ramdisk_device *ramdisk;
380 device_handler_cancel_default(handler);
381 /* Cancel any pending non-default boot */
382 if (handler->pending_boot) {
383 boot_cancel(handler->pending_boot);
384 handler->pending_boot = NULL;
385 handler->pending_boot_is_default = false;
388 /* Cancel any remaining async jobs */
389 process_stop_async_all();
390 pending_network_jobs_cancel();
392 /* free unresolved boot options */
393 list_for_each_entry_safe(&handler->unresolved_boot_options,
396 list_init(&handler->unresolved_boot_options);
398 /* drop all devices */
399 for (i = 0; i < handler->n_devices; i++) {
400 discover_server_notify_device_remove(handler->server,
401 handler->devices[i]->device);
402 ramdisk = handler->devices[i]->ramdisk;
403 talloc_free(handler->devices[i]);
404 talloc_free(ramdisk);
407 talloc_free(handler->devices);
408 handler->devices = NULL;
409 handler->n_devices = 0;
410 talloc_free(handler->ramdisks);
411 handler->ramdisks = NULL;
412 handler->n_ramdisks = 0;
414 /* drop any known plugins */
415 for (i = 0; i < handler->n_plugins; i++)
416 talloc_free(handler->plugins[i]);
417 talloc_free(handler->plugins);
418 handler->plugins = NULL;
419 handler->n_plugins = 0;
421 discover_server_notify_plugins_remove(handler->server);
423 device_handler_reinit_sources(handler);
426 void device_handler_remove(struct device_handler *handler,
427 struct discover_device *device)
429 struct discover_boot_option *opt, *tmp;
432 list_for_each_entry_safe(&device->boot_options, opt, tmp, list) {
433 if (opt == handler->default_boot_option) {
434 pb_log("Default option %s cancelled since device removed",
436 device_handler_cancel_default(handler);
441 for (i = 0; i < handler->n_devices; i++)
442 if (handler->devices[i] == device)
445 if (i == handler->n_devices) {
450 /* Free any unresolved options, as they're currently allocated
451 * against the handler */
452 list_for_each_entry_safe(&handler->unresolved_boot_options,
454 if (opt->device != device)
456 list_remove(&opt->list);
460 /* if this is a network device, we have to unregister it from the
462 if (device->device->type == DEVICE_TYPE_NETWORK)
463 network_unregister_device(handler->network, device);
465 handler->n_devices--;
466 memmove(&handler->devices[i], &handler->devices[i + 1],
467 (handler->n_devices - i) * sizeof(handler->devices[0]));
468 handler->devices = talloc_realloc(handler, handler->devices,
469 struct discover_device *, handler->n_devices);
471 if (device->notified)
472 discover_server_notify_device_remove(handler->server,
478 void device_handler_status(struct device_handler *handler,
479 struct status *status)
481 discover_server_notify_boot_status(handler->server, status);
484 static void _device_handler_vstatus(struct device_handler *handler,
485 enum status_type type, const char *fmt, va_list ap)
487 struct status status;
490 status.message = talloc_vasprintf(handler, fmt, ap);
491 status.backlog = false;
493 device_handler_status(handler, &status);
495 talloc_free(status.message);
498 static void _device_handler_vdevstatus(struct device_handler *handler,
499 struct discover_device *device, enum status_type type,
500 const char *fmt, va_list ap)
504 msg = talloc_asprintf(handler, "[%s] %s",
505 device ? device->device->id : "unknown", fmt);
506 _device_handler_vstatus(handler, type, msg, ap);
510 void device_handler_status_dev_info(struct device_handler *handler,
511 struct discover_device *dev, const char *fmt, ...)
516 _device_handler_vdevstatus(handler, dev, STATUS_INFO, fmt, ap);
520 void device_handler_status_dev_err(struct device_handler *handler,
521 struct discover_device *dev, const char *fmt, ...)
526 _device_handler_vdevstatus(handler, dev, STATUS_ERROR, fmt, ap);
530 void device_handler_status_info(struct device_handler *handler,
531 const char *fmt, ...)
536 _device_handler_vstatus(handler, STATUS_INFO, fmt, ap);
540 void device_handler_status_err(struct device_handler *handler,
541 const char *fmt, ...)
546 _device_handler_vstatus(handler, STATUS_ERROR, fmt, ap);
550 void device_handler_status_download(struct device_handler *handler,
551 const struct process_info *procinfo,
552 unsigned int percentage, unsigned int size, char suffix)
554 struct progress_info *p, *progress = NULL;
555 uint64_t current_converted, current = 0;
556 const char *units = " kMGTP";
557 unsigned long size_bytes;
563 list_for_each_entry(&handler->progress, p, list)
564 if (p->procinfo == procinfo)
568 pb_log("Registering new progress struct\n");
569 progress = talloc_zero(handler, struct progress_info);
571 pb_log("Failed to allocate room for progress struct\n");
574 progress->procinfo = procinfo;
575 list_add(&handler->progress, &progress->list);
576 handler->n_progress++;
580 for (i = 0; i < strlen(units); i++) {
581 if (units[i] == suffix)
585 if (i >= strlen(units)) {
586 pb_log("Couldn't recognise suffix '%c'\n", suffix);
593 progress->percentage = percentage;
594 progress->size = size_bytes;
597 * Aggregate the info we have and update status. If a progress struct
598 * has zero for both percentage and size we assume progress information
599 * is unavailable and fall back to a generic progress message.
601 list_for_each_entry(&handler->progress, p, list) {
604 if (!p->percentage || !p->size) {
605 update = talloc_asprintf(handler,
606 _("%u downloads in progress..."),
607 handler->n_progress);
613 t = (100 * c) / p->percentage;
620 current_converted = current;
621 while (current_converted >= 1000) {
622 current_converted >>= 10;
625 update = talloc_asprintf(handler,
626 _("%u %s downloading: %.0f%% - %lu%cB"),
628 ngettext("item", "items", handler->n_progress),
629 (current / total) * 100, current_converted,
634 pb_log("%s: failed to allocate new status\n", __func__);
636 device_handler_status_info(handler, "%s\n", update);
641 static void device_handler_plugin_scan_device(struct device_handler *handler,
642 struct discover_device *dev)
646 pb_debug("Scanning %s for plugin files\n", dev->device->id);
648 rc = process_run_simple(handler, pb_system_apps.pb_plugin,
649 "scan", dev->mount_path,
652 pb_log("Error from pb-plugin scan %s\n",
656 void device_handler_status_download_remove(struct device_handler *handler,
657 struct process_info *procinfo)
659 struct progress_info *p, *tmp;
661 list_for_each_entry_safe(&handler->progress, p, tmp, list)
662 if (p->procinfo == procinfo) {
663 list_remove(&p->list);
665 handler->n_progress--;
669 static void device_handler_boot_status_cb(void *arg, struct status *status)
671 device_handler_status(arg, status);
674 static void countdown_status(struct device_handler *handler,
675 struct discover_boot_option *opt, unsigned int sec)
677 struct status status;
679 status.type = STATUS_INFO;
680 status.message = talloc_asprintf(handler,
681 _("Booting in %d sec: [%s] %s"), sec,
682 opt->device->device->id, opt->option->name);
683 status.backlog = false;
685 device_handler_status(handler, &status);
687 talloc_free(status.message);
690 static int default_timeout(void *arg)
692 struct device_handler *handler = arg;
693 struct discover_boot_option *opt;
695 if (!handler->default_boot_option)
698 if (handler->pending_boot)
701 opt = handler->default_boot_option;
703 if (handler->sec_to_boot) {
704 countdown_status(handler, opt, handler->sec_to_boot);
705 handler->sec_to_boot--;
706 handler->timeout_waiter = waiter_register_timeout(
707 handler->waitset, 1000,
708 default_timeout, handler);
712 handler->timeout_waiter = NULL;
714 pb_log("Timeout expired, booting default option %s\n", opt->option->id);
718 handler->pending_boot = boot(handler, handler->default_boot_option,
719 NULL, handler->dry_run, device_handler_boot_status_cb,
721 handler->pending_boot_is_default = true;
726 enum ipmi_bootdev ipmi_type;
727 enum device_type device_type;
728 } device_type_map[] = {
729 { IPMI_BOOTDEV_NETWORK, DEVICE_TYPE_NETWORK },
730 { IPMI_BOOTDEV_DISK, DEVICE_TYPE_DISK },
731 { IPMI_BOOTDEV_DISK, DEVICE_TYPE_USB },
732 { IPMI_BOOTDEV_CDROM, DEVICE_TYPE_OPTICAL },
735 static bool ipmi_device_type_matches(enum ipmi_bootdev ipmi_type,
736 enum device_type device_type)
740 for (i = 0; i < ARRAY_SIZE(device_type_map); i++) {
741 if (device_type_map[i].device_type == device_type)
742 return device_type_map[i].ipmi_type == ipmi_type;
748 static int autoboot_option_priority(const struct config *config,
749 struct discover_boot_option *opt)
751 enum device_type type = opt->device->device->type;
752 const char *uuid = opt->device->uuid;
753 struct autoboot_option *auto_opt;
756 for (i = 0; i < config->n_autoboot_opts; i++) {
757 auto_opt = &config->autoboot_opts[i];
758 if (auto_opt->boot_type == BOOT_DEVICE_UUID)
759 if (!strcmp(auto_opt->uuid, uuid))
760 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
762 if (auto_opt->boot_type == BOOT_DEVICE_TYPE)
763 if (auto_opt->type == type ||
764 auto_opt->type == DEVICE_TYPE_ANY)
765 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
772 * We have different priorities to resolve conflicts between boot options that
773 * report to be the default for their device. This function assigns a priority
776 static enum default_priority default_option_priority(
777 struct discover_boot_option *opt)
779 const struct config *config;
781 config = config_get();
783 /* We give highest priority to IPMI-configured boot options. If
784 * we have an IPMI bootdev configuration set, then we don't allow
785 * any other defaults */
786 if (config->ipmi_bootdev) {
787 bool ipmi_match = ipmi_device_type_matches(config->ipmi_bootdev,
788 opt->device->device->type);
790 return DEFAULT_PRIORITY_REMOTE;
792 pb_debug("handler: disabled default priority due to "
793 "non-matching IPMI type %x\n",
794 config->ipmi_bootdev);
795 return DEFAULT_PRIORITY_DISABLED;
798 /* Next, try to match the option against the user-defined autoboot
799 * options, either by device UUID or type. */
800 if (config->n_autoboot_opts) {
801 int boot_match = autoboot_option_priority(config, opt);
806 /* If the option didn't match any entry in the array, it is disabled */
807 pb_debug("handler: disabled default priority due to "
808 "non-matching UUID or type\n");
809 return DEFAULT_PRIORITY_DISABLED;
812 static void set_default(struct device_handler *handler,
813 struct discover_boot_option *opt)
815 enum default_priority cur_prio, new_prio;
817 if (!handler->autoboot_enabled)
820 pb_debug("handler: new default option: %s\n", opt->option->id);
822 new_prio = default_option_priority(opt);
824 /* Anything outside our range prevents a default boot */
825 if (new_prio >= DEFAULT_PRIORITY_DISABLED)
828 pb_debug("handler: calculated priority %d\n", new_prio);
830 /* Resolve any conflicts: if we have a new default option, it only
831 * replaces the current if it has a higher priority. */
832 if (handler->default_boot_option) {
834 cur_prio = handler->default_boot_option_priority;
836 if (new_prio < cur_prio) {
837 pb_log("handler: new prio %d beats "
838 "old prio %d for %s\n",
840 handler->default_boot_option
842 handler->default_boot_option = opt;
843 handler->default_boot_option_priority = new_prio;
844 /* extend the timeout a little, so the user sees some
845 * indication of the change */
846 handler->sec_to_boot += 2;
852 handler->sec_to_boot = config_get()->autoboot_timeout_sec;
853 handler->default_boot_option = opt;
854 handler->default_boot_option_priority = new_prio;
856 pb_log("handler: boot option %s set as default, timeout %u sec.\n",
857 opt->option->id, handler->sec_to_boot);
859 default_timeout(handler);
862 static bool resource_is_resolved(struct resource *res)
864 return !res || res->resolved;
867 /* We only use this in an assert, which will disappear if we're compiling
868 * with NDEBUG, so we need the 'used' attribute for these builds */
869 static bool __attribute__((used)) boot_option_is_resolved(
870 struct discover_boot_option *opt)
872 return resource_is_resolved(opt->boot_image) &&
873 resource_is_resolved(opt->initrd) &&
874 resource_is_resolved(opt->dtb) &&
875 resource_is_resolved(opt->args_sig_file) &&
876 resource_is_resolved(opt->icon);
879 static bool resource_resolve(struct resource *res, const char *name,
880 struct discover_boot_option *opt,
881 struct device_handler *handler)
883 struct parser *parser = opt->source;
885 if (resource_is_resolved(res))
888 pb_debug("Attempting to resolve resource %s->%s with parser %s\n",
889 opt->option->id, name, parser->name);
890 parser->resolve_resource(handler, res);
892 return res->resolved;
895 static bool boot_option_resolve(struct discover_boot_option *opt,
896 struct device_handler *handler)
898 return resource_resolve(opt->boot_image, "boot_image", opt, handler) &&
899 resource_resolve(opt->initrd, "initrd", opt, handler) &&
900 resource_resolve(opt->dtb, "dtb", opt, handler) &&
901 resource_resolve(opt->args_sig_file, "args_sig_file", opt,
903 resource_resolve(opt->icon, "icon", opt, handler);
906 static void boot_option_finalise(struct device_handler *handler,
907 struct discover_boot_option *opt)
909 assert(boot_option_is_resolved(opt));
911 /* check that the parsers haven't set any of the final data */
912 assert(!opt->option->boot_image_file);
913 assert(!opt->option->initrd_file);
914 assert(!opt->option->dtb_file);
915 assert(!opt->option->icon_file);
916 assert(!opt->option->device_id);
917 assert(!opt->option->args_sig_file);
920 opt->option->boot_image_file = opt->boot_image->url->full;
922 opt->option->initrd_file = opt->initrd->url->full;
924 opt->option->dtb_file = opt->dtb->url->full;
926 opt->option->icon_file = opt->icon->url->full;
927 if (opt->args_sig_file)
928 opt->option->args_sig_file = opt->args_sig_file->url->full;
930 opt->option->device_id = opt->device->device->id;
932 if (opt->option->is_default)
933 set_default(handler, opt);
936 static void notify_boot_option(struct device_handler *handler,
937 struct discover_boot_option *opt)
939 struct discover_device *dev = opt->device;
942 discover_server_notify_device_add(handler->server,
943 opt->device->device);
944 dev->notified = true;
945 discover_server_notify_boot_option_add(handler->server, opt->option);
948 static void process_boot_option_queue(struct device_handler *handler)
950 struct discover_boot_option *opt, *tmp;
952 list_for_each_entry_safe(&handler->unresolved_boot_options,
955 pb_debug("queue: attempting resolution for %s\n",
958 if (!boot_option_resolve(opt, handler))
961 pb_debug("\tresolved!\n");
963 list_remove(&opt->list);
964 list_add_tail(&opt->device->boot_options, &opt->list);
965 talloc_steal(opt->device, opt);
966 boot_option_finalise(handler, opt);
967 notify_boot_option(handler, opt);
971 struct discover_context *device_handler_discover_context_create(
972 struct device_handler *handler,
973 struct discover_device *device)
975 struct discover_context *ctx;
977 ctx = talloc_zero(handler, struct discover_context);
978 ctx->handler = handler;
979 ctx->device = device;
980 list_init(&ctx->boot_options);
985 void device_handler_add_device(struct device_handler *handler,
986 struct discover_device *device)
988 handler->n_devices++;
989 handler->devices = talloc_realloc(handler, handler->devices,
990 struct discover_device *, handler->n_devices);
991 handler->devices[handler->n_devices - 1] = device;
993 if (device->device->type == DEVICE_TYPE_NETWORK)
994 network_register_device(handler->network, device);
997 void device_handler_add_ramdisk(struct device_handler *handler,
1000 struct ramdisk_device *dev;
1006 for (i = 0; i < handler->n_ramdisks; i++)
1007 if (!strcmp(handler->ramdisks[i]->path, path))
1010 dev = talloc_zero(handler, struct ramdisk_device);
1012 pb_log("Failed to allocate memory to track %s\n", path);
1016 dev->path = talloc_strdup(handler, path);
1018 handler->ramdisks = talloc_realloc(handler, handler->ramdisks,
1019 struct ramdisk_device *,
1020 handler->n_ramdisks + 1);
1021 if (!handler->ramdisks) {
1022 pb_log("Failed to reallocate memory"
1023 "- ramdisk tracking inconsistent!\n");
1027 handler->ramdisks[i] = dev;
1028 i = handler->n_ramdisks++;
1031 struct ramdisk_device *device_handler_get_ramdisk(
1032 struct device_handler *handler)
1038 /* Check if free ramdisk exists */
1039 for (i = 0; i < handler->n_ramdisks; i++)
1040 if (!handler->ramdisks[i]->snapshot &&
1041 !handler->ramdisks[i]->origin &&
1042 !handler->ramdisks[i]->base)
1043 return handler->ramdisks[i];
1045 /* Otherwise create a new one */
1046 name = talloc_asprintf(handler, "/dev/ram%d",
1047 handler->n_ramdisks);
1049 pb_debug("Failed to allocate memory to name /dev/ram%d",
1050 handler->n_ramdisks);
1054 id = makedev(1, handler->n_ramdisks);
1055 if (mknod(name, S_IFBLK, id)) {
1056 if (errno == EEXIST) {
1057 /* We haven't yet received updates for existing
1058 * ramdisks - add and use this one */
1059 pb_debug("Using untracked ramdisk %s\n", name);
1061 pb_log("Failed to create new ramdisk %s: %s\n",
1062 name, strerror(errno));
1066 device_handler_add_ramdisk(handler, name);
1069 return handler->ramdisks[i];
1072 void device_handler_release_ramdisk(struct discover_device *device)
1074 struct ramdisk_device *ramdisk = device->ramdisk;
1076 talloc_free(ramdisk->snapshot);
1077 talloc_free(ramdisk->origin);
1078 talloc_free(ramdisk->base);
1080 ramdisk->snapshot = ramdisk->origin = ramdisk->base = NULL;
1081 ramdisk->sectors = 0;
1083 device->ramdisk = NULL;
1086 /* Start discovery on a hotplugged device. The device will be in our devices
1087 * array, but has only just been initialised by the hotplug source.
1089 int device_handler_discover(struct device_handler *handler,
1090 struct discover_device *dev)
1092 struct discover_context *ctx;
1095 device_handler_status_dev_info(handler, dev,
1097 * TRANSLATORS: this string will be passed the type of the
1098 * device (eg "disk" or "network"), which will be translated
1101 _("Processing new %s device"),
1102 device_type_display_name(dev->device->type));
1104 /* create our context */
1105 ctx = device_handler_discover_context_create(handler, dev);
1107 rc = mount_device(dev);
1111 /* add this device to our system info */
1112 system_info_register_blockdev(dev->device->id, dev->uuid,
1115 /* run the parsers. This will populate the ctx's boot_option list. */
1116 iterate_parsers(ctx);
1118 /* add discovered stuff to the handler */
1119 device_handler_discover_context_commit(handler, ctx);
1121 process_boot_option_queue(handler);
1123 /* Check this device for pb-plugins */
1124 device_handler_plugin_scan_device(handler, dev);
1126 talloc_unlink(handler, ctx);
1131 /* Incoming dhcp event */
1132 int device_handler_dhcp(struct device_handler *handler,
1133 struct discover_device *dev, struct event *event)
1135 struct discover_context *ctx;
1137 device_handler_status_dev_info(handler, dev,
1138 _("Processing DHCP lease response (ip: %s)"),
1139 event_get_param(event, "ip"));
1141 pending_network_jobs_start();
1143 /* create our context */
1144 ctx = device_handler_discover_context_create(handler, dev);
1145 talloc_steal(ctx, event);
1148 iterate_parsers(ctx);
1150 device_handler_discover_context_commit(handler, ctx);
1152 talloc_unlink(handler, ctx);
1157 static struct discover_boot_option *find_boot_option_by_id(
1158 struct device_handler *handler, const char *id)
1162 for (i = 0; i < handler->n_devices; i++) {
1163 struct discover_device *dev = handler->devices[i];
1164 struct discover_boot_option *opt;
1166 list_for_each_entry(&dev->boot_options, opt, list)
1167 if (!strcmp(opt->option->id, id))
1174 void device_handler_boot(struct device_handler *handler,
1175 struct boot_command *cmd)
1177 struct discover_boot_option *opt = NULL;
1179 if (cmd->option_id && strlen(cmd->option_id))
1180 opt = find_boot_option_by_id(handler, cmd->option_id);
1182 if (handler->pending_boot)
1183 boot_cancel(handler->pending_boot);
1185 platform_pre_boot();
1187 handler->pending_boot = boot(handler, opt, cmd, handler->dry_run,
1188 device_handler_boot_status_cb, handler);
1189 handler->pending_boot_is_default = false;
1192 void device_handler_cancel_default(struct device_handler *handler)
1194 if (handler->timeout_waiter)
1195 waiter_remove(handler->timeout_waiter);
1197 handler->timeout_waiter = NULL;
1198 handler->autoboot_enabled = false;
1200 /* we only send status if we had a default boot option queued */
1201 if (!handler->default_boot_option)
1204 pb_log("Cancelling default boot option\n");
1206 if (handler->pending_boot && handler->pending_boot_is_default) {
1207 boot_cancel(handler->pending_boot);
1208 handler->pending_boot = NULL;
1209 handler->pending_boot_is_default = false;
1212 handler->default_boot_option = NULL;
1214 device_handler_status_info(handler, _("Default boot cancelled"));
1217 void device_handler_update_config(struct device_handler *handler,
1218 struct config *config)
1222 rc = config_set(config);
1226 discover_server_notify_config(handler->server, config);
1227 device_handler_update_lang(config->lang);
1228 device_handler_reinit(handler);
1231 static char *device_from_addr(void *ctx, struct pb_url *url)
1233 char *ipaddr, *buf, *tok, *dev = NULL;
1234 const char *delim = " ";
1235 struct sockaddr_in *ip;
1236 struct sockaddr_in si;
1237 struct addrinfo *res;
1241 /* Note: IPv4 only */
1242 rc = inet_pton(AF_INET, url->host, &(si.sin_addr));
1246 /* need to turn hostname into a valid IP */
1247 rc = getaddrinfo(url->host, NULL, NULL, &res);
1249 pb_debug("%s: Invalid URL\n",__func__);
1252 ipaddr = talloc_array(ctx,char,INET_ADDRSTRLEN);
1253 ip = (struct sockaddr_in *) res->ai_addr;
1254 inet_ntop(AF_INET, &(ip->sin_addr), ipaddr, INET_ADDRSTRLEN);
1258 const char *argv[] = {
1260 "route", "show", "to", "match",
1265 p = process_create(ctx);
1267 p->path = pb_system_apps.ip;
1269 p->keep_stdout = true;
1271 rc = process_run_sync(p);
1273 if (rc || p->exit_status) {
1274 /* ip has complained for some reason; most likely
1275 * there is no route to the host - bail out */
1276 pb_debug("%s: `ip` returns non-zero exit status\n", __func__);
1277 pb_debug("ip buf: %s\n", p->stdout_buf);
1282 buf = p->stdout_buf;
1283 /* If a route is found, ip-route output will be of the form
1284 * "... dev DEVNAME ... " */
1285 tok = strtok(buf, delim);
1287 if (!strcmp(tok, "dev")) {
1288 tok = strtok(NULL, delim);
1289 dev = talloc_strdup(ctx, tok);
1292 tok = strtok(NULL, delim);
1297 pb_debug("%s: Found interface '%s'\n", __func__,dev);
1301 static void process_url_cb(struct load_url_result *result, void *data)
1303 struct device_handler *handler;
1304 struct discover_context *ctx;
1305 struct discover_device *dev;
1306 struct event *event = data;
1309 if (result->status != LOAD_OK) {
1310 pb_log("%s: Load failed for %s\n", __func__, result->url->full);
1317 handler = talloc_parent(event);
1321 event->device = device_from_addr(event, result->url);
1322 if (!event->device) {
1323 pb_log("Downloaded a file but can't find its interface - pretending it was local\n");
1324 event->device = talloc_asprintf(event, "local");
1327 mac = event_get_param(event, "mac");
1328 char *url = talloc_asprintf(event, "file://%s", result->local);
1329 event_set_param(event, "pxeconffile", url);
1331 dev = discover_device_create(handler, mac, event->device);
1332 ctx = device_handler_discover_context_create(handler, dev);
1333 talloc_steal(ctx, event);
1336 iterate_parsers(ctx);
1338 device_handler_discover_context_commit(handler, ctx);
1340 talloc_unlink(handler, ctx);
1343 void device_handler_process_url(struct device_handler *handler,
1344 const char *url, const char *mac, const char *ip)
1346 struct discover_context *ctx;
1347 struct discover_device *dev;
1348 bool allow_async = false;
1349 struct pb_url *pb_url;
1350 struct event *event;
1352 event = talloc_zero(handler, struct event);
1353 event->type = EVENT_TYPE_USER;
1354 event->action = EVENT_ACTION_URL;
1356 pb_url = pb_url_parse(event, url);
1357 if (!pb_url || (pb_url->scheme != pb_url_file && !pb_url->host)) {
1358 device_handler_status_err(handler, _("Invalid config URL!"));
1363 if (url[strlen(url) - 1] == '/') {
1364 event_set_param(event, "pxepathprefix", url);
1365 event_set_param(event, "mac", mac);
1366 event_set_param(event, "ip", ip);
1367 event->device = device_from_addr(event, pb_url);
1368 if (!event->device) {
1369 device_handler_status_err(handler,
1370 _("Unable to route to host %s"),
1376 event_set_param(event, "pxeconffile", url);
1380 if (pb_url->scheme == pb_url_file)
1381 event->device = talloc_asprintf(event, "local");
1382 else if (allow_async) {
1383 /* If file is remote load asynchronously before passing to
1384 * parser. This allows us to wait for network to be available */
1385 if (!load_url_async(handler, pb_url, process_url_cb, event,
1387 pb_log("Failed to load url %s\n", pb_url->full);
1388 device_handler_status_err(handler, _("Failed to load URL!"));
1394 /* If path is local we can parse straight away */
1396 dev = discover_device_create(handler, mac, event->device);
1397 if (pb_url->scheme == pb_url_file)
1398 dev->device->type = DEVICE_TYPE_ANY;
1399 ctx = device_handler_discover_context_create(handler, dev);
1400 talloc_steal(ctx, event);
1403 iterate_parsers(ctx);
1405 device_handler_discover_context_commit(handler, ctx);
1407 talloc_unlink(handler, ctx);
1410 static void plugin_install_cb(struct process *process)
1412 struct device_handler *handler = process->data;
1415 pb_log("%s: Missing data!\n", __func__);
1419 handler->plugin_installing = false;
1420 if (process->exit_status) {
1421 device_handler_status_err(handler, "Plugin failed to install!");
1422 pb_log("Failed to install plugin:\n%s\n", process->stdout_buf);
1426 void device_handler_install_plugin(struct device_handler *handler,
1427 const char *plugin_file)
1432 if (handler->plugin_installing) {
1433 pb_log("Plugin install cancelled - install already running");
1437 p = process_create(handler);
1439 pb_log("install_plugin: Failed to create process\n");
1443 const char *argv[] = {
1444 pb_system_apps.pb_plugin,
1451 p->path = pb_system_apps.pb_plugin;
1453 p->exit_cb = plugin_install_cb;
1455 p->keep_stdout = true;
1457 result = process_run_async(p);
1460 device_handler_status_err(handler, "Could not install plugin");
1462 handler->plugin_installing = true;
1465 #ifndef PETITBOOT_TEST
1468 * context_commit - Commit a temporary discovery context to the handler,
1469 * and notify the clients about any new options / devices
1471 void device_handler_discover_context_commit(struct device_handler *handler,
1472 struct discover_context *ctx)
1474 struct discover_device *dev = ctx->device;
1475 struct discover_boot_option *opt, *tmp;
1477 if (!device_lookup_by_uuid(handler, dev->uuid))
1478 device_handler_add_device(handler, dev);
1480 /* move boot options from the context to the device */
1481 list_for_each_entry_safe(&ctx->boot_options, opt, tmp, list) {
1482 list_remove(&opt->list);
1484 /* All boot options need at least a kernel image */
1485 if (!opt->boot_image || !opt->boot_image->url) {
1486 pb_log("boot option %s is missing boot image, ignoring\n",
1492 if (boot_option_resolve(opt, handler)) {
1493 pb_log("boot option %s is resolved, "
1494 "sending to clients\n",
1496 list_add_tail(&dev->boot_options, &opt->list);
1497 talloc_steal(dev, opt);
1498 boot_option_finalise(handler, opt);
1499 notify_boot_option(handler, opt);
1501 if (!opt->source->resolve_resource) {
1502 pb_log("parser %s gave us an unresolved "
1503 "resource (%s), but no way to "
1505 opt->source->name, opt->option->id);
1508 pb_log("boot option %s is unresolved, "
1509 "adding to queue\n",
1511 list_add(&handler->unresolved_boot_options,
1513 talloc_steal(handler, opt);
1519 void device_handler_add_plugin_option(struct device_handler *handler,
1520 struct plugin_option *opt)
1522 struct plugin_option *tmp;
1525 for (i = 0; i < handler->n_plugins; i++) {
1526 tmp = handler->plugins[i];
1527 /* If both id and version match, ignore */
1528 if (strncmp(opt->id, tmp->id, strlen(opt->id)) == 0 &&
1529 strncmp(opt->version, tmp->version,
1530 strlen(opt->version) == 0)) {
1531 pb_log("discover: Plugin '%s' already exists, ignoring\n",
1537 handler->plugins = talloc_realloc(handler, handler->plugins,
1538 struct plugin_option *, handler->n_plugins + 1);
1539 if (!handler->plugins) {
1540 pb_log("Failed to allocate memory for new plugin\n");
1541 handler->n_plugins = 0;
1545 handler->plugins[handler->n_plugins++] = opt;
1546 discover_server_notify_plugin_option_add(handler->server, opt);
1549 static void device_handler_update_lang(const char *lang)
1551 const char *cur_lang;
1556 cur_lang = setlocale(LC_ALL, NULL);
1557 if (cur_lang && !strcmp(cur_lang, lang))
1560 setlocale(LC_ALL, lang);
1563 static int device_handler_init_sources(struct device_handler *handler)
1565 /* init our device sources: udev, network and user events */
1566 handler->user_event = user_event_init(handler, handler->waitset);
1567 if (!handler->user_event)
1570 handler->network = network_init(handler, handler->waitset,
1572 if (!handler->network)
1575 handler->udev = udev_init(handler, handler->waitset);
1582 static void device_handler_reinit_sources(struct device_handler *handler)
1584 /* if we haven't initialised sources previously (becuase we started in
1585 * safe mode), then init once here. */
1586 if (!(handler->udev || handler->network || handler->user_event)) {
1587 device_handler_init_sources(handler);
1591 system_info_reinit();
1593 network_shutdown(handler->network);
1594 handler->network = network_init(handler, handler->waitset,
1597 udev_reinit(handler->udev);
1600 static inline const char *get_device_path(struct discover_device *dev)
1602 return dev->ramdisk ? dev->ramdisk->snapshot : dev->device_path;
1605 static char *check_subvols(struct discover_device *dev)
1607 const char *fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1612 if (strncmp(fstype, "btrfs", strlen("btrfs")))
1613 return dev->mount_path;
1615 /* On btrfs a device's root may be under a subvolume path */
1616 path = join_paths(dev, dev->mount_path, "@");
1617 rc = stat(path, &sb);
1618 if (!rc && S_ISDIR(sb.st_mode)) {
1619 pb_debug("Using '%s' for btrfs root path\n", path);
1624 return dev->mount_path;
1627 static bool check_existing_mount(struct discover_device *dev)
1629 struct stat devstat, mntstat;
1630 const char *device_path;
1635 device_path = get_device_path(dev);
1637 rc = stat(device_path, &devstat);
1639 pb_debug("%s: stat failed: %s\n", __func__, strerror(errno));
1643 if (!S_ISBLK(devstat.st_mode)) {
1644 pb_debug("%s: %s isn't a block device?\n", __func__,
1649 fp = fopen("/proc/self/mounts", "r");
1652 mnt = getmntent(fp);
1656 if (!mnt->mnt_fsname || mnt->mnt_fsname[0] != '/')
1659 rc = stat(mnt->mnt_fsname, &mntstat);
1663 if (!S_ISBLK(mntstat.st_mode))
1666 if (mntstat.st_rdev == devstat.st_rdev) {
1667 dev->mount_path = talloc_strdup(dev, mnt->mnt_dir);
1668 dev->root_path = check_subvols(dev);
1669 dev->mounted_rw = !!hasmntopt(mnt, "rw");
1670 dev->mounted = true;
1671 dev->unmount = false;
1673 pb_debug("%s: %s is already mounted (r%c) at %s\n",
1674 __func__, dev->device_path,
1675 dev->mounted_rw ? 'w' : 'o',
1687 * Attempt to mount a filesystem safely, while handling certain filesytem-
1690 static int try_mount(const char *device_path, const char *mount_path,
1691 const char *fstype, unsigned long flags,
1694 const char *fs, *safe_opts;
1697 /* Mount ext3 as ext4 instead so 'norecovery' can be used */
1698 if (strncmp(fstype, "ext3", strlen("ext3")) == 0) {
1699 pb_debug("Mounting ext3 filesystem as ext4\n");
1704 if (strncmp(fs, "xfs", strlen("xfs")) == 0 ||
1705 strncmp(fs, "ext4", strlen("ext4")) == 0)
1706 safe_opts = "norecovery";
1711 /* If no snapshot is available don't attempt recovery */
1713 return mount(device_path, mount_path, fs, flags, safe_opts);
1715 rc = mount(device_path, mount_path, fs, flags, NULL);
1720 /* Mounting failed; some filesystems will fail to mount if a recovery
1721 * journal exists (eg. cross-endian XFS), so try again with norecovery
1722 * where that option is available.
1723 * If mounting read-write just return the error as norecovery is not a
1725 if ((flags & MS_RDONLY) != MS_RDONLY || !safe_opts)
1729 return mount(device_path, mount_path, fs, flags, safe_opts);
1732 static int mount_device(struct discover_device *dev)
1734 const char *fstype, *device_path;
1737 if (!dev->device_path)
1743 if (check_existing_mount(dev))
1746 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1750 dev->mount_path = join_paths(dev, mount_base(),
1753 if (pb_mkdir_recursive(dev->mount_path)) {
1754 pb_log("couldn't create mount directory %s: %s\n",
1755 dev->mount_path, strerror(errno));
1759 device_path = get_device_path(dev);
1761 pb_log("mounting device %s read-only\n", dev->device_path);
1762 rc = try_mount(device_path, dev->mount_path, fstype,
1763 MS_RDONLY | MS_SILENT, dev->ramdisk);
1766 dev->mounted = true;
1767 dev->mounted_rw = false;
1768 dev->unmount = true;
1769 dev->root_path = check_subvols(dev);
1773 pb_log("couldn't mount device %s: mount failed: %s\n",
1774 device_path, strerror(errno));
1776 /* If mount fails clean up any snapshot */
1777 devmapper_destroy_snapshot(dev);
1779 pb_rmdir_recursive(mount_base(), dev->mount_path);
1781 talloc_free(dev->mount_path);
1782 dev->mount_path = NULL;
1786 static int umount_device(struct discover_device *dev)
1788 const char *device_path;
1791 if (!dev->mounted || !dev->unmount)
1794 device_path = get_device_path(dev);
1796 pb_log("unmounting device %s\n", device_path);
1797 rc = umount(dev->mount_path);
1801 dev->mounted = false;
1802 devmapper_destroy_snapshot(dev);
1804 pb_rmdir_recursive(mount_base(), dev->mount_path);
1806 talloc_free(dev->mount_path);
1807 dev->mount_path = NULL;
1808 dev->root_path = NULL;
1813 int device_request_write(struct discover_device *dev, bool *release)
1815 const char *fstype, *device_path;
1816 const struct config *config;
1821 config = config_get();
1822 if (!config->allow_writes)
1828 if (dev->mounted_rw)
1831 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1833 device_path = get_device_path(dev);
1835 pb_log("remounting device %s read-write\n", device_path);
1837 rc = umount(dev->mount_path);
1839 pb_log("Failed to unmount %s: %s\n",
1840 dev->mount_path, strerror(errno));
1844 rc = try_mount(device_path, dev->mount_path, fstype,
1845 MS_SILENT, dev->ramdisk);
1849 dev->mounted_rw = true;
1854 pb_log("Unable to remount device %s read-write: %s\n",
1855 device_path, strerror(errno));
1856 rc = try_mount(device_path, dev->mount_path, fstype,
1857 MS_RDONLY | MS_SILENT, dev->ramdisk);
1859 pb_log("Unable to recover mount for %s: %s\n",
1860 device_path, strerror(errno));
1864 void device_release_write(struct discover_device *dev, bool release)
1866 const char *fstype, *device_path;
1871 device_path = get_device_path(dev);
1873 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1875 pb_log("remounting device %s read-only\n", device_path);
1877 if (umount(dev->mount_path)) {
1878 pb_log("Failed to unmount %s\n", dev->mount_path);
1881 dev->mounted_rw = dev->mounted = false;
1884 devmapper_merge_snapshot(dev);
1885 /* device_path becomes stale after merge */
1886 device_path = get_device_path(dev);
1889 if (try_mount(device_path, dev->mount_path, fstype,
1890 MS_RDONLY | MS_SILENT, dev->ramdisk))
1891 pb_log("Failed to remount %s read-only: %s\n",
1892 device_path, strerror(errno));
1894 dev->mounted = true;
1897 void device_sync_snapshots(struct device_handler *handler, const char *device)
1899 struct discover_device *dev = NULL;
1903 /* Find matching device and sync */
1904 dev = device_lookup_by_name(handler, device);
1906 pb_log("%s: device name '%s' unrecognised\n",
1911 device_release_write(dev, true);
1913 pb_log("%s has no snapshot to merge, skipping\n",
1918 /* Otherwise sync all relevant devices */
1919 for (i = 0; i < handler->n_devices; i++) {
1920 dev = handler->devices[i];
1921 if (dev->device->type != DEVICE_TYPE_DISK &&
1922 dev->device->type != DEVICE_TYPE_USB)
1925 device_release_write(dev, true);
1927 pb_log("%s has no snapshot to merge, skipping\n",
1934 void device_handler_discover_context_commit(
1935 struct device_handler *handler __attribute__((unused)),
1936 struct discover_context *ctx __attribute__((unused)))
1938 pb_log("%s stubbed out for test cases\n", __func__);
1941 static void device_handler_update_lang(const char *lang __attribute__((unused)))
1945 static int device_handler_init_sources(
1946 struct device_handler *handler __attribute__((unused)))
1951 static void device_handler_reinit_sources(
1952 struct device_handler *handler __attribute__((unused)))
1956 static int umount_device(struct discover_device *dev __attribute__((unused)))
1961 static int __attribute__((unused)) mount_device(
1962 struct discover_device *dev __attribute__((unused)))
1967 int device_request_write(struct discover_device *dev __attribute__((unused)),
1974 void device_release_write(struct discover_device *dev __attribute__((unused)),
1975 bool release __attribute__((unused)))
1979 void device_sync_snapshots(
1980 struct device_handler *handler __attribute__((unused)),
1981 const char *device __attribute__((unused)))