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;
89 static int mount_device(struct discover_device *dev);
90 static int umount_device(struct discover_device *dev);
92 static int device_handler_init_sources(struct device_handler *handler);
93 static void device_handler_reinit_sources(struct device_handler *handler);
95 static void device_handler_update_lang(const char *lang);
97 void discover_context_add_boot_option(struct discover_context *ctx,
98 struct discover_boot_option *boot_option)
100 boot_option->source = ctx->parser;
101 list_add_tail(&ctx->boot_options, &boot_option->list);
102 talloc_steal(ctx, boot_option);
106 * device_handler_get_device_count - Get the count of current handler devices.
109 int device_handler_get_device_count(const struct device_handler *handler)
111 return handler->n_devices;
115 * device_handler_get_device - Get a handler device by index.
118 const struct discover_device *device_handler_get_device(
119 const struct device_handler *handler, unsigned int index)
121 if (index >= handler->n_devices) {
122 assert(0 && "bad index");
126 return handler->devices[index];
129 struct network *device_handler_get_network(
130 const struct device_handler *handler)
132 return handler->network;
135 struct discover_boot_option *discover_boot_option_create(
136 struct discover_context *ctx,
137 struct discover_device *device)
139 struct discover_boot_option *opt;
141 opt = talloc_zero(ctx, struct discover_boot_option);
142 opt->option = talloc_zero(opt, struct boot_option);
143 opt->device = device;
148 static int device_match_uuid(struct discover_device *dev, const char *uuid)
150 return dev->uuid && !strcmp(dev->uuid, uuid);
153 static int device_match_label(struct discover_device *dev, const char *label)
155 return dev->label && !strcmp(dev->label, label);
158 static int device_match_id(struct discover_device *dev, const char *id)
160 return !strcmp(dev->device->id, id);
163 static int device_match_serial(struct discover_device *dev, const char *serial)
165 const char *val = discover_device_get_param(dev, "ID_SERIAL");
166 return val && !strcmp(val, serial);
169 static struct discover_device *device_lookup(
170 struct device_handler *device_handler,
171 int (match_fn)(struct discover_device *, const char *),
174 struct discover_device *dev;
180 for (i = 0; i < device_handler->n_devices; i++) {
181 dev = device_handler->devices[i];
183 if (match_fn(dev, str))
190 struct discover_device *device_lookup_by_name(struct device_handler *handler,
193 if (!strncmp(name, "/dev/", strlen("/dev/")))
194 name += strlen("/dev/");
196 return device_lookup_by_id(handler, name);
199 struct discover_device *device_lookup_by_uuid(
200 struct device_handler *device_handler,
203 return device_lookup(device_handler, device_match_uuid, uuid);
206 struct discover_device *device_lookup_by_label(
207 struct device_handler *device_handler,
210 return device_lookup(device_handler, device_match_label, label);
213 struct discover_device *device_lookup_by_id(
214 struct device_handler *device_handler,
217 return device_lookup(device_handler, device_match_id, id);
220 struct discover_device *device_lookup_by_serial(
221 struct device_handler *device_handler,
224 return device_lookup(device_handler, device_match_serial, serial);
227 void device_handler_destroy(struct device_handler *handler)
229 talloc_free(handler);
232 static int destroy_device(void *arg)
234 struct discover_device *dev = arg;
241 struct discover_device *discover_device_create(struct device_handler *handler,
242 const char *uuid, const char *id)
244 struct discover_device *dev;
247 dev = device_lookup_by_uuid(handler, uuid);
249 dev = device_lookup_by_id(handler, id);
254 dev = talloc_zero(handler, struct discover_device);
255 dev->device = talloc_zero(dev, struct device);
256 dev->device->id = talloc_strdup(dev->device, id);
257 dev->uuid = talloc_strdup(dev, uuid);
258 list_init(&dev->params);
259 list_init(&dev->boot_options);
261 talloc_set_destructor(dev, destroy_device);
266 struct discover_device_param {
269 struct list_item list;
272 void discover_device_set_param(struct discover_device *device,
273 const char *name, const char *value)
275 struct discover_device_param *param;
278 list_for_each_entry(&device->params, param, list) {
279 if (!strcmp(param->name, name)) {
288 param = talloc(device, struct discover_device_param);
289 param->name = talloc_strdup(param, name);
290 list_add(&device->params, ¶m->list);
293 list_remove(¶m->list);
297 talloc_free(param->value);
300 param->value = talloc_strdup(param, value);
303 const char *discover_device_get_param(struct discover_device *device,
306 struct discover_device_param *param;
308 list_for_each_entry(&device->params, param, list) {
309 if (!strcmp(param->name, name))
315 static void set_env_variables(const struct config *config)
317 if (config->http_proxy)
318 setenv("http_proxy", config->http_proxy, 1);
320 unsetenv("http_proxy");
322 if (config->https_proxy)
323 setenv("https_proxy", config->https_proxy, 1);
325 unsetenv("https_proxy");
327 /* Reduce noise in the log from LVM listing open file descriptors */
328 setenv("LVM_SUPPRESS_FD_WARNINGS", "1", 1);
331 struct device_handler *device_handler_init(struct discover_server *server,
332 struct waitset *waitset, int dry_run)
334 struct device_handler *handler;
337 handler = talloc_zero(NULL, struct device_handler);
338 handler->server = server;
339 handler->waitset = waitset;
340 handler->dry_run = dry_run;
341 handler->autoboot_enabled = config_autoboot_active(config_get());
343 list_init(&handler->unresolved_boot_options);
345 list_init(&handler->progress);
347 /* set up our mount point base */
348 pb_mkdir_recursive(mount_base());
352 if (config_get()->safe_mode)
355 set_env_variables(config_get());
357 rc = device_handler_init_sources(handler);
359 talloc_free(handler);
366 void device_handler_reinit(struct device_handler *handler)
368 struct discover_boot_option *opt, *tmp;
369 struct ramdisk_device *ramdisk;
372 device_handler_cancel_default(handler);
373 /* Cancel any pending non-default boot */
374 if (handler->pending_boot) {
375 boot_cancel(handler->pending_boot);
376 handler->pending_boot = NULL;
377 handler->pending_boot_is_default = false;
380 /* Cancel any remaining async jobs */
381 process_stop_async_all();
382 pending_network_jobs_cancel();
384 /* free unresolved boot options */
385 list_for_each_entry_safe(&handler->unresolved_boot_options,
388 list_init(&handler->unresolved_boot_options);
390 /* drop all devices */
391 for (i = 0; i < handler->n_devices; i++) {
392 discover_server_notify_device_remove(handler->server,
393 handler->devices[i]->device);
394 ramdisk = handler->devices[i]->ramdisk;
395 talloc_free(handler->devices[i]);
396 talloc_free(ramdisk);
399 talloc_free(handler->devices);
400 handler->devices = NULL;
401 handler->n_devices = 0;
402 talloc_free(handler->ramdisks);
403 handler->ramdisks = NULL;
404 handler->n_ramdisks = 0;
406 set_env_variables(config_get());
408 device_handler_reinit_sources(handler);
411 void device_handler_remove(struct device_handler *handler,
412 struct discover_device *device)
414 struct discover_boot_option *opt, *tmp;
417 list_for_each_entry_safe(&device->boot_options, opt, tmp, list) {
418 if (opt == handler->default_boot_option) {
419 pb_log("Default option %s cancelled since device removed",
421 device_handler_cancel_default(handler);
426 for (i = 0; i < handler->n_devices; i++)
427 if (handler->devices[i] == device)
430 if (i == handler->n_devices) {
435 /* Free any unresolved options, as they're currently allocated
436 * against the handler */
437 list_for_each_entry_safe(&handler->unresolved_boot_options,
439 if (opt->device != device)
441 list_remove(&opt->list);
445 /* if this is a network device, we have to unregister it from the
447 if (device->device->type == DEVICE_TYPE_NETWORK)
448 network_unregister_device(handler->network, device);
450 handler->n_devices--;
451 memmove(&handler->devices[i], &handler->devices[i + 1],
452 (handler->n_devices - i) * sizeof(handler->devices[0]));
453 handler->devices = talloc_realloc(handler, handler->devices,
454 struct discover_device *, handler->n_devices);
456 if (device->notified)
457 discover_server_notify_device_remove(handler->server,
463 void device_handler_status(struct device_handler *handler,
464 struct status *status)
466 discover_server_notify_boot_status(handler->server, status);
469 static void _device_handler_vstatus(struct device_handler *handler,
470 enum status_type type, const char *fmt, va_list ap)
472 struct status status;
475 status.message = talloc_vasprintf(handler, fmt, ap);
476 status.backlog = false;
478 device_handler_status(handler, &status);
480 talloc_free(status.message);
483 static void _device_handler_vdevstatus(struct device_handler *handler,
484 struct discover_device *device, enum status_type type,
485 const char *fmt, va_list ap)
489 msg = talloc_asprintf(handler, "[%s] %s",
490 device ? device->device->id : "unknown", fmt);
491 _device_handler_vstatus(handler, type, msg, ap);
495 void device_handler_status_dev_info(struct device_handler *handler,
496 struct discover_device *dev, const char *fmt, ...)
501 _device_handler_vdevstatus(handler, dev, STATUS_INFO, fmt, ap);
505 void device_handler_status_dev_err(struct device_handler *handler,
506 struct discover_device *dev, const char *fmt, ...)
511 _device_handler_vdevstatus(handler, dev, STATUS_ERROR, fmt, ap);
515 void device_handler_status_info(struct device_handler *handler,
516 const char *fmt, ...)
521 _device_handler_vstatus(handler, STATUS_INFO, fmt, ap);
525 void device_handler_status_err(struct device_handler *handler,
526 const char *fmt, ...)
531 _device_handler_vstatus(handler, STATUS_ERROR, fmt, ap);
535 void device_handler_status_download(struct device_handler *handler,
536 const struct process_info *procinfo,
537 unsigned int percentage, unsigned int size, char suffix)
539 struct progress_info *p, *progress = NULL;
540 uint64_t current_converted, current = 0;
541 const char *units = " kMGTP";
542 unsigned long size_bytes;
548 list_for_each_entry(&handler->progress, p, list)
549 if (p->procinfo == procinfo)
553 pb_log("Registering new progress struct\n");
554 progress = talloc_zero(handler, struct progress_info);
556 pb_log("Failed to allocate room for progress struct\n");
559 progress->procinfo = procinfo;
560 list_add(&handler->progress, &progress->list);
561 handler->n_progress++;
565 for (i = 0; i < strlen(units); i++) {
566 if (units[i] == suffix)
570 if (i >= strlen(units)) {
571 pb_log("Couldn't recognise suffix '%c'\n", suffix);
578 progress->percentage = percentage;
579 progress->size = size_bytes;
582 * Aggregate the info we have and update status. If a progress struct
583 * has zero for both percentage and size we assume progress information
584 * is unavailable and fall back to a generic progress message.
586 list_for_each_entry(&handler->progress, p, list) {
589 if (!p->percentage || !p->size) {
590 update = talloc_asprintf(handler,
591 _("%u downloads in progress..."),
592 handler->n_progress);
598 t = (100 * c) / p->percentage;
605 current_converted = current;
606 while (current_converted >= 1000) {
607 current_converted >>= 10;
610 update = talloc_asprintf(handler,
611 _("%u %s downloading: %.0f%% - %lu%cB"),
613 ngettext("item", "items", handler->n_progress),
614 (current / total) * 100, current_converted,
619 pb_log("%s: failed to allocate new status\n", __func__);
621 device_handler_status_info(handler, "%s\n", update);
626 void device_handler_status_download_remove(struct device_handler *handler,
627 struct process_info *procinfo)
629 struct progress_info *p, *tmp;
631 list_for_each_entry_safe(&handler->progress, p, tmp, list)
632 if (p->procinfo == procinfo) {
633 list_remove(&p->list);
635 handler->n_progress--;
639 static void device_handler_boot_status_cb(void *arg, struct status *status)
641 device_handler_status(arg, status);
644 static void countdown_status(struct device_handler *handler,
645 struct discover_boot_option *opt, unsigned int sec)
647 struct status status;
649 status.type = STATUS_INFO;
650 status.message = talloc_asprintf(handler,
651 _("Booting in %d sec: [%s] %s"), sec,
652 opt->device->device->id, opt->option->name);
653 status.backlog = false;
655 device_handler_status(handler, &status);
657 talloc_free(status.message);
660 static int default_timeout(void *arg)
662 struct device_handler *handler = arg;
663 struct discover_boot_option *opt;
665 if (!handler->default_boot_option)
668 if (handler->pending_boot)
671 opt = handler->default_boot_option;
673 if (handler->sec_to_boot) {
674 countdown_status(handler, opt, handler->sec_to_boot);
675 handler->sec_to_boot--;
676 handler->timeout_waiter = waiter_register_timeout(
677 handler->waitset, 1000,
678 default_timeout, handler);
682 handler->timeout_waiter = NULL;
684 pb_log("Timeout expired, booting default option %s\n", opt->option->id);
688 handler->pending_boot = boot(handler, handler->default_boot_option,
689 NULL, handler->dry_run, device_handler_boot_status_cb,
691 handler->pending_boot_is_default = true;
696 enum ipmi_bootdev ipmi_type;
697 enum device_type device_type;
698 } device_type_map[] = {
699 { IPMI_BOOTDEV_NETWORK, DEVICE_TYPE_NETWORK },
700 { IPMI_BOOTDEV_DISK, DEVICE_TYPE_DISK },
701 { IPMI_BOOTDEV_DISK, DEVICE_TYPE_USB },
702 { IPMI_BOOTDEV_CDROM, DEVICE_TYPE_OPTICAL },
705 static bool ipmi_device_type_matches(enum ipmi_bootdev ipmi_type,
706 enum device_type device_type)
710 for (i = 0; i < ARRAY_SIZE(device_type_map); i++) {
711 if (device_type_map[i].device_type == device_type)
712 return device_type_map[i].ipmi_type == ipmi_type;
718 static int autoboot_option_priority(const struct config *config,
719 struct discover_boot_option *opt)
721 enum device_type type = opt->device->device->type;
722 const char *uuid = opt->device->uuid;
723 struct autoboot_option *auto_opt;
726 for (i = 0; i < config->n_autoboot_opts; i++) {
727 auto_opt = &config->autoboot_opts[i];
728 if (auto_opt->boot_type == BOOT_DEVICE_UUID)
729 if (!strcmp(auto_opt->uuid, uuid))
730 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
732 if (auto_opt->boot_type == BOOT_DEVICE_TYPE)
733 if (auto_opt->type == type ||
734 auto_opt->type == DEVICE_TYPE_ANY)
735 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
742 * We have different priorities to resolve conflicts between boot options that
743 * report to be the default for their device. This function assigns a priority
746 static enum default_priority default_option_priority(
747 struct discover_boot_option *opt)
749 const struct config *config;
751 config = config_get();
753 /* We give highest priority to IPMI-configured boot options. If
754 * we have an IPMI bootdev configuration set, then we don't allow
755 * any other defaults */
756 if (config->ipmi_bootdev) {
757 bool ipmi_match = ipmi_device_type_matches(config->ipmi_bootdev,
758 opt->device->device->type);
760 return DEFAULT_PRIORITY_REMOTE;
762 pb_debug("handler: disabled default priority due to "
763 "non-matching IPMI type %x\n",
764 config->ipmi_bootdev);
765 return DEFAULT_PRIORITY_DISABLED;
768 /* Next, try to match the option against the user-defined autoboot
769 * options, either by device UUID or type. */
770 if (config->n_autoboot_opts) {
771 int boot_match = autoboot_option_priority(config, opt);
776 /* If the option didn't match any entry in the array, it is disabled */
777 pb_debug("handler: disabled default priority due to "
778 "non-matching UUID or type\n");
779 return DEFAULT_PRIORITY_DISABLED;
782 static void set_default(struct device_handler *handler,
783 struct discover_boot_option *opt)
785 enum default_priority cur_prio, new_prio;
787 if (!handler->autoboot_enabled)
790 pb_debug("handler: new default option: %s\n", opt->option->id);
792 new_prio = default_option_priority(opt);
794 /* Anything outside our range prevents a default boot */
795 if (new_prio >= DEFAULT_PRIORITY_DISABLED)
798 pb_debug("handler: calculated priority %d\n", new_prio);
800 /* Resolve any conflicts: if we have a new default option, it only
801 * replaces the current if it has a higher priority. */
802 if (handler->default_boot_option) {
804 cur_prio = handler->default_boot_option_priority;
806 if (new_prio < cur_prio) {
807 pb_log("handler: new prio %d beats "
808 "old prio %d for %s\n",
810 handler->default_boot_option
812 handler->default_boot_option = opt;
813 handler->default_boot_option_priority = new_prio;
814 /* extend the timeout a little, so the user sees some
815 * indication of the change */
816 handler->sec_to_boot += 2;
822 handler->sec_to_boot = config_get()->autoboot_timeout_sec;
823 handler->default_boot_option = opt;
824 handler->default_boot_option_priority = new_prio;
826 pb_log("handler: boot option %s set as default, timeout %u sec.\n",
827 opt->option->id, handler->sec_to_boot);
829 default_timeout(handler);
832 static bool resource_is_resolved(struct resource *res)
834 return !res || res->resolved;
837 /* We only use this in an assert, which will disappear if we're compiling
838 * with NDEBUG, so we need the 'used' attribute for these builds */
839 static bool __attribute__((used)) boot_option_is_resolved(
840 struct discover_boot_option *opt)
842 return resource_is_resolved(opt->boot_image) &&
843 resource_is_resolved(opt->initrd) &&
844 resource_is_resolved(opt->dtb) &&
845 resource_is_resolved(opt->args_sig_file) &&
846 resource_is_resolved(opt->icon);
849 static bool resource_resolve(struct resource *res, const char *name,
850 struct discover_boot_option *opt,
851 struct device_handler *handler)
853 struct parser *parser = opt->source;
855 if (resource_is_resolved(res))
858 pb_debug("Attempting to resolve resource %s->%s with parser %s\n",
859 opt->option->id, name, parser->name);
860 parser->resolve_resource(handler, res);
862 return res->resolved;
865 static bool boot_option_resolve(struct discover_boot_option *opt,
866 struct device_handler *handler)
868 return resource_resolve(opt->boot_image, "boot_image", opt, handler) &&
869 resource_resolve(opt->initrd, "initrd", opt, handler) &&
870 resource_resolve(opt->dtb, "dtb", opt, handler) &&
871 resource_resolve(opt->args_sig_file, "args_sig_file", opt,
873 resource_resolve(opt->icon, "icon", opt, handler);
876 static void boot_option_finalise(struct device_handler *handler,
877 struct discover_boot_option *opt)
879 assert(boot_option_is_resolved(opt));
881 /* check that the parsers haven't set any of the final data */
882 assert(!opt->option->boot_image_file);
883 assert(!opt->option->initrd_file);
884 assert(!opt->option->dtb_file);
885 assert(!opt->option->icon_file);
886 assert(!opt->option->device_id);
887 assert(!opt->option->args_sig_file);
890 opt->option->boot_image_file = opt->boot_image->url->full;
892 opt->option->initrd_file = opt->initrd->url->full;
894 opt->option->dtb_file = opt->dtb->url->full;
896 opt->option->icon_file = opt->icon->url->full;
897 if (opt->args_sig_file)
898 opt->option->args_sig_file = opt->args_sig_file->url->full;
900 opt->option->device_id = opt->device->device->id;
902 if (opt->option->is_default)
903 set_default(handler, opt);
906 static void notify_boot_option(struct device_handler *handler,
907 struct discover_boot_option *opt)
909 struct discover_device *dev = opt->device;
912 discover_server_notify_device_add(handler->server,
913 opt->device->device);
914 dev->notified = true;
915 discover_server_notify_boot_option_add(handler->server, opt->option);
918 static void process_boot_option_queue(struct device_handler *handler)
920 struct discover_boot_option *opt, *tmp;
922 list_for_each_entry_safe(&handler->unresolved_boot_options,
925 pb_debug("queue: attempting resolution for %s\n",
928 if (!boot_option_resolve(opt, handler))
931 pb_debug("\tresolved!\n");
933 list_remove(&opt->list);
934 list_add_tail(&opt->device->boot_options, &opt->list);
935 talloc_steal(opt->device, opt);
936 boot_option_finalise(handler, opt);
937 notify_boot_option(handler, opt);
941 struct discover_context *device_handler_discover_context_create(
942 struct device_handler *handler,
943 struct discover_device *device)
945 struct discover_context *ctx;
947 ctx = talloc_zero(handler, struct discover_context);
948 ctx->handler = handler;
949 ctx->device = device;
950 list_init(&ctx->boot_options);
955 void device_handler_add_device(struct device_handler *handler,
956 struct discover_device *device)
958 handler->n_devices++;
959 handler->devices = talloc_realloc(handler, handler->devices,
960 struct discover_device *, handler->n_devices);
961 handler->devices[handler->n_devices - 1] = device;
963 if (device->device->type == DEVICE_TYPE_NETWORK)
964 network_register_device(handler->network, device);
967 void device_handler_add_ramdisk(struct device_handler *handler,
970 struct ramdisk_device *dev;
976 for (i = 0; i < handler->n_ramdisks; i++)
977 if (!strcmp(handler->ramdisks[i]->path, path))
980 dev = talloc_zero(handler, struct ramdisk_device);
982 pb_log("Failed to allocate memory to track %s\n", path);
986 dev->path = talloc_strdup(handler, path);
988 handler->ramdisks = talloc_realloc(handler, handler->ramdisks,
989 struct ramdisk_device *,
990 handler->n_ramdisks + 1);
991 if (!handler->ramdisks) {
992 pb_log("Failed to reallocate memory"
993 "- ramdisk tracking inconsistent!\n");
997 handler->ramdisks[i] = dev;
998 i = handler->n_ramdisks++;
1001 struct ramdisk_device *device_handler_get_ramdisk(
1002 struct device_handler *handler)
1008 /* Check if free ramdisk exists */
1009 for (i = 0; i < handler->n_ramdisks; i++)
1010 if (!handler->ramdisks[i]->snapshot &&
1011 !handler->ramdisks[i]->origin &&
1012 !handler->ramdisks[i]->base)
1013 return handler->ramdisks[i];
1015 /* Otherwise create a new one */
1016 name = talloc_asprintf(handler, "/dev/ram%d",
1017 handler->n_ramdisks);
1019 pb_debug("Failed to allocate memory to name /dev/ram%d",
1020 handler->n_ramdisks);
1024 id = makedev(1, handler->n_ramdisks);
1025 if (mknod(name, S_IFBLK, id)) {
1026 if (errno == EEXIST) {
1027 /* We haven't yet received updates for existing
1028 * ramdisks - add and use this one */
1029 pb_debug("Using untracked ramdisk %s\n", name);
1031 pb_log("Failed to create new ramdisk %s: %s\n",
1032 name, strerror(errno));
1036 device_handler_add_ramdisk(handler, name);
1039 return handler->ramdisks[i];
1042 void device_handler_release_ramdisk(struct discover_device *device)
1044 struct ramdisk_device *ramdisk = device->ramdisk;
1046 talloc_free(ramdisk->snapshot);
1047 talloc_free(ramdisk->origin);
1048 talloc_free(ramdisk->base);
1050 ramdisk->snapshot = ramdisk->origin = ramdisk->base = NULL;
1051 ramdisk->sectors = 0;
1053 device->ramdisk = NULL;
1056 /* Start discovery on a hotplugged device. The device will be in our devices
1057 * array, but has only just been initialised by the hotplug source.
1059 int device_handler_discover(struct device_handler *handler,
1060 struct discover_device *dev)
1062 struct discover_context *ctx;
1065 device_handler_status_dev_info(handler, dev,
1067 * TRANSLATORS: this string will be passed the type of the
1068 * device (eg "disk" or "network"), which will be translated
1071 _("Processing new %s device"),
1072 device_type_display_name(dev->device->type));
1074 /* create our context */
1075 ctx = device_handler_discover_context_create(handler, dev);
1077 rc = mount_device(dev);
1081 /* add this device to our system info */
1082 system_info_register_blockdev(dev->device->id, dev->uuid,
1085 /* run the parsers. This will populate the ctx's boot_option list. */
1086 iterate_parsers(ctx);
1088 /* add discovered stuff to the handler */
1089 device_handler_discover_context_commit(handler, ctx);
1091 process_boot_option_queue(handler);
1093 talloc_unlink(handler, ctx);
1098 /* Incoming dhcp event */
1099 int device_handler_dhcp(struct device_handler *handler,
1100 struct discover_device *dev, struct event *event)
1102 struct discover_context *ctx;
1104 device_handler_status_dev_info(handler, dev,
1105 _("Processing DHCP lease response (ip: %s)"),
1106 event_get_param(event, "ip"));
1108 pending_network_jobs_start();
1110 /* create our context */
1111 ctx = device_handler_discover_context_create(handler, dev);
1112 talloc_steal(ctx, event);
1115 iterate_parsers(ctx);
1117 device_handler_discover_context_commit(handler, ctx);
1119 talloc_unlink(handler, ctx);
1124 static struct discover_boot_option *find_boot_option_by_id(
1125 struct device_handler *handler, const char *id)
1129 for (i = 0; i < handler->n_devices; i++) {
1130 struct discover_device *dev = handler->devices[i];
1131 struct discover_boot_option *opt;
1133 list_for_each_entry(&dev->boot_options, opt, list)
1134 if (!strcmp(opt->option->id, id))
1141 void device_handler_boot(struct device_handler *handler,
1142 struct boot_command *cmd)
1144 struct discover_boot_option *opt = NULL;
1146 if (cmd->option_id && strlen(cmd->option_id))
1147 opt = find_boot_option_by_id(handler, cmd->option_id);
1149 if (handler->pending_boot)
1150 boot_cancel(handler->pending_boot);
1152 platform_pre_boot();
1154 handler->pending_boot = boot(handler, opt, cmd, handler->dry_run,
1155 device_handler_boot_status_cb, handler);
1156 handler->pending_boot_is_default = false;
1159 void device_handler_cancel_default(struct device_handler *handler)
1161 if (handler->timeout_waiter)
1162 waiter_remove(handler->timeout_waiter);
1164 handler->timeout_waiter = NULL;
1165 handler->autoboot_enabled = false;
1167 /* we only send status if we had a default boot option queued */
1168 if (!handler->default_boot_option)
1171 pb_log("Cancelling default boot option\n");
1173 if (handler->pending_boot && handler->pending_boot_is_default) {
1174 boot_cancel(handler->pending_boot);
1175 handler->pending_boot = NULL;
1176 handler->pending_boot_is_default = false;
1179 handler->default_boot_option = NULL;
1181 device_handler_status_info(handler, _("Default boot cancelled"));
1184 void device_handler_update_config(struct device_handler *handler,
1185 struct config *config)
1189 rc = config_set(config);
1193 discover_server_notify_config(handler->server, config);
1194 device_handler_update_lang(config->lang);
1195 device_handler_reinit(handler);
1198 static char *device_from_addr(void *ctx, struct pb_url *url)
1200 char *ipaddr, *buf, *tok, *dev = NULL;
1201 const char *delim = " ";
1202 struct sockaddr_in *ip;
1203 struct sockaddr_in si;
1204 struct addrinfo *res;
1208 /* Note: IPv4 only */
1209 rc = inet_pton(AF_INET, url->host, &(si.sin_addr));
1213 /* need to turn hostname into a valid IP */
1214 rc = getaddrinfo(url->host, NULL, NULL, &res);
1216 pb_debug("%s: Invalid URL\n",__func__);
1219 ipaddr = talloc_array(ctx,char,INET_ADDRSTRLEN);
1220 ip = (struct sockaddr_in *) res->ai_addr;
1221 inet_ntop(AF_INET, &(ip->sin_addr), ipaddr, INET_ADDRSTRLEN);
1225 const char *argv[] = {
1227 "route", "show", "to", "match",
1232 p = process_create(ctx);
1234 p->path = pb_system_apps.ip;
1236 p->keep_stdout = true;
1238 rc = process_run_sync(p);
1240 if (rc || p->exit_status) {
1241 /* ip has complained for some reason; most likely
1242 * there is no route to the host - bail out */
1243 pb_debug("%s: `ip` returns non-zero exit status\n", __func__);
1244 pb_debug("ip buf: %s\n", p->stdout_buf);
1249 buf = p->stdout_buf;
1250 /* If a route is found, ip-route output will be of the form
1251 * "... dev DEVNAME ... " */
1252 tok = strtok(buf, delim);
1254 if (!strcmp(tok, "dev")) {
1255 tok = strtok(NULL, delim);
1256 dev = talloc_strdup(ctx, tok);
1259 tok = strtok(NULL, delim);
1264 pb_debug("%s: Found interface '%s'\n", __func__,dev);
1268 static void process_url_cb(struct load_url_result *result, void *data)
1270 struct device_handler *handler;
1271 struct discover_context *ctx;
1272 struct discover_device *dev;
1273 struct event *event = data;
1276 if (result->status != LOAD_OK) {
1277 pb_log("%s: Load failed for %s\n", __func__, result->url->full);
1284 handler = talloc_parent(event);
1288 event->device = device_from_addr(event, result->url);
1289 if (!event->device) {
1290 pb_log("Downloaded a file but can't find its interface - pretending it was local\n");
1291 event->device = talloc_asprintf(event, "local");
1294 mac = event_get_param(event, "mac");
1295 char *url = talloc_asprintf(event, "file://%s", result->local);
1296 event_set_param(event, "pxeconffile", url);
1298 dev = discover_device_create(handler, mac, event->device);
1299 ctx = device_handler_discover_context_create(handler, dev);
1300 talloc_steal(ctx, event);
1303 iterate_parsers(ctx);
1305 device_handler_discover_context_commit(handler, ctx);
1307 talloc_unlink(handler, ctx);
1310 void device_handler_process_url(struct device_handler *handler,
1311 const char *url, const char *mac, const char *ip)
1313 struct discover_context *ctx;
1314 struct discover_device *dev;
1315 bool allow_async = false;
1316 struct pb_url *pb_url;
1317 struct event *event;
1319 event = talloc_zero(handler, struct event);
1320 event->type = EVENT_TYPE_USER;
1321 event->action = EVENT_ACTION_URL;
1323 pb_url = pb_url_parse(event, url);
1324 if (!pb_url || (pb_url->scheme != pb_url_file && !pb_url->host)) {
1325 device_handler_status_err(handler, _("Invalid config URL!"));
1330 if (url[strlen(url) - 1] == '/') {
1331 event_set_param(event, "pxepathprefix", url);
1332 event_set_param(event, "mac", mac);
1333 event_set_param(event, "ip", ip);
1334 event->device = device_from_addr(event, pb_url);
1335 if (!event->device) {
1336 device_handler_status_err(handler,
1337 _("Unable to route to host %s"),
1343 event_set_param(event, "pxeconffile", url);
1347 if (pb_url->scheme == pb_url_file)
1348 event->device = talloc_asprintf(event, "local");
1349 else if (allow_async) {
1350 /* If file is remote load asynchronously before passing to
1351 * parser. This allows us to wait for network to be available */
1352 if (!load_url_async(handler, pb_url, process_url_cb, event,
1354 pb_log("Failed to load url %s\n", pb_url->full);
1355 device_handler_status_err(handler, _("Failed to load URL!"));
1361 /* If path is local we can parse straight away */
1363 dev = discover_device_create(handler, mac, event->device);
1364 if (pb_url->scheme == pb_url_file)
1365 dev->device->type = DEVICE_TYPE_ANY;
1366 ctx = device_handler_discover_context_create(handler, dev);
1367 talloc_steal(ctx, event);
1370 iterate_parsers(ctx);
1372 device_handler_discover_context_commit(handler, ctx);
1374 talloc_unlink(handler, ctx);
1377 #ifndef PETITBOOT_TEST
1380 * context_commit - Commit a temporary discovery context to the handler,
1381 * and notify the clients about any new options / devices
1383 void device_handler_discover_context_commit(struct device_handler *handler,
1384 struct discover_context *ctx)
1386 struct discover_device *dev = ctx->device;
1387 struct discover_boot_option *opt, *tmp;
1389 if (!device_lookup_by_uuid(handler, dev->uuid))
1390 device_handler_add_device(handler, dev);
1392 /* move boot options from the context to the device */
1393 list_for_each_entry_safe(&ctx->boot_options, opt, tmp, list) {
1394 list_remove(&opt->list);
1396 /* All boot options need at least a kernel image */
1397 if (!opt->boot_image || !opt->boot_image->url) {
1398 pb_log("boot option %s is missing boot image, ignoring\n",
1404 if (boot_option_resolve(opt, handler)) {
1405 pb_log("boot option %s is resolved, "
1406 "sending to clients\n",
1408 list_add_tail(&dev->boot_options, &opt->list);
1409 talloc_steal(dev, opt);
1410 boot_option_finalise(handler, opt);
1411 notify_boot_option(handler, opt);
1413 if (!opt->source->resolve_resource) {
1414 pb_log("parser %s gave us an unresolved "
1415 "resource (%s), but no way to "
1417 opt->source->name, opt->option->id);
1420 pb_log("boot option %s is unresolved, "
1421 "adding to queue\n",
1423 list_add(&handler->unresolved_boot_options,
1425 talloc_steal(handler, opt);
1431 static void device_handler_update_lang(const char *lang)
1433 const char *cur_lang;
1438 cur_lang = setlocale(LC_ALL, NULL);
1439 if (cur_lang && !strcmp(cur_lang, lang))
1442 setlocale(LC_ALL, lang);
1445 static int device_handler_init_sources(struct device_handler *handler)
1447 /* init our device sources: udev, network and user events */
1448 handler->network = network_init(handler, handler->waitset,
1450 if (!handler->network)
1453 handler->udev = udev_init(handler, handler->waitset);
1457 handler->user_event = user_event_init(handler, handler->waitset);
1458 if (!handler->user_event)
1464 static void device_handler_reinit_sources(struct device_handler *handler)
1466 /* if we haven't initialised sources previously (becuase we started in
1467 * safe mode), then init once here. */
1468 if (!(handler->udev || handler->network || handler->user_event)) {
1469 device_handler_init_sources(handler);
1473 system_info_reinit();
1475 network_shutdown(handler->network);
1476 handler->network = network_init(handler, handler->waitset,
1479 udev_reinit(handler->udev);
1482 static inline const char *get_device_path(struct discover_device *dev)
1484 return dev->ramdisk ? dev->ramdisk->snapshot : dev->device_path;
1487 static char *check_subvols(struct discover_device *dev)
1489 const char *fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1494 if (strncmp(fstype, "btrfs", strlen("btrfs")))
1495 return dev->mount_path;
1497 /* On btrfs a device's root may be under a subvolume path */
1498 path = join_paths(dev, dev->mount_path, "@");
1499 rc = stat(path, &sb);
1500 if (!rc && S_ISDIR(sb.st_mode)) {
1501 pb_debug("Using '%s' for btrfs root path\n", path);
1506 return dev->mount_path;
1509 static bool check_existing_mount(struct discover_device *dev)
1511 struct stat devstat, mntstat;
1512 const char *device_path;
1517 device_path = get_device_path(dev);
1519 rc = stat(device_path, &devstat);
1521 pb_debug("%s: stat failed: %s\n", __func__, strerror(errno));
1525 if (!S_ISBLK(devstat.st_mode)) {
1526 pb_debug("%s: %s isn't a block device?\n", __func__,
1531 fp = fopen("/proc/self/mounts", "r");
1534 mnt = getmntent(fp);
1538 if (!mnt->mnt_fsname || mnt->mnt_fsname[0] != '/')
1541 rc = stat(mnt->mnt_fsname, &mntstat);
1545 if (!S_ISBLK(mntstat.st_mode))
1548 if (mntstat.st_rdev == devstat.st_rdev) {
1549 dev->mount_path = talloc_strdup(dev, mnt->mnt_dir);
1550 dev->root_path = check_subvols(dev);
1551 dev->mounted_rw = !!hasmntopt(mnt, "rw");
1552 dev->mounted = true;
1553 dev->unmount = false;
1555 pb_debug("%s: %s is already mounted (r%c) at %s\n",
1556 __func__, dev->device_path,
1557 dev->mounted_rw ? 'w' : 'o',
1569 * Attempt to mount a filesystem safely, while handling certain filesytem-
1572 static int try_mount(const char *device_path, const char *mount_path,
1573 const char *fstype, unsigned long flags,
1576 const char *fs, *safe_opts;
1579 /* Mount ext3 as ext4 instead so 'norecovery' can be used */
1580 if (strncmp(fstype, "ext3", strlen("ext3")) == 0) {
1581 pb_debug("Mounting ext3 filesystem as ext4\n");
1586 if (strncmp(fs, "xfs", strlen("xfs")) == 0 ||
1587 strncmp(fs, "ext4", strlen("ext4")) == 0)
1588 safe_opts = "norecovery";
1593 /* If no snapshot is available don't attempt recovery */
1595 return mount(device_path, mount_path, fs, flags, safe_opts);
1597 rc = mount(device_path, mount_path, fs, flags, NULL);
1602 /* Mounting failed; some filesystems will fail to mount if a recovery
1603 * journal exists (eg. cross-endian XFS), so try again with norecovery
1604 * where that option is available.
1605 * If mounting read-write just return the error as norecovery is not a
1607 if ((flags & MS_RDONLY) != MS_RDONLY || !safe_opts)
1611 return mount(device_path, mount_path, fs, flags, safe_opts);
1614 static int mount_device(struct discover_device *dev)
1616 const char *fstype, *device_path;
1619 if (!dev->device_path)
1625 if (check_existing_mount(dev))
1628 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1632 dev->mount_path = join_paths(dev, mount_base(),
1635 if (pb_mkdir_recursive(dev->mount_path)) {
1636 pb_log("couldn't create mount directory %s: %s\n",
1637 dev->mount_path, strerror(errno));
1641 device_path = get_device_path(dev);
1643 pb_log("mounting device %s read-only\n", dev->device_path);
1644 rc = try_mount(device_path, dev->mount_path, fstype,
1645 MS_RDONLY | MS_SILENT, dev->ramdisk);
1648 dev->mounted = true;
1649 dev->mounted_rw = false;
1650 dev->unmount = true;
1651 dev->root_path = check_subvols(dev);
1655 pb_log("couldn't mount device %s: mount failed: %s\n",
1656 device_path, strerror(errno));
1658 /* If mount fails clean up any snapshot */
1659 devmapper_destroy_snapshot(dev);
1661 pb_rmdir_recursive(mount_base(), dev->mount_path);
1663 talloc_free(dev->mount_path);
1664 dev->mount_path = NULL;
1668 static int umount_device(struct discover_device *dev)
1670 const char *device_path;
1673 if (!dev->mounted || !dev->unmount)
1676 device_path = get_device_path(dev);
1678 pb_log("unmounting device %s\n", device_path);
1679 rc = umount(dev->mount_path);
1683 dev->mounted = false;
1684 devmapper_destroy_snapshot(dev);
1686 pb_rmdir_recursive(mount_base(), dev->mount_path);
1688 talloc_free(dev->mount_path);
1689 dev->mount_path = NULL;
1690 dev->root_path = NULL;
1695 int device_request_write(struct discover_device *dev, bool *release)
1697 const char *fstype, *device_path;
1698 const struct config *config;
1703 config = config_get();
1704 if (!config->allow_writes)
1710 if (dev->mounted_rw)
1713 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1715 device_path = get_device_path(dev);
1717 pb_log("remounting device %s read-write\n", device_path);
1719 rc = umount(dev->mount_path);
1721 pb_log("Failed to unmount %s: %s\n",
1722 dev->mount_path, strerror(errno));
1726 rc = try_mount(device_path, dev->mount_path, fstype,
1727 MS_SILENT, dev->ramdisk);
1731 dev->mounted_rw = true;
1736 pb_log("Unable to remount device %s read-write: %s\n",
1737 device_path, strerror(errno));
1738 rc = try_mount(device_path, dev->mount_path, fstype,
1739 MS_RDONLY | MS_SILENT, dev->ramdisk);
1741 pb_log("Unable to recover mount for %s: %s\n",
1742 device_path, strerror(errno));
1746 void device_release_write(struct discover_device *dev, bool release)
1748 const char *fstype, *device_path;
1753 device_path = get_device_path(dev);
1755 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1757 pb_log("remounting device %s read-only\n", device_path);
1759 if (umount(dev->mount_path)) {
1760 pb_log("Failed to unmount %s\n", dev->mount_path);
1763 dev->mounted_rw = dev->mounted = false;
1766 devmapper_merge_snapshot(dev);
1767 /* device_path becomes stale after merge */
1768 device_path = get_device_path(dev);
1771 if (try_mount(device_path, dev->mount_path, fstype,
1772 MS_RDONLY | MS_SILENT, dev->ramdisk))
1773 pb_log("Failed to remount %s read-only: %s\n",
1774 device_path, strerror(errno));
1776 dev->mounted = true;
1779 void device_sync_snapshots(struct device_handler *handler, const char *device)
1781 struct discover_device *dev = NULL;
1785 /* Find matching device and sync */
1786 dev = device_lookup_by_name(handler, device);
1788 pb_log("%s: device name '%s' unrecognised\n",
1793 device_release_write(dev, true);
1795 pb_log("%s has no snapshot to merge, skipping\n",
1800 /* Otherwise sync all relevant devices */
1801 for (i = 0; i < handler->n_devices; i++) {
1802 dev = handler->devices[i];
1803 if (dev->device->type != DEVICE_TYPE_DISK &&
1804 dev->device->type != DEVICE_TYPE_USB)
1807 device_release_write(dev, true);
1809 pb_log("%s has no snapshot to merge, skipping\n",
1816 void device_handler_discover_context_commit(
1817 struct device_handler *handler __attribute__((unused)),
1818 struct discover_context *ctx __attribute__((unused)))
1820 pb_log("%s stubbed out for test cases\n", __func__);
1823 static void device_handler_update_lang(const char *lang __attribute__((unused)))
1827 static int device_handler_init_sources(
1828 struct device_handler *handler __attribute__((unused)))
1833 static void device_handler_reinit_sources(
1834 struct device_handler *handler __attribute__((unused)))
1838 static int umount_device(struct discover_device *dev __attribute__((unused)))
1843 static int __attribute__((unused)) mount_device(
1844 struct discover_device *dev __attribute__((unused)))
1849 int device_request_write(struct discover_device *dev __attribute__((unused)),
1856 void device_release_write(struct discover_device *dev __attribute__((unused)),
1857 bool release __attribute__((unused)))
1861 void device_sync_snapshots(
1862 struct device_handler *handler __attribute__((unused)),
1863 const char *device __attribute__((unused)))