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