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 static void set_env_variables(const struct config *config)
343 if (config->http_proxy)
344 setenv("http_proxy", config->http_proxy, 1);
346 unsetenv("http_proxy");
348 if (config->https_proxy)
349 setenv("https_proxy", config->https_proxy, 1);
351 unsetenv("https_proxy");
353 /* Reduce noise in the log from LVM listing open file descriptors */
354 setenv("LVM_SUPPRESS_FD_WARNINGS", "1", 1);
357 struct device_handler *device_handler_init(struct discover_server *server,
358 struct waitset *waitset, int dry_run)
360 struct device_handler *handler;
363 handler = talloc_zero(NULL, struct device_handler);
364 handler->server = server;
365 handler->waitset = waitset;
366 handler->dry_run = dry_run;
367 handler->autoboot_enabled = config_autoboot_active(config_get());
369 list_init(&handler->unresolved_boot_options);
371 list_init(&handler->progress);
373 /* set up our mount point base */
374 pb_mkdir_recursive(mount_base());
378 if (config_get()->safe_mode)
381 set_env_variables(config_get());
383 rc = device_handler_init_sources(handler);
385 talloc_free(handler);
392 void device_handler_reinit(struct device_handler *handler)
394 struct discover_boot_option *opt, *tmp;
395 struct ramdisk_device *ramdisk;
398 device_handler_cancel_default(handler);
399 /* Cancel any pending non-default boot */
400 if (handler->pending_boot) {
401 boot_cancel(handler->pending_boot);
402 handler->pending_boot = NULL;
403 handler->pending_boot_is_default = false;
406 /* Cancel any remaining async jobs */
407 process_stop_async_all();
408 pending_network_jobs_cancel();
410 /* free unresolved boot options */
411 list_for_each_entry_safe(&handler->unresolved_boot_options,
414 list_init(&handler->unresolved_boot_options);
416 /* drop all devices */
417 for (i = 0; i < handler->n_devices; i++) {
418 discover_server_notify_device_remove(handler->server,
419 handler->devices[i]->device);
420 ramdisk = handler->devices[i]->ramdisk;
421 talloc_free(handler->devices[i]);
422 talloc_free(ramdisk);
425 talloc_free(handler->devices);
426 handler->devices = NULL;
427 handler->n_devices = 0;
428 talloc_free(handler->ramdisks);
429 handler->ramdisks = NULL;
430 handler->n_ramdisks = 0;
432 /* drop any known plugins */
433 for (i = 0; i < handler->n_plugins; i++)
434 talloc_free(handler->plugins[i]);
435 talloc_free(handler->plugins);
436 handler->plugins = NULL;
437 handler->n_plugins = 0;
439 discover_server_notify_plugins_remove(handler->server);
441 set_env_variables(config_get());
443 device_handler_reinit_sources(handler);
446 void device_handler_remove(struct device_handler *handler,
447 struct discover_device *device)
449 struct discover_boot_option *opt, *tmp;
452 list_for_each_entry_safe(&device->boot_options, opt, tmp, list) {
453 if (opt == handler->default_boot_option) {
454 pb_log("Default option %s cancelled since device removed",
456 device_handler_cancel_default(handler);
461 for (i = 0; i < handler->n_devices; i++)
462 if (handler->devices[i] == device)
465 if (i == handler->n_devices) {
470 /* Free any unresolved options, as they're currently allocated
471 * against the handler */
472 list_for_each_entry_safe(&handler->unresolved_boot_options,
474 if (opt->device != device)
476 list_remove(&opt->list);
480 /* if this is a network device, we have to unregister it from the
482 if (device->device->type == DEVICE_TYPE_NETWORK)
483 network_unregister_device(handler->network, device);
485 handler->n_devices--;
486 memmove(&handler->devices[i], &handler->devices[i + 1],
487 (handler->n_devices - i) * sizeof(handler->devices[0]));
488 handler->devices = talloc_realloc(handler, handler->devices,
489 struct discover_device *, handler->n_devices);
491 if (device->notified)
492 discover_server_notify_device_remove(handler->server,
498 void device_handler_status(struct device_handler *handler,
499 struct status *status)
501 discover_server_notify_boot_status(handler->server, status);
504 static void _device_handler_vstatus(struct device_handler *handler,
505 enum status_type type, const char *fmt, va_list ap)
507 struct status status;
510 status.message = talloc_vasprintf(handler, fmt, ap);
511 status.backlog = false;
513 device_handler_status(handler, &status);
515 talloc_free(status.message);
518 static void _device_handler_vdevstatus(struct device_handler *handler,
519 struct discover_device *device, enum status_type type,
520 const char *fmt, va_list ap)
524 msg = talloc_asprintf(handler, "[%s] %s",
525 device ? device->device->id : "unknown", fmt);
526 _device_handler_vstatus(handler, type, msg, ap);
530 void device_handler_status_dev_info(struct device_handler *handler,
531 struct discover_device *dev, const char *fmt, ...)
536 _device_handler_vdevstatus(handler, dev, STATUS_INFO, fmt, ap);
540 void device_handler_status_dev_err(struct device_handler *handler,
541 struct discover_device *dev, const char *fmt, ...)
546 _device_handler_vdevstatus(handler, dev, STATUS_ERROR, fmt, ap);
550 void device_handler_status_info(struct device_handler *handler,
551 const char *fmt, ...)
556 _device_handler_vstatus(handler, STATUS_INFO, fmt, ap);
560 void device_handler_status_err(struct device_handler *handler,
561 const char *fmt, ...)
566 _device_handler_vstatus(handler, STATUS_ERROR, fmt, ap);
570 void device_handler_status_download(struct device_handler *handler,
571 const struct process_info *procinfo,
572 unsigned int percentage, unsigned int size, char suffix)
574 struct progress_info *p, *progress = NULL;
575 uint64_t current_converted, current = 0;
576 const char *units = " kMGTP";
577 unsigned long size_bytes;
583 list_for_each_entry(&handler->progress, p, list)
584 if (p->procinfo == procinfo)
588 pb_log("Registering new progress struct\n");
589 progress = talloc_zero(handler, struct progress_info);
591 pb_log("Failed to allocate room for progress struct\n");
594 progress->procinfo = procinfo;
595 list_add(&handler->progress, &progress->list);
596 handler->n_progress++;
600 for (i = 0; i < strlen(units); i++) {
601 if (units[i] == suffix)
605 if (i >= strlen(units)) {
606 pb_log("Couldn't recognise suffix '%c'\n", suffix);
613 progress->percentage = percentage;
614 progress->size = size_bytes;
617 * Aggregate the info we have and update status. If a progress struct
618 * has zero for both percentage and size we assume progress information
619 * is unavailable and fall back to a generic progress message.
621 list_for_each_entry(&handler->progress, p, list) {
624 if (!p->percentage || !p->size) {
625 update = talloc_asprintf(handler,
626 _("%u downloads in progress..."),
627 handler->n_progress);
633 t = (100 * c) / p->percentage;
640 current_converted = current;
641 while (current_converted >= 1000) {
642 current_converted >>= 10;
645 update = talloc_asprintf(handler,
646 _("%u %s downloading: %.0f%% - %lu%cB"),
648 ngettext("item", "items", handler->n_progress),
649 (current / total) * 100, current_converted,
654 pb_log("%s: failed to allocate new status\n", __func__);
656 device_handler_status_info(handler, "%s\n", update);
661 static void device_handler_plugin_scan_device(struct device_handler *handler,
662 struct discover_device *dev)
666 pb_debug("Scanning %s for plugin files\n", dev->device->id);
668 rc = process_run_simple(handler, pb_system_apps.pb_plugin,
669 "scan", dev->mount_path,
672 pb_log("Error from pb-plugin scan %s\n",
676 void device_handler_status_download_remove(struct device_handler *handler,
677 struct process_info *procinfo)
679 struct progress_info *p, *tmp;
681 list_for_each_entry_safe(&handler->progress, p, tmp, list)
682 if (p->procinfo == procinfo) {
683 list_remove(&p->list);
685 handler->n_progress--;
689 static void device_handler_boot_status_cb(void *arg, struct status *status)
691 device_handler_status(arg, status);
694 static void countdown_status(struct device_handler *handler,
695 struct discover_boot_option *opt, unsigned int sec)
697 struct status status;
699 status.type = STATUS_INFO;
700 status.message = talloc_asprintf(handler,
701 _("Booting in %d sec: [%s] %s"), sec,
702 opt->device->device->id, opt->option->name);
703 status.backlog = false;
705 device_handler_status(handler, &status);
707 talloc_free(status.message);
710 static int default_timeout(void *arg)
712 struct device_handler *handler = arg;
713 struct discover_boot_option *opt;
715 if (!handler->default_boot_option)
718 if (handler->pending_boot)
721 opt = handler->default_boot_option;
723 if (handler->sec_to_boot) {
724 countdown_status(handler, opt, handler->sec_to_boot);
725 handler->sec_to_boot--;
726 handler->timeout_waiter = waiter_register_timeout(
727 handler->waitset, 1000,
728 default_timeout, handler);
732 handler->timeout_waiter = NULL;
734 pb_log("Timeout expired, booting default option %s\n", opt->option->id);
738 handler->pending_boot = boot(handler, handler->default_boot_option,
739 NULL, handler->dry_run, device_handler_boot_status_cb,
741 handler->pending_boot_is_default = true;
746 enum ipmi_bootdev ipmi_type;
747 enum device_type device_type;
748 } device_type_map[] = {
749 { IPMI_BOOTDEV_NETWORK, DEVICE_TYPE_NETWORK },
750 { IPMI_BOOTDEV_DISK, DEVICE_TYPE_DISK },
751 { IPMI_BOOTDEV_DISK, DEVICE_TYPE_USB },
752 { IPMI_BOOTDEV_CDROM, DEVICE_TYPE_OPTICAL },
755 static bool ipmi_device_type_matches(enum ipmi_bootdev ipmi_type,
756 enum device_type device_type)
760 for (i = 0; i < ARRAY_SIZE(device_type_map); i++) {
761 if (device_type_map[i].device_type == device_type)
762 return device_type_map[i].ipmi_type == ipmi_type;
768 static int autoboot_option_priority(const struct config *config,
769 struct discover_boot_option *opt)
771 enum device_type type = opt->device->device->type;
772 const char *uuid = opt->device->uuid;
773 struct autoboot_option *auto_opt;
776 for (i = 0; i < config->n_autoboot_opts; i++) {
777 auto_opt = &config->autoboot_opts[i];
778 if (auto_opt->boot_type == BOOT_DEVICE_UUID)
779 if (!strcmp(auto_opt->uuid, uuid))
780 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
782 if (auto_opt->boot_type == BOOT_DEVICE_TYPE)
783 if (auto_opt->type == type ||
784 auto_opt->type == DEVICE_TYPE_ANY)
785 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
792 * We have different priorities to resolve conflicts between boot options that
793 * report to be the default for their device. This function assigns a priority
796 static enum default_priority default_option_priority(
797 struct discover_boot_option *opt)
799 const struct config *config;
801 config = config_get();
803 /* We give highest priority to IPMI-configured boot options. If
804 * we have an IPMI bootdev configuration set, then we don't allow
805 * any other defaults */
806 if (config->ipmi_bootdev) {
807 bool ipmi_match = ipmi_device_type_matches(config->ipmi_bootdev,
808 opt->device->device->type);
810 return DEFAULT_PRIORITY_REMOTE;
812 pb_debug("handler: disabled default priority due to "
813 "non-matching IPMI type %x\n",
814 config->ipmi_bootdev);
815 return DEFAULT_PRIORITY_DISABLED;
818 /* Next, try to match the option against the user-defined autoboot
819 * options, either by device UUID or type. */
820 if (config->n_autoboot_opts) {
821 int boot_match = autoboot_option_priority(config, opt);
826 /* If the option didn't match any entry in the array, it is disabled */
827 pb_debug("handler: disabled default priority due to "
828 "non-matching UUID or type\n");
829 return DEFAULT_PRIORITY_DISABLED;
832 static void set_default(struct device_handler *handler,
833 struct discover_boot_option *opt)
835 enum default_priority cur_prio, new_prio;
837 if (!handler->autoboot_enabled)
840 pb_debug("handler: new default option: %s\n", opt->option->id);
842 new_prio = default_option_priority(opt);
844 /* Anything outside our range prevents a default boot */
845 if (new_prio >= DEFAULT_PRIORITY_DISABLED)
848 pb_debug("handler: calculated priority %d\n", new_prio);
850 /* Resolve any conflicts: if we have a new default option, it only
851 * replaces the current if it has a higher priority. */
852 if (handler->default_boot_option) {
854 cur_prio = handler->default_boot_option_priority;
856 if (new_prio < cur_prio) {
857 pb_log("handler: new prio %d beats "
858 "old prio %d for %s\n",
860 handler->default_boot_option
862 handler->default_boot_option = opt;
863 handler->default_boot_option_priority = new_prio;
864 /* extend the timeout a little, so the user sees some
865 * indication of the change */
866 handler->sec_to_boot += 2;
872 handler->sec_to_boot = config_get()->autoboot_timeout_sec;
873 handler->default_boot_option = opt;
874 handler->default_boot_option_priority = new_prio;
876 pb_log("handler: boot option %s set as default, timeout %u sec.\n",
877 opt->option->id, handler->sec_to_boot);
879 default_timeout(handler);
882 static bool resource_is_resolved(struct resource *res)
884 return !res || res->resolved;
887 /* We only use this in an assert, which will disappear if we're compiling
888 * with NDEBUG, so we need the 'used' attribute for these builds */
889 static bool __attribute__((used)) boot_option_is_resolved(
890 struct discover_boot_option *opt)
892 return resource_is_resolved(opt->boot_image) &&
893 resource_is_resolved(opt->initrd) &&
894 resource_is_resolved(opt->dtb) &&
895 resource_is_resolved(opt->args_sig_file) &&
896 resource_is_resolved(opt->icon);
899 static bool resource_resolve(struct resource *res, const char *name,
900 struct discover_boot_option *opt,
901 struct device_handler *handler)
903 struct parser *parser = opt->source;
905 if (resource_is_resolved(res))
908 pb_debug("Attempting to resolve resource %s->%s with parser %s\n",
909 opt->option->id, name, parser->name);
910 parser->resolve_resource(handler, res);
912 return res->resolved;
915 static bool boot_option_resolve(struct discover_boot_option *opt,
916 struct device_handler *handler)
918 return resource_resolve(opt->boot_image, "boot_image", opt, handler) &&
919 resource_resolve(opt->initrd, "initrd", opt, handler) &&
920 resource_resolve(opt->dtb, "dtb", opt, handler) &&
921 resource_resolve(opt->args_sig_file, "args_sig_file", opt,
923 resource_resolve(opt->icon, "icon", opt, handler);
926 static void boot_option_finalise(struct device_handler *handler,
927 struct discover_boot_option *opt)
929 assert(boot_option_is_resolved(opt));
931 /* check that the parsers haven't set any of the final data */
932 assert(!opt->option->boot_image_file);
933 assert(!opt->option->initrd_file);
934 assert(!opt->option->dtb_file);
935 assert(!opt->option->icon_file);
936 assert(!opt->option->device_id);
937 assert(!opt->option->args_sig_file);
940 opt->option->boot_image_file = opt->boot_image->url->full;
942 opt->option->initrd_file = opt->initrd->url->full;
944 opt->option->dtb_file = opt->dtb->url->full;
946 opt->option->icon_file = opt->icon->url->full;
947 if (opt->args_sig_file)
948 opt->option->args_sig_file = opt->args_sig_file->url->full;
950 opt->option->device_id = opt->device->device->id;
952 if (opt->option->is_default)
953 set_default(handler, opt);
956 static void notify_boot_option(struct device_handler *handler,
957 struct discover_boot_option *opt)
959 struct discover_device *dev = opt->device;
962 discover_server_notify_device_add(handler->server,
963 opt->device->device);
964 dev->notified = true;
965 discover_server_notify_boot_option_add(handler->server, opt->option);
968 static void process_boot_option_queue(struct device_handler *handler)
970 struct discover_boot_option *opt, *tmp;
972 list_for_each_entry_safe(&handler->unresolved_boot_options,
975 pb_debug("queue: attempting resolution for %s\n",
978 if (!boot_option_resolve(opt, handler))
981 pb_debug("\tresolved!\n");
983 list_remove(&opt->list);
984 list_add_tail(&opt->device->boot_options, &opt->list);
985 talloc_steal(opt->device, opt);
986 boot_option_finalise(handler, opt);
987 notify_boot_option(handler, opt);
991 struct discover_context *device_handler_discover_context_create(
992 struct device_handler *handler,
993 struct discover_device *device)
995 struct discover_context *ctx;
997 ctx = talloc_zero(handler, struct discover_context);
998 ctx->handler = handler;
999 ctx->device = device;
1000 list_init(&ctx->boot_options);
1005 void device_handler_add_device(struct device_handler *handler,
1006 struct discover_device *device)
1008 handler->n_devices++;
1009 handler->devices = talloc_realloc(handler, handler->devices,
1010 struct discover_device *, handler->n_devices);
1011 handler->devices[handler->n_devices - 1] = device;
1013 if (device->device->type == DEVICE_TYPE_NETWORK)
1014 network_register_device(handler->network, device);
1017 void device_handler_add_ramdisk(struct device_handler *handler,
1020 struct ramdisk_device *dev;
1026 for (i = 0; i < handler->n_ramdisks; i++)
1027 if (!strcmp(handler->ramdisks[i]->path, path))
1030 dev = talloc_zero(handler, struct ramdisk_device);
1032 pb_log("Failed to allocate memory to track %s\n", path);
1036 dev->path = talloc_strdup(handler, path);
1038 handler->ramdisks = talloc_realloc(handler, handler->ramdisks,
1039 struct ramdisk_device *,
1040 handler->n_ramdisks + 1);
1041 if (!handler->ramdisks) {
1042 pb_log("Failed to reallocate memory"
1043 "- ramdisk tracking inconsistent!\n");
1047 handler->ramdisks[i] = dev;
1048 i = handler->n_ramdisks++;
1051 struct ramdisk_device *device_handler_get_ramdisk(
1052 struct device_handler *handler)
1058 /* Check if free ramdisk exists */
1059 for (i = 0; i < handler->n_ramdisks; i++)
1060 if (!handler->ramdisks[i]->snapshot &&
1061 !handler->ramdisks[i]->origin &&
1062 !handler->ramdisks[i]->base)
1063 return handler->ramdisks[i];
1065 /* Otherwise create a new one */
1066 name = talloc_asprintf(handler, "/dev/ram%d",
1067 handler->n_ramdisks);
1069 pb_debug("Failed to allocate memory to name /dev/ram%d",
1070 handler->n_ramdisks);
1074 id = makedev(1, handler->n_ramdisks);
1075 if (mknod(name, S_IFBLK, id)) {
1076 if (errno == EEXIST) {
1077 /* We haven't yet received updates for existing
1078 * ramdisks - add and use this one */
1079 pb_debug("Using untracked ramdisk %s\n", name);
1081 pb_log("Failed to create new ramdisk %s: %s\n",
1082 name, strerror(errno));
1086 device_handler_add_ramdisk(handler, name);
1089 return handler->ramdisks[i];
1092 void device_handler_release_ramdisk(struct discover_device *device)
1094 struct ramdisk_device *ramdisk = device->ramdisk;
1096 talloc_free(ramdisk->snapshot);
1097 talloc_free(ramdisk->origin);
1098 talloc_free(ramdisk->base);
1100 ramdisk->snapshot = ramdisk->origin = ramdisk->base = NULL;
1101 ramdisk->sectors = 0;
1103 device->ramdisk = NULL;
1106 /* Start discovery on a hotplugged device. The device will be in our devices
1107 * array, but has only just been initialised by the hotplug source.
1109 int device_handler_discover(struct device_handler *handler,
1110 struct discover_device *dev)
1112 struct discover_context *ctx;
1115 device_handler_status_dev_info(handler, dev,
1117 * TRANSLATORS: this string will be passed the type of the
1118 * device (eg "disk" or "network"), which will be translated
1121 _("Processing new %s device"),
1122 device_type_display_name(dev->device->type));
1124 /* create our context */
1125 ctx = device_handler_discover_context_create(handler, dev);
1127 rc = mount_device(dev);
1131 /* add this device to our system info */
1132 system_info_register_blockdev(dev->device->id, dev->uuid,
1135 /* run the parsers. This will populate the ctx's boot_option list. */
1136 iterate_parsers(ctx);
1138 /* add discovered stuff to the handler */
1139 device_handler_discover_context_commit(handler, ctx);
1141 process_boot_option_queue(handler);
1143 /* Check this device for pb-plugins */
1144 device_handler_plugin_scan_device(handler, dev);
1146 talloc_unlink(handler, ctx);
1151 /* Incoming dhcp event */
1152 int device_handler_dhcp(struct device_handler *handler,
1153 struct discover_device *dev, struct event *event)
1155 struct discover_context *ctx;
1157 device_handler_status_dev_info(handler, dev,
1158 _("Processing DHCP lease response (ip: %s)"),
1159 event_get_param(event, "ip"));
1161 pending_network_jobs_start();
1163 /* create our context */
1164 ctx = device_handler_discover_context_create(handler, dev);
1165 talloc_steal(ctx, event);
1168 iterate_parsers(ctx);
1170 device_handler_discover_context_commit(handler, ctx);
1172 talloc_unlink(handler, ctx);
1177 static struct discover_boot_option *find_boot_option_by_id(
1178 struct device_handler *handler, const char *id)
1182 for (i = 0; i < handler->n_devices; i++) {
1183 struct discover_device *dev = handler->devices[i];
1184 struct discover_boot_option *opt;
1186 list_for_each_entry(&dev->boot_options, opt, list)
1187 if (!strcmp(opt->option->id, id))
1194 void device_handler_boot(struct device_handler *handler,
1195 struct boot_command *cmd)
1197 struct discover_boot_option *opt = NULL;
1199 if (cmd->option_id && strlen(cmd->option_id))
1200 opt = find_boot_option_by_id(handler, cmd->option_id);
1202 if (handler->pending_boot)
1203 boot_cancel(handler->pending_boot);
1205 platform_pre_boot();
1207 handler->pending_boot = boot(handler, opt, cmd, handler->dry_run,
1208 device_handler_boot_status_cb, handler);
1209 handler->pending_boot_is_default = false;
1212 void device_handler_cancel_default(struct device_handler *handler)
1214 if (handler->timeout_waiter)
1215 waiter_remove(handler->timeout_waiter);
1217 handler->timeout_waiter = NULL;
1218 handler->autoboot_enabled = false;
1220 /* we only send status if we had a default boot option queued */
1221 if (!handler->default_boot_option)
1224 pb_log("Cancelling default boot option\n");
1226 if (handler->pending_boot && handler->pending_boot_is_default) {
1227 boot_cancel(handler->pending_boot);
1228 handler->pending_boot = NULL;
1229 handler->pending_boot_is_default = false;
1232 handler->default_boot_option = NULL;
1234 device_handler_status_info(handler, _("Default boot cancelled"));
1237 void device_handler_update_config(struct device_handler *handler,
1238 struct config *config)
1242 rc = config_set(config);
1246 discover_server_notify_config(handler->server, config);
1247 device_handler_update_lang(config->lang);
1248 device_handler_reinit(handler);
1251 static char *device_from_addr(void *ctx, struct pb_url *url)
1253 char *ipaddr, *buf, *tok, *dev = NULL;
1254 const char *delim = " ";
1255 struct sockaddr_in *ip;
1256 struct sockaddr_in si;
1257 struct addrinfo *res;
1261 /* Note: IPv4 only */
1262 rc = inet_pton(AF_INET, url->host, &(si.sin_addr));
1266 /* need to turn hostname into a valid IP */
1267 rc = getaddrinfo(url->host, NULL, NULL, &res);
1269 pb_debug("%s: Invalid URL\n",__func__);
1272 ipaddr = talloc_array(ctx,char,INET_ADDRSTRLEN);
1273 ip = (struct sockaddr_in *) res->ai_addr;
1274 inet_ntop(AF_INET, &(ip->sin_addr), ipaddr, INET_ADDRSTRLEN);
1278 const char *argv[] = {
1280 "route", "show", "to", "match",
1285 p = process_create(ctx);
1287 p->path = pb_system_apps.ip;
1289 p->keep_stdout = true;
1291 rc = process_run_sync(p);
1293 if (rc || p->exit_status) {
1294 /* ip has complained for some reason; most likely
1295 * there is no route to the host - bail out */
1296 pb_debug("%s: `ip` returns non-zero exit status\n", __func__);
1297 pb_debug("ip buf: %s\n", p->stdout_buf);
1302 buf = p->stdout_buf;
1303 /* If a route is found, ip-route output will be of the form
1304 * "... dev DEVNAME ... " */
1305 tok = strtok(buf, delim);
1307 if (!strcmp(tok, "dev")) {
1308 tok = strtok(NULL, delim);
1309 dev = talloc_strdup(ctx, tok);
1312 tok = strtok(NULL, delim);
1317 pb_debug("%s: Found interface '%s'\n", __func__,dev);
1321 static void process_url_cb(struct load_url_result *result, void *data)
1323 struct device_handler *handler;
1324 struct discover_context *ctx;
1325 struct discover_device *dev;
1326 struct event *event = data;
1329 if (result->status != LOAD_OK) {
1330 pb_log("%s: Load failed for %s\n", __func__, result->url->full);
1337 handler = talloc_parent(event);
1341 event->device = device_from_addr(event, result->url);
1342 if (!event->device) {
1343 pb_log("Downloaded a file but can't find its interface - pretending it was local\n");
1344 event->device = talloc_asprintf(event, "local");
1347 mac = event_get_param(event, "mac");
1348 char *url = talloc_asprintf(event, "file://%s", result->local);
1349 event_set_param(event, "pxeconffile", url);
1351 dev = discover_device_create(handler, mac, event->device);
1352 ctx = device_handler_discover_context_create(handler, dev);
1353 talloc_steal(ctx, event);
1356 iterate_parsers(ctx);
1358 device_handler_discover_context_commit(handler, ctx);
1360 talloc_unlink(handler, ctx);
1363 void device_handler_process_url(struct device_handler *handler,
1364 const char *url, const char *mac, const char *ip)
1366 struct discover_context *ctx;
1367 struct discover_device *dev;
1368 bool allow_async = false;
1369 struct pb_url *pb_url;
1370 struct event *event;
1372 event = talloc_zero(handler, struct event);
1373 event->type = EVENT_TYPE_USER;
1374 event->action = EVENT_ACTION_URL;
1376 pb_url = pb_url_parse(event, url);
1377 if (!pb_url || (pb_url->scheme != pb_url_file && !pb_url->host)) {
1378 device_handler_status_err(handler, _("Invalid config URL!"));
1383 if (url[strlen(url) - 1] == '/') {
1384 event_set_param(event, "pxepathprefix", url);
1385 event_set_param(event, "mac", mac);
1386 event_set_param(event, "ip", ip);
1387 event->device = device_from_addr(event, pb_url);
1388 if (!event->device) {
1389 device_handler_status_err(handler,
1390 _("Unable to route to host %s"),
1396 event_set_param(event, "pxeconffile", url);
1400 if (pb_url->scheme == pb_url_file)
1401 event->device = talloc_asprintf(event, "local");
1402 else if (allow_async) {
1403 /* If file is remote load asynchronously before passing to
1404 * parser. This allows us to wait for network to be available */
1405 if (!load_url_async(handler, pb_url, process_url_cb, event,
1407 pb_log("Failed to load url %s\n", pb_url->full);
1408 device_handler_status_err(handler, _("Failed to load URL!"));
1414 /* If path is local we can parse straight away */
1416 dev = discover_device_create(handler, mac, event->device);
1417 if (pb_url->scheme == pb_url_file)
1418 dev->device->type = DEVICE_TYPE_ANY;
1419 ctx = device_handler_discover_context_create(handler, dev);
1420 talloc_steal(ctx, event);
1423 iterate_parsers(ctx);
1425 device_handler_discover_context_commit(handler, ctx);
1427 talloc_unlink(handler, ctx);
1430 static void plugin_install_cb(struct process *process)
1432 struct device_handler *handler = process->data;
1435 pb_log("%s: Missing data!\n", __func__);
1439 handler->plugin_installing = false;
1440 if (process->exit_status) {
1441 device_handler_status_err(handler, "Plugin failed to install!");
1442 pb_log("Failed to install plugin:\n%s\n", process->stdout_buf);
1446 void device_handler_install_plugin(struct device_handler *handler,
1447 const char *plugin_file)
1452 if (handler->plugin_installing) {
1453 pb_log("Plugin install cancelled - install already running");
1457 p = process_create(handler);
1459 pb_log("install_plugin: Failed to create process\n");
1463 const char *argv[] = {
1464 pb_system_apps.pb_plugin,
1471 p->path = pb_system_apps.pb_plugin;
1473 p->exit_cb = plugin_install_cb;
1475 p->keep_stdout = true;
1477 result = process_run_async(p);
1480 device_handler_status_err(handler, "Could not install plugin");
1482 handler->plugin_installing = true;
1485 #ifndef PETITBOOT_TEST
1488 * context_commit - Commit a temporary discovery context to the handler,
1489 * and notify the clients about any new options / devices
1491 void device_handler_discover_context_commit(struct device_handler *handler,
1492 struct discover_context *ctx)
1494 struct discover_device *dev = ctx->device;
1495 struct discover_boot_option *opt, *tmp;
1497 if (!device_lookup_by_uuid(handler, dev->uuid))
1498 device_handler_add_device(handler, dev);
1500 /* move boot options from the context to the device */
1501 list_for_each_entry_safe(&ctx->boot_options, opt, tmp, list) {
1502 list_remove(&opt->list);
1504 /* All boot options need at least a kernel image */
1505 if (!opt->boot_image || !opt->boot_image->url) {
1506 pb_log("boot option %s is missing boot image, ignoring\n",
1512 if (boot_option_resolve(opt, handler)) {
1513 pb_log("boot option %s is resolved, "
1514 "sending to clients\n",
1516 list_add_tail(&dev->boot_options, &opt->list);
1517 talloc_steal(dev, opt);
1518 boot_option_finalise(handler, opt);
1519 notify_boot_option(handler, opt);
1521 if (!opt->source->resolve_resource) {
1522 pb_log("parser %s gave us an unresolved "
1523 "resource (%s), but no way to "
1525 opt->source->name, opt->option->id);
1528 pb_log("boot option %s is unresolved, "
1529 "adding to queue\n",
1531 list_add(&handler->unresolved_boot_options,
1533 talloc_steal(handler, opt);
1539 void device_handler_add_plugin_option(struct device_handler *handler,
1540 struct plugin_option *opt)
1542 struct plugin_option *tmp;
1545 for (i = 0; i < handler->n_plugins; i++) {
1546 tmp = handler->plugins[i];
1547 /* If both id and version match, ignore */
1548 if (strncmp(opt->id, tmp->id, strlen(opt->id)) == 0 &&
1549 strncmp(opt->version, tmp->version,
1550 strlen(opt->version) == 0)) {
1551 pb_log("discover: Plugin '%s' already exists, ignoring\n",
1557 handler->plugins = talloc_realloc(handler, handler->plugins,
1558 struct plugin_option *, handler->n_plugins + 1);
1559 if (!handler->plugins) {
1560 pb_log("Failed to allocate memory for new plugin\n");
1561 handler->n_plugins = 0;
1565 handler->plugins[handler->n_plugins++] = opt;
1566 discover_server_notify_plugin_option_add(handler->server, opt);
1569 static void device_handler_update_lang(const char *lang)
1571 const char *cur_lang;
1576 cur_lang = setlocale(LC_ALL, NULL);
1577 if (cur_lang && !strcmp(cur_lang, lang))
1580 setlocale(LC_ALL, lang);
1583 static int device_handler_init_sources(struct device_handler *handler)
1585 /* init our device sources: udev, network and user events */
1586 handler->user_event = user_event_init(handler, handler->waitset);
1587 if (!handler->user_event)
1590 handler->network = network_init(handler, handler->waitset,
1592 if (!handler->network)
1595 handler->udev = udev_init(handler, handler->waitset);
1602 static void device_handler_reinit_sources(struct device_handler *handler)
1604 /* if we haven't initialised sources previously (becuase we started in
1605 * safe mode), then init once here. */
1606 if (!(handler->udev || handler->network || handler->user_event)) {
1607 device_handler_init_sources(handler);
1611 system_info_reinit();
1613 network_shutdown(handler->network);
1614 handler->network = network_init(handler, handler->waitset,
1617 udev_reinit(handler->udev);
1620 static inline const char *get_device_path(struct discover_device *dev)
1622 return dev->ramdisk ? dev->ramdisk->snapshot : dev->device_path;
1625 static char *check_subvols(struct discover_device *dev)
1627 const char *fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1632 if (strncmp(fstype, "btrfs", strlen("btrfs")))
1633 return dev->mount_path;
1635 /* On btrfs a device's root may be under a subvolume path */
1636 path = join_paths(dev, dev->mount_path, "@");
1637 rc = stat(path, &sb);
1638 if (!rc && S_ISDIR(sb.st_mode)) {
1639 pb_debug("Using '%s' for btrfs root path\n", path);
1644 return dev->mount_path;
1647 static bool check_existing_mount(struct discover_device *dev)
1649 struct stat devstat, mntstat;
1650 const char *device_path;
1655 device_path = get_device_path(dev);
1657 rc = stat(device_path, &devstat);
1659 pb_debug("%s: stat failed: %s\n", __func__, strerror(errno));
1663 if (!S_ISBLK(devstat.st_mode)) {
1664 pb_debug("%s: %s isn't a block device?\n", __func__,
1669 fp = fopen("/proc/self/mounts", "r");
1672 mnt = getmntent(fp);
1676 if (!mnt->mnt_fsname || mnt->mnt_fsname[0] != '/')
1679 rc = stat(mnt->mnt_fsname, &mntstat);
1683 if (!S_ISBLK(mntstat.st_mode))
1686 if (mntstat.st_rdev == devstat.st_rdev) {
1687 dev->mount_path = talloc_strdup(dev, mnt->mnt_dir);
1688 dev->root_path = check_subvols(dev);
1689 dev->mounted_rw = !!hasmntopt(mnt, "rw");
1690 dev->mounted = true;
1691 dev->unmount = false;
1693 pb_debug("%s: %s is already mounted (r%c) at %s\n",
1694 __func__, dev->device_path,
1695 dev->mounted_rw ? 'w' : 'o',
1707 * Attempt to mount a filesystem safely, while handling certain filesytem-
1710 static int try_mount(const char *device_path, const char *mount_path,
1711 const char *fstype, unsigned long flags,
1714 const char *fs, *safe_opts;
1717 /* Mount ext3 as ext4 instead so 'norecovery' can be used */
1718 if (strncmp(fstype, "ext3", strlen("ext3")) == 0) {
1719 pb_debug("Mounting ext3 filesystem as ext4\n");
1724 if (strncmp(fs, "xfs", strlen("xfs")) == 0 ||
1725 strncmp(fs, "ext4", strlen("ext4")) == 0)
1726 safe_opts = "norecovery";
1731 /* If no snapshot is available don't attempt recovery */
1733 return mount(device_path, mount_path, fs, flags, safe_opts);
1735 rc = mount(device_path, mount_path, fs, flags, NULL);
1740 /* Mounting failed; some filesystems will fail to mount if a recovery
1741 * journal exists (eg. cross-endian XFS), so try again with norecovery
1742 * where that option is available.
1743 * If mounting read-write just return the error as norecovery is not a
1745 if ((flags & MS_RDONLY) != MS_RDONLY || !safe_opts)
1749 return mount(device_path, mount_path, fs, flags, safe_opts);
1752 static int mount_device(struct discover_device *dev)
1754 const char *fstype, *device_path;
1757 if (!dev->device_path)
1763 if (check_existing_mount(dev))
1766 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1770 dev->mount_path = join_paths(dev, mount_base(),
1773 if (pb_mkdir_recursive(dev->mount_path)) {
1774 pb_log("couldn't create mount directory %s: %s\n",
1775 dev->mount_path, strerror(errno));
1779 device_path = get_device_path(dev);
1781 pb_log("mounting device %s read-only\n", dev->device_path);
1782 rc = try_mount(device_path, dev->mount_path, fstype,
1783 MS_RDONLY | MS_SILENT, dev->ramdisk);
1786 dev->mounted = true;
1787 dev->mounted_rw = false;
1788 dev->unmount = true;
1789 dev->root_path = check_subvols(dev);
1793 pb_log("couldn't mount device %s: mount failed: %s\n",
1794 device_path, strerror(errno));
1796 /* If mount fails clean up any snapshot */
1797 devmapper_destroy_snapshot(dev);
1799 pb_rmdir_recursive(mount_base(), dev->mount_path);
1801 talloc_free(dev->mount_path);
1802 dev->mount_path = NULL;
1806 static int umount_device(struct discover_device *dev)
1808 const char *device_path;
1811 if (!dev->mounted || !dev->unmount)
1814 device_path = get_device_path(dev);
1816 pb_log("unmounting device %s\n", device_path);
1817 rc = umount(dev->mount_path);
1821 dev->mounted = false;
1822 devmapper_destroy_snapshot(dev);
1824 pb_rmdir_recursive(mount_base(), dev->mount_path);
1826 talloc_free(dev->mount_path);
1827 dev->mount_path = NULL;
1828 dev->root_path = NULL;
1833 int device_request_write(struct discover_device *dev, bool *release)
1835 const char *fstype, *device_path;
1836 const struct config *config;
1841 config = config_get();
1842 if (!config->allow_writes)
1848 if (dev->mounted_rw)
1851 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1853 device_path = get_device_path(dev);
1855 pb_log("remounting device %s read-write\n", device_path);
1857 rc = umount(dev->mount_path);
1859 pb_log("Failed to unmount %s: %s\n",
1860 dev->mount_path, strerror(errno));
1864 rc = try_mount(device_path, dev->mount_path, fstype,
1865 MS_SILENT, dev->ramdisk);
1869 dev->mounted_rw = true;
1874 pb_log("Unable to remount device %s read-write: %s\n",
1875 device_path, strerror(errno));
1876 rc = try_mount(device_path, dev->mount_path, fstype,
1877 MS_RDONLY | MS_SILENT, dev->ramdisk);
1879 pb_log("Unable to recover mount for %s: %s\n",
1880 device_path, strerror(errno));
1884 void device_release_write(struct discover_device *dev, bool release)
1886 const char *fstype, *device_path;
1891 device_path = get_device_path(dev);
1893 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1895 pb_log("remounting device %s read-only\n", device_path);
1897 if (umount(dev->mount_path)) {
1898 pb_log("Failed to unmount %s\n", dev->mount_path);
1901 dev->mounted_rw = dev->mounted = false;
1904 devmapper_merge_snapshot(dev);
1905 /* device_path becomes stale after merge */
1906 device_path = get_device_path(dev);
1909 if (try_mount(device_path, dev->mount_path, fstype,
1910 MS_RDONLY | MS_SILENT, dev->ramdisk))
1911 pb_log("Failed to remount %s read-only: %s\n",
1912 device_path, strerror(errno));
1914 dev->mounted = true;
1917 void device_sync_snapshots(struct device_handler *handler, const char *device)
1919 struct discover_device *dev = NULL;
1923 /* Find matching device and sync */
1924 dev = device_lookup_by_name(handler, device);
1926 pb_log("%s: device name '%s' unrecognised\n",
1931 device_release_write(dev, true);
1933 pb_log("%s has no snapshot to merge, skipping\n",
1938 /* Otherwise sync all relevant devices */
1939 for (i = 0; i < handler->n_devices; i++) {
1940 dev = handler->devices[i];
1941 if (dev->device->type != DEVICE_TYPE_DISK &&
1942 dev->device->type != DEVICE_TYPE_USB)
1945 device_release_write(dev, true);
1947 pb_log("%s has no snapshot to merge, skipping\n",
1954 void device_handler_discover_context_commit(
1955 struct device_handler *handler __attribute__((unused)),
1956 struct discover_context *ctx __attribute__((unused)))
1958 pb_log("%s stubbed out for test cases\n", __func__);
1961 static void device_handler_update_lang(const char *lang __attribute__((unused)))
1965 static int device_handler_init_sources(
1966 struct device_handler *handler __attribute__((unused)))
1971 static void device_handler_reinit_sources(
1972 struct device_handler *handler __attribute__((unused)))
1976 static int umount_device(struct discover_device *dev __attribute__((unused)))
1981 static int __attribute__((unused)) mount_device(
1982 struct discover_device *dev __attribute__((unused)))
1987 int device_request_write(struct discover_device *dev __attribute__((unused)),
1994 void device_release_write(struct discover_device *dev __attribute__((unused)),
1995 bool release __attribute__((unused)))
1999 void device_sync_snapshots(
2000 struct device_handler *handler __attribute__((unused)),
2001 const char *device __attribute__((unused)))