983c50909ef7f5900f916bb5cf4040b7bdf6d994
[petitboot] / discover / device-handler.c
1 #include <assert.h>
2 #include <inttypes.h>
3 #include <stdlib.h>
4 #include <stdbool.h>
5 #include <unistd.h>
6 #include <string.h>
7 #include <errno.h>
8 #include <mntent.h>
9 #include <locale.h>
10 #include <sys/stat.h>
11 #include <sys/wait.h>
12 #include <sys/mount.h>
13
14 #include <talloc/talloc.h>
15 #include <list/list.h>
16 #include <log/log.h>
17 #include <types/types.h>
18 #include <system/system.h>
19 #include <process/process.h>
20 #include <url/url.h>
21 #include <i18n/i18n.h>
22 #include <pb-config/pb-config.h>
23
24 #include <sys/sysmacros.h>
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <netdb.h>
28 #include <arpa/inet.h>
29
30 #include "device-handler.h"
31 #include "discover-server.h"
32 #include "devmapper.h"
33 #include "user-event.h"
34 #include "platform.h"
35 #include "event.h"
36 #include "parser.h"
37 #include "resource.h"
38 #include "paths.h"
39 #include "sysinfo.h"
40 #include "boot.h"
41 #include "udev.h"
42 #include "network.h"
43 #include "ipmi.h"
44
45 enum default_priority {
46         DEFAULT_PRIORITY_TEMP_USER      = 1,
47         DEFAULT_PRIORITY_REMOTE         = 2,
48         DEFAULT_PRIORITY_LOCAL_FIRST    = 3,
49         DEFAULT_PRIORITY_LOCAL_LAST     = 0xfe,
50         DEFAULT_PRIORITY_DISABLED       = 0xff,
51 };
52
53 static int default_rescan_timeout = 5 * 60; /* seconds */
54
55 struct progress_info {
56         unsigned int                    percentage;
57         unsigned long                   size;           /* size in bytes */
58
59         const struct process_info       *procinfo;
60         struct list_item        list;
61 };
62
63 struct device_handler {
64         struct discover_server  *server;
65         int                     dry_run;
66
67         struct pb_udev          *udev;
68         struct network          *network;
69         struct user_event       *user_event;
70
71         struct discover_device  **devices;
72         unsigned int            n_devices;
73
74         struct ramdisk_device   **ramdisks;
75         unsigned int            n_ramdisks;
76
77         struct waitset          *waitset;
78         struct waiter           *timeout_waiter;
79         bool                    autoboot_enabled;
80         unsigned int            sec_to_boot;
81         struct autoboot_option  *temp_autoboot;
82
83         struct discover_boot_option *default_boot_option;
84         int                     default_boot_option_priority;
85
86         struct list             unresolved_boot_options;
87
88         struct boot_task        *pending_boot;
89         bool                    pending_boot_is_default;
90
91         struct list             progress;
92         unsigned int            n_progress;
93
94         struct plugin_option    **plugins;
95         unsigned int            n_plugins;
96         bool                    plugin_installing;
97 };
98
99 static int mount_device(struct discover_device *dev);
100 static int umount_device(struct discover_device *dev);
101
102 static int device_handler_init_sources(struct device_handler *handler);
103 static void device_handler_reinit_sources(struct device_handler *handler);
104
105 static void device_handler_update_lang(const char *lang);
106
107 void discover_context_add_boot_option(struct discover_context *ctx,
108                 struct discover_boot_option *boot_option)
109 {
110         boot_option->source = ctx->parser;
111         list_add_tail(&ctx->boot_options, &boot_option->list);
112         talloc_steal(ctx, boot_option);
113 }
114
115 /**
116  * device_handler_get_device_count - Get the count of current handler devices.
117  */
118
119 int device_handler_get_device_count(const struct device_handler *handler)
120 {
121         return handler->n_devices;
122 }
123
124 /**
125  * device_handler_get_device - Get a handler device by index.
126  */
127
128 const struct discover_device *device_handler_get_device(
129         const struct device_handler *handler, unsigned int index)
130 {
131         if (index >= handler->n_devices) {
132                 assert(0 && "bad index");
133                 return NULL;
134         }
135
136         return handler->devices[index];
137 }
138
139 /**
140  * device_handler_get_plugin_count - Get the count of current handler plugins.
141  */
142 int device_handler_get_plugin_count(const struct device_handler *handler)
143 {
144         return handler->n_plugins;
145 }
146
147 /**
148  * discover_handler_get_plugin - Get a handler plugin by index.
149  */
150 const struct plugin_option *device_handler_get_plugin(
151         const struct device_handler *handler, unsigned int index)
152 {
153         if (index >= handler->n_plugins) {
154                 assert(0 && "bad index");
155                 return NULL;
156         }
157
158         return handler->plugins[index];
159 }
160
161 struct network *device_handler_get_network(
162                 const struct device_handler *handler)
163 {
164         return handler->network;
165 }
166
167 struct discover_boot_option *discover_boot_option_create(
168                 struct discover_context *ctx,
169                 struct discover_device *device)
170 {
171         struct discover_boot_option *opt;
172
173         opt = talloc_zero(ctx, struct discover_boot_option);
174         opt->option = talloc_zero(opt, struct boot_option);
175         opt->device = device;
176
177         return opt;
178 }
179
180 static int device_match_uuid(struct discover_device *dev, const char *uuid)
181 {
182         return dev->uuid && !strcmp(dev->uuid, uuid);
183 }
184
185 static int device_match_label(struct discover_device *dev, const char *label)
186 {
187         return dev->label && !strcmp(dev->label, label);
188 }
189
190 static int device_match_id(struct discover_device *dev, const char *id)
191 {
192         return !strcmp(dev->device->id, id);
193 }
194
195 static int device_match_serial(struct discover_device *dev, const char *serial)
196 {
197         const char *val = discover_device_get_param(dev, "ID_SERIAL");
198         return val && !strcmp(val, serial);
199 }
200
201 static struct discover_device *device_lookup(
202                 struct device_handler *device_handler,
203                 int (match_fn)(struct discover_device *, const char *),
204                 const char *str)
205 {
206         struct discover_device *dev;
207         unsigned int i;
208
209         if (!str)
210                 return NULL;
211
212         for (i = 0; i < device_handler->n_devices; i++) {
213                 dev = device_handler->devices[i];
214
215                 if (match_fn(dev, str))
216                         return dev;
217         }
218
219         return NULL;
220 }
221
222 struct discover_device *device_lookup_by_name(struct device_handler *handler,
223                 const char *name)
224 {
225         if (!strncmp(name, "/dev/", strlen("/dev/")))
226                 name += strlen("/dev/");
227
228         return device_lookup_by_id(handler, name);
229 }
230
231 struct discover_device *device_lookup_by_uuid(
232                 struct device_handler *device_handler,
233                 const char *uuid)
234 {
235         return device_lookup(device_handler, device_match_uuid, uuid);
236 }
237
238 struct discover_device *device_lookup_by_label(
239                 struct device_handler *device_handler,
240                 const char *label)
241 {
242         return device_lookup(device_handler, device_match_label, label);
243 }
244
245 struct discover_device *device_lookup_by_id(
246                 struct device_handler *device_handler,
247                 const char *id)
248 {
249         return device_lookup(device_handler, device_match_id, id);
250 }
251
252 struct discover_device *device_lookup_by_serial(
253                 struct device_handler *device_handler,
254                 const char *serial)
255 {
256         return device_lookup(device_handler, device_match_serial, serial);
257 }
258
259 void device_handler_destroy(struct device_handler *handler)
260 {
261         talloc_free(handler);
262 }
263
264 static int destroy_device(void *arg)
265 {
266         struct discover_device *dev = arg;
267
268         umount_device(dev);
269
270         return 0;
271 }
272
273 struct discover_device *discover_device_create(struct device_handler *handler,
274                 const char *uuid, const char *id)
275 {
276         struct discover_device *dev;
277
278         if (uuid)
279                 dev = device_lookup_by_uuid(handler, uuid);
280         else
281                 dev = device_lookup_by_id(handler, id);
282
283         if (dev)
284                 return dev;
285
286         dev = talloc_zero(handler, struct discover_device);
287         dev->device = talloc_zero(dev, struct device);
288         dev->device->id = talloc_strdup(dev->device, id);
289         dev->uuid = talloc_strdup(dev, uuid);
290         list_init(&dev->params);
291         list_init(&dev->boot_options);
292
293         talloc_set_destructor(dev, destroy_device);
294
295         return dev;
296 }
297
298 struct discover_device_param {
299         char                    *name;
300         char                    *value;
301         struct list_item        list;
302 };
303
304 void discover_device_set_param(struct discover_device *device,
305                 const char *name, const char *value)
306 {
307         struct discover_device_param *param;
308         bool found = false;
309
310         list_for_each_entry(&device->params, param, list) {
311                 if (!strcmp(param->name, name)) {
312                         found = true;
313                         break;
314                 }
315         }
316
317         if (!found) {
318                 if (!value)
319                         return;
320                 param = talloc(device, struct discover_device_param);
321                 param->name = talloc_strdup(param, name);
322                 list_add(&device->params, &param->list);
323         } else {
324                 if (!value) {
325                         list_remove(&param->list);
326                         talloc_free(param);
327                         return;
328                 }
329                 talloc_free(param->value);
330         }
331
332         param->value = talloc_strdup(param, value);
333 }
334
335 const char *discover_device_get_param(struct discover_device *device,
336                 const char *name)
337 {
338         struct discover_device_param *param;
339
340         list_for_each_entry(&device->params, param, list) {
341                 if (!strcmp(param->name, name))
342                         return param->value;
343         }
344         return NULL;
345 }
346
347 static void set_env_variables(const struct config *config)
348 {
349         if (config->http_proxy)
350                 setenv("http_proxy", config->http_proxy, 1);
351         else
352                 unsetenv("http_proxy");
353
354         if (config->https_proxy)
355                 setenv("https_proxy", config->https_proxy, 1);
356         else
357                 unsetenv("https_proxy");
358
359         /* Reduce noise in the log from LVM listing open file descriptors */
360         setenv("LVM_SUPPRESS_FD_WARNINGS", "1", 1);
361 }
362
363 struct device_handler *device_handler_init(struct discover_server *server,
364                 struct waitset *waitset, int dry_run)
365 {
366         struct device_handler *handler;
367         int rc;
368
369         handler = talloc_zero(NULL, struct device_handler);
370         handler->server = server;
371         handler->waitset = waitset;
372         handler->dry_run = dry_run;
373         handler->autoboot_enabled = config_autoboot_active(config_get());
374
375         list_init(&handler->unresolved_boot_options);
376
377         list_init(&handler->progress);
378
379         /* set up our mount point base */
380         pb_mkdir_recursive(mount_base());
381
382         parser_init();
383
384         if (config_get()->safe_mode)
385                 return handler;
386
387         set_env_variables(config_get());
388
389         rc = device_handler_init_sources(handler);
390         if (rc) {
391                 talloc_free(handler);
392                 return NULL;
393         }
394
395         return handler;
396 }
397
398 void device_handler_reinit(struct device_handler *handler)
399 {
400         struct discover_boot_option *opt, *tmp;
401         struct ramdisk_device *ramdisk;
402         struct config *config;
403         unsigned int i;
404
405         device_handler_cancel_default(handler);
406         /* Cancel any pending non-default boot */
407         if (handler->pending_boot) {
408                 boot_cancel(handler->pending_boot);
409                 handler->pending_boot = NULL;
410                 handler->pending_boot_is_default = false;
411         }
412
413         /* Cancel any remaining async jobs */
414         process_stop_async_all();
415         pending_network_jobs_cancel();
416
417         /* free unresolved boot options */
418         list_for_each_entry_safe(&handler->unresolved_boot_options,
419                         opt, tmp, list)
420                 talloc_free(opt);
421         list_init(&handler->unresolved_boot_options);
422
423         /* drop all devices */
424         for (i = 0; i < handler->n_devices; i++) {
425                 struct discover_device *device = handler->devices[i];
426                 discover_server_notify_device_remove(handler->server,
427                                 device->device);
428                 ramdisk = device->ramdisk;
429                 if (device->requery_waiter)
430                         waiter_remove(device->requery_waiter);
431                 talloc_free(device);
432                 talloc_free(ramdisk);
433         }
434
435         talloc_free(handler->devices);
436         handler->devices = NULL;
437         handler->n_devices = 0;
438         talloc_free(handler->ramdisks);
439         handler->ramdisks = NULL;
440         handler->n_ramdisks = 0;
441
442         /* drop any known plugins */
443         for (i = 0; i < handler->n_plugins; i++)
444                 talloc_free(handler->plugins[i]);
445         talloc_free(handler->plugins);
446         handler->plugins = NULL;
447         handler->n_plugins = 0;
448
449         discover_server_notify_plugins_remove(handler->server);
450
451         set_env_variables(config_get());
452
453         /* If the safe mode warning was active disable it now */
454         if (config_get()->safe_mode) {
455                 config = config_copy(handler, config_get());
456                 config->safe_mode = false;
457                 config_set(config);
458                 discover_server_notify_config(handler->server, config);
459         }
460
461         /* Force rediscovery on SCSI devices */
462         process_run_simple(handler, pb_system_apps.scsi_rescan, NULL);
463
464         device_handler_reinit_sources(handler);
465 }
466
467 void device_handler_remove(struct device_handler *handler,
468                 struct discover_device *device)
469 {
470         struct discover_boot_option *opt, *tmp;
471         unsigned int i;
472
473         if (device->requery_waiter)
474                 waiter_remove(device->requery_waiter);
475
476         list_for_each_entry_safe(&device->boot_options, opt, tmp, list) {
477                 if (opt == handler->default_boot_option) {
478                         pb_log("Default option %s cancelled since device removed",
479                                         opt->option->name);
480                         device_handler_cancel_default(handler);
481                         break;
482                 }
483         }
484
485         for (i = 0; i < handler->n_devices; i++)
486                 if (handler->devices[i] == device)
487                         break;
488
489         if (i == handler->n_devices) {
490                 talloc_free(device);
491                 return;
492         }
493
494         /* Free any unresolved options, as they're currently allocated
495          * against the handler */
496         list_for_each_entry_safe(&handler->unresolved_boot_options,
497                         opt, tmp, list) {
498                 if (opt->device != device)
499                         continue;
500                 list_remove(&opt->list);
501                 talloc_free(opt);
502         }
503
504         /* if this is a network device, we have to unregister it from the
505          * network code */
506         if (device->device->type == DEVICE_TYPE_NETWORK)
507                 network_unregister_device(handler->network, device);
508
509         handler->n_devices--;
510         memmove(&handler->devices[i], &handler->devices[i + 1],
511                 (handler->n_devices - i) * sizeof(handler->devices[0]));
512         handler->devices = talloc_realloc(handler, handler->devices,
513                 struct discover_device *, handler->n_devices);
514
515         if (device->notified)
516                 discover_server_notify_device_remove(handler->server,
517                                                         device->device);
518
519         talloc_free(device);
520 }
521
522 void device_handler_status(struct device_handler *handler,
523                 struct status *status)
524 {
525         pb_debug("%s: %s\n", __func__, status->message);
526         discover_server_notify_boot_status(handler->server, status);
527 }
528
529 static void _device_handler_vstatus(struct device_handler *handler,
530                 enum status_type type, const char *fmt, va_list ap)
531 {
532         struct status status;
533
534         status.type = type;
535         status.message = talloc_vasprintf(handler, fmt, ap);
536         status.backlog = false;
537
538         device_handler_status(handler, &status);
539
540         talloc_free(status.message);
541 }
542
543 static void _device_handler_vdevstatus(struct device_handler *handler,
544                 struct discover_device *device, enum status_type type,
545                 const char *fmt, va_list ap)
546 {
547         char *msg;
548
549         msg = talloc_asprintf(handler, "[%s] %s",
550                         device ? device->device->id : "unknown", fmt);
551         _device_handler_vstatus(handler, type, msg, ap);
552         talloc_free(msg);
553 }
554
555 void device_handler_status_dev_info(struct device_handler *handler,
556                 struct discover_device *dev, const char *fmt, ...)
557 {
558         va_list ap;
559
560         va_start(ap, fmt);
561         _device_handler_vdevstatus(handler, dev, STATUS_INFO, fmt, ap);
562         va_end(ap);
563 }
564
565 void device_handler_status_dev_err(struct device_handler *handler,
566                 struct discover_device *dev, const char *fmt, ...)
567 {
568         va_list ap;
569
570         va_start(ap, fmt);
571         _device_handler_vdevstatus(handler, dev, STATUS_ERROR, fmt, ap);
572         va_end(ap);
573 }
574
575 void device_handler_status_info(struct device_handler *handler,
576                 const char *fmt, ...)
577 {
578         va_list ap;
579
580         va_start(ap, fmt);
581         _device_handler_vstatus(handler, STATUS_INFO, fmt, ap);
582         va_end(ap);
583 }
584
585 void device_handler_status_err(struct device_handler *handler,
586                 const char *fmt, ...)
587 {
588         va_list ap;
589
590         va_start(ap, fmt);
591         _device_handler_vstatus(handler, STATUS_ERROR, fmt, ap);
592         va_end(ap);
593 }
594
595 void device_handler_status_download(struct device_handler *handler,
596                 const struct process_info *procinfo,
597                 unsigned int percentage, unsigned int size, char suffix)
598 {
599         struct progress_info *p, *progress = NULL;
600         uint64_t current_converted, current = 0;
601         const char *units = " kMGTP";
602         unsigned long size_bytes;
603         char *update = NULL;
604         double total = 0;
605         unsigned int i;
606         int unit = 0;
607
608         list_for_each_entry(&handler->progress, p, list)
609                 if (p->procinfo == procinfo)
610                         progress = p;
611
612         if (!progress) {
613                 pb_log("Registering new progress struct\n");
614                 progress = talloc_zero(handler, struct progress_info);
615                 if (!progress) {
616                         pb_log("Failed to allocate room for progress struct\n");
617                         return;
618                 }
619                 progress->procinfo = procinfo;
620                 list_add(&handler->progress, &progress->list);
621                 handler->n_progress++;
622         }
623
624         size_bytes = size;
625         for (i = 0; i < strlen(units); i++) {
626                 if (units[i] == suffix)
627                         break;
628         }
629
630         if (i >= strlen(units)) {
631             pb_log("Couldn't recognise suffix '%c'\n", suffix);
632             size_bytes = 0;
633         } else {
634                 while (i--)
635                         size_bytes <<= 10;
636         }
637
638         progress->percentage = percentage;
639         progress->size = size_bytes;
640
641         /*
642          * Aggregate the info we have and update status. If a progress struct
643          * has zero for both percentage and size we assume progress information
644          * is unavailable and fall back to a generic progress message.
645          */
646         list_for_each_entry(&handler->progress, p, list) {
647                 uint64_t c;
648                 double t;
649                 if (!p->percentage || !p->size) {
650                         update = talloc_asprintf(handler,
651                                         _("%u downloads in progress..."),
652                                         handler->n_progress);
653                         current = total = 0;
654                         break;
655                 }
656
657                 c = p->size;
658                 t = (100 * c) / p->percentage;
659
660                 current += c;
661                 total += t;
662         }
663
664         if (total) {
665                 current_converted = current;
666                 while (current_converted >= 1000) {
667                         current_converted >>= 10;
668                         unit++;
669                 }
670                 update = talloc_asprintf(handler,
671                                 _("%u %s downloading: %.0f%% - %" PRIu64 "%cB"),
672                                 handler->n_progress,
673                                 ngettext("item", "items", handler->n_progress),
674                                 (current / total) * 100, current_converted,
675                                 units[unit]);
676         }
677
678         if (!update) {
679                 pb_log_fn("failed to allocate new status\n");
680         } else {
681                 device_handler_status_info(handler, "%s\n", update);
682                 talloc_free(update);
683         }
684 }
685
686 static void device_handler_plugin_scan_device(struct device_handler *handler,
687                 struct discover_device *dev)
688 {
689         int rc;
690
691         pb_debug("Scanning %s for plugin files\n", dev->device->id);
692
693         rc = process_run_simple(handler, pb_system_apps.pb_plugin,
694                                 "scan", dev->mount_path,
695                                 NULL);
696         if (rc)
697                 pb_log("Error from pb-plugin scan %s\n",
698                                 dev->mount_path);
699 }
700
701 void device_handler_status_download_remove(struct device_handler *handler,
702                 struct process_info *procinfo)
703 {
704         struct progress_info *p, *tmp;
705
706         list_for_each_entry_safe(&handler->progress, p, tmp, list)
707                 if (p->procinfo == procinfo) {
708                         list_remove(&p->list);
709                         talloc_free(p);
710                         handler->n_progress--;
711                 }
712 }
713
714 static void device_handler_boot_status_cb(void *arg, struct status *status)
715 {
716         struct device_handler *handler = arg;
717
718         /* boot had failed; update handler state to allow a new default if one
719          * is found later
720          */
721         if (status->type == STATUS_ERROR) {
722                 handler->pending_boot = NULL;
723                 handler->default_boot_option = NULL;
724         }
725
726         device_handler_status(handler, status);
727 }
728
729 static void countdown_status(struct device_handler *handler,
730                 struct discover_boot_option *opt, unsigned int sec)
731 {
732         struct status status;
733
734         status.type = STATUS_INFO;
735         status.message = talloc_asprintf(handler,
736                         _("Booting in %d sec: [%s] %s"), sec,
737                         opt->device->device->id, opt->option->name);
738         status.backlog = false;
739
740         device_handler_status(handler, &status);
741
742         talloc_free(status.message);
743 }
744
745 static int default_timeout(void *arg)
746 {
747         struct device_handler *handler = arg;
748         struct discover_boot_option *opt;
749
750         if (!handler->default_boot_option)
751                 return 0;
752
753         if (handler->pending_boot)
754                 return 0;
755
756         opt = handler->default_boot_option;
757
758         if (handler->sec_to_boot) {
759                 countdown_status(handler, opt, handler->sec_to_boot);
760                 handler->sec_to_boot--;
761                 handler->timeout_waiter = waiter_register_timeout(
762                                                 handler->waitset, 1000,
763                                                 default_timeout, handler);
764                 return 0;
765         }
766
767         handler->timeout_waiter = NULL;
768
769         pb_log("Timeout expired, booting default option %s\n", opt->option->id);
770
771         platform_pre_boot();
772
773         handler->pending_boot = boot(handler, handler->default_boot_option,
774                         NULL, handler->dry_run, device_handler_boot_status_cb,
775                         handler);
776         handler->pending_boot_is_default = true;
777         return 0;
778 }
779
780 struct {
781         enum ipmi_bootdev       ipmi_type;
782         enum device_type        device_type;
783 } device_type_map[] = {
784         { IPMI_BOOTDEV_NETWORK, DEVICE_TYPE_NETWORK },
785         { IPMI_BOOTDEV_DISK, DEVICE_TYPE_DISK },
786         { IPMI_BOOTDEV_DISK, DEVICE_TYPE_USB },
787         { IPMI_BOOTDEV_CDROM, DEVICE_TYPE_OPTICAL },
788 };
789
790 static bool ipmi_device_type_matches(enum ipmi_bootdev ipmi_type,
791                 enum device_type device_type)
792 {
793         unsigned int i;
794
795         for (i = 0; i < ARRAY_SIZE(device_type_map); i++) {
796                 if (device_type_map[i].device_type == device_type)
797                         return device_type_map[i].ipmi_type == ipmi_type;
798         }
799
800         return false;
801 }
802
803 static bool autoboot_option_matches(struct autoboot_option *opt,
804                 struct discover_device *dev)
805 {
806         if (opt->boot_type == BOOT_DEVICE_UUID)
807                 if (!strcmp(opt->uuid, dev->uuid))
808                         return true;
809
810         if (opt->boot_type == BOOT_DEVICE_TYPE)
811                 if (opt->type == dev->device->type ||
812                     opt->type == DEVICE_TYPE_ANY)
813                         return true;
814
815         return false;
816 }
817
818 static int autoboot_option_priority(const struct config *config,
819                                 struct discover_boot_option *opt)
820 {
821         struct autoboot_option *auto_opt;
822         unsigned int i;
823
824         for (i = 0; i < config->n_autoboot_opts; i++) {
825                 auto_opt = &config->autoboot_opts[i];
826                 if (autoboot_option_matches(auto_opt, opt->device))
827                         return DEFAULT_PRIORITY_LOCAL_FIRST + i;
828         }
829
830         return -1;
831 }
832
833 /*
834  * We have different priorities to resolve conflicts between boot options that
835  * report to be the default for their device. This function assigns a priority
836  * for these options.
837  */
838 static enum default_priority default_option_priority(
839                 struct device_handler *handler,
840                 struct discover_boot_option *opt)
841 {
842         const struct config *config;
843
844         /* Temporary user-provided autoboot options have highest priority */
845         if (handler->temp_autoboot) {
846                 if (autoboot_option_matches(handler->temp_autoboot,
847                                         opt->device))
848                         return DEFAULT_PRIORITY_TEMP_USER;
849
850                 pb_debug("handler: disabled default priority due to "
851                                 "temporary user override\n");
852                 return DEFAULT_PRIORITY_DISABLED;
853         }
854
855         config = config_get();
856
857         /* Next highest priority to IPMI-configured boot options. If we have an
858          * IPMI bootdev configuration set, then we don't allow any other
859          * defaults */
860         if (config->ipmi_bootdev) {
861                 bool ipmi_match = ipmi_device_type_matches(config->ipmi_bootdev,
862                                 opt->device->device->type);
863                 if (ipmi_match)
864                         return DEFAULT_PRIORITY_REMOTE;
865
866                 pb_debug("handler: disabled default priority due to "
867                                 "non-matching IPMI type %x\n",
868                                 config->ipmi_bootdev);
869                 return DEFAULT_PRIORITY_DISABLED;
870         }
871
872         /* Next, try to match the option against the user-defined autoboot
873          * options, either by device UUID or type. */
874         if (config->n_autoboot_opts) {
875                 int boot_match = autoboot_option_priority(config, opt);
876                 if (boot_match > 0)
877                         return boot_match;
878         } else {
879                 /* If there is no specific boot order, boot any device */
880                 return DEFAULT_PRIORITY_LOCAL_FIRST;
881         }
882
883         /* If the option didn't match any entry in the array, it is disabled */
884         pb_debug("handler: disabled default priority due to "
885                         "non-matching UUID or type\n");
886         return DEFAULT_PRIORITY_DISABLED;
887 }
888
889 static void set_default(struct device_handler *handler,
890                 struct discover_boot_option *opt)
891 {
892         enum default_priority cur_prio, new_prio;
893
894         if (!handler->autoboot_enabled)
895                 return;
896
897         pb_debug("handler: new default option: %s\n", opt->option->id);
898
899         new_prio = default_option_priority(handler, opt);
900
901         /* Anything outside our range prevents a default boot */
902         if (new_prio >= DEFAULT_PRIORITY_DISABLED)
903                 return;
904
905         pb_debug("handler: calculated priority %d\n", new_prio);
906
907         /* Resolve any conflicts: if we have a new default option, it only
908          * replaces the current if it has a higher priority. */
909         if (handler->default_boot_option) {
910
911                 cur_prio = handler->default_boot_option_priority;
912
913                 if (new_prio < cur_prio) {
914                         pb_log("handler: new prio %d beats "
915                                         "old prio %d for %s\n",
916                                         new_prio, cur_prio,
917                                         handler->default_boot_option
918                                                 ->option->id);
919                         handler->default_boot_option = opt;
920                         handler->default_boot_option_priority = new_prio;
921                         /* extend the timeout a little, so the user sees some
922                          * indication of the change */
923                         handler->sec_to_boot += 2;
924                 }
925
926                 return;
927         }
928
929         handler->sec_to_boot = config_get()->autoboot_timeout_sec;
930         handler->default_boot_option = opt;
931         handler->default_boot_option_priority = new_prio;
932
933         pb_log("handler: boot option %s set as default, timeout %u sec.\n",
934                opt->option->id, handler->sec_to_boot);
935
936         default_timeout(handler);
937 }
938
939 static char *autoboot_option_desc(void *ctx, const struct autoboot_option *opt)
940 {
941         const char *type, *val;
942
943         if (opt->boot_type == BOOT_DEVICE_TYPE) {
944                 type = _("device type");
945                 val = device_type_display_name(opt->type);
946         } else if (opt->boot_type == BOOT_DEVICE_UUID) {
947                 type = _("device UUID");
948                 val = opt->uuid;
949         } else {
950                 type = _("unknown specifier");
951                 val = NULL;
952         }
953
954         return talloc_asprintf(ctx, "%s = %s", type, val);
955 }
956
957 void device_handler_apply_temp_autoboot(struct device_handler *handler,
958                 struct autoboot_option *opt)
959 {
960         unsigned int i;
961         char *desc;
962
963         handler->temp_autoboot = talloc_steal(handler, opt);
964
965         desc = autoboot_option_desc(handler, opt);
966         device_handler_status_info(handler,
967                         _("Applying temporary autoboot override: %s"),
968                         desc);
969         talloc_free(desc);
970
971         if (!handler->autoboot_enabled)
972                 return;
973
974         if (!handler->default_boot_option)
975                 return;
976
977         if (autoboot_option_matches(opt, handler->default_boot_option->device))
978                 return;
979
980         /* cancel the default, and rescan available options */
981         device_handler_cancel_default(handler);
982
983         handler->autoboot_enabled = true;
984
985         for (i = 0; i < handler->n_devices; i++) {
986                 struct discover_device *dev = handler->devices[i];
987                 struct discover_boot_option *boot_opt;
988
989                 if (!autoboot_option_matches(opt, dev))
990                         continue;
991
992                 list_for_each_entry(&dev->boot_options, boot_opt, list) {
993                         if (boot_opt->option->is_default) {
994                                 set_default(handler, boot_opt);
995                                 break;
996                         }
997                 }
998         }
999 }
1000
1001 static bool resource_is_resolved(struct resource *res)
1002 {
1003         return !res || res->resolved;
1004 }
1005
1006 /* We only use this in an assert, which will disappear if we're compiling
1007  * with NDEBUG, so we need the 'used' attribute for these builds */
1008 static bool __attribute__((used)) boot_option_is_resolved(
1009                 struct discover_boot_option *opt)
1010 {
1011         return resource_is_resolved(opt->boot_image) &&
1012                 resource_is_resolved(opt->initrd) &&
1013                 resource_is_resolved(opt->dtb) &&
1014                 resource_is_resolved(opt->args_sig_file) &&
1015                 resource_is_resolved(opt->icon);
1016 }
1017
1018 static bool resource_resolve(struct resource *res, const char *name,
1019                 struct discover_boot_option *opt,
1020                 struct device_handler *handler)
1021 {
1022         struct parser *parser = opt->source;
1023
1024         if (resource_is_resolved(res))
1025                 return true;
1026
1027         pb_debug("Attempting to resolve resource %s->%s with parser %s\n",
1028                         opt->option->id, name, parser->name);
1029         parser->resolve_resource(handler, res);
1030
1031         return res->resolved;
1032 }
1033
1034 static bool boot_option_resolve(struct discover_boot_option *opt,
1035                 struct device_handler *handler)
1036 {
1037         return resource_resolve(opt->boot_image, "boot_image", opt, handler) &&
1038                 resource_resolve(opt->initrd, "initrd", opt, handler) &&
1039                 resource_resolve(opt->dtb, "dtb", opt, handler) &&
1040                 resource_resolve(opt->args_sig_file, "args_sig_file", opt,
1041                         handler) &&
1042                 resource_resolve(opt->icon, "icon", opt, handler);
1043 }
1044
1045 static void boot_option_finalise(struct device_handler *handler,
1046                 struct discover_boot_option *opt)
1047 {
1048         assert(boot_option_is_resolved(opt));
1049
1050         /* check that the parsers haven't set any of the final data */
1051         assert(!opt->option->boot_image_file);
1052         assert(!opt->option->initrd_file);
1053         assert(!opt->option->dtb_file);
1054         assert(!opt->option->icon_file);
1055         assert(!opt->option->device_id);
1056         assert(!opt->option->args_sig_file);
1057
1058         if (opt->boot_image)
1059                 opt->option->boot_image_file = opt->boot_image->url->full;
1060         if (opt->initrd)
1061                 opt->option->initrd_file = opt->initrd->url->full;
1062         if (opt->dtb)
1063                 opt->option->dtb_file = opt->dtb->url->full;
1064         if (opt->icon)
1065                 opt->option->icon_file = opt->icon->url->full;
1066         if (opt->args_sig_file)
1067                 opt->option->args_sig_file = opt->args_sig_file->url->full;
1068
1069         opt->option->device_id = opt->device->device->id;
1070
1071         if (opt->option->is_default)
1072                 set_default(handler, opt);
1073 }
1074
1075 static void notify_boot_option(struct device_handler *handler,
1076                 struct discover_boot_option *opt)
1077 {
1078         struct discover_device *dev = opt->device;
1079
1080         if (!dev->notified)
1081                 discover_server_notify_device_add(handler->server,
1082                                                   opt->device->device);
1083         dev->notified = true;
1084         discover_server_notify_boot_option_add(handler->server, opt->option);
1085 }
1086
1087 static void process_boot_option_queue(struct device_handler *handler)
1088 {
1089         struct discover_boot_option *opt, *tmp;
1090
1091         list_for_each_entry_safe(&handler->unresolved_boot_options,
1092                         opt, tmp, list) {
1093
1094                 pb_debug("queue: attempting resolution for %s\n",
1095                                 opt->option->id);
1096
1097                 if (!boot_option_resolve(opt, handler))
1098                         continue;
1099
1100                 pb_debug("\tresolved!\n");
1101
1102                 list_remove(&opt->list);
1103                 list_add_tail(&opt->device->boot_options, &opt->list);
1104                 talloc_steal(opt->device, opt);
1105                 boot_option_finalise(handler, opt);
1106                 notify_boot_option(handler, opt);
1107         }
1108 }
1109
1110 struct discover_context *device_handler_discover_context_create(
1111                 struct device_handler *handler,
1112                 struct discover_device *device)
1113 {
1114         struct discover_context *ctx;
1115
1116         ctx = talloc_zero(handler, struct discover_context);
1117         ctx->handler = handler;
1118         ctx->device = device;
1119         list_init(&ctx->boot_options);
1120
1121         return ctx;
1122 }
1123
1124 void device_handler_add_device(struct device_handler *handler,
1125                 struct discover_device *device)
1126 {
1127         handler->n_devices++;
1128         handler->devices = talloc_realloc(handler, handler->devices,
1129                                 struct discover_device *, handler->n_devices);
1130         handler->devices[handler->n_devices - 1] = device;
1131
1132         if (device->device->type == DEVICE_TYPE_NETWORK)
1133                 network_register_device(handler->network, device);
1134 }
1135
1136 void device_handler_add_ramdisk(struct device_handler *handler,
1137                 const char *path)
1138 {
1139         struct ramdisk_device *dev;
1140         unsigned int i;
1141
1142         if (!path)
1143                 return;
1144
1145         for (i = 0; i < handler->n_ramdisks; i++)
1146                 if (!strcmp(handler->ramdisks[i]->path, path))
1147                         return;
1148
1149         dev = talloc_zero(handler, struct ramdisk_device);
1150         if (!dev) {
1151                 pb_log("Failed to allocate memory to track %s\n", path);
1152                 return;
1153         }
1154
1155         dev->path = talloc_strdup(handler, path);
1156
1157         handler->ramdisks = talloc_realloc(handler, handler->ramdisks,
1158                                 struct ramdisk_device *,
1159                                 handler->n_ramdisks + 1);
1160         if (!handler->ramdisks) {
1161                 pb_log("Failed to reallocate memory"
1162                        "- ramdisk tracking inconsistent!\n");
1163                 return;
1164         }
1165
1166         handler->ramdisks[i] = dev;
1167         i = handler->n_ramdisks++;
1168 }
1169
1170 struct ramdisk_device *device_handler_get_ramdisk(
1171                 struct device_handler *handler)
1172 {
1173         unsigned int i;
1174         char *name;
1175         dev_t id;
1176
1177         /* Check if free ramdisk exists */
1178         for (i = 0; i < handler->n_ramdisks; i++)
1179                 if (!handler->ramdisks[i]->snapshot &&
1180                     !handler->ramdisks[i]->origin &&
1181                     !handler->ramdisks[i]->base)
1182                         return handler->ramdisks[i];
1183
1184         /* Otherwise create a new one */
1185         name = talloc_asprintf(handler, "/dev/ram%d",
1186                         handler->n_ramdisks);
1187         if (!name) {
1188                 pb_debug("Failed to allocate memory to name /dev/ram%d",
1189                         handler->n_ramdisks);
1190                 return NULL;
1191         }
1192
1193         id = makedev(1, handler->n_ramdisks);
1194         if (mknod(name, S_IFBLK, id)) {
1195                 if (errno == EEXIST) {
1196                         /* We haven't yet received updates for existing
1197                          * ramdisks - add and use this one */
1198                         pb_debug("Using untracked ramdisk %s\n", name);
1199                 } else {
1200                         pb_log("Failed to create new ramdisk %s: %s\n",
1201                                name, strerror(errno));
1202                         return NULL;
1203                 }
1204         }
1205         device_handler_add_ramdisk(handler, name);
1206         talloc_free(name);
1207
1208         return handler->ramdisks[i];
1209 }
1210
1211 void device_handler_release_ramdisk(struct discover_device *device)
1212 {
1213         struct ramdisk_device *ramdisk = device->ramdisk;
1214
1215         talloc_free(ramdisk->snapshot);
1216         talloc_free(ramdisk->origin);
1217         talloc_free(ramdisk->base);
1218
1219         ramdisk->snapshot = ramdisk->origin = ramdisk->base = NULL;
1220         ramdisk->sectors = 0;
1221
1222         device->ramdisk = NULL;
1223 }
1224
1225 /* Start discovery on a hotplugged device. The device will be in our devices
1226  * array, but has only just been initialised by the hotplug source.
1227  */
1228 int device_handler_discover(struct device_handler *handler,
1229                 struct discover_device *dev)
1230 {
1231         struct discover_context *ctx;
1232         int rc;
1233
1234         device_handler_status_dev_info(handler, dev,
1235                 /*
1236                  * TRANSLATORS: this string will be passed the type of the
1237                  * device (eg "disk" or "network"), which will be translated
1238                  * accordingly.
1239                  */
1240                 _("Processing new %s device"),
1241                 device_type_display_name(dev->device->type));
1242
1243         /* create our context */
1244         ctx = device_handler_discover_context_create(handler, dev);
1245
1246         rc = mount_device(dev);
1247         if (rc)
1248                 goto out;
1249
1250         /* add this device to our system info */
1251         system_info_register_blockdev(dev->device->id, dev->uuid,
1252                         dev->mount_path);
1253
1254         /* run the parsers. This will populate the ctx's boot_option list. */
1255         iterate_parsers(ctx);
1256
1257         /* add discovered stuff to the handler */
1258         device_handler_discover_context_commit(handler, ctx);
1259
1260         process_boot_option_queue(handler);
1261
1262         /* Check this device for pb-plugins */
1263         device_handler_plugin_scan_device(handler, dev);
1264 out:
1265         talloc_unlink(handler, ctx);
1266
1267         return 0;
1268 }
1269
1270 struct requery_data {
1271         struct device_handler   *handler;
1272         struct discover_device  *device;
1273 };
1274
1275 static int device_handler_requery_timeout_fn(void *data)
1276 {
1277         struct discover_boot_option *opt, *tmp;
1278         struct requery_data *rqd = data;
1279         struct device_handler *handler;
1280         struct discover_device *device;
1281         bool autoboot;
1282
1283         handler = rqd->handler;
1284         device = rqd->device;
1285
1286         talloc_free(rqd);
1287
1288         /* network_requery_device may re-add a timeout, so clear the device
1289          * waiter here, so we can potentially start a new one. */
1290         device->requery_waiter = NULL;
1291
1292         /* We keep the device around, but get rid of the parsed boot
1293          * options on that device. That involves delaring out the lists,
1294          * and potentially cancelling a default.
1295          */
1296         list_for_each_entry_safe(&handler->unresolved_boot_options,
1297                         opt, tmp, list) {
1298                 if (opt->device != device)
1299                         continue;
1300                 list_remove(&opt->list);
1301                 talloc_free(opt);
1302         }
1303
1304         /* Track whether autoboot was enabled, if we cancel a default option
1305          * it will be switched off.
1306          */
1307         autoboot = handler->autoboot_enabled;
1308
1309         list_for_each_entry_safe(&device->boot_options, opt, tmp, list) {
1310                 if (opt == handler->default_boot_option) {
1311                         pb_log("Default option %s cancelled since device is being requeried\n",
1312                                         opt->option->name);
1313                         device_handler_cancel_default(handler);
1314                 }
1315                 list_remove(&opt->list);
1316                 talloc_free(opt);
1317         }
1318
1319         handler->autoboot_enabled = autoboot;
1320
1321         discover_server_notify_device_remove(handler->server, device->device);
1322         device->notified = false;
1323
1324         network_requery_device(handler->network, device);
1325
1326         return 0;
1327 }
1328
1329 /* Schedule a requery in timeout (seconds).
1330  *
1331  * Special values of timeout:
1332  *   0: no requery
1333  *  -1: use default
1334  */
1335 void device_handler_start_requery_timeout( struct device_handler *handler,
1336                 struct discover_device *dev, int timeout)
1337 {
1338         struct requery_data *rqd;
1339
1340         if (dev->requery_waiter)
1341                 return;
1342
1343         if (timeout == -1)
1344                 timeout = default_rescan_timeout;
1345         else if (timeout == 0)
1346                 return;
1347
1348         rqd = talloc(dev, struct requery_data);
1349         rqd->handler = handler;
1350         rqd->device = dev;
1351
1352         pb_debug("starting requery timeout for device %s, in %d sec\n",
1353                         dev->device->id, timeout);
1354
1355         dev->requery_waiter = waiter_register_timeout(handler->waitset,
1356                         timeout * 1000, device_handler_requery_timeout_fn, rqd);
1357 }
1358
1359 static int event_requery_timeout(struct event *event)
1360 {
1361         int timeout = -1;
1362         unsigned long x;
1363         const char *str;
1364         char *endp;
1365
1366         if (!event)
1367                 return timeout;
1368
1369         str = event_get_param(event, "reboottime");
1370         if (!str)
1371                 return timeout;
1372
1373         x = strtoul(str, &endp, 0);
1374         if (endp != str)
1375                 timeout = x;
1376
1377         return timeout;
1378 }
1379
1380
1381 /* Incoming dhcp event */
1382 int device_handler_dhcp(struct device_handler *handler,
1383                 struct discover_device *dev, struct event *event)
1384 {
1385         struct discover_context *ctx;
1386         const char *ip;
1387
1388         if (event_get_param(event, "ipv6"))
1389                 ip = event_get_param(event, "ipv6");
1390         else
1391                 ip = event_get_param(event, "ip");
1392
1393         device_handler_status_dev_info(handler, dev,
1394                         _("Processing DHCP lease response (ip: %s)"), ip);
1395
1396         pending_network_jobs_start();
1397
1398         /* create our context */
1399         ctx = device_handler_discover_context_create(handler, dev);
1400         talloc_steal(ctx, event);
1401         ctx->event = event;
1402
1403         device_handler_start_requery_timeout(handler, dev,
1404                         event_requery_timeout(event));
1405
1406         iterate_parsers(ctx);
1407
1408         device_handler_discover_context_commit(handler, ctx);
1409
1410         talloc_unlink(handler, ctx);
1411
1412         return 0;
1413 }
1414
1415 struct discover_boot_option *device_handler_find_option_by_name(
1416                 struct device_handler *handler, const char *device,
1417                 const char *name)
1418 {
1419         size_t len = strlen(name);
1420         unsigned int i;
1421
1422         for (i = 0; i < handler->n_devices; i++) {
1423                 struct discover_device *dev = handler->devices[i];
1424                 struct discover_boot_option *opt;
1425
1426                 list_for_each_entry(&dev->boot_options, opt, list)
1427                         /* Match exactly, partial matches can be quite common */
1428                         if (strlen(opt->option->name) == len &&
1429                                         !strcmp(opt->option->name, name))
1430                                 if (!dev || !strcmp(opt->option->device_id, device))
1431                                         return opt;
1432         }
1433
1434         return NULL;
1435 }
1436
1437 static struct discover_boot_option *find_boot_option_by_id(
1438                 struct device_handler *handler, const char *id)
1439 {
1440         unsigned int i;
1441
1442         for (i = 0; i < handler->n_devices; i++) {
1443                 struct discover_device *dev = handler->devices[i];
1444                 struct discover_boot_option *opt;
1445
1446                 list_for_each_entry(&dev->boot_options, opt, list)
1447                         if (!strcmp(opt->option->id, id))
1448                                 return opt;
1449         }
1450
1451         return NULL;
1452 }
1453
1454 void device_handler_boot(struct device_handler *handler,
1455                 struct boot_command *cmd)
1456 {
1457         struct discover_boot_option *opt = NULL;
1458
1459         if (cmd->option_id && strlen(cmd->option_id))
1460                 opt = find_boot_option_by_id(handler, cmd->option_id);
1461
1462         if (handler->pending_boot)
1463                 boot_cancel(handler->pending_boot);
1464
1465         platform_pre_boot();
1466
1467         handler->pending_boot = boot(handler, opt, cmd, handler->dry_run,
1468                         device_handler_boot_status_cb, handler);
1469         handler->pending_boot_is_default = false;
1470 }
1471
1472 void device_handler_cancel_default(struct device_handler *handler)
1473 {
1474         if (handler->timeout_waiter)
1475                 waiter_remove(handler->timeout_waiter);
1476
1477         handler->timeout_waiter = NULL;
1478         handler->autoboot_enabled = false;
1479
1480         /* we only send status if we had a default boot option queued */
1481         if (!handler->default_boot_option)
1482                 return;
1483
1484         pb_log("Cancelling default boot option\n");
1485
1486         if (handler->pending_boot && handler->pending_boot_is_default) {
1487                 boot_cancel(handler->pending_boot);
1488                 handler->pending_boot = NULL;
1489                 handler->pending_boot_is_default = false;
1490         }
1491
1492         handler->default_boot_option = NULL;
1493
1494         device_handler_status_info(handler, _("Default boot cancelled"));
1495 }
1496
1497 void device_handler_update_config(struct device_handler *handler,
1498                 struct config *config)
1499 {
1500         int rc;
1501
1502         rc = config_set(config);
1503         if (rc)
1504                 return;
1505
1506         discover_server_notify_config(handler->server, config);
1507         device_handler_update_lang(config->lang);
1508         device_handler_reinit(handler);
1509 }
1510
1511 static char *device_from_addr(void *ctx, struct pb_url *url)
1512 {
1513         char *ipaddr, *buf, *tok, *dev = NULL;
1514         bool ipv6_route;
1515         const char *delim = " ";
1516         struct sockaddr_in *ipv4;
1517         struct sockaddr_in6 *ipv6;
1518         struct addrinfo *res;
1519         struct process *p;
1520         int rc;
1521
1522         /* Confirm url->host is either a valid hostname, or a
1523          * valid IPv4 or IPv6 address */
1524         rc = getaddrinfo(url->host, NULL, NULL, &res);
1525         if (rc) {
1526                 pb_debug("%s: Invalid URL\n",__func__);
1527                 return NULL;
1528         }
1529
1530         switch (res->ai_family) {
1531         case AF_INET:   /* ipv4 */
1532                 ipaddr = talloc_array(ctx,char,INET_ADDRSTRLEN);
1533                 ipv4 = (struct sockaddr_in *) res->ai_addr;
1534                 inet_ntop(AF_INET, &(ipv4->sin_addr), ipaddr, INET_ADDRSTRLEN);
1535                 ipv6_route = false;
1536                 break;
1537         case AF_INET6:  /* ipv6 */
1538                 ipaddr = talloc_array(ctx,char,INET6_ADDRSTRLEN);
1539                 ipv6 = (struct sockaddr_in6 *) res->ai_addr;
1540                 inet_ntop(AF_INET6, &(ipv6->sin6_addr), ipaddr, INET6_ADDRSTRLEN);
1541                 ipv6_route = true;
1542                 break;
1543         default:        /* error */
1544                 freeaddrinfo(res);
1545                 return NULL;
1546         }
1547         freeaddrinfo(res);
1548
1549         const char *argv[] = {
1550                 pb_system_apps.ip,
1551                 ipv6_route ? "-6" : "-4",
1552                 "route", "show", "to", "match",
1553                 ipaddr,
1554                 NULL
1555         };
1556
1557         p = process_create(ctx);
1558
1559         p->path = pb_system_apps.ip;
1560         p->argv = argv;
1561         p->keep_stdout = true;
1562
1563         rc = process_run_sync(p);
1564
1565         if (rc || p->exit_status) {
1566                 /* ip has complained for some reason; most likely
1567                  * there is no route to the host - bail out */
1568                 pb_debug("%s: `ip` returns non-zero exit status\n", __func__);
1569                 pb_debug("ip buf: %s\n", p->stdout_buf);
1570                 process_release(p);
1571                 return NULL;
1572         }
1573
1574         buf = p->stdout_buf;
1575         /* If a route is found, ip-route output will be of the form
1576          * "... dev DEVNAME ... " */
1577         tok = strtok(buf, delim);
1578         while (tok) {
1579                 if (!strcmp(tok, "dev")) {
1580                         tok = strtok(NULL, delim);
1581                         dev = talloc_strdup(ctx, tok);
1582                         break;
1583                 }
1584                 tok = strtok(NULL, delim);
1585         }
1586
1587         process_release(p);
1588         if (dev)
1589                 pb_debug("%s: Found interface '%s'\n", __func__,dev);
1590         return dev;
1591 }
1592
1593 static void process_url_cb(struct load_url_result *result, void *data)
1594 {
1595         struct device_handler *handler;
1596         struct discover_context *ctx;
1597         struct discover_device *dev;
1598         struct event *event = data;
1599         const char *mac;
1600
1601         if (result->status != LOAD_OK) {
1602                 pb_log_fn("Load failed for %s\n", result->url->full);
1603                 return;
1604         }
1605
1606         if (!event)
1607                 return;
1608
1609         handler = talloc_parent(event);
1610         if (!handler)
1611                 return;
1612
1613         event->device = device_from_addr(event, result->url);
1614         if (!event->device) {
1615                 pb_log("Downloaded a file but can't find its interface - pretending it was local\n");
1616                 event->device = talloc_asprintf(event, "local");
1617         }
1618
1619         mac = event_get_param(event, "mac");
1620         char *url = talloc_asprintf(event, "file://%s", result->local);
1621         event_set_param(event, "pxeconffile-local", url);
1622
1623         dev = discover_device_create(handler, mac, event->device);
1624         ctx = device_handler_discover_context_create(handler, dev);
1625         talloc_steal(ctx, event);
1626         ctx->event = event;
1627
1628         iterate_parsers(ctx);
1629
1630         device_handler_discover_context_commit(handler, ctx);
1631
1632         talloc_unlink(handler, ctx);
1633 }
1634
1635 void device_handler_process_url(struct device_handler *handler,
1636                 const char *url, const char *mac, const char *ip)
1637 {
1638         struct discover_context *ctx;
1639         struct discover_device *dev;
1640         bool allow_async = false;
1641         struct pb_url *pb_url;
1642         struct event *event;
1643
1644         event = talloc_zero(handler, struct event);
1645         event->type = EVENT_TYPE_USER;
1646         event->action = EVENT_ACTION_URL;
1647
1648         pb_url = pb_url_parse(event, url);
1649         if (!pb_url || (pb_url->scheme != pb_url_file && !pb_url->host)) {
1650                 device_handler_status_err(handler, _("Invalid config URL!"));
1651                 talloc_free(event);
1652                 return;
1653         }
1654
1655         if (url[strlen(url) - 1] == '/') {
1656                 event_set_param(event, "pxepathprefix", url);
1657                 event_set_param(event, "mac", mac);
1658                 event_set_param(event, "ip", ip);
1659                 event->device = device_from_addr(event, pb_url);
1660                 if (!event->device) {
1661                         device_handler_status_err(handler,
1662                                         _("Unable to route to host %s"),
1663                                         pb_url->host);
1664                         talloc_free(event);
1665                         return;
1666                 }
1667         } else {
1668                 event_set_param(event, "pxeconffile", url);
1669                 allow_async = true;
1670         }
1671
1672         if (pb_url->scheme == pb_url_file)
1673                 event->device = talloc_asprintf(event, "local");
1674         else if (allow_async) {
1675                 /* If file is remote load asynchronously before passing to
1676                  * parser. This allows us to wait for network to be available */
1677                 if (!load_url_async(handler, pb_url, process_url_cb, event,
1678                                         NULL, handler)) {
1679                         pb_log("Failed to load url %s\n", pb_url->full);
1680                         device_handler_status_err(handler, _("Failed to load URL!"));
1681                         talloc_free(event);
1682                 }
1683                 return;
1684         }
1685
1686         /* If path is local we can parse straight away */
1687
1688         dev = discover_device_create(handler, mac, event->device);
1689         if (pb_url->scheme == pb_url_file)
1690                 dev->device->type = DEVICE_TYPE_ANY;
1691         ctx = device_handler_discover_context_create(handler, dev);
1692         talloc_steal(ctx, event);
1693         ctx->event = event;
1694
1695         iterate_parsers(ctx);
1696
1697         device_handler_discover_context_commit(handler, ctx);
1698
1699         talloc_unlink(handler, ctx);
1700 }
1701
1702 static void plugin_install_cb(struct process *process)
1703 {
1704         struct device_handler *handler = process->data;
1705
1706         if (!handler) {
1707                 pb_log_fn("Missing data!\n");
1708                 return;
1709         }
1710
1711         handler->plugin_installing = false;
1712         if (process->exit_status) {
1713                 device_handler_status_err(handler, "Plugin failed to install!");
1714                 pb_log("Failed to install plugin:\n%s\n", process->stdout_buf);
1715         }
1716 }
1717
1718 void device_handler_install_plugin(struct device_handler *handler,
1719                 const char *plugin_file)
1720 {
1721         struct process *p;
1722         int result;
1723
1724         if (handler->plugin_installing) {
1725                 pb_log("Plugin install cancelled - install already running");
1726                 return;
1727         }
1728
1729         p = process_create(handler);
1730         if (!p) {
1731                 pb_log("install_plugin: Failed to create process\n");
1732                 return;
1733         }
1734
1735         const char *argv[] = {
1736                 pb_system_apps.pb_plugin,
1737                 "install",
1738                 "auto",
1739                 plugin_file,
1740                 NULL
1741         };
1742
1743         p->path = pb_system_apps.pb_plugin;
1744         p->argv = argv;
1745         p->exit_cb = plugin_install_cb;
1746         p->data = handler;
1747         p->keep_stdout = true;
1748
1749         result = process_run_async(p);
1750
1751         if (result)
1752                 device_handler_status_err(handler, "Could not install plugin");
1753         else
1754                 handler->plugin_installing = true;
1755 }
1756
1757 #ifndef PETITBOOT_TEST
1758
1759 /**
1760  * context_commit - Commit a temporary discovery context to the handler,
1761  * and notify the clients about any new options / devices
1762  */
1763 void device_handler_discover_context_commit(struct device_handler *handler,
1764                 struct discover_context *ctx)
1765 {
1766         struct discover_device *dev = ctx->device;
1767         struct discover_boot_option *opt, *tmp;
1768
1769         if (!device_lookup_by_uuid(handler, dev->uuid))
1770                 device_handler_add_device(handler, dev);
1771
1772         /* move boot options from the context to the device */
1773         list_for_each_entry_safe(&ctx->boot_options, opt, tmp, list) {
1774                 list_remove(&opt->list);
1775
1776                 /* All boot options need at least a kernel image */
1777                 if (!opt->boot_image || !opt->boot_image->url) {
1778                         pb_log("boot option %s is missing boot image, ignoring\n",
1779                                 opt->option->id);
1780                         talloc_free(opt);
1781                         continue;
1782                 }
1783
1784                 if (boot_option_resolve(opt, handler)) {
1785                         pb_log("boot option %s is resolved, "
1786                                         "sending to clients\n",
1787                                         opt->option->id);
1788                         list_add_tail(&dev->boot_options, &opt->list);
1789                         talloc_steal(dev, opt);
1790                         boot_option_finalise(handler, opt);
1791                         notify_boot_option(handler, opt);
1792                 } else {
1793                         if (!opt->source->resolve_resource) {
1794                                 pb_log("parser %s gave us an unresolved "
1795                                         "resource (%s), but no way to "
1796                                         "resolve it\n",
1797                                         opt->source->name, opt->option->id);
1798                                 talloc_free(opt);
1799                         } else {
1800                                 pb_log("boot option %s is unresolved, "
1801                                                 "adding to queue\n",
1802                                                 opt->option->id);
1803                                 list_add(&handler->unresolved_boot_options,
1804                                                 &opt->list);
1805                                 talloc_steal(handler, opt);
1806                         }
1807                 }
1808         }
1809 }
1810
1811 void device_handler_add_plugin_option(struct device_handler *handler,
1812                 struct plugin_option *opt)
1813 {
1814         struct plugin_option *tmp;
1815         unsigned int i;
1816
1817         for (i = 0; i < handler->n_plugins; i++) {
1818                 tmp = handler->plugins[i];
1819                 /* If both id and version match, ignore */
1820                 if (strncmp(opt->id, tmp->id, strlen(opt->id)) == 0 &&
1821                                 strcmp(opt->version, tmp->version) == 0) {
1822                         pb_log("discover: Plugin '%s' already exists, ignoring\n",
1823                                         opt->id);
1824                         return;
1825                 }
1826         }
1827
1828         handler->plugins = talloc_realloc(handler, handler->plugins,
1829                         struct plugin_option *, handler->n_plugins + 1);
1830         if (!handler->plugins) {
1831                 pb_log("Failed to allocate memory for new plugin\n");
1832                 handler->n_plugins = 0;
1833                 return;
1834         }
1835
1836         handler->plugins[handler->n_plugins++] = opt;
1837         discover_server_notify_plugin_option_add(handler->server, opt);
1838 }
1839
1840 static void device_handler_update_lang(const char *lang)
1841 {
1842         const char *cur_lang;
1843
1844         if (!lang)
1845                 return;
1846
1847         cur_lang = setlocale(LC_ALL, NULL);
1848         if (cur_lang && !strcmp(cur_lang, lang))
1849                 return;
1850
1851         setlocale(LC_ALL, lang);
1852 }
1853
1854 static int device_handler_init_sources(struct device_handler *handler)
1855 {
1856         /* init our device sources: udev, network and user events */
1857         handler->user_event = user_event_init(handler, handler->waitset);
1858         if (!handler->user_event)
1859                 return -1;
1860
1861         handler->network = network_init(handler, handler->waitset,
1862                         handler->dry_run);
1863         if (!handler->network)
1864                 return -1;
1865
1866         handler->udev = udev_init(handler, handler->waitset);
1867         if (!handler->udev)
1868                 return -1;
1869
1870         return 0;
1871 }
1872
1873 static void device_handler_reinit_sources(struct device_handler *handler)
1874 {
1875         /* if we haven't initialised sources previously (becuase we started in
1876          * safe mode), then init once here. */
1877         if (!(handler->udev || handler->network || handler->user_event)) {
1878                 device_handler_init_sources(handler);
1879                 return;
1880         }
1881
1882         system_info_reinit();
1883
1884         network_shutdown(handler->network);
1885         handler->network = network_init(handler, handler->waitset,
1886                         handler->dry_run);
1887
1888         udev_reinit(handler->udev);
1889 }
1890
1891 static inline const char *get_device_path(struct discover_device *dev)
1892 {
1893         return dev->ramdisk ? dev->ramdisk->snapshot : dev->device_path;
1894 }
1895
1896 static char *check_subvols(struct discover_device *dev)
1897 {
1898         const char *fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1899         struct stat sb;
1900         char *path;
1901         int rc;
1902
1903         if (strncmp(fstype, "btrfs", strlen("btrfs")))
1904                 return dev->mount_path;
1905
1906         /* On btrfs a device's root may be under a subvolume path */
1907         path = join_paths(dev, dev->mount_path, "@");
1908         rc = stat(path, &sb);
1909         if (!rc && S_ISDIR(sb.st_mode)) {
1910                 pb_debug("Using '%s' for btrfs root path\n", path);
1911                 return path;
1912         }
1913
1914         talloc_free(path);
1915         return dev->mount_path;
1916 }
1917
1918 static bool check_existing_mount(struct discover_device *dev)
1919 {
1920         struct stat devstat, mntstat;
1921         const char *device_path;
1922         struct mntent *mnt;
1923         FILE *fp;
1924         int rc;
1925
1926         device_path = get_device_path(dev);
1927
1928         rc = stat(device_path, &devstat);
1929         if (rc) {
1930                 pb_debug("%s: stat failed: %s\n", __func__, strerror(errno));
1931                 return false;
1932         }
1933
1934         if (!S_ISBLK(devstat.st_mode)) {
1935                 pb_debug("%s: %s isn't a block device?\n", __func__,
1936                                 dev->device_path);
1937                 return false;
1938         }
1939
1940         fp = fopen("/proc/self/mounts", "r");
1941
1942         for (;;) {
1943                 mnt = getmntent(fp);
1944                 if (!mnt)
1945                         break;
1946
1947                 if (!mnt->mnt_fsname || mnt->mnt_fsname[0] != '/')
1948                         continue;
1949
1950                 rc = stat(mnt->mnt_fsname, &mntstat);
1951                 if (rc)
1952                         continue;
1953
1954                 if (!S_ISBLK(mntstat.st_mode))
1955                         continue;
1956
1957                 if (mntstat.st_rdev == devstat.st_rdev) {
1958                         dev->mount_path = talloc_strdup(dev, mnt->mnt_dir);
1959                         dev->root_path = check_subvols(dev);
1960                         dev->mounted_rw = !!hasmntopt(mnt, "rw");
1961                         dev->mounted = true;
1962                         dev->unmount = false;
1963
1964                         pb_debug("%s: %s is already mounted (r%c) at %s\n",
1965                                         __func__, dev->device_path,
1966                                         dev->mounted_rw ? 'w' : 'o',
1967                                         mnt->mnt_dir);
1968                         break;
1969                 }
1970         }
1971
1972         fclose(fp);
1973
1974         return mnt != NULL;
1975 }
1976
1977 /*
1978  * Attempt to mount a filesystem safely, while handling certain filesytem-
1979  * specific options
1980  */
1981 static int try_mount(const char *device_path, const char *mount_path,
1982                              const char *fstype, unsigned long flags,
1983                              bool have_snapshot)
1984 {
1985         const char *fs, *safe_opts;
1986         int rc;
1987
1988         /* Mount ext3 as ext4 instead so 'norecovery' can be used */
1989         if (strncmp(fstype, "ext3", strlen("ext3")) == 0) {
1990                 pb_debug("Mounting ext3 filesystem as ext4\n");
1991                 fs = "ext4";
1992         } else
1993                 fs = fstype;
1994
1995         if (strncmp(fs, "xfs", strlen("xfs")) == 0 ||
1996             strncmp(fs, "ext4", strlen("ext4")) == 0)
1997                 safe_opts = "norecovery";
1998         else
1999                 safe_opts = NULL;
2000
2001         errno = 0;
2002         /* If no snapshot is available don't attempt recovery */
2003         if (!have_snapshot)
2004                 return mount(device_path, mount_path, fs, flags, safe_opts);
2005
2006         rc = mount(device_path, mount_path, fs, flags, NULL);
2007
2008         if (!rc)
2009                 return rc;
2010
2011         /* Mounting failed; some filesystems will fail to mount if a recovery
2012          * journal exists (eg. cross-endian XFS), so try again with norecovery
2013          * where that option is available.
2014          * If mounting read-write just return the error as norecovery is not a
2015          * valid option */
2016         if ((flags & MS_RDONLY) != MS_RDONLY || !safe_opts)
2017                 return rc;
2018
2019         errno = 0;
2020         return mount(device_path, mount_path, fs, flags, safe_opts);
2021 }
2022
2023 static int mount_device(struct discover_device *dev)
2024 {
2025         const char *fstype, *device_path;
2026         int rc;
2027
2028         if (!dev->device_path)
2029                 return -1;
2030
2031         if (dev->mounted)
2032                 return 0;
2033
2034         if (check_existing_mount(dev))
2035                 return 0;
2036
2037         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
2038         if (!fstype)
2039                 return 0;
2040
2041         dev->mount_path = join_paths(dev, mount_base(),
2042                                         dev->device_path);
2043
2044         if (pb_mkdir_recursive(dev->mount_path)) {
2045                 pb_log("couldn't create mount directory %s: %s\n",
2046                                 dev->mount_path, strerror(errno));
2047                 goto err_free;
2048         }
2049
2050         device_path = get_device_path(dev);
2051
2052         pb_log("mounting device %s read-only\n", dev->device_path);
2053         rc = try_mount(device_path, dev->mount_path, fstype,
2054                        MS_RDONLY | MS_SILENT, dev->ramdisk);
2055
2056         /* If mount fails clean up any snapshot and try again */
2057         if (rc && dev->ramdisk) {
2058                 pb_log("couldn't mount snapshot for %s: mount failed: %s\n",
2059                                 device_path, strerror(errno));
2060                 pb_log("falling back to actual device\n");
2061
2062                 devmapper_destroy_snapshot(dev);
2063
2064                 device_path = get_device_path(dev);
2065                 pb_log("mounting device %s read-only\n", dev->device_path);
2066                 rc = try_mount(device_path, dev->mount_path, fstype,
2067                                MS_RDONLY | MS_SILENT, dev->ramdisk);
2068         }
2069
2070         if (!rc) {
2071                 dev->mounted = true;
2072                 dev->mounted_rw = false;
2073                 dev->unmount = true;
2074                 dev->root_path = check_subvols(dev);
2075                 return 0;
2076         }
2077
2078         pb_log("couldn't mount device %s: mount failed: %s\n",
2079                         device_path, strerror(errno));
2080
2081         pb_rmdir_recursive(mount_base(), dev->mount_path);
2082 err_free:
2083         talloc_free(dev->mount_path);
2084         dev->mount_path = NULL;
2085         return -1;
2086 }
2087
2088 static int umount_device(struct discover_device *dev)
2089 {
2090         const char *device_path;
2091         int rc;
2092
2093         if (!dev->mounted || !dev->unmount)
2094                 return 0;
2095
2096         device_path = get_device_path(dev);
2097
2098         pb_log("unmounting device %s\n", device_path);
2099         rc = umount(dev->mount_path);
2100         if (rc)
2101                 return -1;
2102
2103         dev->mounted = false;
2104         devmapper_destroy_snapshot(dev);
2105
2106         pb_rmdir_recursive(mount_base(), dev->mount_path);
2107
2108         talloc_free(dev->mount_path);
2109         dev->mount_path = NULL;
2110         dev->root_path = NULL;
2111
2112         return 0;
2113 }
2114
2115 int device_request_write(struct discover_device *dev, bool *release)
2116 {
2117         const char *fstype, *device_path;
2118         const struct config *config;
2119         int rc;
2120
2121         *release = false;
2122
2123         config = config_get();
2124         if (!config->allow_writes)
2125                 return -1;
2126
2127         if (!dev->mounted)
2128                 return -1;
2129
2130         if (dev->mounted_rw)
2131                 return 0;
2132
2133         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
2134
2135         device_path = get_device_path(dev);
2136
2137         pb_log("remounting device %s read-write\n", device_path);
2138
2139         rc = umount(dev->mount_path);
2140         if (rc) {
2141                 pb_log("Failed to unmount %s: %s\n",
2142                        dev->mount_path, strerror(errno));
2143                 return -1;
2144         }
2145
2146         rc = try_mount(device_path, dev->mount_path, fstype,
2147                        MS_SILENT, dev->ramdisk);
2148         if (rc)
2149                 goto mount_ro;
2150
2151         dev->mounted_rw = true;
2152         *release = true;
2153         return 0;
2154
2155 mount_ro:
2156         pb_log("Unable to remount device %s read-write: %s\n",
2157                device_path, strerror(errno));
2158         rc = try_mount(device_path, dev->mount_path, fstype,
2159                        MS_RDONLY | MS_SILENT, dev->ramdisk);
2160         if (rc)
2161                 pb_log("Unable to recover mount for %s: %s\n",
2162                        device_path, strerror(errno));
2163         return -1;
2164 }
2165
2166 void device_release_write(struct discover_device *dev, bool release)
2167 {
2168         const char *fstype, *device_path;
2169
2170         if (!release)
2171                 return;
2172
2173         device_path = get_device_path(dev);
2174
2175         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
2176
2177         pb_log("remounting device %s read-only\n", device_path);
2178
2179         if (umount(dev->mount_path)) {
2180                 pb_log("Failed to unmount %s\n", dev->mount_path);
2181                 return;
2182         }
2183         dev->mounted_rw = dev->mounted = false;
2184
2185         if (dev->ramdisk) {
2186                 devmapper_merge_snapshot(dev);
2187                 /* device_path becomes stale after merge */
2188                 device_path = get_device_path(dev);
2189         }
2190
2191         if (try_mount(device_path, dev->mount_path, fstype,
2192                        MS_RDONLY | MS_SILENT, dev->ramdisk))
2193                 pb_log("Failed to remount %s read-only: %s\n",
2194                        device_path, strerror(errno));
2195         else
2196                 dev->mounted = true;
2197 }
2198
2199 void device_sync_snapshots(struct device_handler *handler, const char *device)
2200 {
2201         struct discover_device *dev = NULL;
2202         unsigned int i;
2203
2204         if (device) {
2205                 /* Find matching device and sync */
2206                 dev = device_lookup_by_name(handler, device);
2207                 if (!dev) {
2208                         pb_log("%s: device name '%s' unrecognised\n",
2209                                 __func__, device);
2210                         return;
2211                 }
2212                 if (dev->ramdisk)
2213                         device_release_write(dev, true);
2214                 else
2215                         pb_log("%s has no snapshot to merge, skipping\n",
2216                                 dev->device->id);
2217                 return;
2218         }
2219
2220         /* Otherwise sync all relevant devices */
2221         for (i = 0; i < handler->n_devices; i++) {
2222                 dev = handler->devices[i];
2223                 if (dev->device->type != DEVICE_TYPE_DISK &&
2224                         dev->device->type != DEVICE_TYPE_USB)
2225                         continue;
2226                 if (dev->ramdisk)
2227                         device_release_write(dev, true);
2228                 else
2229                         pb_log("%s has no snapshot to merge, skipping\n",
2230                                 dev->device->id);
2231         }
2232 }
2233
2234 #else
2235
2236 void device_handler_discover_context_commit(
2237                 struct device_handler *handler __attribute__((unused)),
2238                 struct discover_context *ctx __attribute__((unused)))
2239 {
2240         pb_log_fn("stubbed out for test cases\n");
2241 }
2242
2243 static void device_handler_update_lang(const char *lang __attribute__((unused)))
2244 {
2245 }
2246
2247 static int device_handler_init_sources(
2248                 struct device_handler *handler __attribute__((unused)))
2249 {
2250         return 0;
2251 }
2252
2253 static void device_handler_reinit_sources(
2254                 struct device_handler *handler __attribute__((unused)))
2255 {
2256 }
2257
2258 static int umount_device(struct discover_device *dev __attribute__((unused)))
2259 {
2260         return 0;
2261 }
2262
2263 static int __attribute__((unused)) mount_device(
2264                 struct discover_device *dev __attribute__((unused)))
2265 {
2266         return 0;
2267 }
2268
2269 int device_request_write(struct discover_device *dev __attribute__((unused)),
2270                 bool *release)
2271 {
2272         *release = true;
2273         return 0;
2274 }
2275
2276 void device_release_write(struct discover_device *dev __attribute__((unused)),
2277         bool release __attribute__((unused)))
2278 {
2279 }
2280
2281 void device_sync_snapshots(
2282                 struct device_handler *handler __attribute__((unused)),
2283                 const char *device __attribute__((unused)))
2284 {
2285 }
2286
2287 #endif