11 #include <sys/mount.h>
13 #include <talloc/talloc.h>
14 #include <list/list.h>
16 #include <types/types.h>
17 #include <system/system.h>
18 #include <process/process.h>
20 #include <i18n/i18n.h>
22 #include <sys/sysmacros.h>
23 #include <sys/types.h>
24 #include <sys/socket.h>
26 #include <arpa/inet.h>
28 #include "device-handler.h"
29 #include "discover-server.h"
30 #include "devmapper.h"
31 #include "user-event.h"
43 enum default_priority {
44 DEFAULT_PRIORITY_REMOTE = 1,
45 DEFAULT_PRIORITY_LOCAL_FIRST = 2,
46 DEFAULT_PRIORITY_LOCAL_LAST = 0xfe,
47 DEFAULT_PRIORITY_DISABLED = 0xff,
50 struct progress_info {
51 unsigned int percentage;
52 unsigned long size; /* size in bytes */
54 const struct process_info *procinfo;
55 struct list_item list;
58 struct device_handler {
59 struct discover_server *server;
63 struct network *network;
64 struct user_event *user_event;
66 struct discover_device **devices;
67 unsigned int n_devices;
69 struct ramdisk_device **ramdisks;
70 unsigned int n_ramdisks;
72 struct waitset *waitset;
73 struct waiter *timeout_waiter;
74 bool autoboot_enabled;
75 unsigned int sec_to_boot;
77 struct discover_boot_option *default_boot_option;
78 int default_boot_option_priority;
80 struct list unresolved_boot_options;
82 struct boot_task *pending_boot;
83 bool pending_boot_is_default;
86 unsigned int n_progress;
88 struct plugin_option **plugins;
89 unsigned int n_plugins;
92 static int mount_device(struct discover_device *dev);
93 static int umount_device(struct discover_device *dev);
95 static int device_handler_init_sources(struct device_handler *handler);
96 static void device_handler_reinit_sources(struct device_handler *handler);
98 static void device_handler_update_lang(const char *lang);
100 void discover_context_add_boot_option(struct discover_context *ctx,
101 struct discover_boot_option *boot_option)
103 boot_option->source = ctx->parser;
104 list_add_tail(&ctx->boot_options, &boot_option->list);
105 talloc_steal(ctx, boot_option);
109 * device_handler_get_device_count - Get the count of current handler devices.
112 int device_handler_get_device_count(const struct device_handler *handler)
114 return handler->n_devices;
118 * device_handler_get_device - Get a handler device by index.
121 const struct discover_device *device_handler_get_device(
122 const struct device_handler *handler, unsigned int index)
124 if (index >= handler->n_devices) {
125 assert(0 && "bad index");
129 return handler->devices[index];
133 * device_handler_get_plugin_count - Get the count of current handler plugins.
135 int device_handler_get_plugin_count(const struct device_handler *handler)
137 return handler->n_plugins;
141 * discover_handler_get_plugin - Get a handler plugin by index.
143 const struct plugin_option *device_handler_get_plugin(
144 const struct device_handler *handler, unsigned int index)
146 if (index >= handler->n_plugins) {
147 assert(0 && "bad index");
151 return handler->plugins[index];
154 struct network *device_handler_get_network(
155 const struct device_handler *handler)
157 return handler->network;
160 struct discover_boot_option *discover_boot_option_create(
161 struct discover_context *ctx,
162 struct discover_device *device)
164 struct discover_boot_option *opt;
166 opt = talloc_zero(ctx, struct discover_boot_option);
167 opt->option = talloc_zero(opt, struct boot_option);
168 opt->device = device;
173 static int device_match_uuid(struct discover_device *dev, const char *uuid)
175 return dev->uuid && !strcmp(dev->uuid, uuid);
178 static int device_match_label(struct discover_device *dev, const char *label)
180 return dev->label && !strcmp(dev->label, label);
183 static int device_match_id(struct discover_device *dev, const char *id)
185 return !strcmp(dev->device->id, id);
188 static int device_match_serial(struct discover_device *dev, const char *serial)
190 const char *val = discover_device_get_param(dev, "ID_SERIAL");
191 return val && !strcmp(val, serial);
194 static struct discover_device *device_lookup(
195 struct device_handler *device_handler,
196 int (match_fn)(struct discover_device *, const char *),
199 struct discover_device *dev;
205 for (i = 0; i < device_handler->n_devices; i++) {
206 dev = device_handler->devices[i];
208 if (match_fn(dev, str))
215 struct discover_device *device_lookup_by_name(struct device_handler *handler,
218 if (!strncmp(name, "/dev/", strlen("/dev/")))
219 name += strlen("/dev/");
221 return device_lookup_by_id(handler, name);
224 struct discover_device *device_lookup_by_uuid(
225 struct device_handler *device_handler,
228 return device_lookup(device_handler, device_match_uuid, uuid);
231 struct discover_device *device_lookup_by_label(
232 struct device_handler *device_handler,
235 return device_lookup(device_handler, device_match_label, label);
238 struct discover_device *device_lookup_by_id(
239 struct device_handler *device_handler,
242 return device_lookup(device_handler, device_match_id, id);
245 struct discover_device *device_lookup_by_serial(
246 struct device_handler *device_handler,
249 return device_lookup(device_handler, device_match_serial, serial);
252 void device_handler_destroy(struct device_handler *handler)
254 talloc_free(handler);
257 static int destroy_device(void *arg)
259 struct discover_device *dev = arg;
266 struct discover_device *discover_device_create(struct device_handler *handler,
267 const char *uuid, const char *id)
269 struct discover_device *dev;
272 dev = device_lookup_by_uuid(handler, uuid);
274 dev = device_lookup_by_id(handler, id);
279 dev = talloc_zero(handler, struct discover_device);
280 dev->device = talloc_zero(dev, struct device);
281 dev->device->id = talloc_strdup(dev->device, id);
282 dev->uuid = talloc_strdup(dev, uuid);
283 list_init(&dev->params);
284 list_init(&dev->boot_options);
286 talloc_set_destructor(dev, destroy_device);
291 struct discover_device_param {
294 struct list_item list;
297 void discover_device_set_param(struct discover_device *device,
298 const char *name, const char *value)
300 struct discover_device_param *param;
303 list_for_each_entry(&device->params, param, list) {
304 if (!strcmp(param->name, name)) {
313 param = talloc(device, struct discover_device_param);
314 param->name = talloc_strdup(param, name);
315 list_add(&device->params, ¶m->list);
318 list_remove(¶m->list);
322 talloc_free(param->value);
325 param->value = talloc_strdup(param, value);
328 const char *discover_device_get_param(struct discover_device *device,
331 struct discover_device_param *param;
333 list_for_each_entry(&device->params, param, list) {
334 if (!strcmp(param->name, name))
340 struct device_handler *device_handler_init(struct discover_server *server,
341 struct waitset *waitset, int dry_run)
343 struct device_handler *handler;
346 handler = talloc_zero(NULL, struct device_handler);
347 handler->server = server;
348 handler->waitset = waitset;
349 handler->dry_run = dry_run;
350 handler->autoboot_enabled = config_autoboot_active(config_get());
352 list_init(&handler->unresolved_boot_options);
354 list_init(&handler->progress);
356 /* set up our mount point base */
357 pb_mkdir_recursive(mount_base());
361 if (config_get()->safe_mode)
364 rc = device_handler_init_sources(handler);
366 talloc_free(handler);
373 void device_handler_reinit(struct device_handler *handler)
375 struct discover_boot_option *opt, *tmp;
376 struct ramdisk_device *ramdisk;
379 device_handler_cancel_default(handler);
380 /* Cancel any pending non-default boot */
381 if (handler->pending_boot) {
382 boot_cancel(handler->pending_boot);
383 handler->pending_boot = NULL;
384 handler->pending_boot_is_default = false;
387 /* Cancel any remaining async jobs */
388 process_stop_async_all();
389 pending_network_jobs_cancel();
391 /* free unresolved boot options */
392 list_for_each_entry_safe(&handler->unresolved_boot_options,
395 list_init(&handler->unresolved_boot_options);
397 /* drop all devices */
398 for (i = 0; i < handler->n_devices; i++) {
399 discover_server_notify_device_remove(handler->server,
400 handler->devices[i]->device);
401 ramdisk = handler->devices[i]->ramdisk;
402 talloc_free(handler->devices[i]);
403 talloc_free(ramdisk);
406 talloc_free(handler->devices);
407 handler->devices = NULL;
408 handler->n_devices = 0;
409 talloc_free(handler->ramdisks);
410 handler->ramdisks = NULL;
411 handler->n_ramdisks = 0;
413 /* drop any known plugins */
414 for (i = 0; i < handler->n_plugins; i++)
415 talloc_free(handler->plugins[i]);
416 talloc_free(handler->plugins);
417 handler->plugins = NULL;
418 handler->n_plugins = 0;
420 discover_server_notify_plugins_remove(handler->server);
422 device_handler_reinit_sources(handler);
425 void device_handler_remove(struct device_handler *handler,
426 struct discover_device *device)
428 struct discover_boot_option *opt, *tmp;
431 list_for_each_entry_safe(&device->boot_options, opt, tmp, list) {
432 if (opt == handler->default_boot_option) {
433 pb_log("Default option %s cancelled since device removed",
435 device_handler_cancel_default(handler);
440 for (i = 0; i < handler->n_devices; i++)
441 if (handler->devices[i] == device)
444 if (i == handler->n_devices) {
449 /* Free any unresolved options, as they're currently allocated
450 * against the handler */
451 list_for_each_entry_safe(&handler->unresolved_boot_options,
453 if (opt->device != device)
455 list_remove(&opt->list);
459 /* if this is a network device, we have to unregister it from the
461 if (device->device->type == DEVICE_TYPE_NETWORK)
462 network_unregister_device(handler->network, device);
464 handler->n_devices--;
465 memmove(&handler->devices[i], &handler->devices[i + 1],
466 (handler->n_devices - i) * sizeof(handler->devices[0]));
467 handler->devices = talloc_realloc(handler, handler->devices,
468 struct discover_device *, handler->n_devices);
470 if (device->notified)
471 discover_server_notify_device_remove(handler->server,
477 void device_handler_status(struct device_handler *handler,
478 struct status *status)
480 discover_server_notify_boot_status(handler->server, status);
483 static void _device_handler_vstatus(struct device_handler *handler,
484 enum status_type type, const char *fmt, va_list ap)
486 struct status status;
489 status.message = talloc_vasprintf(handler, fmt, ap);
490 status.backlog = false;
492 device_handler_status(handler, &status);
494 talloc_free(status.message);
497 static void _device_handler_vdevstatus(struct device_handler *handler,
498 struct discover_device *device, enum status_type type,
499 const char *fmt, va_list ap)
503 msg = talloc_asprintf(handler, "[%s] %s",
504 device ? device->device->id : "unknown", fmt);
505 _device_handler_vstatus(handler, type, msg, ap);
509 void device_handler_status_dev_info(struct device_handler *handler,
510 struct discover_device *dev, const char *fmt, ...)
515 _device_handler_vdevstatus(handler, dev, STATUS_INFO, fmt, ap);
519 void device_handler_status_dev_err(struct device_handler *handler,
520 struct discover_device *dev, const char *fmt, ...)
525 _device_handler_vdevstatus(handler, dev, STATUS_ERROR, fmt, ap);
529 void device_handler_status_info(struct device_handler *handler,
530 const char *fmt, ...)
535 _device_handler_vstatus(handler, STATUS_INFO, fmt, ap);
539 void device_handler_status_err(struct device_handler *handler,
540 const char *fmt, ...)
545 _device_handler_vstatus(handler, STATUS_ERROR, fmt, ap);
549 void device_handler_status_download(struct device_handler *handler,
550 const struct process_info *procinfo,
551 unsigned int percentage, unsigned int size, char suffix)
553 struct progress_info *p, *progress = NULL;
554 uint64_t current_converted, current = 0;
555 const char *units = " kMGTP";
556 unsigned long size_bytes;
562 list_for_each_entry(&handler->progress, p, list)
563 if (p->procinfo == procinfo)
567 pb_log("Registering new progress struct\n");
568 progress = talloc_zero(handler, struct progress_info);
570 pb_log("Failed to allocate room for progress struct\n");
573 progress->procinfo = procinfo;
574 list_add(&handler->progress, &progress->list);
575 handler->n_progress++;
579 for (i = 0; i < strlen(units); i++) {
580 if (units[i] == suffix)
584 if (i >= strlen(units)) {
585 pb_log("Couldn't recognise suffix '%c'\n", suffix);
592 progress->percentage = percentage;
593 progress->size = size_bytes;
596 * Aggregate the info we have and update status. If a progress struct
597 * has zero for both percentage and size we assume progress information
598 * is unavailable and fall back to a generic progress message.
600 list_for_each_entry(&handler->progress, p, list) {
603 if (!p->percentage || !p->size) {
604 update = talloc_asprintf(handler,
605 _("%u downloads in progress..."),
606 handler->n_progress);
612 t = (100 * c) / p->percentage;
619 current_converted = current;
620 while (current_converted >= 1000) {
621 current_converted >>= 10;
624 update = talloc_asprintf(handler,
625 _("%u %s downloading: %.0f%% - %lu%cB"),
627 ngettext("item", "items", handler->n_progress),
628 (current / total) * 100, current_converted,
633 pb_log("%s: failed to allocate new status\n", __func__);
635 device_handler_status_info(handler, "%s\n", update);
640 static void device_handler_plugin_scan_device(struct device_handler *handler,
641 struct discover_device *dev)
645 pb_debug("Scanning %s for plugin files\n", dev->device->id);
647 rc = process_run_simple(handler, pb_system_apps.pb_plugin,
648 "scan", dev->mount_path,
651 pb_log("Error from pb-plugin scan %s\n",
655 void device_handler_status_download_remove(struct device_handler *handler,
656 struct process_info *procinfo)
658 struct progress_info *p, *tmp;
660 list_for_each_entry_safe(&handler->progress, p, tmp, list)
661 if (p->procinfo == procinfo) {
662 list_remove(&p->list);
664 handler->n_progress--;
668 static void device_handler_boot_status_cb(void *arg, struct status *status)
670 device_handler_status(arg, status);
673 static void countdown_status(struct device_handler *handler,
674 struct discover_boot_option *opt, unsigned int sec)
676 struct status status;
678 status.type = STATUS_INFO;
679 status.message = talloc_asprintf(handler,
680 _("Booting in %d sec: [%s] %s"), sec,
681 opt->device->device->id, opt->option->name);
682 status.backlog = false;
684 device_handler_status(handler, &status);
686 talloc_free(status.message);
689 static int default_timeout(void *arg)
691 struct device_handler *handler = arg;
692 struct discover_boot_option *opt;
694 if (!handler->default_boot_option)
697 if (handler->pending_boot)
700 opt = handler->default_boot_option;
702 if (handler->sec_to_boot) {
703 countdown_status(handler, opt, handler->sec_to_boot);
704 handler->sec_to_boot--;
705 handler->timeout_waiter = waiter_register_timeout(
706 handler->waitset, 1000,
707 default_timeout, handler);
711 handler->timeout_waiter = NULL;
713 pb_log("Timeout expired, booting default option %s\n", opt->option->id);
717 handler->pending_boot = boot(handler, handler->default_boot_option,
718 NULL, handler->dry_run, device_handler_boot_status_cb,
720 handler->pending_boot_is_default = true;
725 enum ipmi_bootdev ipmi_type;
726 enum device_type device_type;
727 } device_type_map[] = {
728 { IPMI_BOOTDEV_NETWORK, DEVICE_TYPE_NETWORK },
729 { IPMI_BOOTDEV_DISK, DEVICE_TYPE_DISK },
730 { IPMI_BOOTDEV_DISK, DEVICE_TYPE_USB },
731 { IPMI_BOOTDEV_CDROM, DEVICE_TYPE_OPTICAL },
734 static bool ipmi_device_type_matches(enum ipmi_bootdev ipmi_type,
735 enum device_type device_type)
739 for (i = 0; i < ARRAY_SIZE(device_type_map); i++) {
740 if (device_type_map[i].device_type == device_type)
741 return device_type_map[i].ipmi_type == ipmi_type;
747 static int autoboot_option_priority(const struct config *config,
748 struct discover_boot_option *opt)
750 enum device_type type = opt->device->device->type;
751 const char *uuid = opt->device->uuid;
752 struct autoboot_option *auto_opt;
755 for (i = 0; i < config->n_autoboot_opts; i++) {
756 auto_opt = &config->autoboot_opts[i];
757 if (auto_opt->boot_type == BOOT_DEVICE_UUID)
758 if (!strcmp(auto_opt->uuid, uuid))
759 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
761 if (auto_opt->boot_type == BOOT_DEVICE_TYPE)
762 if (auto_opt->type == type ||
763 auto_opt->type == DEVICE_TYPE_ANY)
764 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
771 * We have different priorities to resolve conflicts between boot options that
772 * report to be the default for their device. This function assigns a priority
775 static enum default_priority default_option_priority(
776 struct discover_boot_option *opt)
778 const struct config *config;
780 config = config_get();
782 /* We give highest priority to IPMI-configured boot options. If
783 * we have an IPMI bootdev configuration set, then we don't allow
784 * any other defaults */
785 if (config->ipmi_bootdev) {
786 bool ipmi_match = ipmi_device_type_matches(config->ipmi_bootdev,
787 opt->device->device->type);
789 return DEFAULT_PRIORITY_REMOTE;
791 pb_debug("handler: disabled default priority due to "
792 "non-matching IPMI type %x\n",
793 config->ipmi_bootdev);
794 return DEFAULT_PRIORITY_DISABLED;
797 /* Next, try to match the option against the user-defined autoboot
798 * options, either by device UUID or type. */
799 if (config->n_autoboot_opts) {
800 int boot_match = autoboot_option_priority(config, opt);
805 /* If the option didn't match any entry in the array, it is disabled */
806 pb_debug("handler: disabled default priority due to "
807 "non-matching UUID or type\n");
808 return DEFAULT_PRIORITY_DISABLED;
811 static void set_default(struct device_handler *handler,
812 struct discover_boot_option *opt)
814 enum default_priority cur_prio, new_prio;
816 if (!handler->autoboot_enabled)
819 pb_debug("handler: new default option: %s\n", opt->option->id);
821 new_prio = default_option_priority(opt);
823 /* Anything outside our range prevents a default boot */
824 if (new_prio >= DEFAULT_PRIORITY_DISABLED)
827 pb_debug("handler: calculated priority %d\n", new_prio);
829 /* Resolve any conflicts: if we have a new default option, it only
830 * replaces the current if it has a higher priority. */
831 if (handler->default_boot_option) {
833 cur_prio = handler->default_boot_option_priority;
835 if (new_prio < cur_prio) {
836 pb_log("handler: new prio %d beats "
837 "old prio %d for %s\n",
839 handler->default_boot_option
841 handler->default_boot_option = opt;
842 handler->default_boot_option_priority = new_prio;
843 /* extend the timeout a little, so the user sees some
844 * indication of the change */
845 handler->sec_to_boot += 2;
851 handler->sec_to_boot = config_get()->autoboot_timeout_sec;
852 handler->default_boot_option = opt;
853 handler->default_boot_option_priority = new_prio;
855 pb_log("handler: boot option %s set as default, timeout %u sec.\n",
856 opt->option->id, handler->sec_to_boot);
858 default_timeout(handler);
861 static bool resource_is_resolved(struct resource *res)
863 return !res || res->resolved;
866 /* We only use this in an assert, which will disappear if we're compiling
867 * with NDEBUG, so we need the 'used' attribute for these builds */
868 static bool __attribute__((used)) boot_option_is_resolved(
869 struct discover_boot_option *opt)
871 return resource_is_resolved(opt->boot_image) &&
872 resource_is_resolved(opt->initrd) &&
873 resource_is_resolved(opt->dtb) &&
874 resource_is_resolved(opt->args_sig_file) &&
875 resource_is_resolved(opt->icon);
878 static bool resource_resolve(struct resource *res, const char *name,
879 struct discover_boot_option *opt,
880 struct device_handler *handler)
882 struct parser *parser = opt->source;
884 if (resource_is_resolved(res))
887 pb_debug("Attempting to resolve resource %s->%s with parser %s\n",
888 opt->option->id, name, parser->name);
889 parser->resolve_resource(handler, res);
891 return res->resolved;
894 static bool boot_option_resolve(struct discover_boot_option *opt,
895 struct device_handler *handler)
897 return resource_resolve(opt->boot_image, "boot_image", opt, handler) &&
898 resource_resolve(opt->initrd, "initrd", opt, handler) &&
899 resource_resolve(opt->dtb, "dtb", opt, handler) &&
900 resource_resolve(opt->args_sig_file, "args_sig_file", opt,
902 resource_resolve(opt->icon, "icon", opt, handler);
905 static void boot_option_finalise(struct device_handler *handler,
906 struct discover_boot_option *opt)
908 assert(boot_option_is_resolved(opt));
910 /* check that the parsers haven't set any of the final data */
911 assert(!opt->option->boot_image_file);
912 assert(!opt->option->initrd_file);
913 assert(!opt->option->dtb_file);
914 assert(!opt->option->icon_file);
915 assert(!opt->option->device_id);
916 assert(!opt->option->args_sig_file);
919 opt->option->boot_image_file = opt->boot_image->url->full;
921 opt->option->initrd_file = opt->initrd->url->full;
923 opt->option->dtb_file = opt->dtb->url->full;
925 opt->option->icon_file = opt->icon->url->full;
926 if (opt->args_sig_file)
927 opt->option->args_sig_file = opt->args_sig_file->url->full;
929 opt->option->device_id = opt->device->device->id;
931 if (opt->option->is_default)
932 set_default(handler, opt);
935 static void notify_boot_option(struct device_handler *handler,
936 struct discover_boot_option *opt)
938 struct discover_device *dev = opt->device;
941 discover_server_notify_device_add(handler->server,
942 opt->device->device);
943 dev->notified = true;
944 discover_server_notify_boot_option_add(handler->server, opt->option);
947 static void process_boot_option_queue(struct device_handler *handler)
949 struct discover_boot_option *opt, *tmp;
951 list_for_each_entry_safe(&handler->unresolved_boot_options,
954 pb_debug("queue: attempting resolution for %s\n",
957 if (!boot_option_resolve(opt, handler))
960 pb_debug("\tresolved!\n");
962 list_remove(&opt->list);
963 list_add_tail(&opt->device->boot_options, &opt->list);
964 talloc_steal(opt->device, opt);
965 boot_option_finalise(handler, opt);
966 notify_boot_option(handler, opt);
970 struct discover_context *device_handler_discover_context_create(
971 struct device_handler *handler,
972 struct discover_device *device)
974 struct discover_context *ctx;
976 ctx = talloc_zero(handler, struct discover_context);
977 ctx->handler = handler;
978 ctx->device = device;
979 list_init(&ctx->boot_options);
984 void device_handler_add_device(struct device_handler *handler,
985 struct discover_device *device)
987 handler->n_devices++;
988 handler->devices = talloc_realloc(handler, handler->devices,
989 struct discover_device *, handler->n_devices);
990 handler->devices[handler->n_devices - 1] = device;
992 if (device->device->type == DEVICE_TYPE_NETWORK)
993 network_register_device(handler->network, device);
996 void device_handler_add_ramdisk(struct device_handler *handler,
999 struct ramdisk_device *dev;
1005 for (i = 0; i < handler->n_ramdisks; i++)
1006 if (!strcmp(handler->ramdisks[i]->path, path))
1009 dev = talloc_zero(handler, struct ramdisk_device);
1011 pb_log("Failed to allocate memory to track %s\n", path);
1015 dev->path = talloc_strdup(handler, path);
1017 handler->ramdisks = talloc_realloc(handler, handler->ramdisks,
1018 struct ramdisk_device *,
1019 handler->n_ramdisks + 1);
1020 if (!handler->ramdisks) {
1021 pb_log("Failed to reallocate memory"
1022 "- ramdisk tracking inconsistent!\n");
1026 handler->ramdisks[i] = dev;
1027 i = handler->n_ramdisks++;
1030 struct ramdisk_device *device_handler_get_ramdisk(
1031 struct device_handler *handler)
1037 /* Check if free ramdisk exists */
1038 for (i = 0; i < handler->n_ramdisks; i++)
1039 if (!handler->ramdisks[i]->snapshot &&
1040 !handler->ramdisks[i]->origin &&
1041 !handler->ramdisks[i]->base)
1042 return handler->ramdisks[i];
1044 /* Otherwise create a new one */
1045 name = talloc_asprintf(handler, "/dev/ram%d",
1046 handler->n_ramdisks);
1048 pb_debug("Failed to allocate memory to name /dev/ram%d",
1049 handler->n_ramdisks);
1053 id = makedev(1, handler->n_ramdisks);
1054 if (mknod(name, S_IFBLK, id)) {
1055 if (errno == EEXIST) {
1056 /* We haven't yet received updates for existing
1057 * ramdisks - add and use this one */
1058 pb_debug("Using untracked ramdisk %s\n", name);
1060 pb_log("Failed to create new ramdisk %s: %s\n",
1061 name, strerror(errno));
1065 device_handler_add_ramdisk(handler, name);
1068 return handler->ramdisks[i];
1071 void device_handler_release_ramdisk(struct discover_device *device)
1073 struct ramdisk_device *ramdisk = device->ramdisk;
1075 talloc_free(ramdisk->snapshot);
1076 talloc_free(ramdisk->origin);
1077 talloc_free(ramdisk->base);
1079 ramdisk->snapshot = ramdisk->origin = ramdisk->base = NULL;
1080 ramdisk->sectors = 0;
1082 device->ramdisk = NULL;
1085 /* Start discovery on a hotplugged device. The device will be in our devices
1086 * array, but has only just been initialised by the hotplug source.
1088 int device_handler_discover(struct device_handler *handler,
1089 struct discover_device *dev)
1091 struct discover_context *ctx;
1094 device_handler_status_dev_info(handler, dev,
1096 * TRANSLATORS: this string will be passed the type of the
1097 * device (eg "disk" or "network"), which will be translated
1100 _("Processing new %s device"),
1101 device_type_display_name(dev->device->type));
1103 /* create our context */
1104 ctx = device_handler_discover_context_create(handler, dev);
1106 rc = mount_device(dev);
1110 /* add this device to our system info */
1111 system_info_register_blockdev(dev->device->id, dev->uuid,
1114 /* run the parsers. This will populate the ctx's boot_option list. */
1115 iterate_parsers(ctx);
1117 /* add discovered stuff to the handler */
1118 device_handler_discover_context_commit(handler, ctx);
1120 process_boot_option_queue(handler);
1122 /* Check this device for pb-plugins */
1123 device_handler_plugin_scan_device(handler, dev);
1125 talloc_unlink(handler, ctx);
1130 /* Incoming dhcp event */
1131 int device_handler_dhcp(struct device_handler *handler,
1132 struct discover_device *dev, struct event *event)
1134 struct discover_context *ctx;
1136 device_handler_status_dev_info(handler, dev,
1137 _("Processing DHCP lease response (ip: %s)"),
1138 event_get_param(event, "ip"));
1140 pending_network_jobs_start();
1142 /* create our context */
1143 ctx = device_handler_discover_context_create(handler, dev);
1144 talloc_steal(ctx, event);
1147 iterate_parsers(ctx);
1149 device_handler_discover_context_commit(handler, ctx);
1151 talloc_unlink(handler, ctx);
1156 static struct discover_boot_option *find_boot_option_by_id(
1157 struct device_handler *handler, const char *id)
1161 for (i = 0; i < handler->n_devices; i++) {
1162 struct discover_device *dev = handler->devices[i];
1163 struct discover_boot_option *opt;
1165 list_for_each_entry(&dev->boot_options, opt, list)
1166 if (!strcmp(opt->option->id, id))
1173 void device_handler_boot(struct device_handler *handler,
1174 struct boot_command *cmd)
1176 struct discover_boot_option *opt = NULL;
1178 if (cmd->option_id && strlen(cmd->option_id))
1179 opt = find_boot_option_by_id(handler, cmd->option_id);
1181 if (handler->pending_boot)
1182 boot_cancel(handler->pending_boot);
1184 platform_pre_boot();
1186 handler->pending_boot = boot(handler, opt, cmd, handler->dry_run,
1187 device_handler_boot_status_cb, handler);
1188 handler->pending_boot_is_default = false;
1191 void device_handler_cancel_default(struct device_handler *handler)
1193 if (handler->timeout_waiter)
1194 waiter_remove(handler->timeout_waiter);
1196 handler->timeout_waiter = NULL;
1197 handler->autoboot_enabled = false;
1199 /* we only send status if we had a default boot option queued */
1200 if (!handler->default_boot_option)
1203 pb_log("Cancelling default boot option\n");
1205 if (handler->pending_boot && handler->pending_boot_is_default) {
1206 boot_cancel(handler->pending_boot);
1207 handler->pending_boot = NULL;
1208 handler->pending_boot_is_default = false;
1211 handler->default_boot_option = NULL;
1213 device_handler_status_info(handler, _("Default boot cancelled"));
1216 void device_handler_update_config(struct device_handler *handler,
1217 struct config *config)
1221 rc = config_set(config);
1225 discover_server_notify_config(handler->server, config);
1226 device_handler_update_lang(config->lang);
1227 device_handler_reinit(handler);
1230 static char *device_from_addr(void *ctx, struct pb_url *url)
1232 char *ipaddr, *buf, *tok, *dev = NULL;
1233 const char *delim = " ";
1234 struct sockaddr_in *ip;
1235 struct sockaddr_in si;
1236 struct addrinfo *res;
1240 /* Note: IPv4 only */
1241 rc = inet_pton(AF_INET, url->host, &(si.sin_addr));
1245 /* need to turn hostname into a valid IP */
1246 rc = getaddrinfo(url->host, NULL, NULL, &res);
1248 pb_debug("%s: Invalid URL\n",__func__);
1251 ipaddr = talloc_array(ctx,char,INET_ADDRSTRLEN);
1252 ip = (struct sockaddr_in *) res->ai_addr;
1253 inet_ntop(AF_INET, &(ip->sin_addr), ipaddr, INET_ADDRSTRLEN);
1257 const char *argv[] = {
1259 "route", "show", "to", "match",
1264 p = process_create(ctx);
1266 p->path = pb_system_apps.ip;
1268 p->keep_stdout = true;
1270 rc = process_run_sync(p);
1272 if (rc || p->exit_status) {
1273 /* ip has complained for some reason; most likely
1274 * there is no route to the host - bail out */
1275 pb_debug("%s: `ip` returns non-zero exit status\n", __func__);
1276 pb_debug("ip buf: %s\n", p->stdout_buf);
1281 buf = p->stdout_buf;
1282 /* If a route is found, ip-route output will be of the form
1283 * "... dev DEVNAME ... " */
1284 tok = strtok(buf, delim);
1286 if (!strcmp(tok, "dev")) {
1287 tok = strtok(NULL, delim);
1288 dev = talloc_strdup(ctx, tok);
1291 tok = strtok(NULL, delim);
1296 pb_debug("%s: Found interface '%s'\n", __func__,dev);
1300 static void process_url_cb(struct load_url_result *result, void *data)
1302 struct device_handler *handler;
1303 struct discover_context *ctx;
1304 struct discover_device *dev;
1305 struct event *event = data;
1308 if (result->status != LOAD_OK) {
1309 pb_log("%s: Load failed for %s\n", __func__, result->url->full);
1316 handler = talloc_parent(event);
1320 event->device = device_from_addr(event, result->url);
1321 if (!event->device) {
1322 pb_log("Downloaded a file but can't find its interface - pretending it was local\n");
1323 event->device = talloc_asprintf(event, "local");
1326 mac = event_get_param(event, "mac");
1327 char *url = talloc_asprintf(event, "file://%s", result->local);
1328 event_set_param(event, "pxeconffile", url);
1330 dev = discover_device_create(handler, mac, event->device);
1331 ctx = device_handler_discover_context_create(handler, dev);
1332 talloc_steal(ctx, event);
1335 iterate_parsers(ctx);
1337 device_handler_discover_context_commit(handler, ctx);
1339 talloc_unlink(handler, ctx);
1342 void device_handler_process_url(struct device_handler *handler,
1343 const char *url, const char *mac, const char *ip)
1345 struct discover_context *ctx;
1346 struct discover_device *dev;
1347 bool allow_async = false;
1348 struct pb_url *pb_url;
1349 struct event *event;
1351 event = talloc_zero(handler, struct event);
1352 event->type = EVENT_TYPE_USER;
1353 event->action = EVENT_ACTION_URL;
1355 pb_url = pb_url_parse(event, url);
1356 if (!pb_url || (pb_url->scheme != pb_url_file && !pb_url->host)) {
1357 device_handler_status_err(handler, _("Invalid config URL!"));
1362 if (url[strlen(url) - 1] == '/') {
1363 event_set_param(event, "pxepathprefix", url);
1364 event_set_param(event, "mac", mac);
1365 event_set_param(event, "ip", ip);
1366 event->device = device_from_addr(event, pb_url);
1367 if (!event->device) {
1368 device_handler_status_err(handler,
1369 _("Unable to route to host %s"),
1375 event_set_param(event, "pxeconffile", url);
1379 if (pb_url->scheme == pb_url_file)
1380 event->device = talloc_asprintf(event, "local");
1381 else if (allow_async) {
1382 /* If file is remote load asynchronously before passing to
1383 * parser. This allows us to wait for network to be available */
1384 if (!load_url_async(handler, pb_url, process_url_cb, event,
1386 pb_log("Failed to load url %s\n", pb_url->full);
1387 device_handler_status_err(handler, _("Failed to load URL!"));
1393 /* If path is local we can parse straight away */
1395 dev = discover_device_create(handler, mac, event->device);
1396 if (pb_url->scheme == pb_url_file)
1397 dev->device->type = DEVICE_TYPE_ANY;
1398 ctx = device_handler_discover_context_create(handler, dev);
1399 talloc_steal(ctx, event);
1402 iterate_parsers(ctx);
1404 device_handler_discover_context_commit(handler, ctx);
1406 talloc_unlink(handler, ctx);
1409 #ifndef PETITBOOT_TEST
1412 * context_commit - Commit a temporary discovery context to the handler,
1413 * and notify the clients about any new options / devices
1415 void device_handler_discover_context_commit(struct device_handler *handler,
1416 struct discover_context *ctx)
1418 struct discover_device *dev = ctx->device;
1419 struct discover_boot_option *opt, *tmp;
1421 if (!device_lookup_by_uuid(handler, dev->uuid))
1422 device_handler_add_device(handler, dev);
1424 /* move boot options from the context to the device */
1425 list_for_each_entry_safe(&ctx->boot_options, opt, tmp, list) {
1426 list_remove(&opt->list);
1428 /* All boot options need at least a kernel image */
1429 if (!opt->boot_image || !opt->boot_image->url) {
1430 pb_log("boot option %s is missing boot image, ignoring\n",
1436 if (boot_option_resolve(opt, handler)) {
1437 pb_log("boot option %s is resolved, "
1438 "sending to clients\n",
1440 list_add_tail(&dev->boot_options, &opt->list);
1441 talloc_steal(dev, opt);
1442 boot_option_finalise(handler, opt);
1443 notify_boot_option(handler, opt);
1445 if (!opt->source->resolve_resource) {
1446 pb_log("parser %s gave us an unresolved "
1447 "resource (%s), but no way to "
1449 opt->source->name, opt->option->id);
1452 pb_log("boot option %s is unresolved, "
1453 "adding to queue\n",
1455 list_add(&handler->unresolved_boot_options,
1457 talloc_steal(handler, opt);
1463 void device_handler_add_plugin_option(struct device_handler *handler,
1464 struct plugin_option *opt)
1466 struct plugin_option *tmp;
1469 for (i = 0; i < handler->n_plugins; i++) {
1470 tmp = handler->plugins[i];
1471 /* If both id and version match, ignore */
1472 if (strncmp(opt->id, tmp->id, strlen(opt->id)) == 0 &&
1473 strncmp(opt->version, tmp->version,
1474 strlen(opt->version) == 0)) {
1475 pb_log("discover: Plugin '%s' already exists, ignoring\n",
1481 handler->plugins = talloc_realloc(handler, handler->plugins,
1482 struct plugin_option *, handler->n_plugins + 1);
1483 if (!handler->plugins) {
1484 pb_log("Failed to allocate memory for new plugin\n");
1485 handler->n_plugins = 0;
1489 handler->plugins[handler->n_plugins++] = opt;
1490 discover_server_notify_plugin_option_add(handler->server, opt);
1493 static void device_handler_update_lang(const char *lang)
1495 const char *cur_lang;
1500 cur_lang = setlocale(LC_ALL, NULL);
1501 if (cur_lang && !strcmp(cur_lang, lang))
1504 setlocale(LC_ALL, lang);
1507 static int device_handler_init_sources(struct device_handler *handler)
1509 /* init our device sources: udev, network and user events */
1510 handler->network = network_init(handler, handler->waitset,
1512 if (!handler->network)
1515 handler->udev = udev_init(handler, handler->waitset);
1519 handler->user_event = user_event_init(handler, handler->waitset);
1520 if (!handler->user_event)
1526 static void device_handler_reinit_sources(struct device_handler *handler)
1528 /* if we haven't initialised sources previously (becuase we started in
1529 * safe mode), then init once here. */
1530 if (!(handler->udev || handler->network || handler->user_event)) {
1531 device_handler_init_sources(handler);
1535 system_info_reinit();
1537 network_shutdown(handler->network);
1538 handler->network = network_init(handler, handler->waitset,
1541 udev_reinit(handler->udev);
1544 static inline const char *get_device_path(struct discover_device *dev)
1546 return dev->ramdisk ? dev->ramdisk->snapshot : dev->device_path;
1549 static char *check_subvols(struct discover_device *dev)
1551 const char *fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1556 if (strncmp(fstype, "btrfs", strlen("btrfs")))
1557 return dev->mount_path;
1559 /* On btrfs a device's root may be under a subvolume path */
1560 path = join_paths(dev, dev->mount_path, "@");
1561 rc = stat(path, &sb);
1562 if (!rc && S_ISDIR(sb.st_mode)) {
1563 pb_debug("Using '%s' for btrfs root path\n", path);
1568 return dev->mount_path;
1571 static bool check_existing_mount(struct discover_device *dev)
1573 struct stat devstat, mntstat;
1574 const char *device_path;
1579 device_path = get_device_path(dev);
1581 rc = stat(device_path, &devstat);
1583 pb_debug("%s: stat failed: %s\n", __func__, strerror(errno));
1587 if (!S_ISBLK(devstat.st_mode)) {
1588 pb_debug("%s: %s isn't a block device?\n", __func__,
1593 fp = fopen("/proc/self/mounts", "r");
1596 mnt = getmntent(fp);
1600 if (!mnt->mnt_fsname || mnt->mnt_fsname[0] != '/')
1603 rc = stat(mnt->mnt_fsname, &mntstat);
1607 if (!S_ISBLK(mntstat.st_mode))
1610 if (mntstat.st_rdev == devstat.st_rdev) {
1611 dev->mount_path = talloc_strdup(dev, mnt->mnt_dir);
1612 dev->root_path = check_subvols(dev);
1613 dev->mounted_rw = !!hasmntopt(mnt, "rw");
1614 dev->mounted = true;
1615 dev->unmount = false;
1617 pb_debug("%s: %s is already mounted (r%c) at %s\n",
1618 __func__, dev->device_path,
1619 dev->mounted_rw ? 'w' : 'o',
1631 * Attempt to mount a filesystem safely, while handling certain filesytem-
1634 static int try_mount(const char *device_path, const char *mount_path,
1635 const char *fstype, unsigned long flags,
1638 const char *fs, *safe_opts;
1641 /* Mount ext3 as ext4 instead so 'norecovery' can be used */
1642 if (strncmp(fstype, "ext3", strlen("ext3")) == 0) {
1643 pb_debug("Mounting ext3 filesystem as ext4\n");
1648 if (strncmp(fs, "xfs", strlen("xfs")) == 0 ||
1649 strncmp(fs, "ext4", strlen("ext4")) == 0)
1650 safe_opts = "norecovery";
1655 /* If no snapshot is available don't attempt recovery */
1657 return mount(device_path, mount_path, fs, flags, safe_opts);
1659 rc = mount(device_path, mount_path, fs, flags, NULL);
1664 /* Mounting failed; some filesystems will fail to mount if a recovery
1665 * journal exists (eg. cross-endian XFS), so try again with norecovery
1666 * where that option is available.
1667 * If mounting read-write just return the error as norecovery is not a
1669 if ((flags & MS_RDONLY) != MS_RDONLY || !safe_opts)
1673 return mount(device_path, mount_path, fs, flags, safe_opts);
1676 static int mount_device(struct discover_device *dev)
1678 const char *fstype, *device_path;
1681 if (!dev->device_path)
1687 if (check_existing_mount(dev))
1690 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1694 dev->mount_path = join_paths(dev, mount_base(),
1697 if (pb_mkdir_recursive(dev->mount_path)) {
1698 pb_log("couldn't create mount directory %s: %s\n",
1699 dev->mount_path, strerror(errno));
1703 device_path = get_device_path(dev);
1705 pb_log("mounting device %s read-only\n", dev->device_path);
1706 rc = try_mount(device_path, dev->mount_path, fstype,
1707 MS_RDONLY | MS_SILENT, dev->ramdisk);
1710 dev->mounted = true;
1711 dev->mounted_rw = false;
1712 dev->unmount = true;
1713 dev->root_path = check_subvols(dev);
1717 pb_log("couldn't mount device %s: mount failed: %s\n",
1718 device_path, strerror(errno));
1720 /* If mount fails clean up any snapshot */
1721 devmapper_destroy_snapshot(dev);
1723 pb_rmdir_recursive(mount_base(), dev->mount_path);
1725 talloc_free(dev->mount_path);
1726 dev->mount_path = NULL;
1730 static int umount_device(struct discover_device *dev)
1732 const char *device_path;
1735 if (!dev->mounted || !dev->unmount)
1738 device_path = get_device_path(dev);
1740 pb_log("unmounting device %s\n", device_path);
1741 rc = umount(dev->mount_path);
1745 dev->mounted = false;
1746 devmapper_destroy_snapshot(dev);
1748 pb_rmdir_recursive(mount_base(), dev->mount_path);
1750 talloc_free(dev->mount_path);
1751 dev->mount_path = NULL;
1752 dev->root_path = NULL;
1757 int device_request_write(struct discover_device *dev, bool *release)
1759 const char *fstype, *device_path;
1760 const struct config *config;
1765 config = config_get();
1766 if (!config->allow_writes)
1772 if (dev->mounted_rw)
1775 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1777 device_path = get_device_path(dev);
1779 pb_log("remounting device %s read-write\n", device_path);
1781 rc = umount(dev->mount_path);
1783 pb_log("Failed to unmount %s: %s\n",
1784 dev->mount_path, strerror(errno));
1788 rc = try_mount(device_path, dev->mount_path, fstype,
1789 MS_SILENT, dev->ramdisk);
1793 dev->mounted_rw = true;
1798 pb_log("Unable to remount device %s read-write: %s\n",
1799 device_path, strerror(errno));
1800 rc = try_mount(device_path, dev->mount_path, fstype,
1801 MS_RDONLY | MS_SILENT, dev->ramdisk);
1803 pb_log("Unable to recover mount for %s: %s\n",
1804 device_path, strerror(errno));
1808 void device_release_write(struct discover_device *dev, bool release)
1810 const char *fstype, *device_path;
1815 device_path = get_device_path(dev);
1817 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1819 pb_log("remounting device %s read-only\n", device_path);
1821 if (umount(dev->mount_path)) {
1822 pb_log("Failed to unmount %s\n", dev->mount_path);
1825 dev->mounted_rw = dev->mounted = false;
1828 devmapper_merge_snapshot(dev);
1829 /* device_path becomes stale after merge */
1830 device_path = get_device_path(dev);
1833 if (try_mount(device_path, dev->mount_path, fstype,
1834 MS_RDONLY | MS_SILENT, dev->ramdisk))
1835 pb_log("Failed to remount %s read-only: %s\n",
1836 device_path, strerror(errno));
1838 dev->mounted = true;
1841 void device_sync_snapshots(struct device_handler *handler, const char *device)
1843 struct discover_device *dev = NULL;
1847 /* Find matching device and sync */
1848 dev = device_lookup_by_name(handler, device);
1850 pb_log("%s: device name '%s' unrecognised\n",
1855 device_release_write(dev, true);
1857 pb_log("%s has no snapshot to merge, skipping\n",
1862 /* Otherwise sync all relevant devices */
1863 for (i = 0; i < handler->n_devices; i++) {
1864 dev = handler->devices[i];
1865 if (dev->device->type != DEVICE_TYPE_DISK &&
1866 dev->device->type != DEVICE_TYPE_USB)
1869 device_release_write(dev, true);
1871 pb_log("%s has no snapshot to merge, skipping\n",
1878 void device_handler_discover_context_commit(
1879 struct device_handler *handler __attribute__((unused)),
1880 struct discover_context *ctx __attribute__((unused)))
1882 pb_log("%s stubbed out for test cases\n", __func__);
1885 static void device_handler_update_lang(const char *lang __attribute__((unused)))
1889 static int device_handler_init_sources(
1890 struct device_handler *handler __attribute__((unused)))
1895 static void device_handler_reinit_sources(
1896 struct device_handler *handler __attribute__((unused)))
1900 static int umount_device(struct discover_device *dev __attribute__((unused)))
1905 static int __attribute__((unused)) mount_device(
1906 struct discover_device *dev __attribute__((unused)))
1911 int device_request_write(struct discover_device *dev __attribute__((unused)),
1918 void device_release_write(struct discover_device *dev __attribute__((unused)),
1919 bool release __attribute__((unused)))
1923 void device_sync_snapshots(
1924 struct device_handler *handler __attribute__((unused)),
1925 const char *device __attribute__((unused)))