12 #include <sys/mount.h>
14 #include <talloc/talloc.h>
15 #include <list/list.h>
17 #include <types/types.h>
18 #include <system/system.h>
19 #include <process/process.h>
21 #include <i18n/i18n.h>
22 #include <pb-config/pb-config.h>
24 #include <sys/sysmacros.h>
25 #include <sys/types.h>
26 #include <sys/socket.h>
28 #include <arpa/inet.h>
30 #include "device-handler.h"
31 #include "discover-server.h"
32 #include "devmapper.h"
33 #include "user-event.h"
45 enum default_priority {
46 DEFAULT_PRIORITY_REMOTE = 1,
47 DEFAULT_PRIORITY_LOCAL_FIRST = 2,
48 DEFAULT_PRIORITY_LOCAL_LAST = 0xfe,
49 DEFAULT_PRIORITY_DISABLED = 0xff,
52 struct progress_info {
53 unsigned int percentage;
54 unsigned long size; /* size in bytes */
56 const struct process_info *procinfo;
57 struct list_item list;
60 struct device_handler {
61 struct discover_server *server;
65 struct network *network;
66 struct user_event *user_event;
68 struct discover_device **devices;
69 unsigned int n_devices;
71 struct ramdisk_device **ramdisks;
72 unsigned int n_ramdisks;
74 struct waitset *waitset;
75 struct waiter *timeout_waiter;
76 bool autoboot_enabled;
77 unsigned int sec_to_boot;
79 struct discover_boot_option *default_boot_option;
80 int default_boot_option_priority;
82 struct list unresolved_boot_options;
84 struct boot_task *pending_boot;
85 bool pending_boot_is_default;
88 unsigned int n_progress;
90 struct plugin_option **plugins;
91 unsigned int n_plugins;
92 bool plugin_installing;
95 static int mount_device(struct discover_device *dev);
96 static int umount_device(struct discover_device *dev);
98 static int device_handler_init_sources(struct device_handler *handler);
99 static void device_handler_reinit_sources(struct device_handler *handler);
101 static void device_handler_update_lang(const char *lang);
103 void discover_context_add_boot_option(struct discover_context *ctx,
104 struct discover_boot_option *boot_option)
106 boot_option->source = ctx->parser;
107 list_add_tail(&ctx->boot_options, &boot_option->list);
108 talloc_steal(ctx, boot_option);
112 * device_handler_get_device_count - Get the count of current handler devices.
115 int device_handler_get_device_count(const struct device_handler *handler)
117 return handler->n_devices;
121 * device_handler_get_device - Get a handler device by index.
124 const struct discover_device *device_handler_get_device(
125 const struct device_handler *handler, unsigned int index)
127 if (index >= handler->n_devices) {
128 assert(0 && "bad index");
132 return handler->devices[index];
136 * device_handler_get_plugin_count - Get the count of current handler plugins.
138 int device_handler_get_plugin_count(const struct device_handler *handler)
140 return handler->n_plugins;
144 * discover_handler_get_plugin - Get a handler plugin by index.
146 const struct plugin_option *device_handler_get_plugin(
147 const struct device_handler *handler, unsigned int index)
149 if (index >= handler->n_plugins) {
150 assert(0 && "bad index");
154 return handler->plugins[index];
157 struct network *device_handler_get_network(
158 const struct device_handler *handler)
160 return handler->network;
163 struct discover_boot_option *discover_boot_option_create(
164 struct discover_context *ctx,
165 struct discover_device *device)
167 struct discover_boot_option *opt;
169 opt = talloc_zero(ctx, struct discover_boot_option);
170 opt->option = talloc_zero(opt, struct boot_option);
171 opt->device = device;
176 static int device_match_uuid(struct discover_device *dev, const char *uuid)
178 return dev->uuid && !strcmp(dev->uuid, uuid);
181 static int device_match_label(struct discover_device *dev, const char *label)
183 return dev->label && !strcmp(dev->label, label);
186 static int device_match_id(struct discover_device *dev, const char *id)
188 return !strcmp(dev->device->id, id);
191 static int device_match_serial(struct discover_device *dev, const char *serial)
193 const char *val = discover_device_get_param(dev, "ID_SERIAL");
194 return val && !strcmp(val, serial);
197 static struct discover_device *device_lookup(
198 struct device_handler *device_handler,
199 int (match_fn)(struct discover_device *, const char *),
202 struct discover_device *dev;
208 for (i = 0; i < device_handler->n_devices; i++) {
209 dev = device_handler->devices[i];
211 if (match_fn(dev, str))
218 struct discover_device *device_lookup_by_name(struct device_handler *handler,
221 if (!strncmp(name, "/dev/", strlen("/dev/")))
222 name += strlen("/dev/");
224 return device_lookup_by_id(handler, name);
227 struct discover_device *device_lookup_by_uuid(
228 struct device_handler *device_handler,
231 return device_lookup(device_handler, device_match_uuid, uuid);
234 struct discover_device *device_lookup_by_label(
235 struct device_handler *device_handler,
238 return device_lookup(device_handler, device_match_label, label);
241 struct discover_device *device_lookup_by_id(
242 struct device_handler *device_handler,
245 return device_lookup(device_handler, device_match_id, id);
248 struct discover_device *device_lookup_by_serial(
249 struct device_handler *device_handler,
252 return device_lookup(device_handler, device_match_serial, serial);
255 void device_handler_destroy(struct device_handler *handler)
257 talloc_free(handler);
260 static int destroy_device(void *arg)
262 struct discover_device *dev = arg;
269 struct discover_device *discover_device_create(struct device_handler *handler,
270 const char *uuid, const char *id)
272 struct discover_device *dev;
275 dev = device_lookup_by_uuid(handler, uuid);
277 dev = device_lookup_by_id(handler, id);
282 dev = talloc_zero(handler, struct discover_device);
283 dev->device = talloc_zero(dev, struct device);
284 dev->device->id = talloc_strdup(dev->device, id);
285 dev->uuid = talloc_strdup(dev, uuid);
286 list_init(&dev->params);
287 list_init(&dev->boot_options);
289 talloc_set_destructor(dev, destroy_device);
294 struct discover_device_param {
297 struct list_item list;
300 void discover_device_set_param(struct discover_device *device,
301 const char *name, const char *value)
303 struct discover_device_param *param;
306 list_for_each_entry(&device->params, param, list) {
307 if (!strcmp(param->name, name)) {
316 param = talloc(device, struct discover_device_param);
317 param->name = talloc_strdup(param, name);
318 list_add(&device->params, ¶m->list);
321 list_remove(¶m->list);
325 talloc_free(param->value);
328 param->value = talloc_strdup(param, value);
331 const char *discover_device_get_param(struct discover_device *device,
334 struct discover_device_param *param;
336 list_for_each_entry(&device->params, param, list) {
337 if (!strcmp(param->name, name))
343 static void set_env_variables(const struct config *config)
345 if (config->http_proxy)
346 setenv("http_proxy", config->http_proxy, 1);
348 unsetenv("http_proxy");
350 if (config->https_proxy)
351 setenv("https_proxy", config->https_proxy, 1);
353 unsetenv("https_proxy");
355 /* Reduce noise in the log from LVM listing open file descriptors */
356 setenv("LVM_SUPPRESS_FD_WARNINGS", "1", 1);
359 struct device_handler *device_handler_init(struct discover_server *server,
360 struct waitset *waitset, int dry_run)
362 struct device_handler *handler;
365 handler = talloc_zero(NULL, struct device_handler);
366 handler->server = server;
367 handler->waitset = waitset;
368 handler->dry_run = dry_run;
369 handler->autoboot_enabled = config_autoboot_active(config_get());
371 list_init(&handler->unresolved_boot_options);
373 list_init(&handler->progress);
375 /* set up our mount point base */
376 pb_mkdir_recursive(mount_base());
380 if (config_get()->safe_mode)
383 set_env_variables(config_get());
385 rc = device_handler_init_sources(handler);
387 talloc_free(handler);
394 void device_handler_reinit(struct device_handler *handler)
396 struct discover_boot_option *opt, *tmp;
397 struct ramdisk_device *ramdisk;
398 struct config *config;
401 device_handler_cancel_default(handler);
402 /* Cancel any pending non-default boot */
403 if (handler->pending_boot) {
404 boot_cancel(handler->pending_boot);
405 handler->pending_boot = NULL;
406 handler->pending_boot_is_default = false;
409 /* Cancel any remaining async jobs */
410 process_stop_async_all();
411 pending_network_jobs_cancel();
413 /* free unresolved boot options */
414 list_for_each_entry_safe(&handler->unresolved_boot_options,
417 list_init(&handler->unresolved_boot_options);
419 /* drop all devices */
420 for (i = 0; i < handler->n_devices; i++) {
421 discover_server_notify_device_remove(handler->server,
422 handler->devices[i]->device);
423 ramdisk = handler->devices[i]->ramdisk;
424 talloc_free(handler->devices[i]);
425 talloc_free(ramdisk);
428 talloc_free(handler->devices);
429 handler->devices = NULL;
430 handler->n_devices = 0;
431 talloc_free(handler->ramdisks);
432 handler->ramdisks = NULL;
433 handler->n_ramdisks = 0;
435 /* drop any known plugins */
436 for (i = 0; i < handler->n_plugins; i++)
437 talloc_free(handler->plugins[i]);
438 talloc_free(handler->plugins);
439 handler->plugins = NULL;
440 handler->n_plugins = 0;
442 discover_server_notify_plugins_remove(handler->server);
444 set_env_variables(config_get());
446 /* If the safe mode warning was active disable it now */
447 if (config_get()->safe_mode) {
448 config = config_copy(handler, config_get());
449 config->safe_mode = false;
451 discover_server_notify_config(handler->server, config);
454 device_handler_reinit_sources(handler);
457 void device_handler_remove(struct device_handler *handler,
458 struct discover_device *device)
460 struct discover_boot_option *opt, *tmp;
463 list_for_each_entry_safe(&device->boot_options, opt, tmp, list) {
464 if (opt == handler->default_boot_option) {
465 pb_log("Default option %s cancelled since device removed",
467 device_handler_cancel_default(handler);
472 for (i = 0; i < handler->n_devices; i++)
473 if (handler->devices[i] == device)
476 if (i == handler->n_devices) {
481 /* Free any unresolved options, as they're currently allocated
482 * against the handler */
483 list_for_each_entry_safe(&handler->unresolved_boot_options,
485 if (opt->device != device)
487 list_remove(&opt->list);
491 /* if this is a network device, we have to unregister it from the
493 if (device->device->type == DEVICE_TYPE_NETWORK)
494 network_unregister_device(handler->network, device);
496 handler->n_devices--;
497 memmove(&handler->devices[i], &handler->devices[i + 1],
498 (handler->n_devices - i) * sizeof(handler->devices[0]));
499 handler->devices = talloc_realloc(handler, handler->devices,
500 struct discover_device *, handler->n_devices);
502 if (device->notified)
503 discover_server_notify_device_remove(handler->server,
509 void device_handler_status(struct device_handler *handler,
510 struct status *status)
512 discover_server_notify_boot_status(handler->server, status);
515 static void _device_handler_vstatus(struct device_handler *handler,
516 enum status_type type, const char *fmt, va_list ap)
518 struct status status;
521 status.message = talloc_vasprintf(handler, fmt, ap);
522 status.backlog = false;
524 device_handler_status(handler, &status);
526 talloc_free(status.message);
529 static void _device_handler_vdevstatus(struct device_handler *handler,
530 struct discover_device *device, enum status_type type,
531 const char *fmt, va_list ap)
535 msg = talloc_asprintf(handler, "[%s] %s",
536 device ? device->device->id : "unknown", fmt);
537 _device_handler_vstatus(handler, type, msg, ap);
541 void device_handler_status_dev_info(struct device_handler *handler,
542 struct discover_device *dev, const char *fmt, ...)
547 _device_handler_vdevstatus(handler, dev, STATUS_INFO, fmt, ap);
551 void device_handler_status_dev_err(struct device_handler *handler,
552 struct discover_device *dev, const char *fmt, ...)
557 _device_handler_vdevstatus(handler, dev, STATUS_ERROR, fmt, ap);
561 void device_handler_status_info(struct device_handler *handler,
562 const char *fmt, ...)
567 _device_handler_vstatus(handler, STATUS_INFO, fmt, ap);
571 void device_handler_status_err(struct device_handler *handler,
572 const char *fmt, ...)
577 _device_handler_vstatus(handler, STATUS_ERROR, fmt, ap);
581 void device_handler_status_download(struct device_handler *handler,
582 const struct process_info *procinfo,
583 unsigned int percentage, unsigned int size, char suffix)
585 struct progress_info *p, *progress = NULL;
586 uint64_t current_converted, current = 0;
587 const char *units = " kMGTP";
588 unsigned long size_bytes;
594 list_for_each_entry(&handler->progress, p, list)
595 if (p->procinfo == procinfo)
599 pb_log("Registering new progress struct\n");
600 progress = talloc_zero(handler, struct progress_info);
602 pb_log("Failed to allocate room for progress struct\n");
605 progress->procinfo = procinfo;
606 list_add(&handler->progress, &progress->list);
607 handler->n_progress++;
611 for (i = 0; i < strlen(units); i++) {
612 if (units[i] == suffix)
616 if (i >= strlen(units)) {
617 pb_log("Couldn't recognise suffix '%c'\n", suffix);
624 progress->percentage = percentage;
625 progress->size = size_bytes;
628 * Aggregate the info we have and update status. If a progress struct
629 * has zero for both percentage and size we assume progress information
630 * is unavailable and fall back to a generic progress message.
632 list_for_each_entry(&handler->progress, p, list) {
635 if (!p->percentage || !p->size) {
636 update = talloc_asprintf(handler,
637 _("%u downloads in progress..."),
638 handler->n_progress);
644 t = (100 * c) / p->percentage;
651 current_converted = current;
652 while (current_converted >= 1000) {
653 current_converted >>= 10;
656 update = talloc_asprintf(handler,
657 _("%u %s downloading: %.0f%% - %" PRIu64 "%cB"),
659 ngettext("item", "items", handler->n_progress),
660 (current / total) * 100, current_converted,
665 pb_log("%s: failed to allocate new status\n", __func__);
667 device_handler_status_info(handler, "%s\n", update);
672 static void device_handler_plugin_scan_device(struct device_handler *handler,
673 struct discover_device *dev)
677 pb_debug("Scanning %s for plugin files\n", dev->device->id);
679 rc = process_run_simple(handler, pb_system_apps.pb_plugin,
680 "scan", dev->mount_path,
683 pb_log("Error from pb-plugin scan %s\n",
687 void device_handler_status_download_remove(struct device_handler *handler,
688 struct process_info *procinfo)
690 struct progress_info *p, *tmp;
692 list_for_each_entry_safe(&handler->progress, p, tmp, list)
693 if (p->procinfo == procinfo) {
694 list_remove(&p->list);
696 handler->n_progress--;
700 static void device_handler_boot_status_cb(void *arg, struct status *status)
702 device_handler_status(arg, status);
705 static void countdown_status(struct device_handler *handler,
706 struct discover_boot_option *opt, unsigned int sec)
708 struct status status;
710 status.type = STATUS_INFO;
711 status.message = talloc_asprintf(handler,
712 _("Booting in %d sec: [%s] %s"), sec,
713 opt->device->device->id, opt->option->name);
714 status.backlog = false;
716 device_handler_status(handler, &status);
718 talloc_free(status.message);
721 static int default_timeout(void *arg)
723 struct device_handler *handler = arg;
724 struct discover_boot_option *opt;
726 if (!handler->default_boot_option)
729 if (handler->pending_boot)
732 opt = handler->default_boot_option;
734 if (handler->sec_to_boot) {
735 countdown_status(handler, opt, handler->sec_to_boot);
736 handler->sec_to_boot--;
737 handler->timeout_waiter = waiter_register_timeout(
738 handler->waitset, 1000,
739 default_timeout, handler);
743 handler->timeout_waiter = NULL;
745 pb_log("Timeout expired, booting default option %s\n", opt->option->id);
749 handler->pending_boot = boot(handler, handler->default_boot_option,
750 NULL, handler->dry_run, device_handler_boot_status_cb,
752 handler->pending_boot_is_default = true;
757 enum ipmi_bootdev ipmi_type;
758 enum device_type device_type;
759 } device_type_map[] = {
760 { IPMI_BOOTDEV_NETWORK, DEVICE_TYPE_NETWORK },
761 { IPMI_BOOTDEV_DISK, DEVICE_TYPE_DISK },
762 { IPMI_BOOTDEV_DISK, DEVICE_TYPE_USB },
763 { IPMI_BOOTDEV_CDROM, DEVICE_TYPE_OPTICAL },
766 static bool ipmi_device_type_matches(enum ipmi_bootdev ipmi_type,
767 enum device_type device_type)
771 for (i = 0; i < ARRAY_SIZE(device_type_map); i++) {
772 if (device_type_map[i].device_type == device_type)
773 return device_type_map[i].ipmi_type == ipmi_type;
779 static int autoboot_option_priority(const struct config *config,
780 struct discover_boot_option *opt)
782 enum device_type type = opt->device->device->type;
783 const char *uuid = opt->device->uuid;
784 struct autoboot_option *auto_opt;
787 for (i = 0; i < config->n_autoboot_opts; i++) {
788 auto_opt = &config->autoboot_opts[i];
789 if (auto_opt->boot_type == BOOT_DEVICE_UUID)
790 if (!strcmp(auto_opt->uuid, uuid))
791 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
793 if (auto_opt->boot_type == BOOT_DEVICE_TYPE)
794 if (auto_opt->type == type ||
795 auto_opt->type == DEVICE_TYPE_ANY)
796 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
803 * We have different priorities to resolve conflicts between boot options that
804 * report to be the default for their device. This function assigns a priority
807 static enum default_priority default_option_priority(
808 struct discover_boot_option *opt)
810 const struct config *config;
812 config = config_get();
814 /* We give highest priority to IPMI-configured boot options. If
815 * we have an IPMI bootdev configuration set, then we don't allow
816 * any other defaults */
817 if (config->ipmi_bootdev) {
818 bool ipmi_match = ipmi_device_type_matches(config->ipmi_bootdev,
819 opt->device->device->type);
821 return DEFAULT_PRIORITY_REMOTE;
823 pb_debug("handler: disabled default priority due to "
824 "non-matching IPMI type %x\n",
825 config->ipmi_bootdev);
826 return DEFAULT_PRIORITY_DISABLED;
829 /* Next, try to match the option against the user-defined autoboot
830 * options, either by device UUID or type. */
831 if (config->n_autoboot_opts) {
832 int boot_match = autoboot_option_priority(config, opt);
837 /* If the option didn't match any entry in the array, it is disabled */
838 pb_debug("handler: disabled default priority due to "
839 "non-matching UUID or type\n");
840 return DEFAULT_PRIORITY_DISABLED;
843 static void set_default(struct device_handler *handler,
844 struct discover_boot_option *opt)
846 enum default_priority cur_prio, new_prio;
848 if (!handler->autoboot_enabled)
851 pb_debug("handler: new default option: %s\n", opt->option->id);
853 new_prio = default_option_priority(opt);
855 /* Anything outside our range prevents a default boot */
856 if (new_prio >= DEFAULT_PRIORITY_DISABLED)
859 pb_debug("handler: calculated priority %d\n", new_prio);
861 /* Resolve any conflicts: if we have a new default option, it only
862 * replaces the current if it has a higher priority. */
863 if (handler->default_boot_option) {
865 cur_prio = handler->default_boot_option_priority;
867 if (new_prio < cur_prio) {
868 pb_log("handler: new prio %d beats "
869 "old prio %d for %s\n",
871 handler->default_boot_option
873 handler->default_boot_option = opt;
874 handler->default_boot_option_priority = new_prio;
875 /* extend the timeout a little, so the user sees some
876 * indication of the change */
877 handler->sec_to_boot += 2;
883 handler->sec_to_boot = config_get()->autoboot_timeout_sec;
884 handler->default_boot_option = opt;
885 handler->default_boot_option_priority = new_prio;
887 pb_log("handler: boot option %s set as default, timeout %u sec.\n",
888 opt->option->id, handler->sec_to_boot);
890 default_timeout(handler);
893 static bool resource_is_resolved(struct resource *res)
895 return !res || res->resolved;
898 /* We only use this in an assert, which will disappear if we're compiling
899 * with NDEBUG, so we need the 'used' attribute for these builds */
900 static bool __attribute__((used)) boot_option_is_resolved(
901 struct discover_boot_option *opt)
903 return resource_is_resolved(opt->boot_image) &&
904 resource_is_resolved(opt->initrd) &&
905 resource_is_resolved(opt->dtb) &&
906 resource_is_resolved(opt->args_sig_file) &&
907 resource_is_resolved(opt->icon);
910 static bool resource_resolve(struct resource *res, const char *name,
911 struct discover_boot_option *opt,
912 struct device_handler *handler)
914 struct parser *parser = opt->source;
916 if (resource_is_resolved(res))
919 pb_debug("Attempting to resolve resource %s->%s with parser %s\n",
920 opt->option->id, name, parser->name);
921 parser->resolve_resource(handler, res);
923 return res->resolved;
926 static bool boot_option_resolve(struct discover_boot_option *opt,
927 struct device_handler *handler)
929 return resource_resolve(opt->boot_image, "boot_image", opt, handler) &&
930 resource_resolve(opt->initrd, "initrd", opt, handler) &&
931 resource_resolve(opt->dtb, "dtb", opt, handler) &&
932 resource_resolve(opt->args_sig_file, "args_sig_file", opt,
934 resource_resolve(opt->icon, "icon", opt, handler);
937 static void boot_option_finalise(struct device_handler *handler,
938 struct discover_boot_option *opt)
940 assert(boot_option_is_resolved(opt));
942 /* check that the parsers haven't set any of the final data */
943 assert(!opt->option->boot_image_file);
944 assert(!opt->option->initrd_file);
945 assert(!opt->option->dtb_file);
946 assert(!opt->option->icon_file);
947 assert(!opt->option->device_id);
948 assert(!opt->option->args_sig_file);
951 opt->option->boot_image_file = opt->boot_image->url->full;
953 opt->option->initrd_file = opt->initrd->url->full;
955 opt->option->dtb_file = opt->dtb->url->full;
957 opt->option->icon_file = opt->icon->url->full;
958 if (opt->args_sig_file)
959 opt->option->args_sig_file = opt->args_sig_file->url->full;
961 opt->option->device_id = opt->device->device->id;
963 if (opt->option->is_default)
964 set_default(handler, opt);
967 static void notify_boot_option(struct device_handler *handler,
968 struct discover_boot_option *opt)
970 struct discover_device *dev = opt->device;
973 discover_server_notify_device_add(handler->server,
974 opt->device->device);
975 dev->notified = true;
976 discover_server_notify_boot_option_add(handler->server, opt->option);
979 static void process_boot_option_queue(struct device_handler *handler)
981 struct discover_boot_option *opt, *tmp;
983 list_for_each_entry_safe(&handler->unresolved_boot_options,
986 pb_debug("queue: attempting resolution for %s\n",
989 if (!boot_option_resolve(opt, handler))
992 pb_debug("\tresolved!\n");
994 list_remove(&opt->list);
995 list_add_tail(&opt->device->boot_options, &opt->list);
996 talloc_steal(opt->device, opt);
997 boot_option_finalise(handler, opt);
998 notify_boot_option(handler, opt);
1002 struct discover_context *device_handler_discover_context_create(
1003 struct device_handler *handler,
1004 struct discover_device *device)
1006 struct discover_context *ctx;
1008 ctx = talloc_zero(handler, struct discover_context);
1009 ctx->handler = handler;
1010 ctx->device = device;
1011 list_init(&ctx->boot_options);
1016 void device_handler_add_device(struct device_handler *handler,
1017 struct discover_device *device)
1019 handler->n_devices++;
1020 handler->devices = talloc_realloc(handler, handler->devices,
1021 struct discover_device *, handler->n_devices);
1022 handler->devices[handler->n_devices - 1] = device;
1024 if (device->device->type == DEVICE_TYPE_NETWORK)
1025 network_register_device(handler->network, device);
1028 void device_handler_add_ramdisk(struct device_handler *handler,
1031 struct ramdisk_device *dev;
1037 for (i = 0; i < handler->n_ramdisks; i++)
1038 if (!strcmp(handler->ramdisks[i]->path, path))
1041 dev = talloc_zero(handler, struct ramdisk_device);
1043 pb_log("Failed to allocate memory to track %s\n", path);
1047 dev->path = talloc_strdup(handler, path);
1049 handler->ramdisks = talloc_realloc(handler, handler->ramdisks,
1050 struct ramdisk_device *,
1051 handler->n_ramdisks + 1);
1052 if (!handler->ramdisks) {
1053 pb_log("Failed to reallocate memory"
1054 "- ramdisk tracking inconsistent!\n");
1058 handler->ramdisks[i] = dev;
1059 i = handler->n_ramdisks++;
1062 struct ramdisk_device *device_handler_get_ramdisk(
1063 struct device_handler *handler)
1069 /* Check if free ramdisk exists */
1070 for (i = 0; i < handler->n_ramdisks; i++)
1071 if (!handler->ramdisks[i]->snapshot &&
1072 !handler->ramdisks[i]->origin &&
1073 !handler->ramdisks[i]->base)
1074 return handler->ramdisks[i];
1076 /* Otherwise create a new one */
1077 name = talloc_asprintf(handler, "/dev/ram%d",
1078 handler->n_ramdisks);
1080 pb_debug("Failed to allocate memory to name /dev/ram%d",
1081 handler->n_ramdisks);
1085 id = makedev(1, handler->n_ramdisks);
1086 if (mknod(name, S_IFBLK, id)) {
1087 if (errno == EEXIST) {
1088 /* We haven't yet received updates for existing
1089 * ramdisks - add and use this one */
1090 pb_debug("Using untracked ramdisk %s\n", name);
1092 pb_log("Failed to create new ramdisk %s: %s\n",
1093 name, strerror(errno));
1097 device_handler_add_ramdisk(handler, name);
1100 return handler->ramdisks[i];
1103 void device_handler_release_ramdisk(struct discover_device *device)
1105 struct ramdisk_device *ramdisk = device->ramdisk;
1107 talloc_free(ramdisk->snapshot);
1108 talloc_free(ramdisk->origin);
1109 talloc_free(ramdisk->base);
1111 ramdisk->snapshot = ramdisk->origin = ramdisk->base = NULL;
1112 ramdisk->sectors = 0;
1114 device->ramdisk = NULL;
1117 /* Start discovery on a hotplugged device. The device will be in our devices
1118 * array, but has only just been initialised by the hotplug source.
1120 int device_handler_discover(struct device_handler *handler,
1121 struct discover_device *dev)
1123 struct discover_context *ctx;
1126 device_handler_status_dev_info(handler, dev,
1128 * TRANSLATORS: this string will be passed the type of the
1129 * device (eg "disk" or "network"), which will be translated
1132 _("Processing new %s device"),
1133 device_type_display_name(dev->device->type));
1135 /* create our context */
1136 ctx = device_handler_discover_context_create(handler, dev);
1138 rc = mount_device(dev);
1142 /* add this device to our system info */
1143 system_info_register_blockdev(dev->device->id, dev->uuid,
1146 /* run the parsers. This will populate the ctx's boot_option list. */
1147 iterate_parsers(ctx);
1149 /* add discovered stuff to the handler */
1150 device_handler_discover_context_commit(handler, ctx);
1152 process_boot_option_queue(handler);
1154 /* Check this device for pb-plugins */
1155 device_handler_plugin_scan_device(handler, dev);
1157 talloc_unlink(handler, ctx);
1162 /* Incoming dhcp event */
1163 int device_handler_dhcp(struct device_handler *handler,
1164 struct discover_device *dev, struct event *event)
1166 struct discover_context *ctx;
1168 device_handler_status_dev_info(handler, dev,
1169 _("Processing DHCP lease response (ip: %s)"),
1170 event_get_param(event, "ip"));
1172 pending_network_jobs_start();
1174 /* create our context */
1175 ctx = device_handler_discover_context_create(handler, dev);
1176 talloc_steal(ctx, event);
1179 iterate_parsers(ctx);
1181 device_handler_discover_context_commit(handler, ctx);
1183 talloc_unlink(handler, ctx);
1188 static struct discover_boot_option *find_boot_option_by_id(
1189 struct device_handler *handler, const char *id)
1193 for (i = 0; i < handler->n_devices; i++) {
1194 struct discover_device *dev = handler->devices[i];
1195 struct discover_boot_option *opt;
1197 list_for_each_entry(&dev->boot_options, opt, list)
1198 if (!strcmp(opt->option->id, id))
1205 void device_handler_boot(struct device_handler *handler,
1206 struct boot_command *cmd)
1208 struct discover_boot_option *opt = NULL;
1210 if (cmd->option_id && strlen(cmd->option_id))
1211 opt = find_boot_option_by_id(handler, cmd->option_id);
1213 if (handler->pending_boot)
1214 boot_cancel(handler->pending_boot);
1216 platform_pre_boot();
1218 handler->pending_boot = boot(handler, opt, cmd, handler->dry_run,
1219 device_handler_boot_status_cb, handler);
1220 handler->pending_boot_is_default = false;
1223 void device_handler_cancel_default(struct device_handler *handler)
1225 if (handler->timeout_waiter)
1226 waiter_remove(handler->timeout_waiter);
1228 handler->timeout_waiter = NULL;
1229 handler->autoboot_enabled = false;
1231 /* we only send status if we had a default boot option queued */
1232 if (!handler->default_boot_option)
1235 pb_log("Cancelling default boot option\n");
1237 if (handler->pending_boot && handler->pending_boot_is_default) {
1238 boot_cancel(handler->pending_boot);
1239 handler->pending_boot = NULL;
1240 handler->pending_boot_is_default = false;
1243 handler->default_boot_option = NULL;
1245 device_handler_status_info(handler, _("Default boot cancelled"));
1248 void device_handler_update_config(struct device_handler *handler,
1249 struct config *config)
1253 rc = config_set(config);
1257 discover_server_notify_config(handler->server, config);
1258 device_handler_update_lang(config->lang);
1259 device_handler_reinit(handler);
1262 static char *device_from_addr(void *ctx, struct pb_url *url)
1264 char *ipaddr, *buf, *tok, *dev = NULL;
1265 const char *delim = " ";
1266 struct sockaddr_in *ip;
1267 struct sockaddr_in si;
1268 struct addrinfo *res;
1272 /* Note: IPv4 only */
1273 rc = inet_pton(AF_INET, url->host, &(si.sin_addr));
1277 /* need to turn hostname into a valid IP */
1278 rc = getaddrinfo(url->host, NULL, NULL, &res);
1280 pb_debug("%s: Invalid URL\n",__func__);
1283 ipaddr = talloc_array(ctx,char,INET_ADDRSTRLEN);
1284 ip = (struct sockaddr_in *) res->ai_addr;
1285 inet_ntop(AF_INET, &(ip->sin_addr), ipaddr, INET_ADDRSTRLEN);
1289 const char *argv[] = {
1291 "route", "show", "to", "match",
1296 p = process_create(ctx);
1298 p->path = pb_system_apps.ip;
1300 p->keep_stdout = true;
1302 rc = process_run_sync(p);
1304 if (rc || p->exit_status) {
1305 /* ip has complained for some reason; most likely
1306 * there is no route to the host - bail out */
1307 pb_debug("%s: `ip` returns non-zero exit status\n", __func__);
1308 pb_debug("ip buf: %s\n", p->stdout_buf);
1313 buf = p->stdout_buf;
1314 /* If a route is found, ip-route output will be of the form
1315 * "... dev DEVNAME ... " */
1316 tok = strtok(buf, delim);
1318 if (!strcmp(tok, "dev")) {
1319 tok = strtok(NULL, delim);
1320 dev = talloc_strdup(ctx, tok);
1323 tok = strtok(NULL, delim);
1328 pb_debug("%s: Found interface '%s'\n", __func__,dev);
1332 static void process_url_cb(struct load_url_result *result, void *data)
1334 struct device_handler *handler;
1335 struct discover_context *ctx;
1336 struct discover_device *dev;
1337 struct event *event = data;
1340 if (result->status != LOAD_OK) {
1341 pb_log("%s: Load failed for %s\n", __func__, result->url->full);
1348 handler = talloc_parent(event);
1352 event->device = device_from_addr(event, result->url);
1353 if (!event->device) {
1354 pb_log("Downloaded a file but can't find its interface - pretending it was local\n");
1355 event->device = talloc_asprintf(event, "local");
1358 mac = event_get_param(event, "mac");
1359 char *url = talloc_asprintf(event, "file://%s", result->local);
1360 event_set_param(event, "pxeconffile-local", url);
1362 dev = discover_device_create(handler, mac, event->device);
1363 ctx = device_handler_discover_context_create(handler, dev);
1364 talloc_steal(ctx, event);
1367 iterate_parsers(ctx);
1369 device_handler_discover_context_commit(handler, ctx);
1371 talloc_unlink(handler, ctx);
1374 void device_handler_process_url(struct device_handler *handler,
1375 const char *url, const char *mac, const char *ip)
1377 struct discover_context *ctx;
1378 struct discover_device *dev;
1379 bool allow_async = false;
1380 struct pb_url *pb_url;
1381 struct event *event;
1383 event = talloc_zero(handler, struct event);
1384 event->type = EVENT_TYPE_USER;
1385 event->action = EVENT_ACTION_URL;
1387 pb_url = pb_url_parse(event, url);
1388 if (!pb_url || (pb_url->scheme != pb_url_file && !pb_url->host)) {
1389 device_handler_status_err(handler, _("Invalid config URL!"));
1394 if (url[strlen(url) - 1] == '/') {
1395 event_set_param(event, "pxepathprefix", url);
1396 event_set_param(event, "mac", mac);
1397 event_set_param(event, "ip", ip);
1398 event->device = device_from_addr(event, pb_url);
1399 if (!event->device) {
1400 device_handler_status_err(handler,
1401 _("Unable to route to host %s"),
1407 event_set_param(event, "pxeconffile", url);
1411 if (pb_url->scheme == pb_url_file)
1412 event->device = talloc_asprintf(event, "local");
1413 else if (allow_async) {
1414 /* If file is remote load asynchronously before passing to
1415 * parser. This allows us to wait for network to be available */
1416 if (!load_url_async(handler, pb_url, process_url_cb, event,
1418 pb_log("Failed to load url %s\n", pb_url->full);
1419 device_handler_status_err(handler, _("Failed to load URL!"));
1425 /* If path is local we can parse straight away */
1427 dev = discover_device_create(handler, mac, event->device);
1428 if (pb_url->scheme == pb_url_file)
1429 dev->device->type = DEVICE_TYPE_ANY;
1430 ctx = device_handler_discover_context_create(handler, dev);
1431 talloc_steal(ctx, event);
1434 iterate_parsers(ctx);
1436 device_handler_discover_context_commit(handler, ctx);
1438 talloc_unlink(handler, ctx);
1441 static void plugin_install_cb(struct process *process)
1443 struct device_handler *handler = process->data;
1446 pb_log("%s: Missing data!\n", __func__);
1450 handler->plugin_installing = false;
1451 if (process->exit_status) {
1452 device_handler_status_err(handler, "Plugin failed to install!");
1453 pb_log("Failed to install plugin:\n%s\n", process->stdout_buf);
1457 void device_handler_install_plugin(struct device_handler *handler,
1458 const char *plugin_file)
1463 if (handler->plugin_installing) {
1464 pb_log("Plugin install cancelled - install already running");
1468 p = process_create(handler);
1470 pb_log("install_plugin: Failed to create process\n");
1474 const char *argv[] = {
1475 pb_system_apps.pb_plugin,
1482 p->path = pb_system_apps.pb_plugin;
1484 p->exit_cb = plugin_install_cb;
1486 p->keep_stdout = true;
1488 result = process_run_async(p);
1491 device_handler_status_err(handler, "Could not install plugin");
1493 handler->plugin_installing = true;
1496 #ifndef PETITBOOT_TEST
1499 * context_commit - Commit a temporary discovery context to the handler,
1500 * and notify the clients about any new options / devices
1502 void device_handler_discover_context_commit(struct device_handler *handler,
1503 struct discover_context *ctx)
1505 struct discover_device *dev = ctx->device;
1506 struct discover_boot_option *opt, *tmp;
1508 if (!device_lookup_by_uuid(handler, dev->uuid))
1509 device_handler_add_device(handler, dev);
1511 /* move boot options from the context to the device */
1512 list_for_each_entry_safe(&ctx->boot_options, opt, tmp, list) {
1513 list_remove(&opt->list);
1515 /* All boot options need at least a kernel image */
1516 if (!opt->boot_image || !opt->boot_image->url) {
1517 pb_log("boot option %s is missing boot image, ignoring\n",
1523 if (boot_option_resolve(opt, handler)) {
1524 pb_log("boot option %s is resolved, "
1525 "sending to clients\n",
1527 list_add_tail(&dev->boot_options, &opt->list);
1528 talloc_steal(dev, opt);
1529 boot_option_finalise(handler, opt);
1530 notify_boot_option(handler, opt);
1532 if (!opt->source->resolve_resource) {
1533 pb_log("parser %s gave us an unresolved "
1534 "resource (%s), but no way to "
1536 opt->source->name, opt->option->id);
1539 pb_log("boot option %s is unresolved, "
1540 "adding to queue\n",
1542 list_add(&handler->unresolved_boot_options,
1544 talloc_steal(handler, opt);
1550 void device_handler_add_plugin_option(struct device_handler *handler,
1551 struct plugin_option *opt)
1553 struct plugin_option *tmp;
1556 for (i = 0; i < handler->n_plugins; i++) {
1557 tmp = handler->plugins[i];
1558 /* If both id and version match, ignore */
1559 if (strncmp(opt->id, tmp->id, strlen(opt->id)) == 0 &&
1560 strncmp(opt->version, tmp->version,
1561 strlen(opt->version) == 0)) {
1562 pb_log("discover: Plugin '%s' already exists, ignoring\n",
1568 handler->plugins = talloc_realloc(handler, handler->plugins,
1569 struct plugin_option *, handler->n_plugins + 1);
1570 if (!handler->plugins) {
1571 pb_log("Failed to allocate memory for new plugin\n");
1572 handler->n_plugins = 0;
1576 handler->plugins[handler->n_plugins++] = opt;
1577 discover_server_notify_plugin_option_add(handler->server, opt);
1580 static void device_handler_update_lang(const char *lang)
1582 const char *cur_lang;
1587 cur_lang = setlocale(LC_ALL, NULL);
1588 if (cur_lang && !strcmp(cur_lang, lang))
1591 setlocale(LC_ALL, lang);
1594 static int device_handler_init_sources(struct device_handler *handler)
1596 /* init our device sources: udev, network and user events */
1597 handler->user_event = user_event_init(handler, handler->waitset);
1598 if (!handler->user_event)
1601 handler->network = network_init(handler, handler->waitset,
1603 if (!handler->network)
1606 handler->udev = udev_init(handler, handler->waitset);
1613 static void device_handler_reinit_sources(struct device_handler *handler)
1615 /* if we haven't initialised sources previously (becuase we started in
1616 * safe mode), then init once here. */
1617 if (!(handler->udev || handler->network || handler->user_event)) {
1618 device_handler_init_sources(handler);
1622 system_info_reinit();
1624 network_shutdown(handler->network);
1625 handler->network = network_init(handler, handler->waitset,
1628 udev_reinit(handler->udev);
1631 static inline const char *get_device_path(struct discover_device *dev)
1633 return dev->ramdisk ? dev->ramdisk->snapshot : dev->device_path;
1636 static char *check_subvols(struct discover_device *dev)
1638 const char *fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1643 if (strncmp(fstype, "btrfs", strlen("btrfs")))
1644 return dev->mount_path;
1646 /* On btrfs a device's root may be under a subvolume path */
1647 path = join_paths(dev, dev->mount_path, "@");
1648 rc = stat(path, &sb);
1649 if (!rc && S_ISDIR(sb.st_mode)) {
1650 pb_debug("Using '%s' for btrfs root path\n", path);
1655 return dev->mount_path;
1658 static bool check_existing_mount(struct discover_device *dev)
1660 struct stat devstat, mntstat;
1661 const char *device_path;
1666 device_path = get_device_path(dev);
1668 rc = stat(device_path, &devstat);
1670 pb_debug("%s: stat failed: %s\n", __func__, strerror(errno));
1674 if (!S_ISBLK(devstat.st_mode)) {
1675 pb_debug("%s: %s isn't a block device?\n", __func__,
1680 fp = fopen("/proc/self/mounts", "r");
1683 mnt = getmntent(fp);
1687 if (!mnt->mnt_fsname || mnt->mnt_fsname[0] != '/')
1690 rc = stat(mnt->mnt_fsname, &mntstat);
1694 if (!S_ISBLK(mntstat.st_mode))
1697 if (mntstat.st_rdev == devstat.st_rdev) {
1698 dev->mount_path = talloc_strdup(dev, mnt->mnt_dir);
1699 dev->root_path = check_subvols(dev);
1700 dev->mounted_rw = !!hasmntopt(mnt, "rw");
1701 dev->mounted = true;
1702 dev->unmount = false;
1704 pb_debug("%s: %s is already mounted (r%c) at %s\n",
1705 __func__, dev->device_path,
1706 dev->mounted_rw ? 'w' : 'o',
1718 * Attempt to mount a filesystem safely, while handling certain filesytem-
1721 static int try_mount(const char *device_path, const char *mount_path,
1722 const char *fstype, unsigned long flags,
1725 const char *fs, *safe_opts;
1728 /* Mount ext3 as ext4 instead so 'norecovery' can be used */
1729 if (strncmp(fstype, "ext3", strlen("ext3")) == 0) {
1730 pb_debug("Mounting ext3 filesystem as ext4\n");
1735 if (strncmp(fs, "xfs", strlen("xfs")) == 0 ||
1736 strncmp(fs, "ext4", strlen("ext4")) == 0)
1737 safe_opts = "norecovery";
1742 /* If no snapshot is available don't attempt recovery */
1744 return mount(device_path, mount_path, fs, flags, safe_opts);
1746 rc = mount(device_path, mount_path, fs, flags, NULL);
1751 /* Mounting failed; some filesystems will fail to mount if a recovery
1752 * journal exists (eg. cross-endian XFS), so try again with norecovery
1753 * where that option is available.
1754 * If mounting read-write just return the error as norecovery is not a
1756 if ((flags & MS_RDONLY) != MS_RDONLY || !safe_opts)
1760 return mount(device_path, mount_path, fs, flags, safe_opts);
1763 static int mount_device(struct discover_device *dev)
1765 const char *fstype, *device_path;
1768 if (!dev->device_path)
1774 if (check_existing_mount(dev))
1777 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1781 dev->mount_path = join_paths(dev, mount_base(),
1784 if (pb_mkdir_recursive(dev->mount_path)) {
1785 pb_log("couldn't create mount directory %s: %s\n",
1786 dev->mount_path, strerror(errno));
1790 device_path = get_device_path(dev);
1792 pb_log("mounting device %s read-only\n", dev->device_path);
1793 rc = try_mount(device_path, dev->mount_path, fstype,
1794 MS_RDONLY | MS_SILENT, dev->ramdisk);
1796 /* If mount fails clean up any snapshot and try again */
1797 if (rc && dev->ramdisk) {
1798 pb_log("couldn't mount snapshot for %s: mount failed: %s\n",
1799 device_path, strerror(errno));
1800 pb_log("falling back to actual device\n");
1802 devmapper_destroy_snapshot(dev);
1804 device_path = get_device_path(dev);
1805 pb_log("mounting device %s read-only\n", dev->device_path);
1806 rc = try_mount(device_path, dev->mount_path, fstype,
1807 MS_RDONLY | MS_SILENT, dev->ramdisk);
1811 dev->mounted = true;
1812 dev->mounted_rw = false;
1813 dev->unmount = true;
1814 dev->root_path = check_subvols(dev);
1818 pb_log("couldn't mount device %s: mount failed: %s\n",
1819 device_path, strerror(errno));
1821 pb_rmdir_recursive(mount_base(), dev->mount_path);
1823 talloc_free(dev->mount_path);
1824 dev->mount_path = NULL;
1828 static int umount_device(struct discover_device *dev)
1830 const char *device_path;
1833 if (!dev->mounted || !dev->unmount)
1836 device_path = get_device_path(dev);
1838 pb_log("unmounting device %s\n", device_path);
1839 rc = umount(dev->mount_path);
1843 dev->mounted = false;
1844 devmapper_destroy_snapshot(dev);
1846 pb_rmdir_recursive(mount_base(), dev->mount_path);
1848 talloc_free(dev->mount_path);
1849 dev->mount_path = NULL;
1850 dev->root_path = NULL;
1855 int device_request_write(struct discover_device *dev, bool *release)
1857 const char *fstype, *device_path;
1858 const struct config *config;
1863 config = config_get();
1864 if (!config->allow_writes)
1870 if (dev->mounted_rw)
1873 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1875 device_path = get_device_path(dev);
1877 pb_log("remounting device %s read-write\n", device_path);
1879 rc = umount(dev->mount_path);
1881 pb_log("Failed to unmount %s: %s\n",
1882 dev->mount_path, strerror(errno));
1886 rc = try_mount(device_path, dev->mount_path, fstype,
1887 MS_SILENT, dev->ramdisk);
1891 dev->mounted_rw = true;
1896 pb_log("Unable to remount device %s read-write: %s\n",
1897 device_path, strerror(errno));
1898 rc = try_mount(device_path, dev->mount_path, fstype,
1899 MS_RDONLY | MS_SILENT, dev->ramdisk);
1901 pb_log("Unable to recover mount for %s: %s\n",
1902 device_path, strerror(errno));
1906 void device_release_write(struct discover_device *dev, bool release)
1908 const char *fstype, *device_path;
1913 device_path = get_device_path(dev);
1915 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1917 pb_log("remounting device %s read-only\n", device_path);
1919 if (umount(dev->mount_path)) {
1920 pb_log("Failed to unmount %s\n", dev->mount_path);
1923 dev->mounted_rw = dev->mounted = false;
1926 devmapper_merge_snapshot(dev);
1927 /* device_path becomes stale after merge */
1928 device_path = get_device_path(dev);
1931 if (try_mount(device_path, dev->mount_path, fstype,
1932 MS_RDONLY | MS_SILENT, dev->ramdisk))
1933 pb_log("Failed to remount %s read-only: %s\n",
1934 device_path, strerror(errno));
1936 dev->mounted = true;
1939 void device_sync_snapshots(struct device_handler *handler, const char *device)
1941 struct discover_device *dev = NULL;
1945 /* Find matching device and sync */
1946 dev = device_lookup_by_name(handler, device);
1948 pb_log("%s: device name '%s' unrecognised\n",
1953 device_release_write(dev, true);
1955 pb_log("%s has no snapshot to merge, skipping\n",
1960 /* Otherwise sync all relevant devices */
1961 for (i = 0; i < handler->n_devices; i++) {
1962 dev = handler->devices[i];
1963 if (dev->device->type != DEVICE_TYPE_DISK &&
1964 dev->device->type != DEVICE_TYPE_USB)
1967 device_release_write(dev, true);
1969 pb_log("%s has no snapshot to merge, skipping\n",
1976 void device_handler_discover_context_commit(
1977 struct device_handler *handler __attribute__((unused)),
1978 struct discover_context *ctx __attribute__((unused)))
1980 pb_log("%s stubbed out for test cases\n", __func__);
1983 static void device_handler_update_lang(const char *lang __attribute__((unused)))
1987 static int device_handler_init_sources(
1988 struct device_handler *handler __attribute__((unused)))
1993 static void device_handler_reinit_sources(
1994 struct device_handler *handler __attribute__((unused)))
1998 static int umount_device(struct discover_device *dev __attribute__((unused)))
2003 static int __attribute__((unused)) mount_device(
2004 struct discover_device *dev __attribute__((unused)))
2009 int device_request_write(struct discover_device *dev __attribute__((unused)),
2016 void device_release_write(struct discover_device *dev __attribute__((unused)),
2017 bool release __attribute__((unused)))
2021 void device_sync_snapshots(
2022 struct device_handler *handler __attribute__((unused)),
2023 const char *device __attribute__((unused)))