discover: Display warning if saving config fails
[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         status.boot_active = false;
538
539         device_handler_status(handler, &status);
540
541         talloc_free(status.message);
542 }
543
544 static void _device_handler_vdevstatus(struct device_handler *handler,
545                 struct discover_device *device, enum status_type type,
546                 const char *fmt, va_list ap)
547 {
548         char *msg;
549
550         msg = talloc_asprintf(handler, "[%s] %s",
551                         device ? device->device->id : "unknown", fmt);
552         _device_handler_vstatus(handler, type, msg, ap);
553         talloc_free(msg);
554 }
555
556 void device_handler_status_dev_info(struct device_handler *handler,
557                 struct discover_device *dev, const char *fmt, ...)
558 {
559         va_list ap;
560
561         va_start(ap, fmt);
562         _device_handler_vdevstatus(handler, dev, STATUS_INFO, fmt, ap);
563         va_end(ap);
564 }
565
566 void device_handler_status_dev_err(struct device_handler *handler,
567                 struct discover_device *dev, const char *fmt, ...)
568 {
569         va_list ap;
570
571         va_start(ap, fmt);
572         _device_handler_vdevstatus(handler, dev, STATUS_ERROR, fmt, ap);
573         va_end(ap);
574 }
575
576 void device_handler_status_info(struct device_handler *handler,
577                 const char *fmt, ...)
578 {
579         va_list ap;
580
581         va_start(ap, fmt);
582         _device_handler_vstatus(handler, STATUS_INFO, fmt, ap);
583         va_end(ap);
584 }
585
586 void device_handler_status_err(struct device_handler *handler,
587                 const char *fmt, ...)
588 {
589         va_list ap;
590
591         va_start(ap, fmt);
592         _device_handler_vstatus(handler, STATUS_ERROR, fmt, ap);
593         va_end(ap);
594 }
595
596 void device_handler_status_download(struct device_handler *handler,
597                 const struct process_info *procinfo,
598                 unsigned int percentage, unsigned int size, char suffix)
599 {
600         struct progress_info *p, *progress = NULL;
601         uint64_t current_converted, current = 0;
602         const char *units = " kMGTP";
603         unsigned long size_bytes;
604         char *update = NULL;
605         double total = 0;
606         unsigned int i;
607         int unit = 0;
608
609         list_for_each_entry(&handler->progress, p, list)
610                 if (p->procinfo == procinfo)
611                         progress = p;
612
613         if (!progress) {
614                 pb_log("Registering new progress struct\n");
615                 progress = talloc_zero(handler, struct progress_info);
616                 if (!progress) {
617                         pb_log("Failed to allocate room for progress struct\n");
618                         return;
619                 }
620                 progress->procinfo = procinfo;
621                 list_add(&handler->progress, &progress->list);
622                 handler->n_progress++;
623         }
624
625         size_bytes = size;
626         for (i = 0; i < strlen(units); i++) {
627                 if (units[i] == suffix)
628                         break;
629         }
630
631         if (i >= strlen(units)) {
632             pb_log("Couldn't recognise suffix '%c'\n", suffix);
633             size_bytes = 0;
634         } else {
635                 while (i--)
636                         size_bytes <<= 10;
637         }
638
639         progress->percentage = percentage;
640         progress->size = size_bytes;
641
642         /*
643          * Aggregate the info we have and update status. If a progress struct
644          * has zero for both percentage and size we assume progress information
645          * is unavailable and fall back to a generic progress message.
646          */
647         list_for_each_entry(&handler->progress, p, list) {
648                 uint64_t c;
649                 double t;
650                 if (!p->percentage || !p->size) {
651                         update = talloc_asprintf(handler,
652                                         _("%u downloads in progress..."),
653                                         handler->n_progress);
654                         current = total = 0;
655                         break;
656                 }
657
658                 c = p->size;
659                 t = (100 * c) / p->percentage;
660
661                 current += c;
662                 total += t;
663         }
664
665         if (total) {
666                 current_converted = current;
667                 while (current_converted >= 1000) {
668                         current_converted >>= 10;
669                         unit++;
670                 }
671                 update = talloc_asprintf(handler,
672                                 _("%u %s downloading: %.0f%% - %" PRIu64 "%cB"),
673                                 handler->n_progress,
674                                 ngettext("item", "items", handler->n_progress),
675                                 (current / total) * 100, current_converted,
676                                 units[unit]);
677         }
678
679         if (!update) {
680                 pb_log_fn("failed to allocate new status\n");
681         } else {
682                 device_handler_status_info(handler, "%s\n", update);
683                 talloc_free(update);
684         }
685 }
686
687 static void device_handler_plugin_scan_device(struct device_handler *handler,
688                 struct discover_device *dev)
689 {
690         int rc;
691
692         pb_debug("Scanning %s for plugin files\n", dev->device->id);
693
694         rc = process_run_simple(handler, pb_system_apps.pb_plugin,
695                                 "scan", dev->mount_path,
696                                 NULL);
697         if (rc)
698                 pb_log("Error from pb-plugin scan %s\n",
699                                 dev->mount_path);
700 }
701
702 void device_handler_status_download_remove(struct device_handler *handler,
703                 struct process_info *procinfo)
704 {
705         struct progress_info *p, *tmp;
706
707         list_for_each_entry_safe(&handler->progress, p, tmp, list)
708                 if (p->procinfo == procinfo) {
709                         list_remove(&p->list);
710                         talloc_free(p);
711                         handler->n_progress--;
712                 }
713 }
714
715 static void device_handler_boot_status_cb(void *arg, struct status *status)
716 {
717         struct device_handler *handler = arg;
718
719         /* boot had failed; update handler state to allow a new default if one
720          * is found later
721          */
722         if (status->type == STATUS_ERROR) {
723                 handler->pending_boot = NULL;
724                 handler->default_boot_option = NULL;
725         }
726
727         device_handler_status(handler, status);
728 }
729
730 static void countdown_status(struct device_handler *handler,
731                 struct discover_boot_option *opt, unsigned int sec)
732 {
733         struct status status;
734
735         status.type = STATUS_INFO;
736         status.message = talloc_asprintf(handler,
737                         _("Booting in %d sec: [%s] %s"), sec,
738                         opt->device->device->id, opt->option->name);
739         status.backlog = false;
740
741         device_handler_status(handler, &status);
742
743         talloc_free(status.message);
744 }
745
746 static int default_timeout(void *arg)
747 {
748         struct device_handler *handler = arg;
749         struct discover_boot_option *opt;
750
751         if (!handler->default_boot_option)
752                 return 0;
753
754         if (handler->pending_boot)
755                 return 0;
756
757         opt = handler->default_boot_option;
758
759         if (handler->sec_to_boot) {
760                 countdown_status(handler, opt, handler->sec_to_boot);
761                 handler->sec_to_boot--;
762                 handler->timeout_waiter = waiter_register_timeout(
763                                                 handler->waitset, 1000,
764                                                 default_timeout, handler);
765                 return 0;
766         }
767
768         handler->timeout_waiter = NULL;
769
770         pb_log("Timeout expired, booting default option %s\n", opt->option->id);
771
772         platform_pre_boot();
773
774         handler->pending_boot = boot(handler, handler->default_boot_option,
775                         NULL, handler->dry_run, device_handler_boot_status_cb,
776                         handler);
777         handler->pending_boot_is_default = true;
778         return 0;
779 }
780
781 struct {
782         enum ipmi_bootdev       ipmi_type;
783         enum device_type        device_type;
784 } device_type_map[] = {
785         { IPMI_BOOTDEV_NETWORK, DEVICE_TYPE_NETWORK },
786         { IPMI_BOOTDEV_DISK, DEVICE_TYPE_DISK },
787         { IPMI_BOOTDEV_DISK, DEVICE_TYPE_USB },
788         { IPMI_BOOTDEV_CDROM, DEVICE_TYPE_OPTICAL },
789 };
790
791 static bool ipmi_device_type_matches(enum ipmi_bootdev ipmi_type,
792                 enum device_type device_type)
793 {
794         unsigned int i;
795
796         for (i = 0; i < ARRAY_SIZE(device_type_map); i++) {
797                 if (device_type_map[i].device_type == device_type)
798                         return device_type_map[i].ipmi_type == ipmi_type;
799         }
800
801         return false;
802 }
803
804 static bool autoboot_option_matches(struct autoboot_option *opt,
805                 struct discover_device *dev)
806 {
807         if (opt->boot_type == BOOT_DEVICE_UUID)
808                 if (!strcmp(opt->uuid, dev->uuid))
809                         return true;
810
811         if (opt->boot_type == BOOT_DEVICE_TYPE)
812                 if (opt->type == dev->device->type ||
813                     opt->type == DEVICE_TYPE_ANY)
814                         return true;
815
816         return false;
817 }
818
819 static int autoboot_option_priority(const struct config *config,
820                                 struct discover_boot_option *opt)
821 {
822         struct autoboot_option *auto_opt;
823         unsigned int i;
824
825         for (i = 0; i < config->n_autoboot_opts; i++) {
826                 auto_opt = &config->autoboot_opts[i];
827                 if (autoboot_option_matches(auto_opt, opt->device))
828                         return DEFAULT_PRIORITY_LOCAL_FIRST + i;
829         }
830
831         return -1;
832 }
833
834 /*
835  * We have different priorities to resolve conflicts between boot options that
836  * report to be the default for their device. This function assigns a priority
837  * for these options.
838  */
839 static enum default_priority default_option_priority(
840                 struct device_handler *handler,
841                 struct discover_boot_option *opt)
842 {
843         const struct config *config;
844
845         /* Temporary user-provided autoboot options have highest priority */
846         if (handler->temp_autoboot) {
847                 if (autoboot_option_matches(handler->temp_autoboot,
848                                         opt->device))
849                         return DEFAULT_PRIORITY_TEMP_USER;
850
851                 pb_debug("handler: disabled default priority due to "
852                                 "temporary user override\n");
853                 return DEFAULT_PRIORITY_DISABLED;
854         }
855
856         config = config_get();
857
858         /* Next highest priority to IPMI-configured boot options. If we have an
859          * IPMI bootdev configuration set, then we don't allow any other
860          * defaults */
861         if (config->ipmi_bootdev) {
862                 bool ipmi_match = ipmi_device_type_matches(config->ipmi_bootdev,
863                                 opt->device->device->type);
864                 if (ipmi_match)
865                         return DEFAULT_PRIORITY_REMOTE;
866
867                 pb_debug("handler: disabled default priority due to "
868                                 "non-matching IPMI type %x\n",
869                                 config->ipmi_bootdev);
870                 return DEFAULT_PRIORITY_DISABLED;
871         }
872
873         /* Next, try to match the option against the user-defined autoboot
874          * options, either by device UUID or type. */
875         if (config->n_autoboot_opts) {
876                 int boot_match = autoboot_option_priority(config, opt);
877                 if (boot_match > 0)
878                         return boot_match;
879         } else {
880                 /* If there is no specific boot order, boot any device */
881                 return DEFAULT_PRIORITY_LOCAL_FIRST;
882         }
883
884         /* If the option didn't match any entry in the array, it is disabled */
885         pb_debug("handler: disabled default priority due to "
886                         "non-matching UUID or type\n");
887         return DEFAULT_PRIORITY_DISABLED;
888 }
889
890 static void set_default(struct device_handler *handler,
891                 struct discover_boot_option *opt)
892 {
893         enum default_priority cur_prio, new_prio;
894
895         if (!handler->autoboot_enabled)
896                 return;
897
898         pb_debug("handler: new default option: %s\n", opt->option->id);
899
900         new_prio = default_option_priority(handler, opt);
901
902         /* Anything outside our range prevents a default boot */
903         if (new_prio >= DEFAULT_PRIORITY_DISABLED)
904                 return;
905
906         pb_debug("handler: calculated priority %d\n", new_prio);
907
908         /* Resolve any conflicts: if we have a new default option, it only
909          * replaces the current if it has a higher priority. */
910         if (handler->default_boot_option) {
911
912                 cur_prio = handler->default_boot_option_priority;
913
914                 if (new_prio < cur_prio) {
915                         pb_log("handler: new prio %d beats "
916                                         "old prio %d for %s\n",
917                                         new_prio, cur_prio,
918                                         handler->default_boot_option
919                                                 ->option->id);
920                         handler->default_boot_option = opt;
921                         handler->default_boot_option_priority = new_prio;
922                         /* extend the timeout a little, so the user sees some
923                          * indication of the change */
924                         handler->sec_to_boot += 2;
925                 }
926
927                 return;
928         }
929
930         handler->sec_to_boot = config_get()->autoboot_timeout_sec;
931         handler->default_boot_option = opt;
932         handler->default_boot_option_priority = new_prio;
933
934         pb_log("handler: boot option %s set as default, timeout %u sec.\n",
935                opt->option->id, handler->sec_to_boot);
936
937         default_timeout(handler);
938 }
939
940 static char *autoboot_option_desc(void *ctx, const struct autoboot_option *opt)
941 {
942         const char *type, *val;
943
944         if (opt->boot_type == BOOT_DEVICE_TYPE) {
945                 type = _("device type");
946                 val = device_type_display_name(opt->type);
947         } else if (opt->boot_type == BOOT_DEVICE_UUID) {
948                 type = _("device UUID");
949                 val = opt->uuid;
950         } else {
951                 type = _("unknown specifier");
952                 val = NULL;
953         }
954
955         return talloc_asprintf(ctx, "%s = %s", type, val);
956 }
957
958 void device_handler_apply_temp_autoboot(struct device_handler *handler,
959                 struct autoboot_option *opt)
960 {
961         unsigned int i;
962         char *desc;
963
964         handler->temp_autoboot = talloc_steal(handler, opt);
965
966         desc = autoboot_option_desc(handler, opt);
967         device_handler_status_info(handler,
968                         _("Applying temporary autoboot override: %s"),
969                         desc);
970         talloc_free(desc);
971
972         if (!handler->autoboot_enabled)
973                 return;
974
975         if (!handler->default_boot_option)
976                 return;
977
978         if (autoboot_option_matches(opt, handler->default_boot_option->device))
979                 return;
980
981         /* cancel the default, and rescan available options */
982         device_handler_cancel_default(handler);
983
984         handler->autoboot_enabled = true;
985
986         for (i = 0; i < handler->n_devices; i++) {
987                 struct discover_device *dev = handler->devices[i];
988                 struct discover_boot_option *boot_opt;
989
990                 if (!autoboot_option_matches(opt, dev))
991                         continue;
992
993                 list_for_each_entry(&dev->boot_options, boot_opt, list) {
994                         if (boot_opt->option->is_default) {
995                                 set_default(handler, boot_opt);
996                                 break;
997                         }
998                 }
999         }
1000 }
1001
1002 static bool resource_is_resolved(struct resource *res)
1003 {
1004         return !res || res->resolved;
1005 }
1006
1007 /* We only use this in an assert, which will disappear if we're compiling
1008  * with NDEBUG, so we need the 'used' attribute for these builds */
1009 static bool __attribute__((used)) boot_option_is_resolved(
1010                 struct discover_boot_option *opt)
1011 {
1012         return resource_is_resolved(opt->boot_image) &&
1013                 resource_is_resolved(opt->initrd) &&
1014                 resource_is_resolved(opt->dtb) &&
1015                 resource_is_resolved(opt->args_sig_file) &&
1016                 resource_is_resolved(opt->icon);
1017 }
1018
1019 static bool resource_resolve(struct resource *res, const char *name,
1020                 struct discover_boot_option *opt,
1021                 struct device_handler *handler)
1022 {
1023         struct parser *parser = opt->source;
1024
1025         if (resource_is_resolved(res))
1026                 return true;
1027
1028         pb_debug("Attempting to resolve resource %s->%s with parser %s\n",
1029                         opt->option->id, name, parser->name);
1030         parser->resolve_resource(handler, res);
1031
1032         return res->resolved;
1033 }
1034
1035 static bool boot_option_resolve(struct discover_boot_option *opt,
1036                 struct device_handler *handler)
1037 {
1038         return resource_resolve(opt->boot_image, "boot_image", opt, handler) &&
1039                 resource_resolve(opt->initrd, "initrd", opt, handler) &&
1040                 resource_resolve(opt->dtb, "dtb", opt, handler) &&
1041                 resource_resolve(opt->args_sig_file, "args_sig_file", opt,
1042                         handler) &&
1043                 resource_resolve(opt->icon, "icon", opt, handler);
1044 }
1045
1046 static void boot_option_finalise(struct device_handler *handler,
1047                 struct discover_boot_option *opt)
1048 {
1049         assert(boot_option_is_resolved(opt));
1050
1051         /* check that the parsers haven't set any of the final data */
1052         assert(!opt->option->boot_image_file);
1053         assert(!opt->option->initrd_file);
1054         assert(!opt->option->dtb_file);
1055         assert(!opt->option->icon_file);
1056         assert(!opt->option->device_id);
1057         assert(!opt->option->args_sig_file);
1058
1059         if (opt->boot_image)
1060                 opt->option->boot_image_file = opt->boot_image->url->full;
1061         if (opt->initrd)
1062                 opt->option->initrd_file = opt->initrd->url->full;
1063         if (opt->dtb)
1064                 opt->option->dtb_file = opt->dtb->url->full;
1065         if (opt->icon)
1066                 opt->option->icon_file = opt->icon->url->full;
1067         if (opt->args_sig_file)
1068                 opt->option->args_sig_file = opt->args_sig_file->url->full;
1069
1070         opt->option->device_id = opt->device->device->id;
1071
1072         if (opt->option->is_default)
1073                 set_default(handler, opt);
1074 }
1075
1076 static void notify_boot_option(struct device_handler *handler,
1077                 struct discover_boot_option *opt)
1078 {
1079         struct discover_device *dev = opt->device;
1080
1081         if (!dev->notified)
1082                 discover_server_notify_device_add(handler->server,
1083                                                   opt->device->device);
1084         dev->notified = true;
1085         discover_server_notify_boot_option_add(handler->server, opt->option);
1086 }
1087
1088 static void process_boot_option_queue(struct device_handler *handler)
1089 {
1090         struct discover_boot_option *opt, *tmp;
1091
1092         list_for_each_entry_safe(&handler->unresolved_boot_options,
1093                         opt, tmp, list) {
1094
1095                 pb_debug("queue: attempting resolution for %s\n",
1096                                 opt->option->id);
1097
1098                 if (!boot_option_resolve(opt, handler))
1099                         continue;
1100
1101                 pb_debug("\tresolved!\n");
1102
1103                 list_remove(&opt->list);
1104                 list_add_tail(&opt->device->boot_options, &opt->list);
1105                 talloc_steal(opt->device, opt);
1106                 boot_option_finalise(handler, opt);
1107                 notify_boot_option(handler, opt);
1108         }
1109 }
1110
1111 struct discover_context *device_handler_discover_context_create(
1112                 struct device_handler *handler,
1113                 struct discover_device *device)
1114 {
1115         struct discover_context *ctx;
1116
1117         ctx = talloc_zero(handler, struct discover_context);
1118         ctx->handler = handler;
1119         ctx->device = device;
1120         list_init(&ctx->boot_options);
1121
1122         return ctx;
1123 }
1124
1125 void device_handler_add_device(struct device_handler *handler,
1126                 struct discover_device *device)
1127 {
1128         handler->n_devices++;
1129         handler->devices = talloc_realloc(handler, handler->devices,
1130                                 struct discover_device *, handler->n_devices);
1131         handler->devices[handler->n_devices - 1] = device;
1132
1133         if (device->device->type == DEVICE_TYPE_NETWORK)
1134                 network_register_device(handler->network, device);
1135 }
1136
1137 void device_handler_add_ramdisk(struct device_handler *handler,
1138                 const char *path)
1139 {
1140         struct ramdisk_device *dev;
1141         unsigned int i;
1142
1143         if (!path)
1144                 return;
1145
1146         for (i = 0; i < handler->n_ramdisks; i++)
1147                 if (!strcmp(handler->ramdisks[i]->path, path))
1148                         return;
1149
1150         dev = talloc_zero(handler, struct ramdisk_device);
1151         if (!dev) {
1152                 pb_log("Failed to allocate memory to track %s\n", path);
1153                 return;
1154         }
1155
1156         dev->path = talloc_strdup(handler, path);
1157
1158         handler->ramdisks = talloc_realloc(handler, handler->ramdisks,
1159                                 struct ramdisk_device *,
1160                                 handler->n_ramdisks + 1);
1161         if (!handler->ramdisks) {
1162                 pb_log("Failed to reallocate memory"
1163                        "- ramdisk tracking inconsistent!\n");
1164                 return;
1165         }
1166
1167         handler->ramdisks[i] = dev;
1168         i = handler->n_ramdisks++;
1169 }
1170
1171 struct ramdisk_device *device_handler_get_ramdisk(
1172                 struct device_handler *handler)
1173 {
1174         unsigned int i;
1175         char *name;
1176         dev_t id;
1177
1178         /* Check if free ramdisk exists */
1179         for (i = 0; i < handler->n_ramdisks; i++)
1180                 if (!handler->ramdisks[i]->snapshot &&
1181                     !handler->ramdisks[i]->origin &&
1182                     !handler->ramdisks[i]->base)
1183                         return handler->ramdisks[i];
1184
1185         /* Otherwise create a new one */
1186         name = talloc_asprintf(handler, "/dev/ram%d",
1187                         handler->n_ramdisks);
1188         if (!name) {
1189                 pb_debug("Failed to allocate memory to name /dev/ram%d",
1190                         handler->n_ramdisks);
1191                 return NULL;
1192         }
1193
1194         id = makedev(1, handler->n_ramdisks);
1195         if (mknod(name, S_IFBLK, id)) {
1196                 if (errno == EEXIST) {
1197                         /* We haven't yet received updates for existing
1198                          * ramdisks - add and use this one */
1199                         pb_debug("Using untracked ramdisk %s\n", name);
1200                 } else {
1201                         pb_log("Failed to create new ramdisk %s: %s\n",
1202                                name, strerror(errno));
1203                         return NULL;
1204                 }
1205         }
1206         device_handler_add_ramdisk(handler, name);
1207         talloc_free(name);
1208
1209         return handler->ramdisks[i];
1210 }
1211
1212 void device_handler_release_ramdisk(struct discover_device *device)
1213 {
1214         struct ramdisk_device *ramdisk = device->ramdisk;
1215
1216         talloc_free(ramdisk->snapshot);
1217         talloc_free(ramdisk->origin);
1218         talloc_free(ramdisk->base);
1219
1220         ramdisk->snapshot = ramdisk->origin = ramdisk->base = NULL;
1221         ramdisk->sectors = 0;
1222
1223         device->ramdisk = NULL;
1224 }
1225
1226 /* Start discovery on a hotplugged device. The device will be in our devices
1227  * array, but has only just been initialised by the hotplug source.
1228  */
1229 int device_handler_discover(struct device_handler *handler,
1230                 struct discover_device *dev)
1231 {
1232         struct discover_context *ctx;
1233         int rc;
1234
1235         device_handler_status_dev_info(handler, dev,
1236                 /*
1237                  * TRANSLATORS: this string will be passed the type of the
1238                  * device (eg "disk" or "network"), which will be translated
1239                  * accordingly.
1240                  */
1241                 _("Processing new %s device"),
1242                 device_type_display_name(dev->device->type));
1243
1244         /* create our context */
1245         ctx = device_handler_discover_context_create(handler, dev);
1246
1247         rc = mount_device(dev);
1248         if (rc)
1249                 goto out;
1250
1251         /* add this device to our system info */
1252         system_info_register_blockdev(dev->device->id, dev->uuid,
1253                         dev->mount_path);
1254
1255         /* run the parsers. This will populate the ctx's boot_option list. */
1256         iterate_parsers(ctx);
1257
1258         /* add discovered stuff to the handler */
1259         device_handler_discover_context_commit(handler, ctx);
1260
1261         process_boot_option_queue(handler);
1262
1263         /* Check this device for pb-plugins */
1264         device_handler_plugin_scan_device(handler, dev);
1265 out:
1266         talloc_unlink(handler, ctx);
1267
1268         return 0;
1269 }
1270
1271 struct requery_data {
1272         struct device_handler   *handler;
1273         struct discover_device  *device;
1274 };
1275
1276 static int device_handler_requery_timeout_fn(void *data)
1277 {
1278         struct discover_boot_option *opt, *tmp;
1279         struct requery_data *rqd = data;
1280         struct device_handler *handler;
1281         struct discover_device *device;
1282         bool autoboot;
1283
1284         handler = rqd->handler;
1285         device = rqd->device;
1286
1287         talloc_free(rqd);
1288
1289         /* network_requery_device may re-add a timeout, so clear the device
1290          * waiter here, so we can potentially start a new one. */
1291         device->requery_waiter = NULL;
1292
1293         /* We keep the device around, but get rid of the parsed boot
1294          * options on that device. That involves delaring out the lists,
1295          * and potentially cancelling a default.
1296          */
1297         list_for_each_entry_safe(&handler->unresolved_boot_options,
1298                         opt, tmp, list) {
1299                 if (opt->device != device)
1300                         continue;
1301                 list_remove(&opt->list);
1302                 talloc_free(opt);
1303         }
1304
1305         /* Track whether autoboot was enabled, if we cancel a default option
1306          * it will be switched off.
1307          */
1308         autoboot = handler->autoboot_enabled;
1309
1310         list_for_each_entry_safe(&device->boot_options, opt, tmp, list) {
1311                 if (opt == handler->default_boot_option) {
1312                         pb_log("Default option %s cancelled since device is being requeried\n",
1313                                         opt->option->name);
1314                         device_handler_cancel_default(handler);
1315                 }
1316                 list_remove(&opt->list);
1317                 talloc_free(opt);
1318         }
1319
1320         handler->autoboot_enabled = autoboot;
1321
1322         discover_server_notify_device_remove(handler->server, device->device);
1323         device->notified = false;
1324
1325         network_requery_device(handler->network, device);
1326
1327         return 0;
1328 }
1329
1330 /* Schedule a requery in timeout (seconds).
1331  *
1332  * Special values of timeout:
1333  *   0: no requery
1334  *  -1: use default
1335  */
1336 void device_handler_start_requery_timeout( struct device_handler *handler,
1337                 struct discover_device *dev, int timeout)
1338 {
1339         struct requery_data *rqd;
1340
1341         if (dev->requery_waiter)
1342                 return;
1343
1344         if (timeout == -1)
1345                 timeout = default_rescan_timeout;
1346         else if (timeout == 0)
1347                 return;
1348
1349         rqd = talloc(dev, struct requery_data);
1350         rqd->handler = handler;
1351         rqd->device = dev;
1352
1353         pb_debug("starting requery timeout for device %s, in %d sec\n",
1354                         dev->device->id, timeout);
1355
1356         dev->requery_waiter = waiter_register_timeout(handler->waitset,
1357                         timeout * 1000, device_handler_requery_timeout_fn, rqd);
1358 }
1359
1360 static int event_requery_timeout(struct event *event)
1361 {
1362         int timeout = -1;
1363         unsigned long x;
1364         const char *str;
1365         char *endp;
1366
1367         if (!event)
1368                 return timeout;
1369
1370         str = event_get_param(event, "reboottime");
1371         if (!str)
1372                 return timeout;
1373
1374         x = strtoul(str, &endp, 0);
1375         if (endp != str)
1376                 timeout = x;
1377
1378         return timeout;
1379 }
1380
1381
1382 /* Incoming dhcp event */
1383 int device_handler_dhcp(struct device_handler *handler,
1384                 struct discover_device *dev, struct event *event)
1385 {
1386         struct discover_context *ctx;
1387         const char *ip;
1388
1389         if (event_get_param(event, "ipv6"))
1390                 ip = event_get_param(event, "ipv6");
1391         else
1392                 ip = event_get_param(event, "ip");
1393
1394         device_handler_status_dev_info(handler, dev,
1395                         _("Processing DHCP lease response (ip: %s)"), ip);
1396
1397         pending_network_jobs_start();
1398
1399         /* create our context */
1400         ctx = device_handler_discover_context_create(handler, dev);
1401         talloc_steal(ctx, event);
1402         ctx->event = event;
1403
1404         device_handler_start_requery_timeout(handler, dev,
1405                         event_requery_timeout(event));
1406
1407         iterate_parsers(ctx);
1408
1409         device_handler_discover_context_commit(handler, ctx);
1410
1411         talloc_unlink(handler, ctx);
1412
1413         return 0;
1414 }
1415
1416 struct discover_boot_option *device_handler_find_option_by_name(
1417                 struct device_handler *handler, const char *device,
1418                 const char *name)
1419 {
1420         size_t len = strlen(name);
1421         unsigned int i;
1422
1423         for (i = 0; i < handler->n_devices; i++) {
1424                 struct discover_device *dev = handler->devices[i];
1425                 struct discover_boot_option *opt;
1426
1427                 list_for_each_entry(&dev->boot_options, opt, list)
1428                         /* Match exactly, partial matches can be quite common */
1429                         if (strlen(opt->option->name) == len &&
1430                                         !strcmp(opt->option->name, name))
1431                                 if (!dev || !strcmp(opt->option->device_id, device))
1432                                         return opt;
1433         }
1434
1435         return NULL;
1436 }
1437
1438 static struct discover_boot_option *find_boot_option_by_id(
1439                 struct device_handler *handler, const char *id)
1440 {
1441         unsigned int i;
1442
1443         for (i = 0; i < handler->n_devices; i++) {
1444                 struct discover_device *dev = handler->devices[i];
1445                 struct discover_boot_option *opt;
1446
1447                 list_for_each_entry(&dev->boot_options, opt, list)
1448                         if (!strcmp(opt->option->id, id))
1449                                 return opt;
1450         }
1451
1452         return NULL;
1453 }
1454
1455 void device_handler_boot(struct device_handler *handler,
1456                 struct boot_command *cmd)
1457 {
1458         struct discover_boot_option *opt = NULL;
1459
1460         if (cmd->option_id && strlen(cmd->option_id))
1461                 opt = find_boot_option_by_id(handler, cmd->option_id);
1462
1463         if (handler->pending_boot)
1464                 boot_cancel(handler->pending_boot);
1465
1466         platform_pre_boot();
1467
1468         handler->pending_boot = boot(handler, opt, cmd, handler->dry_run,
1469                         device_handler_boot_status_cb, handler);
1470         handler->pending_boot_is_default = false;
1471 }
1472
1473 void device_handler_cancel_default(struct device_handler *handler)
1474 {
1475         if (handler->timeout_waiter)
1476                 waiter_remove(handler->timeout_waiter);
1477
1478         handler->timeout_waiter = NULL;
1479         handler->autoboot_enabled = false;
1480
1481         /* we only send status if we had a default boot option queued */
1482         if (!handler->default_boot_option)
1483                 return;
1484
1485         pb_log("Cancelling default boot option\n");
1486
1487         if (handler->pending_boot && handler->pending_boot_is_default) {
1488                 boot_cancel(handler->pending_boot);
1489                 handler->pending_boot = NULL;
1490                 handler->pending_boot_is_default = false;
1491         }
1492
1493         handler->default_boot_option = NULL;
1494
1495         device_handler_status_info(handler, _("Default boot cancelled"));
1496 }
1497
1498 void device_handler_update_config(struct device_handler *handler,
1499                 struct config *config)
1500 {
1501         int rc;
1502
1503         rc = config_set(config);
1504         if (rc) {
1505                 device_handler_status_err(handler,
1506                                 "Failed to update configuration!");
1507                 return;
1508         }
1509
1510         discover_server_notify_config(handler->server, config);
1511         device_handler_update_lang(config->lang);
1512         device_handler_reinit(handler);
1513 }
1514
1515 static char *device_from_addr(void *ctx, struct pb_url *url)
1516 {
1517         char *ipaddr, *buf, *tok, *dev = NULL;
1518         bool ipv6_route;
1519         const char *delim = " ";
1520         struct sockaddr_in *ipv4;
1521         struct sockaddr_in6 *ipv6;
1522         struct addrinfo *res;
1523         struct process *p;
1524         int rc;
1525
1526         /* Confirm url->host is either a valid hostname, or a
1527          * valid IPv4 or IPv6 address */
1528         rc = getaddrinfo(url->host, NULL, NULL, &res);
1529         if (rc) {
1530                 pb_debug("%s: Invalid URL\n",__func__);
1531                 return NULL;
1532         }
1533
1534         switch (res->ai_family) {
1535         case AF_INET:   /* ipv4 */
1536                 ipaddr = talloc_array(ctx,char,INET_ADDRSTRLEN);
1537                 ipv4 = (struct sockaddr_in *) res->ai_addr;
1538                 inet_ntop(AF_INET, &(ipv4->sin_addr), ipaddr, INET_ADDRSTRLEN);
1539                 ipv6_route = false;
1540                 break;
1541         case AF_INET6:  /* ipv6 */
1542                 ipaddr = talloc_array(ctx,char,INET6_ADDRSTRLEN);
1543                 ipv6 = (struct sockaddr_in6 *) res->ai_addr;
1544                 inet_ntop(AF_INET6, &(ipv6->sin6_addr), ipaddr, INET6_ADDRSTRLEN);
1545                 ipv6_route = true;
1546                 break;
1547         default:        /* error */
1548                 freeaddrinfo(res);
1549                 return NULL;
1550         }
1551         freeaddrinfo(res);
1552
1553         const char *argv[] = {
1554                 pb_system_apps.ip,
1555                 ipv6_route ? "-6" : "-4",
1556                 "route", "show", "to", "match",
1557                 ipaddr,
1558                 NULL
1559         };
1560
1561         p = process_create(ctx);
1562
1563         p->path = pb_system_apps.ip;
1564         p->argv = argv;
1565         p->keep_stdout = true;
1566
1567         rc = process_run_sync(p);
1568
1569         if (rc || p->exit_status) {
1570                 /* ip has complained for some reason; most likely
1571                  * there is no route to the host - bail out */
1572                 pb_debug("%s: `ip` returns non-zero exit status\n", __func__);
1573                 pb_debug("ip buf: %s\n", p->stdout_buf);
1574                 process_release(p);
1575                 return NULL;
1576         }
1577
1578         buf = p->stdout_buf;
1579         /* If a route is found, ip-route output will be of the form
1580          * "... dev DEVNAME ... " */
1581         tok = strtok(buf, delim);
1582         while (tok) {
1583                 if (!strcmp(tok, "dev")) {
1584                         tok = strtok(NULL, delim);
1585                         dev = talloc_strdup(ctx, tok);
1586                         break;
1587                 }
1588                 tok = strtok(NULL, delim);
1589         }
1590
1591         process_release(p);
1592         if (dev)
1593                 pb_debug("%s: Found interface '%s'\n", __func__,dev);
1594         return dev;
1595 }
1596
1597 static void process_url_cb(struct load_url_result *result, void *data)
1598 {
1599         struct device_handler *handler;
1600         struct discover_context *ctx;
1601         struct discover_device *dev;
1602         struct event *event = data;
1603         const char *mac;
1604
1605         if (result->status != LOAD_OK) {
1606                 pb_log_fn("Load failed for %s\n", result->url->full);
1607                 return;
1608         }
1609
1610         if (!event)
1611                 return;
1612
1613         handler = talloc_parent(event);
1614         if (!handler)
1615                 return;
1616
1617         event->device = device_from_addr(event, result->url);
1618         if (!event->device) {
1619                 pb_log("Downloaded a file but can't find its interface - pretending it was local\n");
1620                 event->device = talloc_asprintf(event, "local");
1621         }
1622
1623         mac = event_get_param(event, "mac");
1624         char *url = talloc_asprintf(event, "file://%s", result->local);
1625         event_set_param(event, "pxeconffile-local", url);
1626
1627         dev = discover_device_create(handler, mac, event->device);
1628         ctx = device_handler_discover_context_create(handler, dev);
1629         talloc_steal(ctx, event);
1630         ctx->event = event;
1631
1632         iterate_parsers(ctx);
1633
1634         device_handler_discover_context_commit(handler, ctx);
1635
1636         talloc_unlink(handler, ctx);
1637 }
1638
1639 void device_handler_process_url(struct device_handler *handler,
1640                 const char *url, const char *mac, const char *ip)
1641 {
1642         struct discover_context *ctx;
1643         struct discover_device *dev;
1644         bool allow_async = false;
1645         struct pb_url *pb_url;
1646         struct event *event;
1647
1648         event = talloc_zero(handler, struct event);
1649         event->type = EVENT_TYPE_USER;
1650         event->action = EVENT_ACTION_URL;
1651
1652         pb_url = pb_url_parse(event, url);
1653         if (!pb_url || (pb_url->scheme != pb_url_file && !pb_url->host)) {
1654                 device_handler_status_err(handler, _("Invalid config URL!"));
1655                 talloc_free(event);
1656                 return;
1657         }
1658
1659         if (url[strlen(url) - 1] == '/') {
1660                 event_set_param(event, "pxepathprefix", url);
1661                 event_set_param(event, "mac", mac);
1662                 event_set_param(event, "ip", ip);
1663                 event->device = device_from_addr(event, pb_url);
1664                 if (!event->device) {
1665                         device_handler_status_err(handler,
1666                                         _("Unable to route to host %s"),
1667                                         pb_url->host);
1668                         talloc_free(event);
1669                         return;
1670                 }
1671         } else {
1672                 event_set_param(event, "pxeconffile", url);
1673                 allow_async = true;
1674         }
1675
1676         if (pb_url->scheme == pb_url_file)
1677                 event->device = talloc_asprintf(event, "local");
1678         else if (allow_async) {
1679                 /* If file is remote load asynchronously before passing to
1680                  * parser. This allows us to wait for network to be available */
1681                 if (!load_url_async(handler, pb_url, process_url_cb, event,
1682                                         NULL, handler)) {
1683                         pb_log("Failed to load url %s\n", pb_url->full);
1684                         device_handler_status_err(handler, _("Failed to load URL!"));
1685                         talloc_free(event);
1686                 }
1687                 return;
1688         }
1689
1690         /* If path is local we can parse straight away */
1691
1692         dev = discover_device_create(handler, mac, event->device);
1693         if (pb_url->scheme == pb_url_file)
1694                 dev->device->type = DEVICE_TYPE_ANY;
1695         ctx = device_handler_discover_context_create(handler, dev);
1696         talloc_steal(ctx, event);
1697         ctx->event = event;
1698
1699         iterate_parsers(ctx);
1700
1701         device_handler_discover_context_commit(handler, ctx);
1702
1703         talloc_unlink(handler, ctx);
1704 }
1705
1706 static void plugin_install_cb(struct process *process)
1707 {
1708         struct device_handler *handler = process->data;
1709
1710         if (!handler) {
1711                 pb_log_fn("Missing data!\n");
1712                 return;
1713         }
1714
1715         handler->plugin_installing = false;
1716         if (process->exit_status) {
1717                 device_handler_status_err(handler, "Plugin failed to install!");
1718                 pb_log("Failed to install plugin:\n%s\n", process->stdout_buf);
1719         }
1720 }
1721
1722 void device_handler_install_plugin(struct device_handler *handler,
1723                 const char *plugin_file)
1724 {
1725         struct process *p;
1726         int result;
1727
1728         if (handler->plugin_installing) {
1729                 pb_log("Plugin install cancelled - install already running");
1730                 return;
1731         }
1732
1733         p = process_create(handler);
1734         if (!p) {
1735                 pb_log("install_plugin: Failed to create process\n");
1736                 return;
1737         }
1738
1739         const char *argv[] = {
1740                 pb_system_apps.pb_plugin,
1741                 "install",
1742                 "auto",
1743                 plugin_file,
1744                 NULL
1745         };
1746
1747         p->path = pb_system_apps.pb_plugin;
1748         p->argv = argv;
1749         p->exit_cb = plugin_install_cb;
1750         p->data = handler;
1751         p->keep_stdout = true;
1752
1753         result = process_run_async(p);
1754
1755         if (result)
1756                 device_handler_status_err(handler, "Could not install plugin");
1757         else
1758                 handler->plugin_installing = true;
1759 }
1760
1761 #ifndef PETITBOOT_TEST
1762
1763 /**
1764  * context_commit - Commit a temporary discovery context to the handler,
1765  * and notify the clients about any new options / devices
1766  */
1767 void device_handler_discover_context_commit(struct device_handler *handler,
1768                 struct discover_context *ctx)
1769 {
1770         struct discover_device *dev = ctx->device;
1771         struct discover_boot_option *opt, *tmp;
1772
1773         if (!device_lookup_by_uuid(handler, dev->uuid))
1774                 device_handler_add_device(handler, dev);
1775
1776         /* move boot options from the context to the device */
1777         list_for_each_entry_safe(&ctx->boot_options, opt, tmp, list) {
1778                 list_remove(&opt->list);
1779
1780                 /* All boot options need at least a kernel image */
1781                 if (!opt->boot_image || !opt->boot_image->url) {
1782                         pb_log("boot option %s is missing boot image, ignoring\n",
1783                                 opt->option->id);
1784                         talloc_free(opt);
1785                         continue;
1786                 }
1787
1788                 if (boot_option_resolve(opt, handler)) {
1789                         pb_log("boot option %s is resolved, "
1790                                         "sending to clients\n",
1791                                         opt->option->id);
1792                         list_add_tail(&dev->boot_options, &opt->list);
1793                         talloc_steal(dev, opt);
1794                         boot_option_finalise(handler, opt);
1795                         notify_boot_option(handler, opt);
1796                 } else {
1797                         if (!opt->source->resolve_resource) {
1798                                 pb_log("parser %s gave us an unresolved "
1799                                         "resource (%s), but no way to "
1800                                         "resolve it\n",
1801                                         opt->source->name, opt->option->id);
1802                                 talloc_free(opt);
1803                         } else {
1804                                 pb_log("boot option %s is unresolved, "
1805                                                 "adding to queue\n",
1806                                                 opt->option->id);
1807                                 list_add(&handler->unresolved_boot_options,
1808                                                 &opt->list);
1809                                 talloc_steal(handler, opt);
1810                         }
1811                 }
1812         }
1813 }
1814
1815 void device_handler_add_plugin_option(struct device_handler *handler,
1816                 struct plugin_option *opt)
1817 {
1818         struct plugin_option *tmp;
1819         unsigned int i;
1820
1821         for (i = 0; i < handler->n_plugins; i++) {
1822                 tmp = handler->plugins[i];
1823                 /* If both id and version match, ignore */
1824                 if (strncmp(opt->id, tmp->id, strlen(opt->id)) == 0 &&
1825                                 strcmp(opt->version, tmp->version) == 0) {
1826                         pb_log("discover: Plugin '%s' already exists, ignoring\n",
1827                                         opt->id);
1828                         return;
1829                 }
1830         }
1831
1832         handler->plugins = talloc_realloc(handler, handler->plugins,
1833                         struct plugin_option *, handler->n_plugins + 1);
1834         if (!handler->plugins) {
1835                 pb_log("Failed to allocate memory for new plugin\n");
1836                 handler->n_plugins = 0;
1837                 return;
1838         }
1839
1840         handler->plugins[handler->n_plugins++] = opt;
1841         discover_server_notify_plugin_option_add(handler->server, opt);
1842 }
1843
1844 static void device_handler_update_lang(const char *lang)
1845 {
1846         const char *cur_lang;
1847
1848         if (!lang)
1849                 return;
1850
1851         cur_lang = setlocale(LC_ALL, NULL);
1852         if (cur_lang && !strcmp(cur_lang, lang))
1853                 return;
1854
1855         setlocale(LC_ALL, lang);
1856 }
1857
1858 static int device_handler_init_sources(struct device_handler *handler)
1859 {
1860         /* init our device sources: udev, network and user events */
1861         handler->user_event = user_event_init(handler, handler->waitset);
1862         if (!handler->user_event)
1863                 return -1;
1864
1865         handler->network = network_init(handler, handler->waitset,
1866                         handler->dry_run);
1867         if (!handler->network)
1868                 return -1;
1869
1870         handler->udev = udev_init(handler, handler->waitset);
1871         if (!handler->udev)
1872                 return -1;
1873
1874         return 0;
1875 }
1876
1877 static void device_handler_reinit_sources(struct device_handler *handler)
1878 {
1879         /* if we haven't initialised sources previously (becuase we started in
1880          * safe mode), then init once here. */
1881         if (!(handler->udev || handler->network || handler->user_event)) {
1882                 device_handler_init_sources(handler);
1883                 return;
1884         }
1885
1886         system_info_reinit();
1887
1888         network_shutdown(handler->network);
1889         handler->network = network_init(handler, handler->waitset,
1890                         handler->dry_run);
1891
1892         udev_reinit(handler->udev);
1893 }
1894
1895 static inline const char *get_device_path(struct discover_device *dev)
1896 {
1897         return dev->ramdisk ? dev->ramdisk->snapshot : dev->device_path;
1898 }
1899
1900 static char *check_subvols(struct discover_device *dev)
1901 {
1902         const char *fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1903         struct stat sb;
1904         char *path;
1905         int rc;
1906
1907         if (strncmp(fstype, "btrfs", strlen("btrfs")))
1908                 return dev->mount_path;
1909
1910         /* On btrfs a device's root may be under a subvolume path */
1911         path = join_paths(dev, dev->mount_path, "@");
1912         rc = stat(path, &sb);
1913         if (!rc && S_ISDIR(sb.st_mode)) {
1914                 pb_debug("Using '%s' for btrfs root path\n", path);
1915                 return path;
1916         }
1917
1918         talloc_free(path);
1919         return dev->mount_path;
1920 }
1921
1922 static bool check_existing_mount(struct discover_device *dev)
1923 {
1924         struct stat devstat, mntstat;
1925         const char *device_path;
1926         struct mntent *mnt;
1927         FILE *fp;
1928         int rc;
1929
1930         device_path = get_device_path(dev);
1931
1932         rc = stat(device_path, &devstat);
1933         if (rc) {
1934                 pb_debug("%s: stat failed: %s\n", __func__, strerror(errno));
1935                 return false;
1936         }
1937
1938         if (!S_ISBLK(devstat.st_mode)) {
1939                 pb_debug("%s: %s isn't a block device?\n", __func__,
1940                                 dev->device_path);
1941                 return false;
1942         }
1943
1944         fp = fopen("/proc/self/mounts", "r");
1945
1946         for (;;) {
1947                 mnt = getmntent(fp);
1948                 if (!mnt)
1949                         break;
1950
1951                 if (!mnt->mnt_fsname || mnt->mnt_fsname[0] != '/')
1952                         continue;
1953
1954                 rc = stat(mnt->mnt_fsname, &mntstat);
1955                 if (rc)
1956                         continue;
1957
1958                 if (!S_ISBLK(mntstat.st_mode))
1959                         continue;
1960
1961                 if (mntstat.st_rdev == devstat.st_rdev) {
1962                         dev->mount_path = talloc_strdup(dev, mnt->mnt_dir);
1963                         dev->root_path = check_subvols(dev);
1964                         dev->mounted_rw = !!hasmntopt(mnt, "rw");
1965                         dev->mounted = true;
1966                         dev->unmount = false;
1967
1968                         pb_debug("%s: %s is already mounted (r%c) at %s\n",
1969                                         __func__, dev->device_path,
1970                                         dev->mounted_rw ? 'w' : 'o',
1971                                         mnt->mnt_dir);
1972                         break;
1973                 }
1974         }
1975
1976         fclose(fp);
1977
1978         return mnt != NULL;
1979 }
1980
1981 /*
1982  * Attempt to mount a filesystem safely, while handling certain filesytem-
1983  * specific options
1984  */
1985 static int try_mount(const char *device_path, const char *mount_path,
1986                              const char *fstype, unsigned long flags,
1987                              bool have_snapshot)
1988 {
1989         const char *fs, *safe_opts;
1990         int rc;
1991
1992         /* Mount ext3 as ext4 instead so 'norecovery' can be used */
1993         if (strncmp(fstype, "ext3", strlen("ext3")) == 0) {
1994                 pb_debug("Mounting ext3 filesystem as ext4\n");
1995                 fs = "ext4";
1996         } else
1997                 fs = fstype;
1998
1999         if (strncmp(fs, "xfs", strlen("xfs")) == 0 ||
2000             strncmp(fs, "ext4", strlen("ext4")) == 0)
2001                 safe_opts = "norecovery";
2002         else
2003                 safe_opts = NULL;
2004
2005         errno = 0;
2006         /* If no snapshot is available don't attempt recovery */
2007         if (!have_snapshot)
2008                 return mount(device_path, mount_path, fs, flags, safe_opts);
2009
2010         rc = mount(device_path, mount_path, fs, flags, NULL);
2011
2012         if (!rc)
2013                 return rc;
2014
2015         /* Mounting failed; some filesystems will fail to mount if a recovery
2016          * journal exists (eg. cross-endian XFS), so try again with norecovery
2017          * where that option is available.
2018          * If mounting read-write just return the error as norecovery is not a
2019          * valid option */
2020         if ((flags & MS_RDONLY) != MS_RDONLY || !safe_opts)
2021                 return rc;
2022
2023         errno = 0;
2024         return mount(device_path, mount_path, fs, flags, safe_opts);
2025 }
2026
2027 static int mount_device(struct discover_device *dev)
2028 {
2029         const char *fstype, *device_path;
2030         int rc;
2031
2032         if (!dev->device_path)
2033                 return -1;
2034
2035         if (dev->mounted)
2036                 return 0;
2037
2038         if (check_existing_mount(dev))
2039                 return 0;
2040
2041         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
2042         if (!fstype)
2043                 return 0;
2044
2045         dev->mount_path = join_paths(dev, mount_base(),
2046                                         dev->device_path);
2047
2048         if (pb_mkdir_recursive(dev->mount_path)) {
2049                 pb_log("couldn't create mount directory %s: %s\n",
2050                                 dev->mount_path, strerror(errno));
2051                 goto err_free;
2052         }
2053
2054         device_path = get_device_path(dev);
2055
2056         pb_log("mounting device %s read-only\n", dev->device_path);
2057         rc = try_mount(device_path, dev->mount_path, fstype,
2058                        MS_RDONLY | MS_SILENT, dev->ramdisk);
2059
2060         /* If mount fails clean up any snapshot and try again */
2061         if (rc && dev->ramdisk) {
2062                 pb_log("couldn't mount snapshot for %s: mount failed: %s\n",
2063                                 device_path, strerror(errno));
2064                 pb_log("falling back to actual device\n");
2065
2066                 devmapper_destroy_snapshot(dev);
2067
2068                 device_path = get_device_path(dev);
2069                 pb_log("mounting device %s read-only\n", dev->device_path);
2070                 rc = try_mount(device_path, dev->mount_path, fstype,
2071                                MS_RDONLY | MS_SILENT, dev->ramdisk);
2072         }
2073
2074         if (!rc) {
2075                 dev->mounted = true;
2076                 dev->mounted_rw = false;
2077                 dev->unmount = true;
2078                 dev->root_path = check_subvols(dev);
2079                 return 0;
2080         }
2081
2082         pb_log("couldn't mount device %s: mount failed: %s\n",
2083                         device_path, strerror(errno));
2084
2085         pb_rmdir_recursive(mount_base(), dev->mount_path);
2086 err_free:
2087         talloc_free(dev->mount_path);
2088         dev->mount_path = NULL;
2089         return -1;
2090 }
2091
2092 static int umount_device(struct discover_device *dev)
2093 {
2094         const char *device_path;
2095         int rc;
2096
2097         if (!dev->mounted || !dev->unmount)
2098                 return 0;
2099
2100         device_path = get_device_path(dev);
2101
2102         pb_log("unmounting device %s\n", device_path);
2103         rc = umount(dev->mount_path);
2104         if (rc)
2105                 return -1;
2106
2107         dev->mounted = false;
2108         devmapper_destroy_snapshot(dev);
2109
2110         pb_rmdir_recursive(mount_base(), dev->mount_path);
2111
2112         talloc_free(dev->mount_path);
2113         dev->mount_path = NULL;
2114         dev->root_path = NULL;
2115
2116         return 0;
2117 }
2118
2119 int device_request_write(struct discover_device *dev, bool *release)
2120 {
2121         const char *fstype, *device_path;
2122         const struct config *config;
2123         int rc;
2124
2125         *release = false;
2126
2127         config = config_get();
2128         if (!config->allow_writes)
2129                 return -1;
2130
2131         if (!dev->mounted)
2132                 return -1;
2133
2134         if (dev->mounted_rw)
2135                 return 0;
2136
2137         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
2138
2139         device_path = get_device_path(dev);
2140
2141         pb_log("remounting device %s read-write\n", device_path);
2142
2143         rc = umount(dev->mount_path);
2144         if (rc) {
2145                 pb_log("Failed to unmount %s: %s\n",
2146                        dev->mount_path, strerror(errno));
2147                 return -1;
2148         }
2149
2150         rc = try_mount(device_path, dev->mount_path, fstype,
2151                        MS_SILENT, dev->ramdisk);
2152         if (rc)
2153                 goto mount_ro;
2154
2155         dev->mounted_rw = true;
2156         *release = true;
2157         return 0;
2158
2159 mount_ro:
2160         pb_log("Unable to remount device %s read-write: %s\n",
2161                device_path, strerror(errno));
2162         rc = try_mount(device_path, dev->mount_path, fstype,
2163                        MS_RDONLY | MS_SILENT, dev->ramdisk);
2164         if (rc)
2165                 pb_log("Unable to recover mount for %s: %s\n",
2166                        device_path, strerror(errno));
2167         return -1;
2168 }
2169
2170 void device_release_write(struct discover_device *dev, bool release)
2171 {
2172         const char *fstype, *device_path;
2173
2174         if (!release)
2175                 return;
2176
2177         device_path = get_device_path(dev);
2178
2179         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
2180
2181         pb_log("remounting device %s read-only\n", device_path);
2182
2183         if (umount(dev->mount_path)) {
2184                 pb_log("Failed to unmount %s\n", dev->mount_path);
2185                 return;
2186         }
2187         dev->mounted_rw = dev->mounted = false;
2188
2189         if (dev->ramdisk) {
2190                 devmapper_merge_snapshot(dev);
2191                 /* device_path becomes stale after merge */
2192                 device_path = get_device_path(dev);
2193         }
2194
2195         if (try_mount(device_path, dev->mount_path, fstype,
2196                        MS_RDONLY | MS_SILENT, dev->ramdisk))
2197                 pb_log("Failed to remount %s read-only: %s\n",
2198                        device_path, strerror(errno));
2199         else
2200                 dev->mounted = true;
2201 }
2202
2203 void device_sync_snapshots(struct device_handler *handler, const char *device)
2204 {
2205         struct discover_device *dev = NULL;
2206         unsigned int i;
2207
2208         if (device) {
2209                 /* Find matching device and sync */
2210                 dev = device_lookup_by_name(handler, device);
2211                 if (!dev) {
2212                         pb_log("%s: device name '%s' unrecognised\n",
2213                                 __func__, device);
2214                         return;
2215                 }
2216                 if (dev->ramdisk)
2217                         device_release_write(dev, true);
2218                 else
2219                         pb_log("%s has no snapshot to merge, skipping\n",
2220                                 dev->device->id);
2221                 return;
2222         }
2223
2224         /* Otherwise sync all relevant devices */
2225         for (i = 0; i < handler->n_devices; i++) {
2226                 dev = handler->devices[i];
2227                 if (dev->device->type != DEVICE_TYPE_DISK &&
2228                         dev->device->type != DEVICE_TYPE_USB)
2229                         continue;
2230                 if (dev->ramdisk)
2231                         device_release_write(dev, true);
2232                 else
2233                         pb_log("%s has no snapshot to merge, skipping\n",
2234                                 dev->device->id);
2235         }
2236 }
2237
2238 #else
2239
2240 void device_handler_discover_context_commit(
2241                 struct device_handler *handler __attribute__((unused)),
2242                 struct discover_context *ctx __attribute__((unused)))
2243 {
2244         pb_log_fn("stubbed out for test cases\n");
2245 }
2246
2247 static void device_handler_update_lang(const char *lang __attribute__((unused)))
2248 {
2249 }
2250
2251 static int device_handler_init_sources(
2252                 struct device_handler *handler __attribute__((unused)))
2253 {
2254         return 0;
2255 }
2256
2257 static void device_handler_reinit_sources(
2258                 struct device_handler *handler __attribute__((unused)))
2259 {
2260 }
2261
2262 static int umount_device(struct discover_device *dev __attribute__((unused)))
2263 {
2264         return 0;
2265 }
2266
2267 static int __attribute__((unused)) mount_device(
2268                 struct discover_device *dev __attribute__((unused)))
2269 {
2270         return 0;
2271 }
2272
2273 int device_request_write(struct discover_device *dev __attribute__((unused)),
2274                 bool *release)
2275 {
2276         *release = true;
2277         return 0;
2278 }
2279
2280 void device_release_write(struct discover_device *dev __attribute__((unused)),
2281         bool release __attribute__((unused)))
2282 {
2283 }
2284
2285 void device_sync_snapshots(
2286                 struct device_handler *handler __attribute__((unused)),
2287                 const char *device __attribute__((unused)))
2288 {
2289 }
2290
2291 #endif