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] %s"), sec,
632 opt->device->device->id, opt->option->name);
633 status.backlog = false;
635 device_handler_status(handler, &status);
637 talloc_free(status.message);
640 static int default_timeout(void *arg)
642 struct device_handler *handler = arg;
643 struct discover_boot_option *opt;
645 if (!handler->default_boot_option)
648 if (handler->pending_boot)
651 opt = handler->default_boot_option;
653 if (handler->sec_to_boot) {
654 countdown_status(handler, opt, handler->sec_to_boot);
655 handler->sec_to_boot--;
656 handler->timeout_waiter = waiter_register_timeout(
657 handler->waitset, 1000,
658 default_timeout, handler);
662 handler->timeout_waiter = NULL;
664 pb_log("Timeout expired, booting default option %s\n", opt->option->id);
668 handler->pending_boot = boot(handler, handler->default_boot_option,
669 NULL, handler->dry_run, device_handler_boot_status_cb,
671 handler->pending_boot_is_default = true;
676 enum ipmi_bootdev ipmi_type;
677 enum device_type device_type;
678 } device_type_map[] = {
679 { IPMI_BOOTDEV_NETWORK, DEVICE_TYPE_NETWORK },
680 { IPMI_BOOTDEV_DISK, DEVICE_TYPE_DISK },
681 { IPMI_BOOTDEV_DISK, DEVICE_TYPE_USB },
682 { IPMI_BOOTDEV_CDROM, DEVICE_TYPE_OPTICAL },
685 static bool ipmi_device_type_matches(enum ipmi_bootdev ipmi_type,
686 enum device_type device_type)
690 for (i = 0; i < ARRAY_SIZE(device_type_map); i++) {
691 if (device_type_map[i].device_type == device_type)
692 return device_type_map[i].ipmi_type == ipmi_type;
698 static int autoboot_option_priority(const struct config *config,
699 struct discover_boot_option *opt)
701 enum device_type type = opt->device->device->type;
702 const char *uuid = opt->device->uuid;
703 struct autoboot_option *auto_opt;
706 for (i = 0; i < config->n_autoboot_opts; i++) {
707 auto_opt = &config->autoboot_opts[i];
708 if (auto_opt->boot_type == BOOT_DEVICE_UUID)
709 if (!strcmp(auto_opt->uuid, uuid))
710 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
712 if (auto_opt->boot_type == BOOT_DEVICE_TYPE)
713 if (auto_opt->type == type ||
714 auto_opt->type == DEVICE_TYPE_ANY)
715 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
722 * We have different priorities to resolve conflicts between boot options that
723 * report to be the default for their device. This function assigns a priority
726 static enum default_priority default_option_priority(
727 struct discover_boot_option *opt)
729 const struct config *config;
731 config = config_get();
733 /* We give highest priority to IPMI-configured boot options. If
734 * we have an IPMI bootdev configuration set, then we don't allow
735 * any other defaults */
736 if (config->ipmi_bootdev) {
737 bool ipmi_match = ipmi_device_type_matches(config->ipmi_bootdev,
738 opt->device->device->type);
740 return DEFAULT_PRIORITY_REMOTE;
742 pb_debug("handler: disabled default priority due to "
743 "non-matching IPMI type %x\n",
744 config->ipmi_bootdev);
745 return DEFAULT_PRIORITY_DISABLED;
748 /* Next, try to match the option against the user-defined autoboot
749 * options, either by device UUID or type. */
750 if (config->n_autoboot_opts) {
751 int boot_match = autoboot_option_priority(config, opt);
756 /* If the option didn't match any entry in the array, it is disabled */
757 pb_debug("handler: disabled default priority due to "
758 "non-matching UUID or type\n");
759 return DEFAULT_PRIORITY_DISABLED;
762 static void set_default(struct device_handler *handler,
763 struct discover_boot_option *opt)
765 enum default_priority cur_prio, new_prio;
767 if (!handler->autoboot_enabled)
770 pb_debug("handler: new default option: %s\n", opt->option->id);
772 new_prio = default_option_priority(opt);
774 /* Anything outside our range prevents a default boot */
775 if (new_prio >= DEFAULT_PRIORITY_DISABLED)
778 pb_debug("handler: calculated priority %d\n", new_prio);
780 /* Resolve any conflicts: if we have a new default option, it only
781 * replaces the current if it has a higher priority. */
782 if (handler->default_boot_option) {
784 cur_prio = handler->default_boot_option_priority;
786 if (new_prio < cur_prio) {
787 pb_log("handler: new prio %d beats "
788 "old prio %d for %s\n",
790 handler->default_boot_option
792 handler->default_boot_option = opt;
793 handler->default_boot_option_priority = new_prio;
794 /* extend the timeout a little, so the user sees some
795 * indication of the change */
796 handler->sec_to_boot += 2;
802 handler->sec_to_boot = config_get()->autoboot_timeout_sec;
803 handler->default_boot_option = opt;
804 handler->default_boot_option_priority = new_prio;
806 pb_log("handler: boot option %s set as default, timeout %u sec.\n",
807 opt->option->id, handler->sec_to_boot);
809 default_timeout(handler);
812 static bool resource_is_resolved(struct resource *res)
814 return !res || res->resolved;
817 /* We only use this in an assert, which will disappear if we're compiling
818 * with NDEBUG, so we need the 'used' attribute for these builds */
819 static bool __attribute__((used)) boot_option_is_resolved(
820 struct discover_boot_option *opt)
822 return resource_is_resolved(opt->boot_image) &&
823 resource_is_resolved(opt->initrd) &&
824 resource_is_resolved(opt->dtb) &&
825 resource_is_resolved(opt->args_sig_file) &&
826 resource_is_resolved(opt->icon);
829 static bool resource_resolve(struct resource *res, const char *name,
830 struct discover_boot_option *opt,
831 struct device_handler *handler)
833 struct parser *parser = opt->source;
835 if (resource_is_resolved(res))
838 pb_debug("Attempting to resolve resource %s->%s with parser %s\n",
839 opt->option->id, name, parser->name);
840 parser->resolve_resource(handler, res);
842 return res->resolved;
845 static bool boot_option_resolve(struct discover_boot_option *opt,
846 struct device_handler *handler)
848 return resource_resolve(opt->boot_image, "boot_image", opt, handler) &&
849 resource_resolve(opt->initrd, "initrd", opt, handler) &&
850 resource_resolve(opt->dtb, "dtb", opt, handler) &&
851 resource_resolve(opt->args_sig_file, "args_sig_file", opt,
853 resource_resolve(opt->icon, "icon", opt, handler);
856 static void boot_option_finalise(struct device_handler *handler,
857 struct discover_boot_option *opt)
859 assert(boot_option_is_resolved(opt));
861 /* check that the parsers haven't set any of the final data */
862 assert(!opt->option->boot_image_file);
863 assert(!opt->option->initrd_file);
864 assert(!opt->option->dtb_file);
865 assert(!opt->option->icon_file);
866 assert(!opt->option->device_id);
867 assert(!opt->option->args_sig_file);
870 opt->option->boot_image_file = opt->boot_image->url->full;
872 opt->option->initrd_file = opt->initrd->url->full;
874 opt->option->dtb_file = opt->dtb->url->full;
876 opt->option->icon_file = opt->icon->url->full;
877 if (opt->args_sig_file)
878 opt->option->args_sig_file = opt->args_sig_file->url->full;
880 opt->option->device_id = opt->device->device->id;
882 if (opt->option->is_default)
883 set_default(handler, opt);
886 static void notify_boot_option(struct device_handler *handler,
887 struct discover_boot_option *opt)
889 struct discover_device *dev = opt->device;
892 discover_server_notify_device_add(handler->server,
893 opt->device->device);
894 dev->notified = true;
895 discover_server_notify_boot_option_add(handler->server, opt->option);
898 static void process_boot_option_queue(struct device_handler *handler)
900 struct discover_boot_option *opt, *tmp;
902 list_for_each_entry_safe(&handler->unresolved_boot_options,
905 pb_debug("queue: attempting resolution for %s\n",
908 if (!boot_option_resolve(opt, handler))
911 pb_debug("\tresolved!\n");
913 list_remove(&opt->list);
914 list_add_tail(&opt->device->boot_options, &opt->list);
915 talloc_steal(opt->device, opt);
916 boot_option_finalise(handler, opt);
917 notify_boot_option(handler, opt);
921 struct discover_context *device_handler_discover_context_create(
922 struct device_handler *handler,
923 struct discover_device *device)
925 struct discover_context *ctx;
927 ctx = talloc_zero(handler, struct discover_context);
928 ctx->handler = handler;
929 ctx->device = device;
930 list_init(&ctx->boot_options);
935 void device_handler_add_device(struct device_handler *handler,
936 struct discover_device *device)
938 handler->n_devices++;
939 handler->devices = talloc_realloc(handler, handler->devices,
940 struct discover_device *, handler->n_devices);
941 handler->devices[handler->n_devices - 1] = device;
943 if (device->device->type == DEVICE_TYPE_NETWORK)
944 network_register_device(handler->network, device);
947 void device_handler_add_ramdisk(struct device_handler *handler,
950 struct ramdisk_device *dev;
956 for (i = 0; i < handler->n_ramdisks; i++)
957 if (!strcmp(handler->ramdisks[i]->path, path))
960 dev = talloc_zero(handler, struct ramdisk_device);
962 pb_log("Failed to allocate memory to track %s\n", path);
966 dev->path = talloc_strdup(handler, path);
968 handler->ramdisks = talloc_realloc(handler, handler->ramdisks,
969 struct ramdisk_device *,
970 handler->n_ramdisks + 1);
971 if (!handler->ramdisks) {
972 pb_log("Failed to reallocate memory"
973 "- ramdisk tracking inconsistent!\n");
977 handler->ramdisks[i] = dev;
978 i = handler->n_ramdisks++;
981 struct ramdisk_device *device_handler_get_ramdisk(
982 struct device_handler *handler)
988 /* Check if free ramdisk exists */
989 for (i = 0; i < handler->n_ramdisks; i++)
990 if (!handler->ramdisks[i]->snapshot &&
991 !handler->ramdisks[i]->origin &&
992 !handler->ramdisks[i]->base)
993 return handler->ramdisks[i];
995 /* Otherwise create a new one */
996 name = talloc_asprintf(handler, "/dev/ram%d",
997 handler->n_ramdisks);
999 pb_debug("Failed to allocate memory to name /dev/ram%d",
1000 handler->n_ramdisks);
1004 id = makedev(1, handler->n_ramdisks);
1005 if (mknod(name, S_IFBLK, id)) {
1006 if (errno == EEXIST) {
1007 /* We haven't yet received updates for existing
1008 * ramdisks - add and use this one */
1009 pb_debug("Using untracked ramdisk %s\n", name);
1011 pb_log("Failed to create new ramdisk %s: %s\n",
1012 name, strerror(errno));
1016 device_handler_add_ramdisk(handler, name);
1019 return handler->ramdisks[i];
1022 void device_handler_release_ramdisk(struct discover_device *device)
1024 struct ramdisk_device *ramdisk = device->ramdisk;
1026 talloc_free(ramdisk->snapshot);
1027 talloc_free(ramdisk->origin);
1028 talloc_free(ramdisk->base);
1030 ramdisk->snapshot = ramdisk->origin = ramdisk->base = NULL;
1031 ramdisk->sectors = 0;
1033 device->ramdisk = NULL;
1036 /* Start discovery on a hotplugged device. The device will be in our devices
1037 * array, but has only just been initialised by the hotplug source.
1039 int device_handler_discover(struct device_handler *handler,
1040 struct discover_device *dev)
1042 struct discover_context *ctx;
1045 device_handler_status_dev_info(handler, dev,
1047 * TRANSLATORS: this string will be passed the type of the
1048 * device (eg "disk" or "network"), which will be translated
1051 _("Processing new %s device"),
1052 device_type_display_name(dev->device->type));
1054 /* create our context */
1055 ctx = device_handler_discover_context_create(handler, dev);
1057 rc = mount_device(dev);
1061 /* add this device to our system info */
1062 system_info_register_blockdev(dev->device->id, dev->uuid,
1065 /* run the parsers. This will populate the ctx's boot_option list. */
1066 iterate_parsers(ctx);
1068 /* add discovered stuff to the handler */
1069 device_handler_discover_context_commit(handler, ctx);
1071 process_boot_option_queue(handler);
1073 talloc_unlink(handler, ctx);
1078 /* Incoming dhcp event */
1079 int device_handler_dhcp(struct device_handler *handler,
1080 struct discover_device *dev, struct event *event)
1082 struct discover_context *ctx;
1084 device_handler_status_dev_info(handler, dev,
1085 _("Processing DHCP lease response (ip: %s)"),
1086 event_get_param(event, "ip"));
1088 pending_network_jobs_start();
1090 /* create our context */
1091 ctx = device_handler_discover_context_create(handler, dev);
1092 talloc_steal(ctx, event);
1095 iterate_parsers(ctx);
1097 device_handler_discover_context_commit(handler, ctx);
1099 talloc_unlink(handler, ctx);
1104 static struct discover_boot_option *find_boot_option_by_id(
1105 struct device_handler *handler, const char *id)
1109 for (i = 0; i < handler->n_devices; i++) {
1110 struct discover_device *dev = handler->devices[i];
1111 struct discover_boot_option *opt;
1113 list_for_each_entry(&dev->boot_options, opt, list)
1114 if (!strcmp(opt->option->id, id))
1121 void device_handler_boot(struct device_handler *handler,
1122 struct boot_command *cmd)
1124 struct discover_boot_option *opt = NULL;
1126 if (cmd->option_id && strlen(cmd->option_id))
1127 opt = find_boot_option_by_id(handler, cmd->option_id);
1129 if (handler->pending_boot)
1130 boot_cancel(handler->pending_boot);
1132 platform_pre_boot();
1134 handler->pending_boot = boot(handler, opt, cmd, handler->dry_run,
1135 device_handler_boot_status_cb, handler);
1136 handler->pending_boot_is_default = false;
1139 void device_handler_cancel_default(struct device_handler *handler)
1141 if (handler->timeout_waiter)
1142 waiter_remove(handler->timeout_waiter);
1144 handler->timeout_waiter = NULL;
1145 handler->autoboot_enabled = false;
1147 /* we only send status if we had a default boot option queued */
1148 if (!handler->default_boot_option)
1151 pb_log("Cancelling default boot option\n");
1153 if (handler->pending_boot && handler->pending_boot_is_default) {
1154 boot_cancel(handler->pending_boot);
1155 handler->pending_boot = NULL;
1156 handler->pending_boot_is_default = false;
1159 handler->default_boot_option = NULL;
1161 device_handler_status_info(handler, _("Default boot cancelled"));
1164 void device_handler_update_config(struct device_handler *handler,
1165 struct config *config)
1169 rc = config_set(config);
1173 discover_server_notify_config(handler->server, config);
1174 device_handler_update_lang(config->lang);
1175 device_handler_reinit(handler);
1178 static char *device_from_addr(void *ctx, struct pb_url *url)
1180 char *ipaddr, *buf, *tok, *dev = NULL;
1181 const char *delim = " ";
1182 struct sockaddr_in *ip;
1183 struct sockaddr_in si;
1184 struct addrinfo *res;
1188 /* Note: IPv4 only */
1189 rc = inet_pton(AF_INET, url->host, &(si.sin_addr));
1193 /* need to turn hostname into a valid IP */
1194 rc = getaddrinfo(url->host, NULL, NULL, &res);
1196 pb_debug("%s: Invalid URL\n",__func__);
1199 ipaddr = talloc_array(ctx,char,INET_ADDRSTRLEN);
1200 ip = (struct sockaddr_in *) res->ai_addr;
1201 inet_ntop(AF_INET, &(ip->sin_addr), ipaddr, INET_ADDRSTRLEN);
1205 const char *argv[] = {
1207 "route", "show", "to", "match",
1212 p = process_create(ctx);
1214 p->path = pb_system_apps.ip;
1216 p->keep_stdout = true;
1218 rc = process_run_sync(p);
1220 if (rc || p->exit_status) {
1221 /* ip has complained for some reason; most likely
1222 * there is no route to the host - bail out */
1223 pb_debug("%s: `ip` returns non-zero exit status\n", __func__);
1224 pb_debug("ip buf: %s\n", p->stdout_buf);
1229 buf = p->stdout_buf;
1230 /* If a route is found, ip-route output will be of the form
1231 * "... dev DEVNAME ... " */
1232 tok = strtok(buf, delim);
1234 if (!strcmp(tok, "dev")) {
1235 tok = strtok(NULL, delim);
1236 dev = talloc_strdup(ctx, tok);
1239 tok = strtok(NULL, delim);
1244 pb_debug("%s: Found interface '%s'\n", __func__,dev);
1248 static void process_url_cb(struct load_url_result *result, void *data)
1250 struct device_handler *handler;
1251 struct discover_context *ctx;
1252 struct discover_device *dev;
1253 struct event *event = data;
1256 if (result->status != LOAD_OK) {
1257 pb_log("%s: Load failed for %s\n", __func__, result->url->full);
1264 handler = talloc_parent(event);
1268 event->device = device_from_addr(event, result->url);
1269 if (!event->device) {
1270 pb_log("Downloaded a file but can't find its interface - pretending it was local\n");
1271 event->device = talloc_asprintf(event, "local");
1274 mac = event_get_param(event, "mac");
1275 char *url = talloc_asprintf(event, "file://%s", result->local);
1276 event_set_param(event, "pxeconffile", url);
1278 dev = discover_device_create(handler, mac, event->device);
1279 ctx = device_handler_discover_context_create(handler, dev);
1280 talloc_steal(ctx, event);
1283 iterate_parsers(ctx);
1285 device_handler_discover_context_commit(handler, ctx);
1287 talloc_unlink(handler, ctx);
1290 void device_handler_process_url(struct device_handler *handler,
1291 const char *url, const char *mac, const char *ip)
1293 struct discover_context *ctx;
1294 struct discover_device *dev;
1295 bool allow_async = false;
1296 struct pb_url *pb_url;
1297 struct event *event;
1299 event = talloc_zero(handler, struct event);
1300 event->type = EVENT_TYPE_USER;
1301 event->action = EVENT_ACTION_URL;
1303 pb_url = pb_url_parse(event, url);
1304 if (!pb_url || (pb_url->scheme != pb_url_file && !pb_url->host)) {
1305 device_handler_status_err(handler, _("Invalid config URL!"));
1310 if (url[strlen(url) - 1] == '/') {
1311 event_set_param(event, "pxepathprefix", url);
1312 event_set_param(event, "mac", mac);
1313 event_set_param(event, "ip", ip);
1314 event->device = device_from_addr(event, pb_url);
1315 if (!event->device) {
1316 device_handler_status_err(handler,
1317 _("Unable to route to host %s"),
1323 event_set_param(event, "pxeconffile", url);
1327 if (pb_url->scheme == pb_url_file)
1328 event->device = talloc_asprintf(event, "local");
1329 else if (allow_async) {
1330 /* If file is remote load asynchronously before passing to
1331 * parser. This allows us to wait for network to be available */
1332 if (!load_url_async(handler, pb_url, process_url_cb, event,
1334 pb_log("Failed to load url %s\n", pb_url->full);
1335 device_handler_status_err(handler, _("Failed to load URL!"));
1341 /* If path is local we can parse straight away */
1343 dev = discover_device_create(handler, mac, event->device);
1344 if (pb_url->scheme == pb_url_file)
1345 dev->device->type = DEVICE_TYPE_ANY;
1346 ctx = device_handler_discover_context_create(handler, dev);
1347 talloc_steal(ctx, event);
1350 iterate_parsers(ctx);
1352 device_handler_discover_context_commit(handler, ctx);
1354 talloc_unlink(handler, ctx);
1357 #ifndef PETITBOOT_TEST
1360 * context_commit - Commit a temporary discovery context to the handler,
1361 * and notify the clients about any new options / devices
1363 void device_handler_discover_context_commit(struct device_handler *handler,
1364 struct discover_context *ctx)
1366 struct discover_device *dev = ctx->device;
1367 struct discover_boot_option *opt, *tmp;
1369 if (!device_lookup_by_uuid(handler, dev->uuid))
1370 device_handler_add_device(handler, dev);
1372 /* move boot options from the context to the device */
1373 list_for_each_entry_safe(&ctx->boot_options, opt, tmp, list) {
1374 list_remove(&opt->list);
1376 /* All boot options need at least a kernel image */
1377 if (!opt->boot_image || !opt->boot_image->url) {
1378 pb_log("boot option %s is missing boot image, ignoring\n",
1384 if (boot_option_resolve(opt, handler)) {
1385 pb_log("boot option %s is resolved, "
1386 "sending to clients\n",
1388 list_add_tail(&dev->boot_options, &opt->list);
1389 talloc_steal(dev, opt);
1390 boot_option_finalise(handler, opt);
1391 notify_boot_option(handler, opt);
1393 if (!opt->source->resolve_resource) {
1394 pb_log("parser %s gave us an unresolved "
1395 "resource (%s), but no way to "
1397 opt->source->name, opt->option->id);
1400 pb_log("boot option %s is unresolved, "
1401 "adding to queue\n",
1403 list_add(&handler->unresolved_boot_options,
1405 talloc_steal(handler, opt);
1411 static void device_handler_update_lang(const char *lang)
1413 const char *cur_lang;
1418 cur_lang = setlocale(LC_ALL, NULL);
1419 if (cur_lang && !strcmp(cur_lang, lang))
1422 setlocale(LC_ALL, lang);
1425 static int device_handler_init_sources(struct device_handler *handler)
1427 /* init our device sources: udev, network and user events */
1428 handler->network = network_init(handler, handler->waitset,
1430 if (!handler->network)
1433 handler->udev = udev_init(handler, handler->waitset);
1437 handler->user_event = user_event_init(handler, handler->waitset);
1438 if (!handler->user_event)
1444 static void device_handler_reinit_sources(struct device_handler *handler)
1446 /* if we haven't initialised sources previously (becuase we started in
1447 * safe mode), then init once here. */
1448 if (!(handler->udev || handler->network || handler->user_event)) {
1449 device_handler_init_sources(handler);
1453 system_info_reinit();
1455 network_shutdown(handler->network);
1456 handler->network = network_init(handler, handler->waitset,
1459 udev_reinit(handler->udev);
1462 static inline const char *get_device_path(struct discover_device *dev)
1464 return dev->ramdisk ? dev->ramdisk->snapshot : dev->device_path;
1467 static char *check_subvols(struct discover_device *dev)
1469 const char *fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1474 if (strncmp(fstype, "btrfs", strlen("btrfs")))
1475 return dev->mount_path;
1477 /* On btrfs a device's root may be under a subvolume path */
1478 path = join_paths(dev, dev->mount_path, "@");
1479 rc = stat(path, &sb);
1480 if (!rc && S_ISDIR(sb.st_mode)) {
1481 pb_debug("Using '%s' for btrfs root path\n", path);
1486 return dev->mount_path;
1489 static bool check_existing_mount(struct discover_device *dev)
1491 struct stat devstat, mntstat;
1492 const char *device_path;
1497 device_path = get_device_path(dev);
1499 rc = stat(device_path, &devstat);
1501 pb_debug("%s: stat failed: %s\n", __func__, strerror(errno));
1505 if (!S_ISBLK(devstat.st_mode)) {
1506 pb_debug("%s: %s isn't a block device?\n", __func__,
1511 fp = fopen("/proc/self/mounts", "r");
1514 mnt = getmntent(fp);
1518 if (!mnt->mnt_fsname || mnt->mnt_fsname[0] != '/')
1521 rc = stat(mnt->mnt_fsname, &mntstat);
1525 if (!S_ISBLK(mntstat.st_mode))
1528 if (mntstat.st_rdev == devstat.st_rdev) {
1529 dev->mount_path = talloc_strdup(dev, mnt->mnt_dir);
1530 dev->root_path = check_subvols(dev);
1531 dev->mounted_rw = !!hasmntopt(mnt, "rw");
1532 dev->mounted = true;
1533 dev->unmount = false;
1535 pb_debug("%s: %s is already mounted (r%c) at %s\n",
1536 __func__, dev->device_path,
1537 dev->mounted_rw ? 'w' : 'o',
1549 * Attempt to mount a filesystem safely, while handling certain filesytem-
1552 static int try_mount(const char *device_path, const char *mount_path,
1553 const char *fstype, unsigned long flags,
1556 const char *fs, *safe_opts;
1559 /* Mount ext3 as ext4 instead so 'norecovery' can be used */
1560 if (strncmp(fstype, "ext3", strlen("ext3")) == 0) {
1561 pb_debug("Mounting ext3 filesystem as ext4\n");
1566 if (strncmp(fs, "xfs", strlen("xfs")) == 0 ||
1567 strncmp(fs, "ext4", strlen("ext4")) == 0)
1568 safe_opts = "norecovery";
1573 /* If no snapshot is available don't attempt recovery */
1575 return mount(device_path, mount_path, fs, flags, safe_opts);
1577 rc = mount(device_path, mount_path, fs, flags, NULL);
1582 /* Mounting failed; some filesystems will fail to mount if a recovery
1583 * journal exists (eg. cross-endian XFS), so try again with norecovery
1584 * where that option is available.
1585 * If mounting read-write just return the error as norecovery is not a
1587 if ((flags & MS_RDONLY) != MS_RDONLY || !safe_opts)
1591 return mount(device_path, mount_path, fs, flags, safe_opts);
1594 static int mount_device(struct discover_device *dev)
1596 const char *fstype, *device_path;
1599 if (!dev->device_path)
1605 if (check_existing_mount(dev))
1608 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1612 dev->mount_path = join_paths(dev, mount_base(),
1615 if (pb_mkdir_recursive(dev->mount_path)) {
1616 pb_log("couldn't create mount directory %s: %s\n",
1617 dev->mount_path, strerror(errno));
1621 device_path = get_device_path(dev);
1623 pb_log("mounting device %s read-only\n", dev->device_path);
1624 rc = try_mount(device_path, dev->mount_path, fstype,
1625 MS_RDONLY | MS_SILENT, dev->ramdisk);
1628 dev->mounted = true;
1629 dev->mounted_rw = false;
1630 dev->unmount = true;
1631 dev->root_path = check_subvols(dev);
1635 pb_log("couldn't mount device %s: mount failed: %s\n",
1636 device_path, strerror(errno));
1638 /* If mount fails clean up any snapshot */
1639 devmapper_destroy_snapshot(dev);
1641 pb_rmdir_recursive(mount_base(), dev->mount_path);
1643 talloc_free(dev->mount_path);
1644 dev->mount_path = NULL;
1648 static int umount_device(struct discover_device *dev)
1650 const char *device_path;
1653 if (!dev->mounted || !dev->unmount)
1656 device_path = get_device_path(dev);
1658 pb_log("unmounting device %s\n", device_path);
1659 rc = umount(dev->mount_path);
1663 dev->mounted = false;
1664 devmapper_destroy_snapshot(dev);
1666 pb_rmdir_recursive(mount_base(), dev->mount_path);
1668 talloc_free(dev->mount_path);
1669 dev->mount_path = NULL;
1670 dev->root_path = NULL;
1675 int device_request_write(struct discover_device *dev, bool *release)
1677 const char *fstype, *device_path;
1678 const struct config *config;
1683 config = config_get();
1684 if (!config->allow_writes)
1690 if (dev->mounted_rw)
1693 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1695 device_path = get_device_path(dev);
1697 pb_log("remounting device %s read-write\n", device_path);
1699 rc = umount(dev->mount_path);
1701 pb_log("Failed to unmount %s: %s\n",
1702 dev->mount_path, strerror(errno));
1706 rc = try_mount(device_path, dev->mount_path, fstype,
1707 MS_SILENT, dev->ramdisk);
1711 dev->mounted_rw = true;
1716 pb_log("Unable to remount device %s read-write: %s\n",
1717 device_path, strerror(errno));
1718 rc = try_mount(device_path, dev->mount_path, fstype,
1719 MS_RDONLY | MS_SILENT, dev->ramdisk);
1721 pb_log("Unable to recover mount for %s: %s\n",
1722 device_path, strerror(errno));
1726 void device_release_write(struct discover_device *dev, bool release)
1728 const char *fstype, *device_path;
1733 device_path = get_device_path(dev);
1735 fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1737 pb_log("remounting device %s read-only\n", device_path);
1739 if (umount(dev->mount_path)) {
1740 pb_log("Failed to unmount %s\n", dev->mount_path);
1743 dev->mounted_rw = dev->mounted = false;
1746 devmapper_merge_snapshot(dev);
1747 /* device_path becomes stale after merge */
1748 device_path = get_device_path(dev);
1751 if (try_mount(device_path, dev->mount_path, fstype,
1752 MS_RDONLY | MS_SILENT, dev->ramdisk))
1753 pb_log("Failed to remount %s read-only: %s\n",
1754 device_path, strerror(errno));
1756 dev->mounted = true;
1759 void device_sync_snapshots(struct device_handler *handler, const char *device)
1761 struct discover_device *dev = NULL;
1765 /* Find matching device and sync */
1766 dev = device_lookup_by_name(handler, device);
1768 pb_log("%s: device name '%s' unrecognised\n",
1773 device_release_write(dev, true);
1775 pb_log("%s has no snapshot to merge, skipping\n",
1780 /* Otherwise sync all relevant devices */
1781 for (i = 0; i < handler->n_devices; i++) {
1782 dev = handler->devices[i];
1783 if (dev->device->type != DEVICE_TYPE_DISK &&
1784 dev->device->type != DEVICE_TYPE_USB)
1787 device_release_write(dev, true);
1789 pb_log("%s has no snapshot to merge, skipping\n",
1796 void device_handler_discover_context_commit(
1797 struct device_handler *handler __attribute__((unused)),
1798 struct discover_context *ctx __attribute__((unused)))
1800 pb_log("%s stubbed out for test cases\n", __func__);
1803 static void device_handler_update_lang(const char *lang __attribute__((unused)))
1807 static int device_handler_init_sources(
1808 struct device_handler *handler __attribute__((unused)))
1813 static void device_handler_reinit_sources(
1814 struct device_handler *handler __attribute__((unused)))
1818 static int umount_device(struct discover_device *dev __attribute__((unused)))
1823 static int __attribute__((unused)) mount_device(
1824 struct discover_device *dev __attribute__((unused)))
1829 int device_request_write(struct discover_device *dev __attribute__((unused)),
1836 void device_release_write(struct discover_device *dev __attribute__((unused)),
1837 bool release __attribute__((unused)))
1841 void device_sync_snapshots(
1842 struct device_handler *handler __attribute__((unused)),
1843 const char *device __attribute__((unused)))