11 #include <sys/mount.h>
13 #include <talloc/talloc.h>
14 #include <list/list.h>
16 #include <types/types.h>
17 #include <system/system.h>
18 #include <process/process.h>
20 #include <i18n/i18n.h>
22 #include <sys/sysmacros.h>
23 #include <sys/types.h>
24 #include <sys/socket.h>
26 #include <arpa/inet.h>
28 #include "device-handler.h"
29 #include "discover-server.h"
30 #include "devmapper.h"
31 #include "user-event.h"
43 enum default_priority {
44 DEFAULT_PRIORITY_REMOTE = 1,
45 DEFAULT_PRIORITY_LOCAL_FIRST = 2,
46 DEFAULT_PRIORITY_LOCAL_LAST = 0xfe,
47 DEFAULT_PRIORITY_DISABLED = 0xff,
50 struct progress_info {
51 unsigned int percentage;
52 unsigned long size; /* size in bytes */
54 const struct process_info *procinfo;
55 struct list_item list;
58 struct device_handler {
59 struct discover_server *server;
63 struct network *network;
64 struct user_event *user_event;
66 struct discover_device **devices;
67 unsigned int n_devices;
69 struct ramdisk_device **ramdisks;
70 unsigned int n_ramdisks;
72 struct waitset *waitset;
73 struct waiter *timeout_waiter;
74 bool autoboot_enabled;
75 unsigned int sec_to_boot;
77 struct discover_boot_option *default_boot_option;
78 int default_boot_option_priority;
80 struct list unresolved_boot_options;
82 struct boot_task *pending_boot;
83 bool pending_boot_is_default;
86 unsigned int n_progress;
89 static int mount_device(struct discover_device *dev);
90 static int umount_device(struct discover_device *dev);
92 static int device_handler_init_sources(struct device_handler *handler);
93 static void device_handler_reinit_sources(struct device_handler *handler);
95 static void device_handler_update_lang(const char *lang);
97 void discover_context_add_boot_option(struct discover_context *ctx,
98 struct discover_boot_option *boot_option)
100 boot_option->source = ctx->parser;
101 list_add_tail(&ctx->boot_options, &boot_option->list);
102 talloc_steal(ctx, boot_option);
106 * device_handler_get_device_count - Get the count of current handler devices.
109 int device_handler_get_device_count(const struct device_handler *handler)
111 return handler->n_devices;
115 * device_handler_get_device - Get a handler device by index.
118 const struct discover_device *device_handler_get_device(
119 const struct device_handler *handler, unsigned int index)
121 if (index >= handler->n_devices) {
122 assert(0 && "bad index");
126 return handler->devices[index];
129 struct network *device_handler_get_network(
130 const struct device_handler *handler)
132 return handler->network;
135 struct discover_boot_option *discover_boot_option_create(
136 struct discover_context *ctx,
137 struct discover_device *device)
139 struct discover_boot_option *opt;
141 opt = talloc_zero(ctx, struct discover_boot_option);
142 opt->option = talloc_zero(opt, struct boot_option);
143 opt->device = device;
148 static int device_match_uuid(struct discover_device *dev, const char *uuid)
150 return dev->uuid && !strcmp(dev->uuid, uuid);
153 static int device_match_label(struct discover_device *dev, const char *label)
155 return dev->label && !strcmp(dev->label, label);
158 static int device_match_id(struct discover_device *dev, const char *id)
160 return !strcmp(dev->device->id, id);
163 static int device_match_serial(struct discover_device *dev, const char *serial)
165 const char *val = discover_device_get_param(dev, "ID_SERIAL");
166 return val && !strcmp(val, serial);
169 static struct discover_device *device_lookup(
170 struct device_handler *device_handler,
171 int (match_fn)(struct discover_device *, const char *),
174 struct discover_device *dev;
180 for (i = 0; i < device_handler->n_devices; i++) {
181 dev = device_handler->devices[i];
183 if (match_fn(dev, str))
190 struct discover_device *device_lookup_by_name(struct device_handler *handler,
193 if (!strncmp(name, "/dev/", strlen("/dev/")))
194 name += strlen("/dev/");
196 return device_lookup_by_id(handler, name);
199 struct discover_device *device_lookup_by_uuid(
200 struct device_handler *device_handler,
203 return device_lookup(device_handler, device_match_uuid, uuid);
206 struct discover_device *device_lookup_by_label(
207 struct device_handler *device_handler,
210 return device_lookup(device_handler, device_match_label, label);
213 struct discover_device *device_lookup_by_id(
214 struct device_handler *device_handler,
217 return device_lookup(device_handler, device_match_id, id);
220 struct discover_device *device_lookup_by_serial(
221 struct device_handler *device_handler,
224 return device_lookup(device_handler, device_match_serial, serial);
227 void device_handler_destroy(struct device_handler *handler)
229 talloc_free(handler);
232 static int destroy_device(void *arg)
234 struct discover_device *dev = arg;
241 struct discover_device *discover_device_create(struct device_handler *handler,
242 const char *uuid, const char *id)
244 struct discover_device *dev;
247 dev = device_lookup_by_uuid(handler, uuid);
249 dev = device_lookup_by_id(handler, id);
254 dev = talloc_zero(handler, struct discover_device);
255 dev->device = talloc_zero(dev, struct device);
256 dev->device->id = talloc_strdup(dev->device, id);
257 dev->uuid = talloc_strdup(dev, uuid);
258 list_init(&dev->params);
259 list_init(&dev->boot_options);
261 talloc_set_destructor(dev, destroy_device);
266 struct discover_device_param {
269 struct list_item list;
272 void discover_device_set_param(struct discover_device *device,
273 const char *name, const char *value)
275 struct discover_device_param *param;
278 list_for_each_entry(&device->params, param, list) {
279 if (!strcmp(param->name, name)) {
288 param = talloc(device, struct discover_device_param);
289 param->name = talloc_strdup(param, name);
290 list_add(&device->params, ¶m->list);
293 list_remove(¶m->list);
297 talloc_free(param->value);
300 param->value = talloc_strdup(param, value);
303 const char *discover_device_get_param(struct discover_device *device,
306 struct discover_device_param *param;
308 list_for_each_entry(&device->params, param, list) {
309 if (!strcmp(param->name, name))
315 struct device_handler *device_handler_init(struct discover_server *server,
316 struct waitset *waitset, int dry_run)
318 struct device_handler *handler;
321 handler = talloc_zero(NULL, struct device_handler);
322 handler->server = server;
323 handler->waitset = waitset;
324 handler->dry_run = dry_run;
325 handler->autoboot_enabled = config_autoboot_active(config_get());
327 list_init(&handler->unresolved_boot_options);
329 list_init(&handler->progress);
331 /* set up our mount point base */
332 pb_mkdir_recursive(mount_base());
336 if (config_get()->safe_mode)
339 rc = device_handler_init_sources(handler);
341 talloc_free(handler);
348 void device_handler_reinit(struct device_handler *handler)
350 struct discover_boot_option *opt, *tmp;
351 struct ramdisk_device *ramdisk;
354 device_handler_cancel_default(handler);
355 /* Cancel any pending non-default boot */
356 if (handler->pending_boot) {
357 boot_cancel(handler->pending_boot);
358 handler->pending_boot = NULL;
359 handler->pending_boot_is_default = false;
362 /* Cancel any remaining async jobs */
363 process_stop_async_all();
364 pending_network_jobs_cancel();
366 /* free unresolved boot options */
367 list_for_each_entry_safe(&handler->unresolved_boot_options,
370 list_init(&handler->unresolved_boot_options);
372 /* drop all devices */
373 for (i = 0; i < handler->n_devices; i++) {
374 discover_server_notify_device_remove(handler->server,
375 handler->devices[i]->device);
376 ramdisk = handler->devices[i]->ramdisk;
377 talloc_free(handler->devices[i]);
378 talloc_free(ramdisk);
381 talloc_free(handler->devices);
382 handler->devices = NULL;
383 handler->n_devices = 0;
384 talloc_free(handler->ramdisks);
385 handler->ramdisks = NULL;
386 handler->n_ramdisks = 0;
388 device_handler_reinit_sources(handler);
391 void device_handler_remove(struct device_handler *handler,
392 struct discover_device *device)
394 struct discover_boot_option *opt, *tmp;
397 list_for_each_entry_safe(&device->boot_options, opt, tmp, list) {
398 if (opt == handler->default_boot_option) {
399 pb_log("Default option %s cancelled since device removed",
401 device_handler_cancel_default(handler);
406 for (i = 0; i < handler->n_devices; i++)
407 if (handler->devices[i] == device)
410 if (i == handler->n_devices) {
415 /* Free any unresolved options, as they're currently allocated
416 * against the handler */
417 list_for_each_entry_safe(&handler->unresolved_boot_options,
419 if (opt->device != device)
421 list_remove(&opt->list);
425 /* if this is a network device, we have to unregister it from the
427 if (device->device->type == DEVICE_TYPE_NETWORK)
428 network_unregister_device(handler->network, device);
430 handler->n_devices--;
431 memmove(&handler->devices[i], &handler->devices[i + 1],
432 (handler->n_devices - i) * sizeof(handler->devices[0]));
433 handler->devices = talloc_realloc(handler, handler->devices,
434 struct discover_device *, handler->n_devices);
436 if (device->notified)
437 discover_server_notify_device_remove(handler->server,
443 void device_handler_status(struct device_handler *handler,
444 struct status *status)
446 discover_server_notify_boot_status(handler->server, status);
449 static void _device_handler_vstatus(struct device_handler *handler,
450 enum status_type type, const char *fmt, va_list ap)
452 struct status status;
455 status.message = talloc_vasprintf(handler, fmt, ap);
456 status.backlog = false;
458 device_handler_status(handler, &status);
460 talloc_free(status.message);
463 static void _device_handler_vdevstatus(struct device_handler *handler,
464 struct discover_device *device, enum status_type type,
465 const char *fmt, va_list ap)
469 msg = talloc_asprintf(handler, "[%s] %s",
470 device ? device->device->id : "unknown", fmt);
471 _device_handler_vstatus(handler, type, msg, ap);
475 void device_handler_status_dev_info(struct device_handler *handler,
476 struct discover_device *dev, const char *fmt, ...)
481 _device_handler_vdevstatus(handler, dev, STATUS_INFO, fmt, ap);
485 void device_handler_status_dev_err(struct device_handler *handler,
486 struct discover_device *dev, const char *fmt, ...)
491 _device_handler_vdevstatus(handler, dev, STATUS_ERROR, fmt, ap);
495 void device_handler_status_info(struct device_handler *handler,
496 const char *fmt, ...)
501 _device_handler_vstatus(handler, STATUS_INFO, fmt, ap);
505 void device_handler_status_err(struct device_handler *handler,
506 const char *fmt, ...)
511 _device_handler_vstatus(handler, STATUS_ERROR, fmt, ap);
515 void device_handler_status_download(struct device_handler *handler,
516 const struct process_info *procinfo,
517 unsigned int percentage, unsigned int size, char suffix)
519 struct progress_info *p, *progress = NULL;
520 uint64_t current_converted, current = 0;
521 const char *units = " kMGTP";
522 unsigned long size_bytes;
528 list_for_each_entry(&handler->progress, p, list)
529 if (p->procinfo == procinfo)
533 pb_log("Registering new progress struct\n");
534 progress = talloc_zero(handler, struct progress_info);
536 pb_log("Failed to allocate room for progress struct\n");
539 progress->procinfo = procinfo;
540 list_add(&handler->progress, &progress->list);
541 handler->n_progress++;
545 for (i = 0; i < strlen(units); i++) {
546 if (units[i] == suffix)
550 if (i >= strlen(units)) {
551 pb_log("Couldn't recognise suffix '%c'\n", suffix);
558 progress->percentage = percentage;
559 progress->size = size_bytes;
562 * Aggregate the info we have and update status. If a progress struct
563 * has zero for both percentage and size we assume progress information
564 * is unavailable and fall back to a generic progress message.
566 list_for_each_entry(&handler->progress, p, list) {
569 if (!p->percentage || !p->size) {
570 update = talloc_asprintf(handler,
571 _("%u downloads in progress..."),
572 handler->n_progress);
578 t = (100 * c) / p->percentage;
585 current_converted = current;
586 while (current_converted >= 1000) {
587 current_converted >>= 10;
590 update = talloc_asprintf(handler,
591 _("%u %s downloading: %.0f%% - %lu%cB"),
593 ngettext("item", "items", handler->n_progress),
594 (current / total) * 100, current_converted,
599 pb_log("%s: failed to allocate new status\n", __func__);
601 device_handler_status_info(handler, "%s\n", update);
606 void device_handler_status_download_remove(struct device_handler *handler,
607 struct process_info *procinfo)
609 struct progress_info *p, *tmp;
611 list_for_each_entry_safe(&handler->progress, p, tmp, list)
612 if (p->procinfo == procinfo) {
613 list_remove(&p->list);
615 handler->n_progress--;
619 static void device_handler_boot_status_cb(void *arg, struct status *status)
621 device_handler_status(arg, status);
624 static void countdown_status(struct device_handler *handler,
625 struct discover_boot_option *opt, unsigned int sec)
627 struct status status;
629 status.type = STATUS_INFO;
630 status.message = talloc_asprintf(handler,
631 _("Booting in %d sec: %s"), sec, opt->option->name);
632 status.backlog = false;
634 device_handler_status(handler, &status);
636 talloc_free(status.message);
639 static int default_timeout(void *arg)
641 struct device_handler *handler = arg;
642 struct discover_boot_option *opt;
644 if (!handler->default_boot_option)
647 if (handler->pending_boot)
650 opt = handler->default_boot_option;
652 if (handler->sec_to_boot) {
653 countdown_status(handler, opt, handler->sec_to_boot);
654 handler->sec_to_boot--;
655 handler->timeout_waiter = waiter_register_timeout(
656 handler->waitset, 1000,
657 default_timeout, handler);
661 handler->timeout_waiter = NULL;
663 pb_log("Timeout expired, booting default option %s\n", opt->option->id);
667 handler->pending_boot = boot(handler, handler->default_boot_option,
668 NULL, handler->dry_run, device_handler_boot_status_cb,
670 handler->pending_boot_is_default = true;
675 enum ipmi_bootdev ipmi_type;
676 enum device_type device_type;
677 } device_type_map[] = {
678 { IPMI_BOOTDEV_NETWORK, DEVICE_TYPE_NETWORK },
679 { IPMI_BOOTDEV_DISK, DEVICE_TYPE_DISK },
680 { IPMI_BOOTDEV_DISK, DEVICE_TYPE_USB },
681 { IPMI_BOOTDEV_CDROM, DEVICE_TYPE_OPTICAL },
684 static bool ipmi_device_type_matches(enum ipmi_bootdev ipmi_type,
685 enum device_type device_type)
689 for (i = 0; i < ARRAY_SIZE(device_type_map); i++) {
690 if (device_type_map[i].device_type == device_type)
691 return device_type_map[i].ipmi_type == ipmi_type;
697 static int autoboot_option_priority(const struct config *config,
698 struct discover_boot_option *opt)
700 enum device_type type = opt->device->device->type;
701 const char *uuid = opt->device->uuid;
702 struct autoboot_option *auto_opt;
705 for (i = 0; i < config->n_autoboot_opts; i++) {
706 auto_opt = &config->autoboot_opts[i];
707 if (auto_opt->boot_type == BOOT_DEVICE_UUID)
708 if (!strcmp(auto_opt->uuid, uuid))
709 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
711 if (auto_opt->boot_type == BOOT_DEVICE_TYPE)
712 if (auto_opt->type == type ||
713 auto_opt->type == DEVICE_TYPE_ANY)
714 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
721 * We have different priorities to resolve conflicts between boot options that
722 * report to be the default for their device. This function assigns a priority
725 static enum default_priority default_option_priority(
726 struct discover_boot_option *opt)
728 const struct config *config;
730 config = config_get();
732 /* We give highest priority to IPMI-configured boot options. If
733 * we have an IPMI bootdev configuration set, then we don't allow
734 * any other defaults */
735 if (config->ipmi_bootdev) {
736 bool ipmi_match = ipmi_device_type_matches(config->ipmi_bootdev,
737 opt->device->device->type);
739 return DEFAULT_PRIORITY_REMOTE;
741 pb_debug("handler: disabled default priority due to "
742 "non-matching IPMI type %x\n",
743 config->ipmi_bootdev);
744 return DEFAULT_PRIORITY_DISABLED;
747 /* Next, try to match the option against the user-defined autoboot
748 * options, either by device UUID or type. */
749 if (config->n_autoboot_opts) {
750 int boot_match = autoboot_option_priority(config, opt);
755 /* If the option didn't match any entry in the array, it is disabled */
756 pb_debug("handler: disabled default priority due to "
757 "non-matching UUID or type\n");
758 return DEFAULT_PRIORITY_DISABLED;
761 static void set_default(struct device_handler *handler,
762 struct discover_boot_option *opt)
764 enum default_priority cur_prio, new_prio;
766 if (!handler->autoboot_enabled)
769 pb_debug("handler: new default option: %s\n", opt->option->id);
771 new_prio = default_option_priority(opt);
773 /* Anything outside our range prevents a default boot */
774 if (new_prio >= DEFAULT_PRIORITY_DISABLED)
777 pb_debug("handler: calculated priority %d\n", new_prio);
779 /* Resolve any conflicts: if we have a new default option, it only
780 * replaces the current if it has a higher priority. */
781 if (handler->default_boot_option) {
783 cur_prio = handler->default_boot_option_priority;
785 if (new_prio < cur_prio) {
786 pb_log("handler: new prio %d beats "
787 "old prio %d for %s\n",
789 handler->default_boot_option
791 handler->default_boot_option = opt;
792 handler->default_boot_option_priority = new_prio;
793 /* extend the timeout a little, so the user sees some
794 * indication of the change */
795 handler->sec_to_boot += 2;
801 handler->sec_to_boot = config_get()->autoboot_timeout_sec;
802 handler->default_boot_option = opt;
803 handler->default_boot_option_priority = new_prio;
805 pb_log("handler: boot option %s set as default, timeout %u sec.\n",
806 opt->option->id, handler->sec_to_boot);
808 default_timeout(handler);
811 static bool resource_is_resolved(struct resource *res)
813 return !res || res->resolved;
816 /* We only use this in an assert, which will disappear if we're compiling
817 * with NDEBUG, so we need the 'used' attribute for these builds */
818 static bool __attribute__((used)) boot_option_is_resolved(
819 struct discover_boot_option *opt)
821 return resource_is_resolved(opt->boot_image) &&
822 resource_is_resolved(opt->initrd) &&
823 resource_is_resolved(opt->dtb) &&
824 resource_is_resolved(opt->args_sig_file) &&
825 resource_is_resolved(opt->icon);
828 static bool resource_resolve(struct resource *res, const char *name,
829 struct discover_boot_option *opt,
830 struct device_handler *handler)
832 struct parser *parser = opt->source;
834 if (resource_is_resolved(res))
837 pb_debug("Attempting to resolve resource %s->%s with parser %s\n",
838 opt->option->id, name, parser->name);
839 parser->resolve_resource(handler, res);
841 return res->resolved;
844 static bool boot_option_resolve(struct discover_boot_option *opt,
845 struct device_handler *handler)
847 return resource_resolve(opt->boot_image, "boot_image", opt, handler) &&
848 resource_resolve(opt->initrd, "initrd", opt, handler) &&
849 resource_resolve(opt->dtb, "dtb", opt, handler) &&
850 resource_resolve(opt->args_sig_file, "args_sig_file", opt,
852 resource_resolve(opt->icon, "icon", opt, handler);
855 static void boot_option_finalise(struct device_handler *handler,
856 struct discover_boot_option *opt)
858 assert(boot_option_is_resolved(opt));
860 /* check that the parsers haven't set any of the final data */
861 assert(!opt->option->boot_image_file);
862 assert(!opt->option->initrd_file);
863 assert(!opt->option->dtb_file);
864 assert(!opt->option->icon_file);
865 assert(!opt->option->device_id);
866 assert(!opt->option->args_sig_file);
869 opt->option->boot_image_file = opt->boot_image->url->full;
871 opt->option->initrd_file = opt->initrd->url->full;
873 opt->option->dtb_file = opt->dtb->url->full;
875 opt->option->icon_file = opt->icon->url->full;
876 if (opt->args_sig_file)
877 opt->option->args_sig_file = opt->args_sig_file->url->full;
879 opt->option->device_id = opt->device->device->id;
881 if (opt->option->is_default)
882 set_default(handler, opt);
885 static void notify_boot_option(struct device_handler *handler,
886 struct discover_boot_option *opt)
888 struct discover_device *dev = opt->device;
891 discover_server_notify_device_add(handler->server,
892 opt->device->device);
893 dev->notified = true;
894 discover_server_notify_boot_option_add(handler->server, opt->option);
897 static void process_boot_option_queue(struct device_handler *handler)
899 struct discover_boot_option *opt, *tmp;
901 list_for_each_entry_safe(&handler->unresolved_boot_options,
904 pb_debug("queue: attempting resolution for %s\n",
907 if (!boot_option_resolve(opt, handler))
910 pb_debug("\tresolved!\n");
912 list_remove(&opt->list);
913 list_add_tail(&opt->device->boot_options, &opt->list);
914 talloc_steal(opt->device, opt);
915 boot_option_finalise(handler, opt);
916 notify_boot_option(handler, opt);
920 struct discover_context *device_handler_discover_context_create(
921 struct device_handler *handler,
922 struct discover_device *device)
924 struct discover_context *ctx;
926 ctx = talloc_zero(handler, struct discover_context);
927 ctx->handler = handler;
928 ctx->device = device;
929 list_init(&ctx->boot_options);
934 void device_handler_add_device(struct device_handler *handler,
935 struct discover_device *device)
937 handler->n_devices++;
938 handler->devices = talloc_realloc(handler, handler->devices,
939 struct discover_device *, handler->n_devices);
940 handler->devices[handler->n_devices - 1] = device;
942 if (device->device->type == DEVICE_TYPE_NETWORK)
943 network_register_device(handler->network, device);
946 void device_handler_add_ramdisk(struct device_handler *handler,
949 struct ramdisk_device *dev;
955 for (i = 0; i < handler->n_ramdisks; i++)
956 if (!strcmp(handler->ramdisks[i]->path, path))
959 dev = talloc_zero(handler, struct ramdisk_device);
961 pb_log("Failed to allocate memory to track %s\n", path);
965 dev->path = talloc_strdup(handler, path);
967 handler->ramdisks = talloc_realloc(handler, handler->ramdisks,
968 struct ramdisk_device *,
969 handler->n_ramdisks + 1);
970 if (!handler->ramdisks) {
971 pb_log("Failed to reallocate memory"
972 "- ramdisk tracking inconsistent!\n");
976 handler->ramdisks[i] = dev;
977 i = handler->n_ramdisks++;
980 struct ramdisk_device *device_handler_get_ramdisk(
981 struct device_handler *handler)
987 /* Check if free ramdisk exists */
988 for (i = 0; i < handler->n_ramdisks; i++)
989 if (!handler->ramdisks[i]->snapshot &&
990 !handler->ramdisks[i]->origin &&
991 !handler->ramdisks[i]->base)
992 return handler->ramdisks[i];
994 /* Otherwise create a new one */
995 name = talloc_asprintf(handler, "/dev/ram%d",
996 handler->n_ramdisks);
998 pb_debug("Failed to allocate memory to name /dev/ram%d",
999 handler->n_ramdisks);
1003 id = makedev(1, handler->n_ramdisks);
1004 if (mknod(name, S_IFBLK, id)) {
1005 if (errno == EEXIST) {
1006 /* We haven't yet received updates for existing
1007 * ramdisks - add and use this one */
1008 pb_debug("Using untracked ramdisk %s\n", name);
1010 pb_log("Failed to create new ramdisk %s: %s\n",
1011 name, strerror(errno));
1015 device_handler_add_ramdisk(handler, name);
1018 return handler->ramdisks[i];
1021 void device_handler_release_ramdisk(struct discover_device *device)
1023 struct ramdisk_device *ramdisk = device->ramdisk;
1025 talloc_free(ramdisk->snapshot);
1026 talloc_free(ramdisk->origin);
1027 talloc_free(ramdisk->base);
1029 ramdisk->snapshot = ramdisk->origin = ramdisk->base = NULL;
1030 ramdisk->sectors = 0;
1032 device->ramdisk = NULL;
1035 /* Start discovery on a hotplugged device. The device will be in our devices
1036 * array, but has only just been initialised by the hotplug source.
1038 int device_handler_discover(struct device_handler *handler,
1039 struct discover_device *dev)
1041 struct discover_context *ctx;
1044 device_handler_status_dev_info(handler, dev,
1046 * TRANSLATORS: this string will be passed the type of the
1047 * device (eg "disk" or "network"), which will be translated
1050 _("Processing new %s device"),
1051 device_type_display_name(dev->device->type));
1053 /* create our context */
1054 ctx = device_handler_discover_context_create(handler, dev);
1056 rc = mount_device(dev);
1060 /* add this device to our system info */
1061 system_info_register_blockdev(dev->device->id, dev->uuid,
1064 /* run the parsers. This will populate the ctx's boot_option list. */
1065 iterate_parsers(ctx);
1067 /* add discovered stuff to the handler */
1068 device_handler_discover_context_commit(handler, ctx);
1070 process_boot_option_queue(handler);
1072 talloc_unlink(handler, ctx);
1077 /* Incoming dhcp event */
1078 int device_handler_dhcp(struct device_handler *handler,
1079 struct discover_device *dev, struct event *event)
1081 struct discover_context *ctx;
1083 device_handler_status_dev_info(handler, dev,
1084 _("Processing DHCP lease response (ip: %s)"),
1085 event_get_param(event, "ip"));
1087 pending_network_jobs_start();
1089 /* create our context */
1090 ctx = device_handler_discover_context_create(handler, dev);
1091 talloc_steal(ctx, event);
1094 iterate_parsers(ctx);
1096 device_handler_discover_context_commit(handler, ctx);
1098 talloc_unlink(handler, ctx);
1103 static struct discover_boot_option *find_boot_option_by_id(
1104 struct device_handler *handler, const char *id)
1108 for (i = 0; i < handler->n_devices; i++) {
1109 struct discover_device *dev = handler->devices[i];
1110 struct discover_boot_option *opt;
1112 list_for_each_entry(&dev->boot_options, opt, list)
1113 if (!strcmp(opt->option->id, id))
1120 void device_handler_boot(struct device_handler *handler,
1121 struct boot_command *cmd)
1123 struct discover_boot_option *opt = NULL;
1125 if (cmd->option_id && strlen(cmd->option_id))
1126 opt = find_boot_option_by_id(handler, cmd->option_id);
1128 if (handler->pending_boot)
1129 boot_cancel(handler->pending_boot);
1131 platform_pre_boot();
1133 handler->pending_boot = boot(handler, opt, cmd, handler->dry_run,
1134 device_handler_boot_status_cb, handler);
1135 handler->pending_boot_is_default = false;
1138 void device_handler_cancel_default(struct device_handler *handler)
1140 if (handler->timeout_waiter)
1141 waiter_remove(handler->timeout_waiter);
1143 handler->timeout_waiter = NULL;
1144 handler->autoboot_enabled = false;
1146 /* we only send status if we had a default boot option queued */
1147 if (!handler->default_boot_option)
1150 pb_log("Cancelling default boot option\n");
1152 if (handler->pending_boot && handler->pending_boot_is_default) {
1153 boot_cancel(handler->pending_boot);
1154 handler->pending_boot = NULL;
1155 handler->pending_boot_is_default = false;
1158 handler->default_boot_option = NULL;
1160 device_handler_status_info(handler, _("Default boot cancelled"));
1163 void device_handler_update_config(struct device_handler *handler,
1164 struct config *config)
1168 rc = config_set(config);
1172 discover_server_notify_config(handler->server, config);
1173 device_handler_update_lang(config->lang);
1174 device_handler_reinit(handler);
1177 static char *device_from_addr(void *ctx, struct pb_url *url)
1179 char *ipaddr, *buf, *tok, *dev = NULL;
1180 const char *delim = " ";
1181 struct sockaddr_in *ip;
1182 struct sockaddr_in si;
1183 struct addrinfo *res;
1187 /* Note: IPv4 only */
1188 rc = inet_pton(AF_INET, url->host, &(si.sin_addr));
1192 /* need to turn hostname into a valid IP */
1193 rc = getaddrinfo(url->host, NULL, NULL, &res);
1195 pb_debug("%s: Invalid URL\n",__func__);
1198 ipaddr = talloc_array(ctx,char,INET_ADDRSTRLEN);
1199 ip = (struct sockaddr_in *) res->ai_addr;
1200 inet_ntop(AF_INET, &(ip->sin_addr), ipaddr, INET_ADDRSTRLEN);
1204 const char *argv[] = {
1206 "route", "show", "to", "match",
1211 p = process_create(ctx);
1213 p->path = pb_system_apps.ip;
1215 p->keep_stdout = true;
1217 rc = process_run_sync(p);
1219 if (rc || p->exit_status) {
1220 /* ip has complained for some reason; most likely
1221 * there is no route to the host - bail out */
1222 pb_debug("%s: `ip` returns non-zero exit status\n", __func__);
1223 pb_debug("ip buf: %s\n", p->stdout_buf);
1228 buf = p->stdout_buf;
1229 /* If a route is found, ip-route output will be of the form
1230 * "... dev DEVNAME ... " */
1231 tok = strtok(buf, delim);
1233 if (!strcmp(tok, "dev")) {
1234 tok = strtok(NULL, delim);
1235 dev = talloc_strdup(ctx, tok);
1238 tok = strtok(NULL, delim);
1243 pb_debug("%s: Found interface '%s'\n", __func__,dev);
1247 static void process_url_cb(struct load_url_result *result, void *data)
1249 struct device_handler *handler;
1250 struct discover_context *ctx;
1251 struct discover_device *dev;
1252 struct event *event = data;
1255 if (result->status != LOAD_OK) {
1256 pb_log("%s: Load failed for %s\n", __func__, result->url->full);
1263 handler = talloc_parent(event);
1267 event->device = device_from_addr(event, result->url);
1268 if (!event->device) {
1269 pb_log("Downloaded a file but can't find its interface - pretending it was local\n");
1270 event->device = talloc_asprintf(event, "local");
1273 mac = event_get_param(event, "mac");
1274 char *url = talloc_asprintf(event, "file://%s", result->local);
1275 event_set_param(event, "pxeconffile", url);
1277 dev = discover_device_create(handler, mac, event->device);
1278 ctx = device_handler_discover_context_create(handler, dev);
1279 talloc_steal(ctx, event);
1282 iterate_parsers(ctx);
1284 device_handler_discover_context_commit(handler, ctx);
1286 talloc_unlink(handler, ctx);
1289 void device_handler_process_url(struct device_handler *handler,
1290 const char *url, const char *mac, const char *ip)
1292 struct discover_context *ctx;
1293 struct discover_device *dev;
1294 bool allow_async = false;
1295 struct pb_url *pb_url;
1296 struct event *event;
1298 event = talloc_zero(handler, struct event);
1299 event->type = EVENT_TYPE_USER;
1300 event->action = EVENT_ACTION_URL;
1302 pb_url = pb_url_parse(event, url);
1303 if (!pb_url || (pb_url->scheme != pb_url_file && !pb_url->host)) {
1304 device_handler_status_err(handler, _("Invalid config URL!"));
1309 if (url[strlen(url) - 1] == '/') {
1310 event_set_param(event, "pxepathprefix", url);
1311 event_set_param(event, "mac", mac);
1312 event_set_param(event, "ip", ip);
1313 event->device = device_from_addr(event, pb_url);
1314 if (!event->device) {
1315 device_handler_status_err(handler,
1316 _("Unable to route to host %s"),
1322 event_set_param(event, "pxeconffile", url);
1326 if (pb_url->scheme == pb_url_file)
1327 event->device = talloc_asprintf(event, "local");
1328 else if (allow_async) {
1329 /* If file is remote load asynchronously before passing to
1330 * parser. This allows us to wait for network to be available */
1331 if (!load_url_async(handler, pb_url, process_url_cb, event,
1333 pb_log("Failed to load url %s\n", pb_url->full);
1334 device_handler_status_err(handler, _("Failed to load URL!"));
1340 /* If path is local we can parse straight away */
1342 dev = discover_device_create(handler, mac, event->device);
1343 if (pb_url->scheme == pb_url_file)
1344 dev->device->type = DEVICE_TYPE_ANY;
1345 ctx = device_handler_discover_context_create(handler, dev);
1346 talloc_steal(ctx, event);
1349 iterate_parsers(ctx);
1351 device_handler_discover_context_commit(handler, ctx);
1353 talloc_unlink(handler, ctx);
1356 #ifndef PETITBOOT_TEST
1359 * context_commit - Commit a temporary discovery context to the handler,
1360 * and notify the clients about any new options / devices
1362 void device_handler_discover_context_commit(struct device_handler *handler,
1363 struct discover_context *ctx)
1365 struct discover_device *dev = ctx->device;
1366 struct discover_boot_option *opt, *tmp;
1368 if (!device_lookup_by_uuid(handler, dev->uuid))
1369 device_handler_add_device(handler, dev);
1371 /* move boot options from the context to the device */
1372 list_for_each_entry_safe(&ctx->boot_options, opt, tmp, list) {
1373 list_remove(&opt->list);
1375 /* All boot options need at least a kernel image */
1376 if (!opt->boot_image || !opt->boot_image->url) {
1377 pb_log("boot option %s is missing boot image, ignoring\n",
1383 if (boot_option_resolve(opt, handler)) {
1384 pb_log("boot option %s is resolved, "
1385 "sending to clients\n",
1387 list_add_tail(&dev->boot_options, &opt->list);
1388 talloc_steal(dev, opt);
1389 boot_option_finalise(handler, opt);
1390 notify_boot_option(handler, opt);
1392 if (!opt->source->resolve_resource) {
1393 pb_log("parser %s gave us an unresolved "
1394 "resource (%s), but no way to "
1396 opt->source->name, opt->option->id);
1399 pb_log("boot option %s is unresolved, "
1400 "adding to queue\n",
1402 list_add(&handler->unresolved_boot_options,
1404 talloc_steal(handler, opt);
1410 static void device_handler_update_lang(const char *lang)
1412 const char *cur_lang;
1417 cur_lang = setlocale(LC_ALL, NULL);
1418 if (cur_lang && !strcmp(cur_lang, lang))
1421 setlocale(LC_ALL, lang);
1424 static int device_handler_init_sources(struct device_handler *handler)
1426 /* init our device sources: udev, network and user events */
1427 handler->udev = udev_init(handler, handler->waitset);
1431 handler->network = network_init(handler, handler->waitset,
1433 if (!handler->network)
1436 handler->user_event = user_event_init(handler, handler->waitset);
1437 if (!handler->user_event)
1443 static void device_handler_reinit_sources(struct device_handler *handler)
1445 /* if we haven't initialised sources previously (becuase we started in
1446 * safe mode), then init once here. */
1447 if (!(handler->udev || handler->network || handler->user_event)) {
1448 device_handler_init_sources(handler);
1452 system_info_reinit();
1454 udev_reinit(handler->udev);
1456 network_shutdown(handler->network);
1457 handler->network = network_init(handler, handler->waitset,
1461 static inline const char *get_device_path(struct discover_device *dev)
1463 return dev->ramdisk ? dev->ramdisk->snapshot : dev->device_path;
1466 static char *check_subvols(struct discover_device *dev)
1468 const char *fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1473 if (strncmp(fstype, "btrfs", strlen("btrfs")))
1474 return dev->mount_path;
1476 /* On btrfs a device's root may be under a subvolume path */
1477 path = join_paths(dev, dev->mount_path, "@");
1478 rc = stat(path, &sb);
1479 if (!rc && S_ISDIR(sb.st_mode)) {
1480 pb_debug("Using '%s' for btrfs root path\n", path);
1485 return dev->mount_path;
1488 static bool check_existing_mount(struct discover_device *dev)
1490 struct stat devstat, mntstat;
1491 const char *device_path;
1496 device_path = get_device_path(dev);
1498 rc = stat(device_path, &devstat);
1500 pb_debug("%s: stat failed: %s\n", __func__, strerror(errno));
1504 if (!S_ISBLK(devstat.st_mode)) {
1505 pb_debug("%s: %s isn't a block device?\n", __func__,
1510 fp = fopen("/proc/self/mounts", "r");
1513 mnt = getmntent(fp);
1517 if (!mnt->mnt_fsname || mnt->mnt_fsname[0] != '/')
1520 rc = stat(mnt->mnt_fsname, &mntstat);
1524 if (!S_ISBLK(mntstat.st_mode))
1527 if (mntstat.st_rdev == devstat.st_rdev) {
1528 dev->mount_path = talloc_strdup(dev, mnt->mnt_dir);
1529 dev->root_path = check_subvols(dev);
1530 dev->mounted_rw = !!hasmntopt(mnt, "rw");
1531 dev->mounted = true;
1532 dev->unmount = false;
1534 pb_debug("%s: %s is already mounted (r%c) at %s\n",
1535 __func__, dev->device_path,
1536 dev->mounted_rw ? 'w' : 'o',
1548 * Attempt to mount a filesystem safely, while handling certain filesytem-
1551 static int try_mount(const char *device_path, const char *mount_path,
1552 const char *fstype, unsigned long flags,
1555 const char *fs, *safe_opts;
1558 /* Mount ext3 as ext4 instead so 'norecovery' can be used */
1559 if (strncmp(fstype, "ext3", strlen("ext3")) == 0) {
1560 pb_debug("Mounting ext3 filesystem as ext4\n");
1565 if (strncmp(fs, "xfs", strlen("xfs")) == 0 ||
1566 strncmp(fs, "ext4", strlen("ext4")) == 0)
1567 safe_opts = "norecovery";
1572 /* If no snapshot is available don't attempt recovery */
1574 return mount(device_path, mount_path, fs, flags, safe_opts);
1576 rc = mount(device_path, mount_path, fs, flags, NULL);
1581 /* Mounting failed; some filesystems will fail to mount if a recovery
1582 * journal exists (eg. cross-endian XFS), so try again with norecovery
1583 * where that option is available.
1584 * If mounting read-write just return the error as norecovery is not a
1586 if ((flags & MS_RDONLY) != MS_RDONLY || !safe_opts)
1590 return mount(device_path, mount_path, fs, flags, safe_opts);
1593 static int mount_device(struct discover_device *dev)
1595 const char *fstype, *device_path;
1598 if (!dev->device_path)
1604 if (check_existing_mount(dev))
1607 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1611 dev->mount_path = join_paths(dev, mount_base(),
1614 if (pb_mkdir_recursive(dev->mount_path)) {
1615 pb_log("couldn't create mount directory %s: %s\n",
1616 dev->mount_path, strerror(errno));
1620 device_path = get_device_path(dev);
1622 pb_log("mounting device %s read-only\n", dev->device_path);
1623 rc = try_mount(device_path, dev->mount_path, fstype,
1624 MS_RDONLY | MS_SILENT, dev->ramdisk);
1627 dev->mounted = true;
1628 dev->mounted_rw = false;
1629 dev->unmount = true;
1630 dev->root_path = check_subvols(dev);
1634 pb_log("couldn't mount device %s: mount failed: %s\n",
1635 device_path, strerror(errno));
1637 /* If mount fails clean up any snapshot */
1638 devmapper_destroy_snapshot(dev);
1640 pb_rmdir_recursive(mount_base(), dev->mount_path);
1642 talloc_free(dev->mount_path);
1643 dev->mount_path = NULL;
1647 static int umount_device(struct discover_device *dev)
1649 const char *device_path;
1652 if (!dev->mounted || !dev->unmount)
1655 device_path = get_device_path(dev);
1657 pb_log("unmounting device %s\n", device_path);
1658 rc = umount(dev->mount_path);
1662 dev->mounted = false;
1663 devmapper_destroy_snapshot(dev);
1665 pb_rmdir_recursive(mount_base(), dev->mount_path);
1667 talloc_free(dev->mount_path);
1668 dev->mount_path = NULL;
1669 dev->root_path = NULL;
1674 int device_request_write(struct discover_device *dev, bool *release)
1676 const char *fstype, *device_path;
1677 const struct config *config;
1682 config = config_get();
1683 if (!config->allow_writes)
1689 if (dev->mounted_rw)
1692 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1694 device_path = get_device_path(dev);
1696 pb_log("remounting device %s read-write\n", device_path);
1698 rc = umount(dev->mount_path);
1700 pb_log("Failed to unmount %s: %s\n",
1701 dev->mount_path, strerror(errno));
1705 rc = try_mount(device_path, dev->mount_path, fstype,
1706 MS_SILENT, dev->ramdisk);
1710 dev->mounted_rw = true;
1715 pb_log("Unable to remount device %s read-write: %s\n",
1716 device_path, strerror(errno));
1717 rc = try_mount(device_path, dev->mount_path, fstype,
1718 MS_RDONLY | MS_SILENT, dev->ramdisk);
1720 pb_log("Unable to recover mount for %s: %s\n",
1721 device_path, strerror(errno));
1725 void device_release_write(struct discover_device *dev, bool release)
1727 const char *fstype, *device_path;
1732 device_path = get_device_path(dev);
1734 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1736 pb_log("remounting device %s read-only\n", device_path);
1738 if (umount(dev->mount_path)) {
1739 pb_log("Failed to unmount %s\n", dev->mount_path);
1742 dev->mounted_rw = dev->mounted = false;
1745 devmapper_merge_snapshot(dev);
1746 /* device_path becomes stale after merge */
1747 device_path = get_device_path(dev);
1750 if (try_mount(device_path, dev->mount_path, fstype,
1751 MS_RDONLY | MS_SILENT, dev->ramdisk))
1752 pb_log("Failed to remount %s read-only: %s\n",
1753 device_path, strerror(errno));
1755 dev->mounted = true;
1758 void device_sync_snapshots(struct device_handler *handler, const char *device)
1760 struct discover_device *dev = NULL;
1764 /* Find matching device and sync */
1765 dev = device_lookup_by_name(handler, device);
1767 pb_log("%s: device name '%s' unrecognised\n",
1772 device_release_write(dev, true);
1774 pb_log("%s has no snapshot to merge, skipping\n",
1779 /* Otherwise sync all relevant devices */
1780 for (i = 0; i < handler->n_devices; i++) {
1781 dev = handler->devices[i];
1782 if (dev->device->type != DEVICE_TYPE_DISK &&
1783 dev->device->type != DEVICE_TYPE_USB)
1786 device_release_write(dev, true);
1788 pb_log("%s has no snapshot to merge, skipping\n",
1795 void device_handler_discover_context_commit(
1796 struct device_handler *handler __attribute__((unused)),
1797 struct discover_context *ctx __attribute__((unused)))
1799 pb_log("%s stubbed out for test cases\n", __func__);
1802 static void device_handler_update_lang(const char *lang __attribute__((unused)))
1806 static int device_handler_init_sources(
1807 struct device_handler *handler __attribute__((unused)))
1812 static void device_handler_reinit_sources(
1813 struct device_handler *handler __attribute__((unused)))
1817 static int umount_device(struct discover_device *dev __attribute__((unused)))
1822 static int __attribute__((unused)) mount_device(
1823 struct discover_device *dev __attribute__((unused)))
1828 int device_request_write(struct discover_device *dev __attribute__((unused)),
1835 void device_release_write(struct discover_device *dev __attribute__((unused)),
1836 bool release __attribute__((unused)))
1840 void device_sync_snapshots(
1841 struct device_handler *handler __attribute__((unused)),
1842 const char *device __attribute__((unused)))