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;
92 static int mount_device(struct discover_device *dev);
93 static int umount_device(struct discover_device *dev);
95 static int device_handler_init_sources(struct device_handler *handler);
96 static void device_handler_reinit_sources(struct device_handler *handler);
98 static void device_handler_update_lang(const char *lang);
100 void discover_context_add_boot_option(struct discover_context *ctx,
101 struct discover_boot_option *boot_option)
103 boot_option->source = ctx->parser;
104 list_add_tail(&ctx->boot_options, &boot_option->list);
105 talloc_steal(ctx, boot_option);
109 * device_handler_get_device_count - Get the count of current handler devices.
112 int device_handler_get_device_count(const struct device_handler *handler)
114 return handler->n_devices;
118 * device_handler_get_device - Get a handler device by index.
121 const struct discover_device *device_handler_get_device(
122 const struct device_handler *handler, unsigned int index)
124 if (index >= handler->n_devices) {
125 assert(0 && "bad index");
129 return handler->devices[index];
133 * device_handler_get_plugin_count - Get the count of current handler plugins.
135 int device_handler_get_plugin_count(const struct device_handler *handler)
137 return handler->n_plugins;
141 * discover_handler_get_plugin - Get a handler plugin by index.
143 const struct plugin_option *device_handler_get_plugin(
144 const struct device_handler *handler, unsigned int index)
146 if (index >= handler->n_plugins) {
147 assert(0 && "bad index");
151 return handler->plugins[index];
154 struct network *device_handler_get_network(
155 const struct device_handler *handler)
157 return handler->network;
160 struct discover_boot_option *discover_boot_option_create(
161 struct discover_context *ctx,
162 struct discover_device *device)
164 struct discover_boot_option *opt;
166 opt = talloc_zero(ctx, struct discover_boot_option);
167 opt->option = talloc_zero(opt, struct boot_option);
168 opt->device = device;
173 static int device_match_uuid(struct discover_device *dev, const char *uuid)
175 return dev->uuid && !strcmp(dev->uuid, uuid);
178 static int device_match_label(struct discover_device *dev, const char *label)
180 return dev->label && !strcmp(dev->label, label);
183 static int device_match_id(struct discover_device *dev, const char *id)
185 return !strcmp(dev->device->id, id);
188 static int device_match_serial(struct discover_device *dev, const char *serial)
190 const char *val = discover_device_get_param(dev, "ID_SERIAL");
191 return val && !strcmp(val, serial);
194 static struct discover_device *device_lookup(
195 struct device_handler *device_handler,
196 int (match_fn)(struct discover_device *, const char *),
199 struct discover_device *dev;
205 for (i = 0; i < device_handler->n_devices; i++) {
206 dev = device_handler->devices[i];
208 if (match_fn(dev, str))
215 struct discover_device *device_lookup_by_name(struct device_handler *handler,
218 if (!strncmp(name, "/dev/", strlen("/dev/")))
219 name += strlen("/dev/");
221 return device_lookup_by_id(handler, name);
224 struct discover_device *device_lookup_by_uuid(
225 struct device_handler *device_handler,
228 return device_lookup(device_handler, device_match_uuid, uuid);
231 struct discover_device *device_lookup_by_label(
232 struct device_handler *device_handler,
235 return device_lookup(device_handler, device_match_label, label);
238 struct discover_device *device_lookup_by_id(
239 struct device_handler *device_handler,
242 return device_lookup(device_handler, device_match_id, id);
245 struct discover_device *device_lookup_by_serial(
246 struct device_handler *device_handler,
249 return device_lookup(device_handler, device_match_serial, serial);
252 void device_handler_destroy(struct device_handler *handler)
254 talloc_free(handler);
257 static int destroy_device(void *arg)
259 struct discover_device *dev = arg;
266 struct discover_device *discover_device_create(struct device_handler *handler,
267 const char *uuid, const char *id)
269 struct discover_device *dev;
272 dev = device_lookup_by_uuid(handler, uuid);
274 dev = device_lookup_by_id(handler, id);
279 dev = talloc_zero(handler, struct discover_device);
280 dev->device = talloc_zero(dev, struct device);
281 dev->device->id = talloc_strdup(dev->device, id);
282 dev->uuid = talloc_strdup(dev, uuid);
283 list_init(&dev->params);
284 list_init(&dev->boot_options);
286 talloc_set_destructor(dev, destroy_device);
291 struct discover_device_param {
294 struct list_item list;
297 void discover_device_set_param(struct discover_device *device,
298 const char *name, const char *value)
300 struct discover_device_param *param;
303 list_for_each_entry(&device->params, param, list) {
304 if (!strcmp(param->name, name)) {
313 param = talloc(device, struct discover_device_param);
314 param->name = talloc_strdup(param, name);
315 list_add(&device->params, ¶m->list);
318 list_remove(¶m->list);
322 talloc_free(param->value);
325 param->value = talloc_strdup(param, value);
328 const char *discover_device_get_param(struct discover_device *device,
331 struct discover_device_param *param;
333 list_for_each_entry(&device->params, param, list) {
334 if (!strcmp(param->name, name))
340 struct device_handler *device_handler_init(struct discover_server *server,
341 struct waitset *waitset, int dry_run)
343 struct device_handler *handler;
346 handler = talloc_zero(NULL, struct device_handler);
347 handler->server = server;
348 handler->waitset = waitset;
349 handler->dry_run = dry_run;
350 handler->autoboot_enabled = config_autoboot_active(config_get());
352 list_init(&handler->unresolved_boot_options);
354 list_init(&handler->progress);
356 /* set up our mount point base */
357 pb_mkdir_recursive(mount_base());
361 if (config_get()->safe_mode)
364 rc = device_handler_init_sources(handler);
366 talloc_free(handler);
373 void device_handler_reinit(struct device_handler *handler)
375 struct discover_boot_option *opt, *tmp;
376 struct ramdisk_device *ramdisk;
379 device_handler_cancel_default(handler);
380 /* Cancel any pending non-default boot */
381 if (handler->pending_boot) {
382 boot_cancel(handler->pending_boot);
383 handler->pending_boot = NULL;
384 handler->pending_boot_is_default = false;
387 /* Cancel any remaining async jobs */
388 process_stop_async_all();
389 pending_network_jobs_cancel();
391 /* free unresolved boot options */
392 list_for_each_entry_safe(&handler->unresolved_boot_options,
395 list_init(&handler->unresolved_boot_options);
397 /* drop all devices */
398 for (i = 0; i < handler->n_devices; i++) {
399 discover_server_notify_device_remove(handler->server,
400 handler->devices[i]->device);
401 ramdisk = handler->devices[i]->ramdisk;
402 talloc_free(handler->devices[i]);
403 talloc_free(ramdisk);
406 talloc_free(handler->devices);
407 handler->devices = NULL;
408 handler->n_devices = 0;
409 talloc_free(handler->ramdisks);
410 handler->ramdisks = NULL;
411 handler->n_ramdisks = 0;
413 /* drop any known plugins */
414 for (i = 0; i < handler->n_plugins; i++)
415 talloc_free(handler->plugins[i]);
416 talloc_free(handler->plugins);
417 handler->plugins = NULL;
418 handler->n_plugins = 0;
420 discover_server_notify_plugins_remove(handler->server);
422 device_handler_reinit_sources(handler);
425 void device_handler_remove(struct device_handler *handler,
426 struct discover_device *device)
428 struct discover_boot_option *opt, *tmp;
431 list_for_each_entry_safe(&device->boot_options, opt, tmp, list) {
432 if (opt == handler->default_boot_option) {
433 pb_log("Default option %s cancelled since device removed",
435 device_handler_cancel_default(handler);
440 for (i = 0; i < handler->n_devices; i++)
441 if (handler->devices[i] == device)
444 if (i == handler->n_devices) {
449 /* Free any unresolved options, as they're currently allocated
450 * against the handler */
451 list_for_each_entry_safe(&handler->unresolved_boot_options,
453 if (opt->device != device)
455 list_remove(&opt->list);
459 /* if this is a network device, we have to unregister it from the
461 if (device->device->type == DEVICE_TYPE_NETWORK)
462 network_unregister_device(handler->network, device);
464 handler->n_devices--;
465 memmove(&handler->devices[i], &handler->devices[i + 1],
466 (handler->n_devices - i) * sizeof(handler->devices[0]));
467 handler->devices = talloc_realloc(handler, handler->devices,
468 struct discover_device *, handler->n_devices);
470 if (device->notified)
471 discover_server_notify_device_remove(handler->server,
477 void device_handler_status(struct device_handler *handler,
478 struct status *status)
480 discover_server_notify_boot_status(handler->server, status);
483 static void _device_handler_vstatus(struct device_handler *handler,
484 enum status_type type, const char *fmt, va_list ap)
486 struct status status;
489 status.message = talloc_vasprintf(handler, fmt, ap);
490 status.backlog = false;
492 device_handler_status(handler, &status);
494 talloc_free(status.message);
497 static void _device_handler_vdevstatus(struct device_handler *handler,
498 struct discover_device *device, enum status_type type,
499 const char *fmt, va_list ap)
503 msg = talloc_asprintf(handler, "[%s] %s",
504 device ? device->device->id : "unknown", fmt);
505 _device_handler_vstatus(handler, type, msg, ap);
509 void device_handler_status_dev_info(struct device_handler *handler,
510 struct discover_device *dev, const char *fmt, ...)
515 _device_handler_vdevstatus(handler, dev, STATUS_INFO, fmt, ap);
519 void device_handler_status_dev_err(struct device_handler *handler,
520 struct discover_device *dev, const char *fmt, ...)
525 _device_handler_vdevstatus(handler, dev, STATUS_ERROR, fmt, ap);
529 void device_handler_status_info(struct device_handler *handler,
530 const char *fmt, ...)
535 _device_handler_vstatus(handler, STATUS_INFO, fmt, ap);
539 void device_handler_status_err(struct device_handler *handler,
540 const char *fmt, ...)
545 _device_handler_vstatus(handler, STATUS_ERROR, fmt, ap);
549 void device_handler_status_download(struct device_handler *handler,
550 const struct process_info *procinfo,
551 unsigned int percentage, unsigned int size, char suffix)
553 struct progress_info *p, *progress = NULL;
554 uint64_t current_converted, current = 0;
555 const char *units = " kMGTP";
556 unsigned long size_bytes;
562 list_for_each_entry(&handler->progress, p, list)
563 if (p->procinfo == procinfo)
567 pb_log("Registering new progress struct\n");
568 progress = talloc_zero(handler, struct progress_info);
570 pb_log("Failed to allocate room for progress struct\n");
573 progress->procinfo = procinfo;
574 list_add(&handler->progress, &progress->list);
575 handler->n_progress++;
579 for (i = 0; i < strlen(units); i++) {
580 if (units[i] == suffix)
584 if (i >= strlen(units)) {
585 pb_log("Couldn't recognise suffix '%c'\n", suffix);
592 progress->percentage = percentage;
593 progress->size = size_bytes;
596 * Aggregate the info we have and update status. If a progress struct
597 * has zero for both percentage and size we assume progress information
598 * is unavailable and fall back to a generic progress message.
600 list_for_each_entry(&handler->progress, p, list) {
603 if (!p->percentage || !p->size) {
604 update = talloc_asprintf(handler,
605 _("%u downloads in progress..."),
606 handler->n_progress);
612 t = (100 * c) / p->percentage;
619 current_converted = current;
620 while (current_converted >= 1000) {
621 current_converted >>= 10;
624 update = talloc_asprintf(handler,
625 _("%u %s downloading: %.0f%% - %lu%cB"),
627 ngettext("item", "items", handler->n_progress),
628 (current / total) * 100, current_converted,
633 pb_log("%s: failed to allocate new status\n", __func__);
635 device_handler_status_info(handler, "%s\n", update);
640 void device_handler_status_download_remove(struct device_handler *handler,
641 struct process_info *procinfo)
643 struct progress_info *p, *tmp;
645 list_for_each_entry_safe(&handler->progress, p, tmp, list)
646 if (p->procinfo == procinfo) {
647 list_remove(&p->list);
649 handler->n_progress--;
653 static void device_handler_boot_status_cb(void *arg, struct status *status)
655 device_handler_status(arg, status);
658 static void countdown_status(struct device_handler *handler,
659 struct discover_boot_option *opt, unsigned int sec)
661 struct status status;
663 status.type = STATUS_INFO;
664 status.message = talloc_asprintf(handler,
665 _("Booting in %d sec: [%s] %s"), sec,
666 opt->device->device->id, opt->option->name);
667 status.backlog = false;
669 device_handler_status(handler, &status);
671 talloc_free(status.message);
674 static int default_timeout(void *arg)
676 struct device_handler *handler = arg;
677 struct discover_boot_option *opt;
679 if (!handler->default_boot_option)
682 if (handler->pending_boot)
685 opt = handler->default_boot_option;
687 if (handler->sec_to_boot) {
688 countdown_status(handler, opt, handler->sec_to_boot);
689 handler->sec_to_boot--;
690 handler->timeout_waiter = waiter_register_timeout(
691 handler->waitset, 1000,
692 default_timeout, handler);
696 handler->timeout_waiter = NULL;
698 pb_log("Timeout expired, booting default option %s\n", opt->option->id);
702 handler->pending_boot = boot(handler, handler->default_boot_option,
703 NULL, handler->dry_run, device_handler_boot_status_cb,
705 handler->pending_boot_is_default = true;
710 enum ipmi_bootdev ipmi_type;
711 enum device_type device_type;
712 } device_type_map[] = {
713 { IPMI_BOOTDEV_NETWORK, DEVICE_TYPE_NETWORK },
714 { IPMI_BOOTDEV_DISK, DEVICE_TYPE_DISK },
715 { IPMI_BOOTDEV_DISK, DEVICE_TYPE_USB },
716 { IPMI_BOOTDEV_CDROM, DEVICE_TYPE_OPTICAL },
719 static bool ipmi_device_type_matches(enum ipmi_bootdev ipmi_type,
720 enum device_type device_type)
724 for (i = 0; i < ARRAY_SIZE(device_type_map); i++) {
725 if (device_type_map[i].device_type == device_type)
726 return device_type_map[i].ipmi_type == ipmi_type;
732 static int autoboot_option_priority(const struct config *config,
733 struct discover_boot_option *opt)
735 enum device_type type = opt->device->device->type;
736 const char *uuid = opt->device->uuid;
737 struct autoboot_option *auto_opt;
740 for (i = 0; i < config->n_autoboot_opts; i++) {
741 auto_opt = &config->autoboot_opts[i];
742 if (auto_opt->boot_type == BOOT_DEVICE_UUID)
743 if (!strcmp(auto_opt->uuid, uuid))
744 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
746 if (auto_opt->boot_type == BOOT_DEVICE_TYPE)
747 if (auto_opt->type == type ||
748 auto_opt->type == DEVICE_TYPE_ANY)
749 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
756 * We have different priorities to resolve conflicts between boot options that
757 * report to be the default for their device. This function assigns a priority
760 static enum default_priority default_option_priority(
761 struct discover_boot_option *opt)
763 const struct config *config;
765 config = config_get();
767 /* We give highest priority to IPMI-configured boot options. If
768 * we have an IPMI bootdev configuration set, then we don't allow
769 * any other defaults */
770 if (config->ipmi_bootdev) {
771 bool ipmi_match = ipmi_device_type_matches(config->ipmi_bootdev,
772 opt->device->device->type);
774 return DEFAULT_PRIORITY_REMOTE;
776 pb_debug("handler: disabled default priority due to "
777 "non-matching IPMI type %x\n",
778 config->ipmi_bootdev);
779 return DEFAULT_PRIORITY_DISABLED;
782 /* Next, try to match the option against the user-defined autoboot
783 * options, either by device UUID or type. */
784 if (config->n_autoboot_opts) {
785 int boot_match = autoboot_option_priority(config, opt);
790 /* If the option didn't match any entry in the array, it is disabled */
791 pb_debug("handler: disabled default priority due to "
792 "non-matching UUID or type\n");
793 return DEFAULT_PRIORITY_DISABLED;
796 static void set_default(struct device_handler *handler,
797 struct discover_boot_option *opt)
799 enum default_priority cur_prio, new_prio;
801 if (!handler->autoboot_enabled)
804 pb_debug("handler: new default option: %s\n", opt->option->id);
806 new_prio = default_option_priority(opt);
808 /* Anything outside our range prevents a default boot */
809 if (new_prio >= DEFAULT_PRIORITY_DISABLED)
812 pb_debug("handler: calculated priority %d\n", new_prio);
814 /* Resolve any conflicts: if we have a new default option, it only
815 * replaces the current if it has a higher priority. */
816 if (handler->default_boot_option) {
818 cur_prio = handler->default_boot_option_priority;
820 if (new_prio < cur_prio) {
821 pb_log("handler: new prio %d beats "
822 "old prio %d for %s\n",
824 handler->default_boot_option
826 handler->default_boot_option = opt;
827 handler->default_boot_option_priority = new_prio;
828 /* extend the timeout a little, so the user sees some
829 * indication of the change */
830 handler->sec_to_boot += 2;
836 handler->sec_to_boot = config_get()->autoboot_timeout_sec;
837 handler->default_boot_option = opt;
838 handler->default_boot_option_priority = new_prio;
840 pb_log("handler: boot option %s set as default, timeout %u sec.\n",
841 opt->option->id, handler->sec_to_boot);
843 default_timeout(handler);
846 static bool resource_is_resolved(struct resource *res)
848 return !res || res->resolved;
851 /* We only use this in an assert, which will disappear if we're compiling
852 * with NDEBUG, so we need the 'used' attribute for these builds */
853 static bool __attribute__((used)) boot_option_is_resolved(
854 struct discover_boot_option *opt)
856 return resource_is_resolved(opt->boot_image) &&
857 resource_is_resolved(opt->initrd) &&
858 resource_is_resolved(opt->dtb) &&
859 resource_is_resolved(opt->args_sig_file) &&
860 resource_is_resolved(opt->icon);
863 static bool resource_resolve(struct resource *res, const char *name,
864 struct discover_boot_option *opt,
865 struct device_handler *handler)
867 struct parser *parser = opt->source;
869 if (resource_is_resolved(res))
872 pb_debug("Attempting to resolve resource %s->%s with parser %s\n",
873 opt->option->id, name, parser->name);
874 parser->resolve_resource(handler, res);
876 return res->resolved;
879 static bool boot_option_resolve(struct discover_boot_option *opt,
880 struct device_handler *handler)
882 return resource_resolve(opt->boot_image, "boot_image", opt, handler) &&
883 resource_resolve(opt->initrd, "initrd", opt, handler) &&
884 resource_resolve(opt->dtb, "dtb", opt, handler) &&
885 resource_resolve(opt->args_sig_file, "args_sig_file", opt,
887 resource_resolve(opt->icon, "icon", opt, handler);
890 static void boot_option_finalise(struct device_handler *handler,
891 struct discover_boot_option *opt)
893 assert(boot_option_is_resolved(opt));
895 /* check that the parsers haven't set any of the final data */
896 assert(!opt->option->boot_image_file);
897 assert(!opt->option->initrd_file);
898 assert(!opt->option->dtb_file);
899 assert(!opt->option->icon_file);
900 assert(!opt->option->device_id);
901 assert(!opt->option->args_sig_file);
904 opt->option->boot_image_file = opt->boot_image->url->full;
906 opt->option->initrd_file = opt->initrd->url->full;
908 opt->option->dtb_file = opt->dtb->url->full;
910 opt->option->icon_file = opt->icon->url->full;
911 if (opt->args_sig_file)
912 opt->option->args_sig_file = opt->args_sig_file->url->full;
914 opt->option->device_id = opt->device->device->id;
916 if (opt->option->is_default)
917 set_default(handler, opt);
920 static void notify_boot_option(struct device_handler *handler,
921 struct discover_boot_option *opt)
923 struct discover_device *dev = opt->device;
926 discover_server_notify_device_add(handler->server,
927 opt->device->device);
928 dev->notified = true;
929 discover_server_notify_boot_option_add(handler->server, opt->option);
932 static void process_boot_option_queue(struct device_handler *handler)
934 struct discover_boot_option *opt, *tmp;
936 list_for_each_entry_safe(&handler->unresolved_boot_options,
939 pb_debug("queue: attempting resolution for %s\n",
942 if (!boot_option_resolve(opt, handler))
945 pb_debug("\tresolved!\n");
947 list_remove(&opt->list);
948 list_add_tail(&opt->device->boot_options, &opt->list);
949 talloc_steal(opt->device, opt);
950 boot_option_finalise(handler, opt);
951 notify_boot_option(handler, opt);
955 struct discover_context *device_handler_discover_context_create(
956 struct device_handler *handler,
957 struct discover_device *device)
959 struct discover_context *ctx;
961 ctx = talloc_zero(handler, struct discover_context);
962 ctx->handler = handler;
963 ctx->device = device;
964 list_init(&ctx->boot_options);
969 void device_handler_add_device(struct device_handler *handler,
970 struct discover_device *device)
972 handler->n_devices++;
973 handler->devices = talloc_realloc(handler, handler->devices,
974 struct discover_device *, handler->n_devices);
975 handler->devices[handler->n_devices - 1] = device;
977 if (device->device->type == DEVICE_TYPE_NETWORK)
978 network_register_device(handler->network, device);
981 void device_handler_add_ramdisk(struct device_handler *handler,
984 struct ramdisk_device *dev;
990 for (i = 0; i < handler->n_ramdisks; i++)
991 if (!strcmp(handler->ramdisks[i]->path, path))
994 dev = talloc_zero(handler, struct ramdisk_device);
996 pb_log("Failed to allocate memory to track %s\n", path);
1000 dev->path = talloc_strdup(handler, path);
1002 handler->ramdisks = talloc_realloc(handler, handler->ramdisks,
1003 struct ramdisk_device *,
1004 handler->n_ramdisks + 1);
1005 if (!handler->ramdisks) {
1006 pb_log("Failed to reallocate memory"
1007 "- ramdisk tracking inconsistent!\n");
1011 handler->ramdisks[i] = dev;
1012 i = handler->n_ramdisks++;
1015 struct ramdisk_device *device_handler_get_ramdisk(
1016 struct device_handler *handler)
1022 /* Check if free ramdisk exists */
1023 for (i = 0; i < handler->n_ramdisks; i++)
1024 if (!handler->ramdisks[i]->snapshot &&
1025 !handler->ramdisks[i]->origin &&
1026 !handler->ramdisks[i]->base)
1027 return handler->ramdisks[i];
1029 /* Otherwise create a new one */
1030 name = talloc_asprintf(handler, "/dev/ram%d",
1031 handler->n_ramdisks);
1033 pb_debug("Failed to allocate memory to name /dev/ram%d",
1034 handler->n_ramdisks);
1038 id = makedev(1, handler->n_ramdisks);
1039 if (mknod(name, S_IFBLK, id)) {
1040 if (errno == EEXIST) {
1041 /* We haven't yet received updates for existing
1042 * ramdisks - add and use this one */
1043 pb_debug("Using untracked ramdisk %s\n", name);
1045 pb_log("Failed to create new ramdisk %s: %s\n",
1046 name, strerror(errno));
1050 device_handler_add_ramdisk(handler, name);
1053 return handler->ramdisks[i];
1056 void device_handler_release_ramdisk(struct discover_device *device)
1058 struct ramdisk_device *ramdisk = device->ramdisk;
1060 talloc_free(ramdisk->snapshot);
1061 talloc_free(ramdisk->origin);
1062 talloc_free(ramdisk->base);
1064 ramdisk->snapshot = ramdisk->origin = ramdisk->base = NULL;
1065 ramdisk->sectors = 0;
1067 device->ramdisk = NULL;
1070 /* Start discovery on a hotplugged device. The device will be in our devices
1071 * array, but has only just been initialised by the hotplug source.
1073 int device_handler_discover(struct device_handler *handler,
1074 struct discover_device *dev)
1076 struct discover_context *ctx;
1079 device_handler_status_dev_info(handler, dev,
1081 * TRANSLATORS: this string will be passed the type of the
1082 * device (eg "disk" or "network"), which will be translated
1085 _("Processing new %s device"),
1086 device_type_display_name(dev->device->type));
1088 /* create our context */
1089 ctx = device_handler_discover_context_create(handler, dev);
1091 rc = mount_device(dev);
1095 /* add this device to our system info */
1096 system_info_register_blockdev(dev->device->id, dev->uuid,
1099 /* run the parsers. This will populate the ctx's boot_option list. */
1100 iterate_parsers(ctx);
1102 /* add discovered stuff to the handler */
1103 device_handler_discover_context_commit(handler, ctx);
1105 process_boot_option_queue(handler);
1107 talloc_unlink(handler, ctx);
1112 /* Incoming dhcp event */
1113 int device_handler_dhcp(struct device_handler *handler,
1114 struct discover_device *dev, struct event *event)
1116 struct discover_context *ctx;
1118 device_handler_status_dev_info(handler, dev,
1119 _("Processing DHCP lease response (ip: %s)"),
1120 event_get_param(event, "ip"));
1122 pending_network_jobs_start();
1124 /* create our context */
1125 ctx = device_handler_discover_context_create(handler, dev);
1126 talloc_steal(ctx, event);
1129 iterate_parsers(ctx);
1131 device_handler_discover_context_commit(handler, ctx);
1133 talloc_unlink(handler, ctx);
1138 static struct discover_boot_option *find_boot_option_by_id(
1139 struct device_handler *handler, const char *id)
1143 for (i = 0; i < handler->n_devices; i++) {
1144 struct discover_device *dev = handler->devices[i];
1145 struct discover_boot_option *opt;
1147 list_for_each_entry(&dev->boot_options, opt, list)
1148 if (!strcmp(opt->option->id, id))
1155 void device_handler_boot(struct device_handler *handler,
1156 struct boot_command *cmd)
1158 struct discover_boot_option *opt = NULL;
1160 if (cmd->option_id && strlen(cmd->option_id))
1161 opt = find_boot_option_by_id(handler, cmd->option_id);
1163 if (handler->pending_boot)
1164 boot_cancel(handler->pending_boot);
1166 platform_pre_boot();
1168 handler->pending_boot = boot(handler, opt, cmd, handler->dry_run,
1169 device_handler_boot_status_cb, handler);
1170 handler->pending_boot_is_default = false;
1173 void device_handler_cancel_default(struct device_handler *handler)
1175 if (handler->timeout_waiter)
1176 waiter_remove(handler->timeout_waiter);
1178 handler->timeout_waiter = NULL;
1179 handler->autoboot_enabled = false;
1181 /* we only send status if we had a default boot option queued */
1182 if (!handler->default_boot_option)
1185 pb_log("Cancelling default boot option\n");
1187 if (handler->pending_boot && handler->pending_boot_is_default) {
1188 boot_cancel(handler->pending_boot);
1189 handler->pending_boot = NULL;
1190 handler->pending_boot_is_default = false;
1193 handler->default_boot_option = NULL;
1195 device_handler_status_info(handler, _("Default boot cancelled"));
1198 void device_handler_update_config(struct device_handler *handler,
1199 struct config *config)
1203 rc = config_set(config);
1207 discover_server_notify_config(handler->server, config);
1208 device_handler_update_lang(config->lang);
1209 device_handler_reinit(handler);
1212 static char *device_from_addr(void *ctx, struct pb_url *url)
1214 char *ipaddr, *buf, *tok, *dev = NULL;
1215 const char *delim = " ";
1216 struct sockaddr_in *ip;
1217 struct sockaddr_in si;
1218 struct addrinfo *res;
1222 /* Note: IPv4 only */
1223 rc = inet_pton(AF_INET, url->host, &(si.sin_addr));
1227 /* need to turn hostname into a valid IP */
1228 rc = getaddrinfo(url->host, NULL, NULL, &res);
1230 pb_debug("%s: Invalid URL\n",__func__);
1233 ipaddr = talloc_array(ctx,char,INET_ADDRSTRLEN);
1234 ip = (struct sockaddr_in *) res->ai_addr;
1235 inet_ntop(AF_INET, &(ip->sin_addr), ipaddr, INET_ADDRSTRLEN);
1239 const char *argv[] = {
1241 "route", "show", "to", "match",
1246 p = process_create(ctx);
1248 p->path = pb_system_apps.ip;
1250 p->keep_stdout = true;
1252 rc = process_run_sync(p);
1254 if (rc || p->exit_status) {
1255 /* ip has complained for some reason; most likely
1256 * there is no route to the host - bail out */
1257 pb_debug("%s: `ip` returns non-zero exit status\n", __func__);
1258 pb_debug("ip buf: %s\n", p->stdout_buf);
1263 buf = p->stdout_buf;
1264 /* If a route is found, ip-route output will be of the form
1265 * "... dev DEVNAME ... " */
1266 tok = strtok(buf, delim);
1268 if (!strcmp(tok, "dev")) {
1269 tok = strtok(NULL, delim);
1270 dev = talloc_strdup(ctx, tok);
1273 tok = strtok(NULL, delim);
1278 pb_debug("%s: Found interface '%s'\n", __func__,dev);
1282 static void process_url_cb(struct load_url_result *result, void *data)
1284 struct device_handler *handler;
1285 struct discover_context *ctx;
1286 struct discover_device *dev;
1287 struct event *event = data;
1290 if (result->status != LOAD_OK) {
1291 pb_log("%s: Load failed for %s\n", __func__, result->url->full);
1298 handler = talloc_parent(event);
1302 event->device = device_from_addr(event, result->url);
1303 if (!event->device) {
1304 pb_log("Downloaded a file but can't find its interface - pretending it was local\n");
1305 event->device = talloc_asprintf(event, "local");
1308 mac = event_get_param(event, "mac");
1309 char *url = talloc_asprintf(event, "file://%s", result->local);
1310 event_set_param(event, "pxeconffile", url);
1312 dev = discover_device_create(handler, mac, event->device);
1313 ctx = device_handler_discover_context_create(handler, dev);
1314 talloc_steal(ctx, event);
1317 iterate_parsers(ctx);
1319 device_handler_discover_context_commit(handler, ctx);
1321 talloc_unlink(handler, ctx);
1324 void device_handler_process_url(struct device_handler *handler,
1325 const char *url, const char *mac, const char *ip)
1327 struct discover_context *ctx;
1328 struct discover_device *dev;
1329 bool allow_async = false;
1330 struct pb_url *pb_url;
1331 struct event *event;
1333 event = talloc_zero(handler, struct event);
1334 event->type = EVENT_TYPE_USER;
1335 event->action = EVENT_ACTION_URL;
1337 pb_url = pb_url_parse(event, url);
1338 if (!pb_url || (pb_url->scheme != pb_url_file && !pb_url->host)) {
1339 device_handler_status_err(handler, _("Invalid config URL!"));
1344 if (url[strlen(url) - 1] == '/') {
1345 event_set_param(event, "pxepathprefix", url);
1346 event_set_param(event, "mac", mac);
1347 event_set_param(event, "ip", ip);
1348 event->device = device_from_addr(event, pb_url);
1349 if (!event->device) {
1350 device_handler_status_err(handler,
1351 _("Unable to route to host %s"),
1357 event_set_param(event, "pxeconffile", url);
1361 if (pb_url->scheme == pb_url_file)
1362 event->device = talloc_asprintf(event, "local");
1363 else if (allow_async) {
1364 /* If file is remote load asynchronously before passing to
1365 * parser. This allows us to wait for network to be available */
1366 if (!load_url_async(handler, pb_url, process_url_cb, event,
1368 pb_log("Failed to load url %s\n", pb_url->full);
1369 device_handler_status_err(handler, _("Failed to load URL!"));
1375 /* If path is local we can parse straight away */
1377 dev = discover_device_create(handler, mac, event->device);
1378 if (pb_url->scheme == pb_url_file)
1379 dev->device->type = DEVICE_TYPE_ANY;
1380 ctx = device_handler_discover_context_create(handler, dev);
1381 talloc_steal(ctx, event);
1384 iterate_parsers(ctx);
1386 device_handler_discover_context_commit(handler, ctx);
1388 talloc_unlink(handler, ctx);
1391 #ifndef PETITBOOT_TEST
1394 * context_commit - Commit a temporary discovery context to the handler,
1395 * and notify the clients about any new options / devices
1397 void device_handler_discover_context_commit(struct device_handler *handler,
1398 struct discover_context *ctx)
1400 struct discover_device *dev = ctx->device;
1401 struct discover_boot_option *opt, *tmp;
1403 if (!device_lookup_by_uuid(handler, dev->uuid))
1404 device_handler_add_device(handler, dev);
1406 /* move boot options from the context to the device */
1407 list_for_each_entry_safe(&ctx->boot_options, opt, tmp, list) {
1408 list_remove(&opt->list);
1410 /* All boot options need at least a kernel image */
1411 if (!opt->boot_image || !opt->boot_image->url) {
1412 pb_log("boot option %s is missing boot image, ignoring\n",
1418 if (boot_option_resolve(opt, handler)) {
1419 pb_log("boot option %s is resolved, "
1420 "sending to clients\n",
1422 list_add_tail(&dev->boot_options, &opt->list);
1423 talloc_steal(dev, opt);
1424 boot_option_finalise(handler, opt);
1425 notify_boot_option(handler, opt);
1427 if (!opt->source->resolve_resource) {
1428 pb_log("parser %s gave us an unresolved "
1429 "resource (%s), but no way to "
1431 opt->source->name, opt->option->id);
1434 pb_log("boot option %s is unresolved, "
1435 "adding to queue\n",
1437 list_add(&handler->unresolved_boot_options,
1439 talloc_steal(handler, opt);
1445 void device_handler_add_plugin_option(struct device_handler *handler,
1446 struct plugin_option *opt)
1448 struct plugin_option *tmp;
1451 for (i = 0; i < handler->n_plugins; i++) {
1452 tmp = handler->plugins[i];
1453 /* If both id and version match, ignore */
1454 if (strncmp(opt->id, tmp->id, strlen(opt->id)) == 0 &&
1455 strncmp(opt->version, tmp->version,
1456 strlen(opt->version) == 0)) {
1457 pb_log("discover: Plugin '%s' already exists, ignoring\n",
1463 handler->plugins = talloc_realloc(handler, handler->plugins,
1464 struct plugin_option *, handler->n_plugins + 1);
1465 if (!handler->plugins) {
1466 pb_log("Failed to allocate memory for new plugin\n");
1467 handler->n_plugins = 0;
1471 handler->plugins[handler->n_plugins++] = opt;
1472 discover_server_notify_plugin_option_add(handler->server, opt);
1475 static void device_handler_update_lang(const char *lang)
1477 const char *cur_lang;
1482 cur_lang = setlocale(LC_ALL, NULL);
1483 if (cur_lang && !strcmp(cur_lang, lang))
1486 setlocale(LC_ALL, lang);
1489 static int device_handler_init_sources(struct device_handler *handler)
1491 /* init our device sources: udev, network and user events */
1492 handler->network = network_init(handler, handler->waitset,
1494 if (!handler->network)
1497 handler->udev = udev_init(handler, handler->waitset);
1501 handler->user_event = user_event_init(handler, handler->waitset);
1502 if (!handler->user_event)
1508 static void device_handler_reinit_sources(struct device_handler *handler)
1510 /* if we haven't initialised sources previously (becuase we started in
1511 * safe mode), then init once here. */
1512 if (!(handler->udev || handler->network || handler->user_event)) {
1513 device_handler_init_sources(handler);
1517 system_info_reinit();
1519 network_shutdown(handler->network);
1520 handler->network = network_init(handler, handler->waitset,
1523 udev_reinit(handler->udev);
1526 static inline const char *get_device_path(struct discover_device *dev)
1528 return dev->ramdisk ? dev->ramdisk->snapshot : dev->device_path;
1531 static char *check_subvols(struct discover_device *dev)
1533 const char *fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1538 if (strncmp(fstype, "btrfs", strlen("btrfs")))
1539 return dev->mount_path;
1541 /* On btrfs a device's root may be under a subvolume path */
1542 path = join_paths(dev, dev->mount_path, "@");
1543 rc = stat(path, &sb);
1544 if (!rc && S_ISDIR(sb.st_mode)) {
1545 pb_debug("Using '%s' for btrfs root path\n", path);
1550 return dev->mount_path;
1553 static bool check_existing_mount(struct discover_device *dev)
1555 struct stat devstat, mntstat;
1556 const char *device_path;
1561 device_path = get_device_path(dev);
1563 rc = stat(device_path, &devstat);
1565 pb_debug("%s: stat failed: %s\n", __func__, strerror(errno));
1569 if (!S_ISBLK(devstat.st_mode)) {
1570 pb_debug("%s: %s isn't a block device?\n", __func__,
1575 fp = fopen("/proc/self/mounts", "r");
1578 mnt = getmntent(fp);
1582 if (!mnt->mnt_fsname || mnt->mnt_fsname[0] != '/')
1585 rc = stat(mnt->mnt_fsname, &mntstat);
1589 if (!S_ISBLK(mntstat.st_mode))
1592 if (mntstat.st_rdev == devstat.st_rdev) {
1593 dev->mount_path = talloc_strdup(dev, mnt->mnt_dir);
1594 dev->root_path = check_subvols(dev);
1595 dev->mounted_rw = !!hasmntopt(mnt, "rw");
1596 dev->mounted = true;
1597 dev->unmount = false;
1599 pb_debug("%s: %s is already mounted (r%c) at %s\n",
1600 __func__, dev->device_path,
1601 dev->mounted_rw ? 'w' : 'o',
1613 * Attempt to mount a filesystem safely, while handling certain filesytem-
1616 static int try_mount(const char *device_path, const char *mount_path,
1617 const char *fstype, unsigned long flags,
1620 const char *fs, *safe_opts;
1623 /* Mount ext3 as ext4 instead so 'norecovery' can be used */
1624 if (strncmp(fstype, "ext3", strlen("ext3")) == 0) {
1625 pb_debug("Mounting ext3 filesystem as ext4\n");
1630 if (strncmp(fs, "xfs", strlen("xfs")) == 0 ||
1631 strncmp(fs, "ext4", strlen("ext4")) == 0)
1632 safe_opts = "norecovery";
1637 /* If no snapshot is available don't attempt recovery */
1639 return mount(device_path, mount_path, fs, flags, safe_opts);
1641 rc = mount(device_path, mount_path, fs, flags, NULL);
1646 /* Mounting failed; some filesystems will fail to mount if a recovery
1647 * journal exists (eg. cross-endian XFS), so try again with norecovery
1648 * where that option is available.
1649 * If mounting read-write just return the error as norecovery is not a
1651 if ((flags & MS_RDONLY) != MS_RDONLY || !safe_opts)
1655 return mount(device_path, mount_path, fs, flags, safe_opts);
1658 static int mount_device(struct discover_device *dev)
1660 const char *fstype, *device_path;
1663 if (!dev->device_path)
1669 if (check_existing_mount(dev))
1672 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1676 dev->mount_path = join_paths(dev, mount_base(),
1679 if (pb_mkdir_recursive(dev->mount_path)) {
1680 pb_log("couldn't create mount directory %s: %s\n",
1681 dev->mount_path, strerror(errno));
1685 device_path = get_device_path(dev);
1687 pb_log("mounting device %s read-only\n", dev->device_path);
1688 rc = try_mount(device_path, dev->mount_path, fstype,
1689 MS_RDONLY | MS_SILENT, dev->ramdisk);
1692 dev->mounted = true;
1693 dev->mounted_rw = false;
1694 dev->unmount = true;
1695 dev->root_path = check_subvols(dev);
1699 pb_log("couldn't mount device %s: mount failed: %s\n",
1700 device_path, strerror(errno));
1702 /* If mount fails clean up any snapshot */
1703 devmapper_destroy_snapshot(dev);
1705 pb_rmdir_recursive(mount_base(), dev->mount_path);
1707 talloc_free(dev->mount_path);
1708 dev->mount_path = NULL;
1712 static int umount_device(struct discover_device *dev)
1714 const char *device_path;
1717 if (!dev->mounted || !dev->unmount)
1720 device_path = get_device_path(dev);
1722 pb_log("unmounting device %s\n", device_path);
1723 rc = umount(dev->mount_path);
1727 dev->mounted = false;
1728 devmapper_destroy_snapshot(dev);
1730 pb_rmdir_recursive(mount_base(), dev->mount_path);
1732 talloc_free(dev->mount_path);
1733 dev->mount_path = NULL;
1734 dev->root_path = NULL;
1739 int device_request_write(struct discover_device *dev, bool *release)
1741 const char *fstype, *device_path;
1742 const struct config *config;
1747 config = config_get();
1748 if (!config->allow_writes)
1754 if (dev->mounted_rw)
1757 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1759 device_path = get_device_path(dev);
1761 pb_log("remounting device %s read-write\n", device_path);
1763 rc = umount(dev->mount_path);
1765 pb_log("Failed to unmount %s: %s\n",
1766 dev->mount_path, strerror(errno));
1770 rc = try_mount(device_path, dev->mount_path, fstype,
1771 MS_SILENT, dev->ramdisk);
1775 dev->mounted_rw = true;
1780 pb_log("Unable to remount device %s read-write: %s\n",
1781 device_path, strerror(errno));
1782 rc = try_mount(device_path, dev->mount_path, fstype,
1783 MS_RDONLY | MS_SILENT, dev->ramdisk);
1785 pb_log("Unable to recover mount for %s: %s\n",
1786 device_path, strerror(errno));
1790 void device_release_write(struct discover_device *dev, bool release)
1792 const char *fstype, *device_path;
1797 device_path = get_device_path(dev);
1799 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1801 pb_log("remounting device %s read-only\n", device_path);
1803 if (umount(dev->mount_path)) {
1804 pb_log("Failed to unmount %s\n", dev->mount_path);
1807 dev->mounted_rw = dev->mounted = false;
1810 devmapper_merge_snapshot(dev);
1811 /* device_path becomes stale after merge */
1812 device_path = get_device_path(dev);
1815 if (try_mount(device_path, dev->mount_path, fstype,
1816 MS_RDONLY | MS_SILENT, dev->ramdisk))
1817 pb_log("Failed to remount %s read-only: %s\n",
1818 device_path, strerror(errno));
1820 dev->mounted = true;
1823 void device_sync_snapshots(struct device_handler *handler, const char *device)
1825 struct discover_device *dev = NULL;
1829 /* Find matching device and sync */
1830 dev = device_lookup_by_name(handler, device);
1832 pb_log("%s: device name '%s' unrecognised\n",
1837 device_release_write(dev, true);
1839 pb_log("%s has no snapshot to merge, skipping\n",
1844 /* Otherwise sync all relevant devices */
1845 for (i = 0; i < handler->n_devices; i++) {
1846 dev = handler->devices[i];
1847 if (dev->device->type != DEVICE_TYPE_DISK &&
1848 dev->device->type != DEVICE_TYPE_USB)
1851 device_release_write(dev, true);
1853 pb_log("%s has no snapshot to merge, skipping\n",
1860 void device_handler_discover_context_commit(
1861 struct device_handler *handler __attribute__((unused)),
1862 struct discover_context *ctx __attribute__((unused)))
1864 pb_log("%s stubbed out for test cases\n", __func__);
1867 static void device_handler_update_lang(const char *lang __attribute__((unused)))
1871 static int device_handler_init_sources(
1872 struct device_handler *handler __attribute__((unused)))
1877 static void device_handler_reinit_sources(
1878 struct device_handler *handler __attribute__((unused)))
1882 static int umount_device(struct discover_device *dev __attribute__((unused)))
1887 static int __attribute__((unused)) mount_device(
1888 struct discover_device *dev __attribute__((unused)))
1893 int device_request_write(struct discover_device *dev __attribute__((unused)),
1900 void device_release_write(struct discover_device *dev __attribute__((unused)),
1901 bool release __attribute__((unused)))
1905 void device_sync_snapshots(
1906 struct device_handler *handler __attribute__((unused)),
1907 const char *device __attribute__((unused)))