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>
21 #include <pb-config/pb-config.h>
23 #include <sys/sysmacros.h>
24 #include <sys/types.h>
25 #include <sys/socket.h>
27 #include <arpa/inet.h>
29 #include "device-handler.h"
30 #include "discover-server.h"
31 #include "devmapper.h"
32 #include "user-event.h"
44 enum default_priority {
45 DEFAULT_PRIORITY_REMOTE = 1,
46 DEFAULT_PRIORITY_LOCAL_FIRST = 2,
47 DEFAULT_PRIORITY_LOCAL_LAST = 0xfe,
48 DEFAULT_PRIORITY_DISABLED = 0xff,
51 struct progress_info {
52 unsigned int percentage;
53 unsigned long size; /* size in bytes */
55 const struct process_info *procinfo;
56 struct list_item list;
59 struct device_handler {
60 struct discover_server *server;
64 struct network *network;
65 struct user_event *user_event;
67 struct discover_device **devices;
68 unsigned int n_devices;
70 struct ramdisk_device **ramdisks;
71 unsigned int n_ramdisks;
73 struct waitset *waitset;
74 struct waiter *timeout_waiter;
75 bool autoboot_enabled;
76 unsigned int sec_to_boot;
78 struct discover_boot_option *default_boot_option;
79 int default_boot_option_priority;
81 struct list unresolved_boot_options;
83 struct boot_task *pending_boot;
84 bool pending_boot_is_default;
87 unsigned int n_progress;
90 static int mount_device(struct discover_device *dev);
91 static int umount_device(struct discover_device *dev);
93 static int device_handler_init_sources(struct device_handler *handler);
94 static void device_handler_reinit_sources(struct device_handler *handler);
96 static void device_handler_update_lang(const char *lang);
98 void discover_context_add_boot_option(struct discover_context *ctx,
99 struct discover_boot_option *boot_option)
101 boot_option->source = ctx->parser;
102 list_add_tail(&ctx->boot_options, &boot_option->list);
103 talloc_steal(ctx, boot_option);
107 * device_handler_get_device_count - Get the count of current handler devices.
110 int device_handler_get_device_count(const struct device_handler *handler)
112 return handler->n_devices;
116 * device_handler_get_device - Get a handler device by index.
119 const struct discover_device *device_handler_get_device(
120 const struct device_handler *handler, unsigned int index)
122 if (index >= handler->n_devices) {
123 assert(0 && "bad index");
127 return handler->devices[index];
130 struct network *device_handler_get_network(
131 const struct device_handler *handler)
133 return handler->network;
136 struct discover_boot_option *discover_boot_option_create(
137 struct discover_context *ctx,
138 struct discover_device *device)
140 struct discover_boot_option *opt;
142 opt = talloc_zero(ctx, struct discover_boot_option);
143 opt->option = talloc_zero(opt, struct boot_option);
144 opt->device = device;
149 static int device_match_uuid(struct discover_device *dev, const char *uuid)
151 return dev->uuid && !strcmp(dev->uuid, uuid);
154 static int device_match_label(struct discover_device *dev, const char *label)
156 return dev->label && !strcmp(dev->label, label);
159 static int device_match_id(struct discover_device *dev, const char *id)
161 return !strcmp(dev->device->id, id);
164 static int device_match_serial(struct discover_device *dev, const char *serial)
166 const char *val = discover_device_get_param(dev, "ID_SERIAL");
167 return val && !strcmp(val, serial);
170 static struct discover_device *device_lookup(
171 struct device_handler *device_handler,
172 int (match_fn)(struct discover_device *, const char *),
175 struct discover_device *dev;
181 for (i = 0; i < device_handler->n_devices; i++) {
182 dev = device_handler->devices[i];
184 if (match_fn(dev, str))
191 struct discover_device *device_lookup_by_name(struct device_handler *handler,
194 if (!strncmp(name, "/dev/", strlen("/dev/")))
195 name += strlen("/dev/");
197 return device_lookup_by_id(handler, name);
200 struct discover_device *device_lookup_by_uuid(
201 struct device_handler *device_handler,
204 return device_lookup(device_handler, device_match_uuid, uuid);
207 struct discover_device *device_lookup_by_label(
208 struct device_handler *device_handler,
211 return device_lookup(device_handler, device_match_label, label);
214 struct discover_device *device_lookup_by_id(
215 struct device_handler *device_handler,
218 return device_lookup(device_handler, device_match_id, id);
221 struct discover_device *device_lookup_by_serial(
222 struct device_handler *device_handler,
225 return device_lookup(device_handler, device_match_serial, serial);
228 void device_handler_destroy(struct device_handler *handler)
230 talloc_free(handler);
233 static int destroy_device(void *arg)
235 struct discover_device *dev = arg;
242 struct discover_device *discover_device_create(struct device_handler *handler,
243 const char *uuid, const char *id)
245 struct discover_device *dev;
248 dev = device_lookup_by_uuid(handler, uuid);
250 dev = device_lookup_by_id(handler, id);
255 dev = talloc_zero(handler, struct discover_device);
256 dev->device = talloc_zero(dev, struct device);
257 dev->device->id = talloc_strdup(dev->device, id);
258 dev->uuid = talloc_strdup(dev, uuid);
259 list_init(&dev->params);
260 list_init(&dev->boot_options);
262 talloc_set_destructor(dev, destroy_device);
267 struct discover_device_param {
270 struct list_item list;
273 void discover_device_set_param(struct discover_device *device,
274 const char *name, const char *value)
276 struct discover_device_param *param;
279 list_for_each_entry(&device->params, param, list) {
280 if (!strcmp(param->name, name)) {
289 param = talloc(device, struct discover_device_param);
290 param->name = talloc_strdup(param, name);
291 list_add(&device->params, ¶m->list);
294 list_remove(¶m->list);
298 talloc_free(param->value);
301 param->value = talloc_strdup(param, value);
304 const char *discover_device_get_param(struct discover_device *device,
307 struct discover_device_param *param;
309 list_for_each_entry(&device->params, param, list) {
310 if (!strcmp(param->name, name))
316 static void set_env_variables(const struct config *config)
318 if (config->http_proxy)
319 setenv("http_proxy", config->http_proxy, 1);
321 unsetenv("http_proxy");
323 if (config->https_proxy)
324 setenv("https_proxy", config->https_proxy, 1);
326 unsetenv("https_proxy");
328 /* Reduce noise in the log from LVM listing open file descriptors */
329 setenv("LVM_SUPPRESS_FD_WARNINGS", "1", 1);
332 struct device_handler *device_handler_init(struct discover_server *server,
333 struct waitset *waitset, int dry_run)
335 struct device_handler *handler;
338 handler = talloc_zero(NULL, struct device_handler);
339 handler->server = server;
340 handler->waitset = waitset;
341 handler->dry_run = dry_run;
342 handler->autoboot_enabled = config_autoboot_active(config_get());
344 list_init(&handler->unresolved_boot_options);
346 list_init(&handler->progress);
348 /* set up our mount point base */
349 pb_mkdir_recursive(mount_base());
353 if (config_get()->safe_mode)
356 set_env_variables(config_get());
358 rc = device_handler_init_sources(handler);
360 talloc_free(handler);
367 void device_handler_reinit(struct device_handler *handler)
369 struct discover_boot_option *opt, *tmp;
370 struct ramdisk_device *ramdisk;
371 struct config *config;
374 device_handler_cancel_default(handler);
375 /* Cancel any pending non-default boot */
376 if (handler->pending_boot) {
377 boot_cancel(handler->pending_boot);
378 handler->pending_boot = NULL;
379 handler->pending_boot_is_default = false;
382 /* Cancel any remaining async jobs */
383 process_stop_async_all();
384 pending_network_jobs_cancel();
386 /* free unresolved boot options */
387 list_for_each_entry_safe(&handler->unresolved_boot_options,
390 list_init(&handler->unresolved_boot_options);
392 /* drop all devices */
393 for (i = 0; i < handler->n_devices; i++) {
394 discover_server_notify_device_remove(handler->server,
395 handler->devices[i]->device);
396 ramdisk = handler->devices[i]->ramdisk;
397 talloc_free(handler->devices[i]);
398 talloc_free(ramdisk);
401 talloc_free(handler->devices);
402 handler->devices = NULL;
403 handler->n_devices = 0;
404 talloc_free(handler->ramdisks);
405 handler->ramdisks = NULL;
406 handler->n_ramdisks = 0;
408 set_env_variables(config_get());
410 /* If the safe mode warning was active disable it now */
411 if (config_get()->safe_mode) {
412 config = config_copy(handler, config_get());
413 config->safe_mode = false;
415 discover_server_notify_config(handler->server, config);
418 device_handler_reinit_sources(handler);
421 void device_handler_remove(struct device_handler *handler,
422 struct discover_device *device)
424 struct discover_boot_option *opt, *tmp;
427 list_for_each_entry_safe(&device->boot_options, opt, tmp, list) {
428 if (opt == handler->default_boot_option) {
429 pb_log("Default option %s cancelled since device removed",
431 device_handler_cancel_default(handler);
436 for (i = 0; i < handler->n_devices; i++)
437 if (handler->devices[i] == device)
440 if (i == handler->n_devices) {
445 /* Free any unresolved options, as they're currently allocated
446 * against the handler */
447 list_for_each_entry_safe(&handler->unresolved_boot_options,
449 if (opt->device != device)
451 list_remove(&opt->list);
455 /* if this is a network device, we have to unregister it from the
457 if (device->device->type == DEVICE_TYPE_NETWORK)
458 network_unregister_device(handler->network, device);
460 handler->n_devices--;
461 memmove(&handler->devices[i], &handler->devices[i + 1],
462 (handler->n_devices - i) * sizeof(handler->devices[0]));
463 handler->devices = talloc_realloc(handler, handler->devices,
464 struct discover_device *, handler->n_devices);
466 if (device->notified)
467 discover_server_notify_device_remove(handler->server,
473 void device_handler_status(struct device_handler *handler,
474 struct status *status)
476 discover_server_notify_boot_status(handler->server, status);
479 static void _device_handler_vstatus(struct device_handler *handler,
480 enum status_type type, const char *fmt, va_list ap)
482 struct status status;
485 status.message = talloc_vasprintf(handler, fmt, ap);
486 status.backlog = false;
488 device_handler_status(handler, &status);
490 talloc_free(status.message);
493 static void _device_handler_vdevstatus(struct device_handler *handler,
494 struct discover_device *device, enum status_type type,
495 const char *fmt, va_list ap)
499 msg = talloc_asprintf(handler, "[%s] %s",
500 device ? device->device->id : "unknown", fmt);
501 _device_handler_vstatus(handler, type, msg, ap);
505 void device_handler_status_dev_info(struct device_handler *handler,
506 struct discover_device *dev, const char *fmt, ...)
511 _device_handler_vdevstatus(handler, dev, STATUS_INFO, fmt, ap);
515 void device_handler_status_dev_err(struct device_handler *handler,
516 struct discover_device *dev, const char *fmt, ...)
521 _device_handler_vdevstatus(handler, dev, STATUS_ERROR, fmt, ap);
525 void device_handler_status_info(struct device_handler *handler,
526 const char *fmt, ...)
531 _device_handler_vstatus(handler, STATUS_INFO, fmt, ap);
535 void device_handler_status_err(struct device_handler *handler,
536 const char *fmt, ...)
541 _device_handler_vstatus(handler, STATUS_ERROR, fmt, ap);
545 void device_handler_status_download(struct device_handler *handler,
546 const struct process_info *procinfo,
547 unsigned int percentage, unsigned int size, char suffix)
549 struct progress_info *p, *progress = NULL;
550 uint64_t current_converted, current = 0;
551 const char *units = " kMGTP";
552 unsigned long size_bytes;
558 list_for_each_entry(&handler->progress, p, list)
559 if (p->procinfo == procinfo)
563 pb_log("Registering new progress struct\n");
564 progress = talloc_zero(handler, struct progress_info);
566 pb_log("Failed to allocate room for progress struct\n");
569 progress->procinfo = procinfo;
570 list_add(&handler->progress, &progress->list);
571 handler->n_progress++;
575 for (i = 0; i < strlen(units); i++) {
576 if (units[i] == suffix)
580 if (i >= strlen(units)) {
581 pb_log("Couldn't recognise suffix '%c'\n", suffix);
588 progress->percentage = percentage;
589 progress->size = size_bytes;
592 * Aggregate the info we have and update status. If a progress struct
593 * has zero for both percentage and size we assume progress information
594 * is unavailable and fall back to a generic progress message.
596 list_for_each_entry(&handler->progress, p, list) {
599 if (!p->percentage || !p->size) {
600 update = talloc_asprintf(handler,
601 _("%u downloads in progress..."),
602 handler->n_progress);
608 t = (100 * c) / p->percentage;
615 current_converted = current;
616 while (current_converted >= 1000) {
617 current_converted >>= 10;
620 update = talloc_asprintf(handler,
621 _("%u %s downloading: %.0f%% - %lu%cB"),
623 ngettext("item", "items", handler->n_progress),
624 (current / total) * 100, current_converted,
629 pb_log("%s: failed to allocate new status\n", __func__);
631 device_handler_status_info(handler, "%s\n", update);
636 void device_handler_status_download_remove(struct device_handler *handler,
637 struct process_info *procinfo)
639 struct progress_info *p, *tmp;
641 list_for_each_entry_safe(&handler->progress, p, tmp, list)
642 if (p->procinfo == procinfo) {
643 list_remove(&p->list);
645 handler->n_progress--;
649 static void device_handler_boot_status_cb(void *arg, struct status *status)
651 device_handler_status(arg, status);
654 static void countdown_status(struct device_handler *handler,
655 struct discover_boot_option *opt, unsigned int sec)
657 struct status status;
659 status.type = STATUS_INFO;
660 status.message = talloc_asprintf(handler,
661 _("Booting in %d sec: [%s] %s"), sec,
662 opt->device->device->id, opt->option->name);
663 status.backlog = false;
665 device_handler_status(handler, &status);
667 talloc_free(status.message);
670 static int default_timeout(void *arg)
672 struct device_handler *handler = arg;
673 struct discover_boot_option *opt;
675 if (!handler->default_boot_option)
678 if (handler->pending_boot)
681 opt = handler->default_boot_option;
683 if (handler->sec_to_boot) {
684 countdown_status(handler, opt, handler->sec_to_boot);
685 handler->sec_to_boot--;
686 handler->timeout_waiter = waiter_register_timeout(
687 handler->waitset, 1000,
688 default_timeout, handler);
692 handler->timeout_waiter = NULL;
694 pb_log("Timeout expired, booting default option %s\n", opt->option->id);
698 handler->pending_boot = boot(handler, handler->default_boot_option,
699 NULL, handler->dry_run, device_handler_boot_status_cb,
701 handler->pending_boot_is_default = true;
706 enum ipmi_bootdev ipmi_type;
707 enum device_type device_type;
708 } device_type_map[] = {
709 { IPMI_BOOTDEV_NETWORK, DEVICE_TYPE_NETWORK },
710 { IPMI_BOOTDEV_DISK, DEVICE_TYPE_DISK },
711 { IPMI_BOOTDEV_DISK, DEVICE_TYPE_USB },
712 { IPMI_BOOTDEV_CDROM, DEVICE_TYPE_OPTICAL },
715 static bool ipmi_device_type_matches(enum ipmi_bootdev ipmi_type,
716 enum device_type device_type)
720 for (i = 0; i < ARRAY_SIZE(device_type_map); i++) {
721 if (device_type_map[i].device_type == device_type)
722 return device_type_map[i].ipmi_type == ipmi_type;
728 static int autoboot_option_priority(const struct config *config,
729 struct discover_boot_option *opt)
731 enum device_type type = opt->device->device->type;
732 const char *uuid = opt->device->uuid;
733 struct autoboot_option *auto_opt;
736 for (i = 0; i < config->n_autoboot_opts; i++) {
737 auto_opt = &config->autoboot_opts[i];
738 if (auto_opt->boot_type == BOOT_DEVICE_UUID)
739 if (!strcmp(auto_opt->uuid, uuid))
740 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
742 if (auto_opt->boot_type == BOOT_DEVICE_TYPE)
743 if (auto_opt->type == type ||
744 auto_opt->type == DEVICE_TYPE_ANY)
745 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
752 * We have different priorities to resolve conflicts between boot options that
753 * report to be the default for their device. This function assigns a priority
756 static enum default_priority default_option_priority(
757 struct discover_boot_option *opt)
759 const struct config *config;
761 config = config_get();
763 /* We give highest priority to IPMI-configured boot options. If
764 * we have an IPMI bootdev configuration set, then we don't allow
765 * any other defaults */
766 if (config->ipmi_bootdev) {
767 bool ipmi_match = ipmi_device_type_matches(config->ipmi_bootdev,
768 opt->device->device->type);
770 return DEFAULT_PRIORITY_REMOTE;
772 pb_debug("handler: disabled default priority due to "
773 "non-matching IPMI type %x\n",
774 config->ipmi_bootdev);
775 return DEFAULT_PRIORITY_DISABLED;
778 /* Next, try to match the option against the user-defined autoboot
779 * options, either by device UUID or type. */
780 if (config->n_autoboot_opts) {
781 int boot_match = autoboot_option_priority(config, opt);
786 /* If the option didn't match any entry in the array, it is disabled */
787 pb_debug("handler: disabled default priority due to "
788 "non-matching UUID or type\n");
789 return DEFAULT_PRIORITY_DISABLED;
792 static void set_default(struct device_handler *handler,
793 struct discover_boot_option *opt)
795 enum default_priority cur_prio, new_prio;
797 if (!handler->autoboot_enabled)
800 pb_debug("handler: new default option: %s\n", opt->option->id);
802 new_prio = default_option_priority(opt);
804 /* Anything outside our range prevents a default boot */
805 if (new_prio >= DEFAULT_PRIORITY_DISABLED)
808 pb_debug("handler: calculated priority %d\n", new_prio);
810 /* Resolve any conflicts: if we have a new default option, it only
811 * replaces the current if it has a higher priority. */
812 if (handler->default_boot_option) {
814 cur_prio = handler->default_boot_option_priority;
816 if (new_prio < cur_prio) {
817 pb_log("handler: new prio %d beats "
818 "old prio %d for %s\n",
820 handler->default_boot_option
822 handler->default_boot_option = opt;
823 handler->default_boot_option_priority = new_prio;
824 /* extend the timeout a little, so the user sees some
825 * indication of the change */
826 handler->sec_to_boot += 2;
832 handler->sec_to_boot = config_get()->autoboot_timeout_sec;
833 handler->default_boot_option = opt;
834 handler->default_boot_option_priority = new_prio;
836 pb_log("handler: boot option %s set as default, timeout %u sec.\n",
837 opt->option->id, handler->sec_to_boot);
839 default_timeout(handler);
842 static bool resource_is_resolved(struct resource *res)
844 return !res || res->resolved;
847 /* We only use this in an assert, which will disappear if we're compiling
848 * with NDEBUG, so we need the 'used' attribute for these builds */
849 static bool __attribute__((used)) boot_option_is_resolved(
850 struct discover_boot_option *opt)
852 return resource_is_resolved(opt->boot_image) &&
853 resource_is_resolved(opt->initrd) &&
854 resource_is_resolved(opt->dtb) &&
855 resource_is_resolved(opt->args_sig_file) &&
856 resource_is_resolved(opt->icon);
859 static bool resource_resolve(struct resource *res, const char *name,
860 struct discover_boot_option *opt,
861 struct device_handler *handler)
863 struct parser *parser = opt->source;
865 if (resource_is_resolved(res))
868 pb_debug("Attempting to resolve resource %s->%s with parser %s\n",
869 opt->option->id, name, parser->name);
870 parser->resolve_resource(handler, res);
872 return res->resolved;
875 static bool boot_option_resolve(struct discover_boot_option *opt,
876 struct device_handler *handler)
878 return resource_resolve(opt->boot_image, "boot_image", opt, handler) &&
879 resource_resolve(opt->initrd, "initrd", opt, handler) &&
880 resource_resolve(opt->dtb, "dtb", opt, handler) &&
881 resource_resolve(opt->args_sig_file, "args_sig_file", opt,
883 resource_resolve(opt->icon, "icon", opt, handler);
886 static void boot_option_finalise(struct device_handler *handler,
887 struct discover_boot_option *opt)
889 assert(boot_option_is_resolved(opt));
891 /* check that the parsers haven't set any of the final data */
892 assert(!opt->option->boot_image_file);
893 assert(!opt->option->initrd_file);
894 assert(!opt->option->dtb_file);
895 assert(!opt->option->icon_file);
896 assert(!opt->option->device_id);
897 assert(!opt->option->args_sig_file);
900 opt->option->boot_image_file = opt->boot_image->url->full;
902 opt->option->initrd_file = opt->initrd->url->full;
904 opt->option->dtb_file = opt->dtb->url->full;
906 opt->option->icon_file = opt->icon->url->full;
907 if (opt->args_sig_file)
908 opt->option->args_sig_file = opt->args_sig_file->url->full;
910 opt->option->device_id = opt->device->device->id;
912 if (opt->option->is_default)
913 set_default(handler, opt);
916 static void notify_boot_option(struct device_handler *handler,
917 struct discover_boot_option *opt)
919 struct discover_device *dev = opt->device;
922 discover_server_notify_device_add(handler->server,
923 opt->device->device);
924 dev->notified = true;
925 discover_server_notify_boot_option_add(handler->server, opt->option);
928 static void process_boot_option_queue(struct device_handler *handler)
930 struct discover_boot_option *opt, *tmp;
932 list_for_each_entry_safe(&handler->unresolved_boot_options,
935 pb_debug("queue: attempting resolution for %s\n",
938 if (!boot_option_resolve(opt, handler))
941 pb_debug("\tresolved!\n");
943 list_remove(&opt->list);
944 list_add_tail(&opt->device->boot_options, &opt->list);
945 talloc_steal(opt->device, opt);
946 boot_option_finalise(handler, opt);
947 notify_boot_option(handler, opt);
951 struct discover_context *device_handler_discover_context_create(
952 struct device_handler *handler,
953 struct discover_device *device)
955 struct discover_context *ctx;
957 ctx = talloc_zero(handler, struct discover_context);
958 ctx->handler = handler;
959 ctx->device = device;
960 list_init(&ctx->boot_options);
965 void device_handler_add_device(struct device_handler *handler,
966 struct discover_device *device)
968 handler->n_devices++;
969 handler->devices = talloc_realloc(handler, handler->devices,
970 struct discover_device *, handler->n_devices);
971 handler->devices[handler->n_devices - 1] = device;
973 if (device->device->type == DEVICE_TYPE_NETWORK)
974 network_register_device(handler->network, device);
977 void device_handler_add_ramdisk(struct device_handler *handler,
980 struct ramdisk_device *dev;
986 for (i = 0; i < handler->n_ramdisks; i++)
987 if (!strcmp(handler->ramdisks[i]->path, path))
990 dev = talloc_zero(handler, struct ramdisk_device);
992 pb_log("Failed to allocate memory to track %s\n", path);
996 dev->path = talloc_strdup(handler, path);
998 handler->ramdisks = talloc_realloc(handler, handler->ramdisks,
999 struct ramdisk_device *,
1000 handler->n_ramdisks + 1);
1001 if (!handler->ramdisks) {
1002 pb_log("Failed to reallocate memory"
1003 "- ramdisk tracking inconsistent!\n");
1007 handler->ramdisks[i] = dev;
1008 i = handler->n_ramdisks++;
1011 struct ramdisk_device *device_handler_get_ramdisk(
1012 struct device_handler *handler)
1018 /* Check if free ramdisk exists */
1019 for (i = 0; i < handler->n_ramdisks; i++)
1020 if (!handler->ramdisks[i]->snapshot &&
1021 !handler->ramdisks[i]->origin &&
1022 !handler->ramdisks[i]->base)
1023 return handler->ramdisks[i];
1025 /* Otherwise create a new one */
1026 name = talloc_asprintf(handler, "/dev/ram%d",
1027 handler->n_ramdisks);
1029 pb_debug("Failed to allocate memory to name /dev/ram%d",
1030 handler->n_ramdisks);
1034 id = makedev(1, handler->n_ramdisks);
1035 if (mknod(name, S_IFBLK, id)) {
1036 if (errno == EEXIST) {
1037 /* We haven't yet received updates for existing
1038 * ramdisks - add and use this one */
1039 pb_debug("Using untracked ramdisk %s\n", name);
1041 pb_log("Failed to create new ramdisk %s: %s\n",
1042 name, strerror(errno));
1046 device_handler_add_ramdisk(handler, name);
1049 return handler->ramdisks[i];
1052 void device_handler_release_ramdisk(struct discover_device *device)
1054 struct ramdisk_device *ramdisk = device->ramdisk;
1056 talloc_free(ramdisk->snapshot);
1057 talloc_free(ramdisk->origin);
1058 talloc_free(ramdisk->base);
1060 ramdisk->snapshot = ramdisk->origin = ramdisk->base = NULL;
1061 ramdisk->sectors = 0;
1063 device->ramdisk = NULL;
1066 /* Start discovery on a hotplugged device. The device will be in our devices
1067 * array, but has only just been initialised by the hotplug source.
1069 int device_handler_discover(struct device_handler *handler,
1070 struct discover_device *dev)
1072 struct discover_context *ctx;
1075 device_handler_status_dev_info(handler, dev,
1077 * TRANSLATORS: this string will be passed the type of the
1078 * device (eg "disk" or "network"), which will be translated
1081 _("Processing new %s device"),
1082 device_type_display_name(dev->device->type));
1084 /* create our context */
1085 ctx = device_handler_discover_context_create(handler, dev);
1087 rc = mount_device(dev);
1091 /* add this device to our system info */
1092 system_info_register_blockdev(dev->device->id, dev->uuid,
1095 /* run the parsers. This will populate the ctx's boot_option list. */
1096 iterate_parsers(ctx);
1098 /* add discovered stuff to the handler */
1099 device_handler_discover_context_commit(handler, ctx);
1101 process_boot_option_queue(handler);
1103 talloc_unlink(handler, ctx);
1108 /* Incoming dhcp event */
1109 int device_handler_dhcp(struct device_handler *handler,
1110 struct discover_device *dev, struct event *event)
1112 struct discover_context *ctx;
1114 device_handler_status_dev_info(handler, dev,
1115 _("Processing DHCP lease response (ip: %s)"),
1116 event_get_param(event, "ip"));
1118 pending_network_jobs_start();
1120 /* create our context */
1121 ctx = device_handler_discover_context_create(handler, dev);
1122 talloc_steal(ctx, event);
1125 iterate_parsers(ctx);
1127 device_handler_discover_context_commit(handler, ctx);
1129 talloc_unlink(handler, ctx);
1134 static struct discover_boot_option *find_boot_option_by_id(
1135 struct device_handler *handler, const char *id)
1139 for (i = 0; i < handler->n_devices; i++) {
1140 struct discover_device *dev = handler->devices[i];
1141 struct discover_boot_option *opt;
1143 list_for_each_entry(&dev->boot_options, opt, list)
1144 if (!strcmp(opt->option->id, id))
1151 void device_handler_boot(struct device_handler *handler,
1152 struct boot_command *cmd)
1154 struct discover_boot_option *opt = NULL;
1156 if (cmd->option_id && strlen(cmd->option_id))
1157 opt = find_boot_option_by_id(handler, cmd->option_id);
1159 if (handler->pending_boot)
1160 boot_cancel(handler->pending_boot);
1162 platform_pre_boot();
1164 handler->pending_boot = boot(handler, opt, cmd, handler->dry_run,
1165 device_handler_boot_status_cb, handler);
1166 handler->pending_boot_is_default = false;
1169 void device_handler_cancel_default(struct device_handler *handler)
1171 if (handler->timeout_waiter)
1172 waiter_remove(handler->timeout_waiter);
1174 handler->timeout_waiter = NULL;
1175 handler->autoboot_enabled = false;
1177 /* we only send status if we had a default boot option queued */
1178 if (!handler->default_boot_option)
1181 pb_log("Cancelling default boot option\n");
1183 if (handler->pending_boot && handler->pending_boot_is_default) {
1184 boot_cancel(handler->pending_boot);
1185 handler->pending_boot = NULL;
1186 handler->pending_boot_is_default = false;
1189 handler->default_boot_option = NULL;
1191 device_handler_status_info(handler, _("Default boot cancelled"));
1194 void device_handler_update_config(struct device_handler *handler,
1195 struct config *config)
1199 rc = config_set(config);
1203 discover_server_notify_config(handler->server, config);
1204 device_handler_update_lang(config->lang);
1205 device_handler_reinit(handler);
1208 static char *device_from_addr(void *ctx, struct pb_url *url)
1210 char *ipaddr, *buf, *tok, *dev = NULL;
1211 const char *delim = " ";
1212 struct sockaddr_in *ip;
1213 struct sockaddr_in si;
1214 struct addrinfo *res;
1218 /* Note: IPv4 only */
1219 rc = inet_pton(AF_INET, url->host, &(si.sin_addr));
1223 /* need to turn hostname into a valid IP */
1224 rc = getaddrinfo(url->host, NULL, NULL, &res);
1226 pb_debug("%s: Invalid URL\n",__func__);
1229 ipaddr = talloc_array(ctx,char,INET_ADDRSTRLEN);
1230 ip = (struct sockaddr_in *) res->ai_addr;
1231 inet_ntop(AF_INET, &(ip->sin_addr), ipaddr, INET_ADDRSTRLEN);
1235 const char *argv[] = {
1237 "route", "show", "to", "match",
1242 p = process_create(ctx);
1244 p->path = pb_system_apps.ip;
1246 p->keep_stdout = true;
1248 rc = process_run_sync(p);
1250 if (rc || p->exit_status) {
1251 /* ip has complained for some reason; most likely
1252 * there is no route to the host - bail out */
1253 pb_debug("%s: `ip` returns non-zero exit status\n", __func__);
1254 pb_debug("ip buf: %s\n", p->stdout_buf);
1259 buf = p->stdout_buf;
1260 /* If a route is found, ip-route output will be of the form
1261 * "... dev DEVNAME ... " */
1262 tok = strtok(buf, delim);
1264 if (!strcmp(tok, "dev")) {
1265 tok = strtok(NULL, delim);
1266 dev = talloc_strdup(ctx, tok);
1269 tok = strtok(NULL, delim);
1274 pb_debug("%s: Found interface '%s'\n", __func__,dev);
1278 static void process_url_cb(struct load_url_result *result, void *data)
1280 struct device_handler *handler;
1281 struct discover_context *ctx;
1282 struct discover_device *dev;
1283 struct event *event = data;
1286 if (result->status != LOAD_OK) {
1287 pb_log("%s: Load failed for %s\n", __func__, result->url->full);
1294 handler = talloc_parent(event);
1298 event->device = device_from_addr(event, result->url);
1299 if (!event->device) {
1300 pb_log("Downloaded a file but can't find its interface - pretending it was local\n");
1301 event->device = talloc_asprintf(event, "local");
1304 mac = event_get_param(event, "mac");
1305 char *url = talloc_asprintf(event, "file://%s", result->local);
1306 event_set_param(event, "pxeconffile", url);
1308 dev = discover_device_create(handler, mac, event->device);
1309 ctx = device_handler_discover_context_create(handler, dev);
1310 talloc_steal(ctx, event);
1313 iterate_parsers(ctx);
1315 device_handler_discover_context_commit(handler, ctx);
1317 talloc_unlink(handler, ctx);
1320 void device_handler_process_url(struct device_handler *handler,
1321 const char *url, const char *mac, const char *ip)
1323 struct discover_context *ctx;
1324 struct discover_device *dev;
1325 bool allow_async = false;
1326 struct pb_url *pb_url;
1327 struct event *event;
1329 event = talloc_zero(handler, struct event);
1330 event->type = EVENT_TYPE_USER;
1331 event->action = EVENT_ACTION_URL;
1333 pb_url = pb_url_parse(event, url);
1334 if (!pb_url || (pb_url->scheme != pb_url_file && !pb_url->host)) {
1335 device_handler_status_err(handler, _("Invalid config URL!"));
1340 if (url[strlen(url) - 1] == '/') {
1341 event_set_param(event, "pxepathprefix", url);
1342 event_set_param(event, "mac", mac);
1343 event_set_param(event, "ip", ip);
1344 event->device = device_from_addr(event, pb_url);
1345 if (!event->device) {
1346 device_handler_status_err(handler,
1347 _("Unable to route to host %s"),
1353 event_set_param(event, "pxeconffile", url);
1357 if (pb_url->scheme == pb_url_file)
1358 event->device = talloc_asprintf(event, "local");
1359 else if (allow_async) {
1360 /* If file is remote load asynchronously before passing to
1361 * parser. This allows us to wait for network to be available */
1362 if (!load_url_async(handler, pb_url, process_url_cb, event,
1364 pb_log("Failed to load url %s\n", pb_url->full);
1365 device_handler_status_err(handler, _("Failed to load URL!"));
1371 /* If path is local we can parse straight away */
1373 dev = discover_device_create(handler, mac, event->device);
1374 if (pb_url->scheme == pb_url_file)
1375 dev->device->type = DEVICE_TYPE_ANY;
1376 ctx = device_handler_discover_context_create(handler, dev);
1377 talloc_steal(ctx, event);
1380 iterate_parsers(ctx);
1382 device_handler_discover_context_commit(handler, ctx);
1384 talloc_unlink(handler, ctx);
1387 #ifndef PETITBOOT_TEST
1390 * context_commit - Commit a temporary discovery context to the handler,
1391 * and notify the clients about any new options / devices
1393 void device_handler_discover_context_commit(struct device_handler *handler,
1394 struct discover_context *ctx)
1396 struct discover_device *dev = ctx->device;
1397 struct discover_boot_option *opt, *tmp;
1399 if (!device_lookup_by_uuid(handler, dev->uuid))
1400 device_handler_add_device(handler, dev);
1402 /* move boot options from the context to the device */
1403 list_for_each_entry_safe(&ctx->boot_options, opt, tmp, list) {
1404 list_remove(&opt->list);
1406 /* All boot options need at least a kernel image */
1407 if (!opt->boot_image || !opt->boot_image->url) {
1408 pb_log("boot option %s is missing boot image, ignoring\n",
1414 if (boot_option_resolve(opt, handler)) {
1415 pb_log("boot option %s is resolved, "
1416 "sending to clients\n",
1418 list_add_tail(&dev->boot_options, &opt->list);
1419 talloc_steal(dev, opt);
1420 boot_option_finalise(handler, opt);
1421 notify_boot_option(handler, opt);
1423 if (!opt->source->resolve_resource) {
1424 pb_log("parser %s gave us an unresolved "
1425 "resource (%s), but no way to "
1427 opt->source->name, opt->option->id);
1430 pb_log("boot option %s is unresolved, "
1431 "adding to queue\n",
1433 list_add(&handler->unresolved_boot_options,
1435 talloc_steal(handler, opt);
1441 static void device_handler_update_lang(const char *lang)
1443 const char *cur_lang;
1448 cur_lang = setlocale(LC_ALL, NULL);
1449 if (cur_lang && !strcmp(cur_lang, lang))
1452 setlocale(LC_ALL, lang);
1455 static int device_handler_init_sources(struct device_handler *handler)
1457 /* init our device sources: udev, network and user events */
1458 handler->network = network_init(handler, handler->waitset,
1460 if (!handler->network)
1463 handler->udev = udev_init(handler, handler->waitset);
1467 handler->user_event = user_event_init(handler, handler->waitset);
1468 if (!handler->user_event)
1474 static void device_handler_reinit_sources(struct device_handler *handler)
1476 /* if we haven't initialised sources previously (becuase we started in
1477 * safe mode), then init once here. */
1478 if (!(handler->udev || handler->network || handler->user_event)) {
1479 device_handler_init_sources(handler);
1483 system_info_reinit();
1485 network_shutdown(handler->network);
1486 handler->network = network_init(handler, handler->waitset,
1489 udev_reinit(handler->udev);
1492 static inline const char *get_device_path(struct discover_device *dev)
1494 return dev->ramdisk ? dev->ramdisk->snapshot : dev->device_path;
1497 static char *check_subvols(struct discover_device *dev)
1499 const char *fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1504 if (strncmp(fstype, "btrfs", strlen("btrfs")))
1505 return dev->mount_path;
1507 /* On btrfs a device's root may be under a subvolume path */
1508 path = join_paths(dev, dev->mount_path, "@");
1509 rc = stat(path, &sb);
1510 if (!rc && S_ISDIR(sb.st_mode)) {
1511 pb_debug("Using '%s' for btrfs root path\n", path);
1516 return dev->mount_path;
1519 static bool check_existing_mount(struct discover_device *dev)
1521 struct stat devstat, mntstat;
1522 const char *device_path;
1527 device_path = get_device_path(dev);
1529 rc = stat(device_path, &devstat);
1531 pb_debug("%s: stat failed: %s\n", __func__, strerror(errno));
1535 if (!S_ISBLK(devstat.st_mode)) {
1536 pb_debug("%s: %s isn't a block device?\n", __func__,
1541 fp = fopen("/proc/self/mounts", "r");
1544 mnt = getmntent(fp);
1548 if (!mnt->mnt_fsname || mnt->mnt_fsname[0] != '/')
1551 rc = stat(mnt->mnt_fsname, &mntstat);
1555 if (!S_ISBLK(mntstat.st_mode))
1558 if (mntstat.st_rdev == devstat.st_rdev) {
1559 dev->mount_path = talloc_strdup(dev, mnt->mnt_dir);
1560 dev->root_path = check_subvols(dev);
1561 dev->mounted_rw = !!hasmntopt(mnt, "rw");
1562 dev->mounted = true;
1563 dev->unmount = false;
1565 pb_debug("%s: %s is already mounted (r%c) at %s\n",
1566 __func__, dev->device_path,
1567 dev->mounted_rw ? 'w' : 'o',
1579 * Attempt to mount a filesystem safely, while handling certain filesytem-
1582 static int try_mount(const char *device_path, const char *mount_path,
1583 const char *fstype, unsigned long flags,
1586 const char *fs, *safe_opts;
1589 /* Mount ext3 as ext4 instead so 'norecovery' can be used */
1590 if (strncmp(fstype, "ext3", strlen("ext3")) == 0) {
1591 pb_debug("Mounting ext3 filesystem as ext4\n");
1596 if (strncmp(fs, "xfs", strlen("xfs")) == 0 ||
1597 strncmp(fs, "ext4", strlen("ext4")) == 0)
1598 safe_opts = "norecovery";
1603 /* If no snapshot is available don't attempt recovery */
1605 return mount(device_path, mount_path, fs, flags, safe_opts);
1607 rc = mount(device_path, mount_path, fs, flags, NULL);
1612 /* Mounting failed; some filesystems will fail to mount if a recovery
1613 * journal exists (eg. cross-endian XFS), so try again with norecovery
1614 * where that option is available.
1615 * If mounting read-write just return the error as norecovery is not a
1617 if ((flags & MS_RDONLY) != MS_RDONLY || !safe_opts)
1621 return mount(device_path, mount_path, fs, flags, safe_opts);
1624 static int mount_device(struct discover_device *dev)
1626 const char *fstype, *device_path;
1629 if (!dev->device_path)
1635 if (check_existing_mount(dev))
1638 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1642 dev->mount_path = join_paths(dev, mount_base(),
1645 if (pb_mkdir_recursive(dev->mount_path)) {
1646 pb_log("couldn't create mount directory %s: %s\n",
1647 dev->mount_path, strerror(errno));
1651 device_path = get_device_path(dev);
1653 pb_log("mounting device %s read-only\n", dev->device_path);
1654 rc = try_mount(device_path, dev->mount_path, fstype,
1655 MS_RDONLY | MS_SILENT, dev->ramdisk);
1658 dev->mounted = true;
1659 dev->mounted_rw = false;
1660 dev->unmount = true;
1661 dev->root_path = check_subvols(dev);
1665 pb_log("couldn't mount device %s: mount failed: %s\n",
1666 device_path, strerror(errno));
1668 /* If mount fails clean up any snapshot */
1669 devmapper_destroy_snapshot(dev);
1671 pb_rmdir_recursive(mount_base(), dev->mount_path);
1673 talloc_free(dev->mount_path);
1674 dev->mount_path = NULL;
1678 static int umount_device(struct discover_device *dev)
1680 const char *device_path;
1683 if (!dev->mounted || !dev->unmount)
1686 device_path = get_device_path(dev);
1688 pb_log("unmounting device %s\n", device_path);
1689 rc = umount(dev->mount_path);
1693 dev->mounted = false;
1694 devmapper_destroy_snapshot(dev);
1696 pb_rmdir_recursive(mount_base(), dev->mount_path);
1698 talloc_free(dev->mount_path);
1699 dev->mount_path = NULL;
1700 dev->root_path = NULL;
1705 int device_request_write(struct discover_device *dev, bool *release)
1707 const char *fstype, *device_path;
1708 const struct config *config;
1713 config = config_get();
1714 if (!config->allow_writes)
1720 if (dev->mounted_rw)
1723 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1725 device_path = get_device_path(dev);
1727 pb_log("remounting device %s read-write\n", device_path);
1729 rc = umount(dev->mount_path);
1731 pb_log("Failed to unmount %s: %s\n",
1732 dev->mount_path, strerror(errno));
1736 rc = try_mount(device_path, dev->mount_path, fstype,
1737 MS_SILENT, dev->ramdisk);
1741 dev->mounted_rw = true;
1746 pb_log("Unable to remount device %s read-write: %s\n",
1747 device_path, strerror(errno));
1748 rc = try_mount(device_path, dev->mount_path, fstype,
1749 MS_RDONLY | MS_SILENT, dev->ramdisk);
1751 pb_log("Unable to recover mount for %s: %s\n",
1752 device_path, strerror(errno));
1756 void device_release_write(struct discover_device *dev, bool release)
1758 const char *fstype, *device_path;
1763 device_path = get_device_path(dev);
1765 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1767 pb_log("remounting device %s read-only\n", device_path);
1769 if (umount(dev->mount_path)) {
1770 pb_log("Failed to unmount %s\n", dev->mount_path);
1773 dev->mounted_rw = dev->mounted = false;
1776 devmapper_merge_snapshot(dev);
1777 /* device_path becomes stale after merge */
1778 device_path = get_device_path(dev);
1781 if (try_mount(device_path, dev->mount_path, fstype,
1782 MS_RDONLY | MS_SILENT, dev->ramdisk))
1783 pb_log("Failed to remount %s read-only: %s\n",
1784 device_path, strerror(errno));
1786 dev->mounted = true;
1789 void device_sync_snapshots(struct device_handler *handler, const char *device)
1791 struct discover_device *dev = NULL;
1795 /* Find matching device and sync */
1796 dev = device_lookup_by_name(handler, device);
1798 pb_log("%s: device name '%s' unrecognised\n",
1803 device_release_write(dev, true);
1805 pb_log("%s has no snapshot to merge, skipping\n",
1810 /* Otherwise sync all relevant devices */
1811 for (i = 0; i < handler->n_devices; i++) {
1812 dev = handler->devices[i];
1813 if (dev->device->type != DEVICE_TYPE_DISK &&
1814 dev->device->type != DEVICE_TYPE_USB)
1817 device_release_write(dev, true);
1819 pb_log("%s has no snapshot to merge, skipping\n",
1826 void device_handler_discover_context_commit(
1827 struct device_handler *handler __attribute__((unused)),
1828 struct discover_context *ctx __attribute__((unused)))
1830 pb_log("%s stubbed out for test cases\n", __func__);
1833 static void device_handler_update_lang(const char *lang __attribute__((unused)))
1837 static int device_handler_init_sources(
1838 struct device_handler *handler __attribute__((unused)))
1843 static void device_handler_reinit_sources(
1844 struct device_handler *handler __attribute__((unused)))
1848 static int umount_device(struct discover_device *dev __attribute__((unused)))
1853 static int __attribute__((unused)) mount_device(
1854 struct discover_device *dev __attribute__((unused)))
1859 int device_request_write(struct discover_device *dev __attribute__((unused)),
1866 void device_release_write(struct discover_device *dev __attribute__((unused)),
1867 bool release __attribute__((unused)))
1871 void device_sync_snapshots(
1872 struct device_handler *handler __attribute__((unused)),
1873 const char *device __attribute__((unused)))