discover: implement a periodic requery for network devices
[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 int autoboot_option_priority(const struct config *config,
801                                 struct discover_boot_option *opt)
802 {
803         enum device_type type = opt->device->device->type;
804         const char *uuid = opt->device->uuid;
805         struct autoboot_option *auto_opt;
806         unsigned int i;
807
808         for (i = 0; i < config->n_autoboot_opts; i++) {
809                 auto_opt = &config->autoboot_opts[i];
810                 if (auto_opt->boot_type == BOOT_DEVICE_UUID)
811                         if (!strcmp(auto_opt->uuid, uuid))
812                                 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
813
814                 if (auto_opt->boot_type == BOOT_DEVICE_TYPE)
815                         if (auto_opt->type == type ||
816                             auto_opt->type == DEVICE_TYPE_ANY)
817                                 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
818         }
819
820         return -1;
821 }
822
823 /*
824  * We have different priorities to resolve conflicts between boot options that
825  * report to be the default for their device. This function assigns a priority
826  * for these options.
827  */
828 static enum default_priority default_option_priority(
829                 struct discover_boot_option *opt)
830 {
831         const struct config *config;
832
833         config = config_get();
834
835         /* We give highest priority to IPMI-configured boot options. If
836          * we have an IPMI bootdev configuration set, then we don't allow
837          * any other defaults */
838         if (config->ipmi_bootdev) {
839                 bool ipmi_match = ipmi_device_type_matches(config->ipmi_bootdev,
840                                 opt->device->device->type);
841                 if (ipmi_match)
842                         return DEFAULT_PRIORITY_REMOTE;
843
844                 pb_debug("handler: disabled default priority due to "
845                                 "non-matching IPMI type %x\n",
846                                 config->ipmi_bootdev);
847                 return DEFAULT_PRIORITY_DISABLED;
848         }
849
850         /* Next, try to match the option against the user-defined autoboot
851          * options, either by device UUID or type. */
852         if (config->n_autoboot_opts) {
853                 int boot_match = autoboot_option_priority(config, opt);
854                 if (boot_match > 0)
855                         return boot_match;
856         } else {
857                 /* If there is no specific boot order, boot any device */
858                 return DEFAULT_PRIORITY_LOCAL_FIRST;
859         }
860
861         /* If the option didn't match any entry in the array, it is disabled */
862         pb_debug("handler: disabled default priority due to "
863                         "non-matching UUID or type\n");
864         return DEFAULT_PRIORITY_DISABLED;
865 }
866
867 static void set_default(struct device_handler *handler,
868                 struct discover_boot_option *opt)
869 {
870         enum default_priority cur_prio, new_prio;
871
872         if (!handler->autoboot_enabled)
873                 return;
874
875         pb_debug("handler: new default option: %s\n", opt->option->id);
876
877         new_prio = default_option_priority(opt);
878
879         /* Anything outside our range prevents a default boot */
880         if (new_prio >= DEFAULT_PRIORITY_DISABLED)
881                 return;
882
883         pb_debug("handler: calculated priority %d\n", new_prio);
884
885         /* Resolve any conflicts: if we have a new default option, it only
886          * replaces the current if it has a higher priority. */
887         if (handler->default_boot_option) {
888
889                 cur_prio = handler->default_boot_option_priority;
890
891                 if (new_prio < cur_prio) {
892                         pb_log("handler: new prio %d beats "
893                                         "old prio %d for %s\n",
894                                         new_prio, cur_prio,
895                                         handler->default_boot_option
896                                                 ->option->id);
897                         handler->default_boot_option = opt;
898                         handler->default_boot_option_priority = new_prio;
899                         /* extend the timeout a little, so the user sees some
900                          * indication of the change */
901                         handler->sec_to_boot += 2;
902                 }
903
904                 return;
905         }
906
907         handler->sec_to_boot = config_get()->autoboot_timeout_sec;
908         handler->default_boot_option = opt;
909         handler->default_boot_option_priority = new_prio;
910
911         pb_log("handler: boot option %s set as default, timeout %u sec.\n",
912                opt->option->id, handler->sec_to_boot);
913
914         default_timeout(handler);
915 }
916
917 static bool resource_is_resolved(struct resource *res)
918 {
919         return !res || res->resolved;
920 }
921
922 /* We only use this in an assert, which will disappear if we're compiling
923  * with NDEBUG, so we need the 'used' attribute for these builds */
924 static bool __attribute__((used)) boot_option_is_resolved(
925                 struct discover_boot_option *opt)
926 {
927         return resource_is_resolved(opt->boot_image) &&
928                 resource_is_resolved(opt->initrd) &&
929                 resource_is_resolved(opt->dtb) &&
930                 resource_is_resolved(opt->args_sig_file) &&
931                 resource_is_resolved(opt->icon);
932 }
933
934 static bool resource_resolve(struct resource *res, const char *name,
935                 struct discover_boot_option *opt,
936                 struct device_handler *handler)
937 {
938         struct parser *parser = opt->source;
939
940         if (resource_is_resolved(res))
941                 return true;
942
943         pb_debug("Attempting to resolve resource %s->%s with parser %s\n",
944                         opt->option->id, name, parser->name);
945         parser->resolve_resource(handler, res);
946
947         return res->resolved;
948 }
949
950 static bool boot_option_resolve(struct discover_boot_option *opt,
951                 struct device_handler *handler)
952 {
953         return resource_resolve(opt->boot_image, "boot_image", opt, handler) &&
954                 resource_resolve(opt->initrd, "initrd", opt, handler) &&
955                 resource_resolve(opt->dtb, "dtb", opt, handler) &&
956                 resource_resolve(opt->args_sig_file, "args_sig_file", opt,
957                         handler) &&
958                 resource_resolve(opt->icon, "icon", opt, handler);
959 }
960
961 static void boot_option_finalise(struct device_handler *handler,
962                 struct discover_boot_option *opt)
963 {
964         assert(boot_option_is_resolved(opt));
965
966         /* check that the parsers haven't set any of the final data */
967         assert(!opt->option->boot_image_file);
968         assert(!opt->option->initrd_file);
969         assert(!opt->option->dtb_file);
970         assert(!opt->option->icon_file);
971         assert(!opt->option->device_id);
972         assert(!opt->option->args_sig_file);
973
974         if (opt->boot_image)
975                 opt->option->boot_image_file = opt->boot_image->url->full;
976         if (opt->initrd)
977                 opt->option->initrd_file = opt->initrd->url->full;
978         if (opt->dtb)
979                 opt->option->dtb_file = opt->dtb->url->full;
980         if (opt->icon)
981                 opt->option->icon_file = opt->icon->url->full;
982         if (opt->args_sig_file)
983                 opt->option->args_sig_file = opt->args_sig_file->url->full;
984
985         opt->option->device_id = opt->device->device->id;
986
987         if (opt->option->is_default)
988                 set_default(handler, opt);
989 }
990
991 static void notify_boot_option(struct device_handler *handler,
992                 struct discover_boot_option *opt)
993 {
994         struct discover_device *dev = opt->device;
995
996         if (!dev->notified)
997                 discover_server_notify_device_add(handler->server,
998                                                   opt->device->device);
999         dev->notified = true;
1000         discover_server_notify_boot_option_add(handler->server, opt->option);
1001 }
1002
1003 static void process_boot_option_queue(struct device_handler *handler)
1004 {
1005         struct discover_boot_option *opt, *tmp;
1006
1007         list_for_each_entry_safe(&handler->unresolved_boot_options,
1008                         opt, tmp, list) {
1009
1010                 pb_debug("queue: attempting resolution for %s\n",
1011                                 opt->option->id);
1012
1013                 if (!boot_option_resolve(opt, handler))
1014                         continue;
1015
1016                 pb_debug("\tresolved!\n");
1017
1018                 list_remove(&opt->list);
1019                 list_add_tail(&opt->device->boot_options, &opt->list);
1020                 talloc_steal(opt->device, opt);
1021                 boot_option_finalise(handler, opt);
1022                 notify_boot_option(handler, opt);
1023         }
1024 }
1025
1026 struct discover_context *device_handler_discover_context_create(
1027                 struct device_handler *handler,
1028                 struct discover_device *device)
1029 {
1030         struct discover_context *ctx;
1031
1032         ctx = talloc_zero(handler, struct discover_context);
1033         ctx->handler = handler;
1034         ctx->device = device;
1035         list_init(&ctx->boot_options);
1036
1037         return ctx;
1038 }
1039
1040 void device_handler_add_device(struct device_handler *handler,
1041                 struct discover_device *device)
1042 {
1043         handler->n_devices++;
1044         handler->devices = talloc_realloc(handler, handler->devices,
1045                                 struct discover_device *, handler->n_devices);
1046         handler->devices[handler->n_devices - 1] = device;
1047
1048         if (device->device->type == DEVICE_TYPE_NETWORK)
1049                 network_register_device(handler->network, device);
1050 }
1051
1052 void device_handler_add_ramdisk(struct device_handler *handler,
1053                 const char *path)
1054 {
1055         struct ramdisk_device *dev;
1056         unsigned int i;
1057
1058         if (!path)
1059                 return;
1060
1061         for (i = 0; i < handler->n_ramdisks; i++)
1062                 if (!strcmp(handler->ramdisks[i]->path, path))
1063                         return;
1064
1065         dev = talloc_zero(handler, struct ramdisk_device);
1066         if (!dev) {
1067                 pb_log("Failed to allocate memory to track %s\n", path);
1068                 return;
1069         }
1070
1071         dev->path = talloc_strdup(handler, path);
1072
1073         handler->ramdisks = talloc_realloc(handler, handler->ramdisks,
1074                                 struct ramdisk_device *,
1075                                 handler->n_ramdisks + 1);
1076         if (!handler->ramdisks) {
1077                 pb_log("Failed to reallocate memory"
1078                        "- ramdisk tracking inconsistent!\n");
1079                 return;
1080         }
1081
1082         handler->ramdisks[i] = dev;
1083         i = handler->n_ramdisks++;
1084 }
1085
1086 struct ramdisk_device *device_handler_get_ramdisk(
1087                 struct device_handler *handler)
1088 {
1089         unsigned int i;
1090         char *name;
1091         dev_t id;
1092
1093         /* Check if free ramdisk exists */
1094         for (i = 0; i < handler->n_ramdisks; i++)
1095                 if (!handler->ramdisks[i]->snapshot &&
1096                     !handler->ramdisks[i]->origin &&
1097                     !handler->ramdisks[i]->base)
1098                         return handler->ramdisks[i];
1099
1100         /* Otherwise create a new one */
1101         name = talloc_asprintf(handler, "/dev/ram%d",
1102                         handler->n_ramdisks);
1103         if (!name) {
1104                 pb_debug("Failed to allocate memory to name /dev/ram%d",
1105                         handler->n_ramdisks);
1106                 return NULL;
1107         }
1108
1109         id = makedev(1, handler->n_ramdisks);
1110         if (mknod(name, S_IFBLK, id)) {
1111                 if (errno == EEXIST) {
1112                         /* We haven't yet received updates for existing
1113                          * ramdisks - add and use this one */
1114                         pb_debug("Using untracked ramdisk %s\n", name);
1115                 } else {
1116                         pb_log("Failed to create new ramdisk %s: %s\n",
1117                                name, strerror(errno));
1118                         return NULL;
1119                 }
1120         }
1121         device_handler_add_ramdisk(handler, name);
1122         talloc_free(name);
1123
1124         return handler->ramdisks[i];
1125 }
1126
1127 void device_handler_release_ramdisk(struct discover_device *device)
1128 {
1129         struct ramdisk_device *ramdisk = device->ramdisk;
1130
1131         talloc_free(ramdisk->snapshot);
1132         talloc_free(ramdisk->origin);
1133         talloc_free(ramdisk->base);
1134
1135         ramdisk->snapshot = ramdisk->origin = ramdisk->base = NULL;
1136         ramdisk->sectors = 0;
1137
1138         device->ramdisk = NULL;
1139 }
1140
1141 /* Start discovery on a hotplugged device. The device will be in our devices
1142  * array, but has only just been initialised by the hotplug source.
1143  */
1144 int device_handler_discover(struct device_handler *handler,
1145                 struct discover_device *dev)
1146 {
1147         struct discover_context *ctx;
1148         int rc;
1149
1150         device_handler_status_dev_info(handler, dev,
1151                 /*
1152                  * TRANSLATORS: this string will be passed the type of the
1153                  * device (eg "disk" or "network"), which will be translated
1154                  * accordingly.
1155                  */
1156                 _("Processing new %s device"),
1157                 device_type_display_name(dev->device->type));
1158
1159         /* create our context */
1160         ctx = device_handler_discover_context_create(handler, dev);
1161
1162         rc = mount_device(dev);
1163         if (rc)
1164                 goto out;
1165
1166         /* add this device to our system info */
1167         system_info_register_blockdev(dev->device->id, dev->uuid,
1168                         dev->mount_path);
1169
1170         /* run the parsers. This will populate the ctx's boot_option list. */
1171         iterate_parsers(ctx);
1172
1173         /* add discovered stuff to the handler */
1174         device_handler_discover_context_commit(handler, ctx);
1175
1176         process_boot_option_queue(handler);
1177
1178         /* Check this device for pb-plugins */
1179         device_handler_plugin_scan_device(handler, dev);
1180 out:
1181         talloc_unlink(handler, ctx);
1182
1183         return 0;
1184 }
1185
1186 struct requery_data {
1187         struct device_handler   *handler;
1188         struct discover_device  *device;
1189 };
1190
1191 static int device_handler_requery_timeout_fn(void *data)
1192 {
1193         struct discover_boot_option *opt, *tmp;
1194         struct requery_data *rqd = data;
1195         struct device_handler *handler;
1196         struct discover_device *device;
1197
1198         handler = rqd->handler;
1199         device = rqd->device;
1200
1201         talloc_free(rqd);
1202
1203         /* network_requery_device may re-add a timeout, so clear the device
1204          * waiter here, so we can potentially start a new one. */
1205         device->requery_waiter = NULL;
1206
1207         /* We keep the device around, but get rid of the parsed boot
1208          * options on that device. That involves delaring out the lists,
1209          * and potentially cancelling a default.
1210          */
1211         list_for_each_entry_safe(&handler->unresolved_boot_options,
1212                         opt, tmp, list) {
1213                 if (opt->device != device)
1214                         continue;
1215                 list_remove(&opt->list);
1216                 talloc_free(opt);
1217         }
1218
1219         list_for_each_entry_safe(&device->boot_options, opt, tmp, list) {
1220                 if (opt == handler->default_boot_option) {
1221                         pb_log("Default option %s cancelled since device is being requeried",
1222                                         opt->option->name);
1223                         device_handler_cancel_default(handler);
1224                 }
1225                 list_remove(&opt->list);
1226                 talloc_free(opt);
1227         }
1228
1229         discover_server_notify_device_remove(handler->server, device->device);
1230         device->notified = false;
1231
1232         network_requery_device(handler->network, device);
1233
1234         return 0;
1235 }
1236
1237 /* Schedule a requery in timeout (seconds).
1238  *
1239  * Special values of timeout:
1240  *   0: no requery
1241  *  -1: use default
1242  */
1243 void device_handler_start_requery_timeout( struct device_handler *handler,
1244                 struct discover_device *dev, int timeout)
1245 {
1246         struct requery_data *rqd;
1247
1248         if (dev->requery_waiter)
1249                 return;
1250
1251         if (timeout == -1)
1252                 timeout = default_rescan_timeout;
1253         else if (timeout == 0)
1254                 return;
1255
1256         rqd = talloc(dev, struct requery_data);
1257         rqd->handler = handler;
1258         rqd->device = dev;
1259
1260         pb_debug("starting requery timeout for device %s, in %d sec\n",
1261                         dev->device->id, timeout);
1262
1263         dev->requery_waiter = waiter_register_timeout(handler->waitset,
1264                         timeout * 1000, device_handler_requery_timeout_fn, rqd);
1265 }
1266
1267 static int event_requery_timeout(struct event *event)
1268 {
1269         int timeout = -1;
1270         unsigned long x;
1271         const char *str;
1272         char *endp;
1273
1274         if (!event)
1275                 return timeout;
1276
1277         str = event_get_param(event, "reboottime");
1278         if (!str)
1279                 return timeout;
1280
1281         x = strtoul(str, &endp, 0);
1282         if (endp != str)
1283                 timeout = x;
1284
1285         return timeout;
1286 }
1287
1288
1289 /* Incoming dhcp event */
1290 int device_handler_dhcp(struct device_handler *handler,
1291                 struct discover_device *dev, struct event *event)
1292 {
1293         struct discover_context *ctx;
1294
1295         device_handler_status_dev_info(handler, dev,
1296                         _("Processing DHCP lease response (ip: %s)"),
1297                         event_get_param(event, "ip"));
1298
1299         pending_network_jobs_start();
1300
1301         /* create our context */
1302         ctx = device_handler_discover_context_create(handler, dev);
1303         talloc_steal(ctx, event);
1304         ctx->event = event;
1305
1306         device_handler_start_requery_timeout(handler, dev,
1307                         event_requery_timeout(event));
1308
1309         iterate_parsers(ctx);
1310
1311         device_handler_discover_context_commit(handler, ctx);
1312
1313         talloc_unlink(handler, ctx);
1314
1315         return 0;
1316 }
1317
1318 static struct discover_boot_option *find_boot_option_by_id(
1319                 struct device_handler *handler, const char *id)
1320 {
1321         unsigned int i;
1322
1323         for (i = 0; i < handler->n_devices; i++) {
1324                 struct discover_device *dev = handler->devices[i];
1325                 struct discover_boot_option *opt;
1326
1327                 list_for_each_entry(&dev->boot_options, opt, list)
1328                         if (!strcmp(opt->option->id, id))
1329                                 return opt;
1330         }
1331
1332         return NULL;
1333 }
1334
1335 void device_handler_boot(struct device_handler *handler,
1336                 struct boot_command *cmd)
1337 {
1338         struct discover_boot_option *opt = NULL;
1339
1340         if (cmd->option_id && strlen(cmd->option_id))
1341                 opt = find_boot_option_by_id(handler, cmd->option_id);
1342
1343         if (handler->pending_boot)
1344                 boot_cancel(handler->pending_boot);
1345
1346         platform_pre_boot();
1347
1348         handler->pending_boot = boot(handler, opt, cmd, handler->dry_run,
1349                         device_handler_boot_status_cb, handler);
1350         handler->pending_boot_is_default = false;
1351 }
1352
1353 void device_handler_cancel_default(struct device_handler *handler)
1354 {
1355         if (handler->timeout_waiter)
1356                 waiter_remove(handler->timeout_waiter);
1357
1358         handler->timeout_waiter = NULL;
1359         handler->autoboot_enabled = false;
1360
1361         /* we only send status if we had a default boot option queued */
1362         if (!handler->default_boot_option)
1363                 return;
1364
1365         pb_log("Cancelling default boot option\n");
1366
1367         if (handler->pending_boot && handler->pending_boot_is_default) {
1368                 boot_cancel(handler->pending_boot);
1369                 handler->pending_boot = NULL;
1370                 handler->pending_boot_is_default = false;
1371         }
1372
1373         handler->default_boot_option = NULL;
1374
1375         device_handler_status_info(handler, _("Default boot cancelled"));
1376 }
1377
1378 void device_handler_update_config(struct device_handler *handler,
1379                 struct config *config)
1380 {
1381         int rc;
1382
1383         rc = config_set(config);
1384         if (rc)
1385                 return;
1386
1387         discover_server_notify_config(handler->server, config);
1388         device_handler_update_lang(config->lang);
1389         device_handler_reinit(handler);
1390 }
1391
1392 static char *device_from_addr(void *ctx, struct pb_url *url)
1393 {
1394         char *ipaddr, *buf, *tok, *dev = NULL;
1395         const char *delim = " ";
1396         struct sockaddr_in *ip;
1397         struct sockaddr_in si;
1398         struct addrinfo *res;
1399         struct process *p;
1400         int rc;
1401
1402         /* Note: IPv4 only */
1403         rc = inet_pton(AF_INET, url->host, &(si.sin_addr));
1404         if (rc > 0) {
1405                 ipaddr = url->host;
1406         } else {
1407                 /* need to turn hostname into a valid IP */
1408                 rc = getaddrinfo(url->host, NULL, NULL, &res);
1409                 if (rc) {
1410                         pb_debug("%s: Invalid URL\n",__func__);
1411                         return NULL;
1412                 }
1413                 ipaddr = talloc_array(ctx,char,INET_ADDRSTRLEN);
1414                 ip = (struct sockaddr_in *) res->ai_addr;
1415                 inet_ntop(AF_INET, &(ip->sin_addr), ipaddr, INET_ADDRSTRLEN);
1416                 freeaddrinfo(res);
1417         }
1418
1419         const char *argv[] = {
1420                 pb_system_apps.ip,
1421                 "route", "show", "to", "match",
1422                 ipaddr,
1423                 NULL
1424         };
1425
1426         p = process_create(ctx);
1427
1428         p->path = pb_system_apps.ip;
1429         p->argv = argv;
1430         p->keep_stdout = true;
1431
1432         rc = process_run_sync(p);
1433
1434         if (rc || p->exit_status) {
1435                 /* ip has complained for some reason; most likely
1436                  * there is no route to the host - bail out */
1437                 pb_debug("%s: `ip` returns non-zero exit status\n", __func__);
1438                 pb_debug("ip buf: %s\n", p->stdout_buf);
1439                 process_release(p);
1440                 return NULL;
1441         }
1442
1443         buf = p->stdout_buf;
1444         /* If a route is found, ip-route output will be of the form
1445          * "... dev DEVNAME ... " */
1446         tok = strtok(buf, delim);
1447         while (tok) {
1448                 if (!strcmp(tok, "dev")) {
1449                         tok = strtok(NULL, delim);
1450                         dev = talloc_strdup(ctx, tok);
1451                         break;
1452                 }
1453                 tok = strtok(NULL, delim);
1454         }
1455
1456         process_release(p);
1457         if (dev)
1458                 pb_debug("%s: Found interface '%s'\n", __func__,dev);
1459         return dev;
1460 }
1461
1462 static void process_url_cb(struct load_url_result *result, void *data)
1463 {
1464         struct device_handler *handler;
1465         struct discover_context *ctx;
1466         struct discover_device *dev;
1467         struct event *event = data;
1468         const char *mac;
1469
1470         if (result->status != LOAD_OK) {
1471                 pb_log("%s: Load failed for %s\n", __func__, result->url->full);
1472                 return;
1473         }
1474
1475         if (!event)
1476                 return;
1477
1478         handler = talloc_parent(event);
1479         if (!handler)
1480                 return;
1481
1482         event->device = device_from_addr(event, result->url);
1483         if (!event->device) {
1484                 pb_log("Downloaded a file but can't find its interface - pretending it was local\n");
1485                 event->device = talloc_asprintf(event, "local");
1486         }
1487
1488         mac = event_get_param(event, "mac");
1489         char *url = talloc_asprintf(event, "file://%s", result->local);
1490         event_set_param(event, "pxeconffile-local", url);
1491
1492         dev = discover_device_create(handler, mac, event->device);
1493         ctx = device_handler_discover_context_create(handler, dev);
1494         talloc_steal(ctx, event);
1495         ctx->event = event;
1496
1497         iterate_parsers(ctx);
1498
1499         device_handler_discover_context_commit(handler, ctx);
1500
1501         talloc_unlink(handler, ctx);
1502 }
1503
1504 void device_handler_process_url(struct device_handler *handler,
1505                 const char *url, const char *mac, const char *ip)
1506 {
1507         struct discover_context *ctx;
1508         struct discover_device *dev;
1509         bool allow_async = false;
1510         struct pb_url *pb_url;
1511         struct event *event;
1512
1513         event = talloc_zero(handler, struct event);
1514         event->type = EVENT_TYPE_USER;
1515         event->action = EVENT_ACTION_URL;
1516
1517         pb_url = pb_url_parse(event, url);
1518         if (!pb_url || (pb_url->scheme != pb_url_file && !pb_url->host)) {
1519                 device_handler_status_err(handler, _("Invalid config URL!"));
1520                 talloc_free(event);
1521                 return;
1522         }
1523
1524         if (url[strlen(url) - 1] == '/') {
1525                 event_set_param(event, "pxepathprefix", url);
1526                 event_set_param(event, "mac", mac);
1527                 event_set_param(event, "ip", ip);
1528                 event->device = device_from_addr(event, pb_url);
1529                 if (!event->device) {
1530                         device_handler_status_err(handler,
1531                                         _("Unable to route to host %s"),
1532                                         pb_url->host);
1533                         talloc_free(event);
1534                         return;
1535                 }
1536         } else {
1537                 event_set_param(event, "pxeconffile", url);
1538                 allow_async = true;
1539         }
1540
1541         if (pb_url->scheme == pb_url_file)
1542                 event->device = talloc_asprintf(event, "local");
1543         else if (allow_async) {
1544                 /* If file is remote load asynchronously before passing to
1545                  * parser. This allows us to wait for network to be available */
1546                 if (!load_url_async(handler, pb_url, process_url_cb, event,
1547                                         NULL, handler)) {
1548                         pb_log("Failed to load url %s\n", pb_url->full);
1549                         device_handler_status_err(handler, _("Failed to load URL!"));
1550                         talloc_free(event);
1551                 }
1552                 return;
1553         }
1554
1555         /* If path is local we can parse straight away */
1556
1557         dev = discover_device_create(handler, mac, event->device);
1558         if (pb_url->scheme == pb_url_file)
1559                 dev->device->type = DEVICE_TYPE_ANY;
1560         ctx = device_handler_discover_context_create(handler, dev);
1561         talloc_steal(ctx, event);
1562         ctx->event = event;
1563
1564         iterate_parsers(ctx);
1565
1566         device_handler_discover_context_commit(handler, ctx);
1567
1568         talloc_unlink(handler, ctx);
1569 }
1570
1571 static void plugin_install_cb(struct process *process)
1572 {
1573         struct device_handler *handler = process->data;
1574
1575         if (!handler) {
1576                 pb_log("%s: Missing data!\n", __func__);
1577                 return;
1578         }
1579
1580         handler->plugin_installing = false;
1581         if (process->exit_status) {
1582                 device_handler_status_err(handler, "Plugin failed to install!");
1583                 pb_log("Failed to install plugin:\n%s\n", process->stdout_buf);
1584         }
1585 }
1586
1587 void device_handler_install_plugin(struct device_handler *handler,
1588                 const char *plugin_file)
1589 {
1590         struct process *p;
1591         int result;
1592
1593         if (handler->plugin_installing) {
1594                 pb_log("Plugin install cancelled - install already running");
1595                 return;
1596         }
1597
1598         p = process_create(handler);
1599         if (!p) {
1600                 pb_log("install_plugin: Failed to create process\n");
1601                 return;
1602         }
1603
1604         const char *argv[] = {
1605                 pb_system_apps.pb_plugin,
1606                 "install",
1607                 "auto",
1608                 plugin_file,
1609                 NULL
1610         };
1611
1612         p->path = pb_system_apps.pb_plugin;
1613         p->argv = argv;
1614         p->exit_cb = plugin_install_cb;
1615         p->data = handler;
1616         p->keep_stdout = true;
1617
1618         result = process_run_async(p);
1619
1620         if (result)
1621                 device_handler_status_err(handler, "Could not install plugin");
1622         else
1623                 handler->plugin_installing = true;
1624 }
1625
1626 #ifndef PETITBOOT_TEST
1627
1628 /**
1629  * context_commit - Commit a temporary discovery context to the handler,
1630  * and notify the clients about any new options / devices
1631  */
1632 void device_handler_discover_context_commit(struct device_handler *handler,
1633                 struct discover_context *ctx)
1634 {
1635         struct discover_device *dev = ctx->device;
1636         struct discover_boot_option *opt, *tmp;
1637
1638         if (!device_lookup_by_uuid(handler, dev->uuid))
1639                 device_handler_add_device(handler, dev);
1640
1641         /* move boot options from the context to the device */
1642         list_for_each_entry_safe(&ctx->boot_options, opt, tmp, list) {
1643                 list_remove(&opt->list);
1644
1645                 /* All boot options need at least a kernel image */
1646                 if (!opt->boot_image || !opt->boot_image->url) {
1647                         pb_log("boot option %s is missing boot image, ignoring\n",
1648                                 opt->option->id);
1649                         talloc_free(opt);
1650                         continue;
1651                 }
1652
1653                 if (boot_option_resolve(opt, handler)) {
1654                         pb_log("boot option %s is resolved, "
1655                                         "sending to clients\n",
1656                                         opt->option->id);
1657                         list_add_tail(&dev->boot_options, &opt->list);
1658                         talloc_steal(dev, opt);
1659                         boot_option_finalise(handler, opt);
1660                         notify_boot_option(handler, opt);
1661                 } else {
1662                         if (!opt->source->resolve_resource) {
1663                                 pb_log("parser %s gave us an unresolved "
1664                                         "resource (%s), but no way to "
1665                                         "resolve it\n",
1666                                         opt->source->name, opt->option->id);
1667                                 talloc_free(opt);
1668                         } else {
1669                                 pb_log("boot option %s is unresolved, "
1670                                                 "adding to queue\n",
1671                                                 opt->option->id);
1672                                 list_add(&handler->unresolved_boot_options,
1673                                                 &opt->list);
1674                                 talloc_steal(handler, opt);
1675                         }
1676                 }
1677         }
1678 }
1679
1680 void device_handler_add_plugin_option(struct device_handler *handler,
1681                 struct plugin_option *opt)
1682 {
1683         struct plugin_option *tmp;
1684         unsigned int i;
1685
1686         for (i = 0; i < handler->n_plugins; i++) {
1687                 tmp = handler->plugins[i];
1688                 /* If both id and version match, ignore */
1689                 if (strncmp(opt->id, tmp->id, strlen(opt->id)) == 0 &&
1690                                 strcmp(opt->version, tmp->version) == 0) {
1691                         pb_log("discover: Plugin '%s' already exists, ignoring\n",
1692                                         opt->id);
1693                         return;
1694                 }
1695         }
1696
1697         handler->plugins = talloc_realloc(handler, handler->plugins,
1698                         struct plugin_option *, handler->n_plugins + 1);
1699         if (!handler->plugins) {
1700                 pb_log("Failed to allocate memory for new plugin\n");
1701                 handler->n_plugins = 0;
1702                 return;
1703         }
1704
1705         handler->plugins[handler->n_plugins++] = opt;
1706         discover_server_notify_plugin_option_add(handler->server, opt);
1707 }
1708
1709 static void device_handler_update_lang(const char *lang)
1710 {
1711         const char *cur_lang;
1712
1713         if (!lang)
1714                 return;
1715
1716         cur_lang = setlocale(LC_ALL, NULL);
1717         if (cur_lang && !strcmp(cur_lang, lang))
1718                 return;
1719
1720         setlocale(LC_ALL, lang);
1721 }
1722
1723 static int device_handler_init_sources(struct device_handler *handler)
1724 {
1725         /* init our device sources: udev, network and user events */
1726         handler->user_event = user_event_init(handler, handler->waitset);
1727         if (!handler->user_event)
1728                 return -1;
1729
1730         handler->network = network_init(handler, handler->waitset,
1731                         handler->dry_run);
1732         if (!handler->network)
1733                 return -1;
1734
1735         handler->udev = udev_init(handler, handler->waitset);
1736         if (!handler->udev)
1737                 return -1;
1738
1739         return 0;
1740 }
1741
1742 static void device_handler_reinit_sources(struct device_handler *handler)
1743 {
1744         /* if we haven't initialised sources previously (becuase we started in
1745          * safe mode), then init once here. */
1746         if (!(handler->udev || handler->network || handler->user_event)) {
1747                 device_handler_init_sources(handler);
1748                 return;
1749         }
1750
1751         system_info_reinit();
1752
1753         network_shutdown(handler->network);
1754         handler->network = network_init(handler, handler->waitset,
1755                         handler->dry_run);
1756
1757         udev_reinit(handler->udev);
1758 }
1759
1760 static inline const char *get_device_path(struct discover_device *dev)
1761 {
1762         return dev->ramdisk ? dev->ramdisk->snapshot : dev->device_path;
1763 }
1764
1765 static char *check_subvols(struct discover_device *dev)
1766 {
1767         const char *fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1768         struct stat sb;
1769         char *path;
1770         int rc;
1771
1772         if (strncmp(fstype, "btrfs", strlen("btrfs")))
1773                 return dev->mount_path;
1774
1775         /* On btrfs a device's root may be under a subvolume path */
1776         path = join_paths(dev, dev->mount_path, "@");
1777         rc = stat(path, &sb);
1778         if (!rc && S_ISDIR(sb.st_mode)) {
1779                 pb_debug("Using '%s' for btrfs root path\n", path);
1780                 return path;
1781         }
1782
1783         talloc_free(path);
1784         return dev->mount_path;
1785 }
1786
1787 static bool check_existing_mount(struct discover_device *dev)
1788 {
1789         struct stat devstat, mntstat;
1790         const char *device_path;
1791         struct mntent *mnt;
1792         FILE *fp;
1793         int rc;
1794
1795         device_path = get_device_path(dev);
1796
1797         rc = stat(device_path, &devstat);
1798         if (rc) {
1799                 pb_debug("%s: stat failed: %s\n", __func__, strerror(errno));
1800                 return false;
1801         }
1802
1803         if (!S_ISBLK(devstat.st_mode)) {
1804                 pb_debug("%s: %s isn't a block device?\n", __func__,
1805                                 dev->device_path);
1806                 return false;
1807         }
1808
1809         fp = fopen("/proc/self/mounts", "r");
1810
1811         for (;;) {
1812                 mnt = getmntent(fp);
1813                 if (!mnt)
1814                         break;
1815
1816                 if (!mnt->mnt_fsname || mnt->mnt_fsname[0] != '/')
1817                         continue;
1818
1819                 rc = stat(mnt->mnt_fsname, &mntstat);
1820                 if (rc)
1821                         continue;
1822
1823                 if (!S_ISBLK(mntstat.st_mode))
1824                         continue;
1825
1826                 if (mntstat.st_rdev == devstat.st_rdev) {
1827                         dev->mount_path = talloc_strdup(dev, mnt->mnt_dir);
1828                         dev->root_path = check_subvols(dev);
1829                         dev->mounted_rw = !!hasmntopt(mnt, "rw");
1830                         dev->mounted = true;
1831                         dev->unmount = false;
1832
1833                         pb_debug("%s: %s is already mounted (r%c) at %s\n",
1834                                         __func__, dev->device_path,
1835                                         dev->mounted_rw ? 'w' : 'o',
1836                                         mnt->mnt_dir);
1837                         break;
1838                 }
1839         }
1840
1841         fclose(fp);
1842
1843         return mnt != NULL;
1844 }
1845
1846 /*
1847  * Attempt to mount a filesystem safely, while handling certain filesytem-
1848  * specific options
1849  */
1850 static int try_mount(const char *device_path, const char *mount_path,
1851                              const char *fstype, unsigned long flags,
1852                              bool have_snapshot)
1853 {
1854         const char *fs, *safe_opts;
1855         int rc;
1856
1857         /* Mount ext3 as ext4 instead so 'norecovery' can be used */
1858         if (strncmp(fstype, "ext3", strlen("ext3")) == 0) {
1859                 pb_debug("Mounting ext3 filesystem as ext4\n");
1860                 fs = "ext4";
1861         } else
1862                 fs = fstype;
1863
1864         if (strncmp(fs, "xfs", strlen("xfs")) == 0 ||
1865             strncmp(fs, "ext4", strlen("ext4")) == 0)
1866                 safe_opts = "norecovery";
1867         else
1868                 safe_opts = NULL;
1869
1870         errno = 0;
1871         /* If no snapshot is available don't attempt recovery */
1872         if (!have_snapshot)
1873                 return mount(device_path, mount_path, fs, flags, safe_opts);
1874
1875         rc = mount(device_path, mount_path, fs, flags, NULL);
1876
1877         if (!rc)
1878                 return rc;
1879
1880         /* Mounting failed; some filesystems will fail to mount if a recovery
1881          * journal exists (eg. cross-endian XFS), so try again with norecovery
1882          * where that option is available.
1883          * If mounting read-write just return the error as norecovery is not a
1884          * valid option */
1885         if ((flags & MS_RDONLY) != MS_RDONLY || !safe_opts)
1886                 return rc;
1887
1888         errno = 0;
1889         return mount(device_path, mount_path, fs, flags, safe_opts);
1890 }
1891
1892 static int mount_device(struct discover_device *dev)
1893 {
1894         const char *fstype, *device_path;
1895         int rc;
1896
1897         if (!dev->device_path)
1898                 return -1;
1899
1900         if (dev->mounted)
1901                 return 0;
1902
1903         if (check_existing_mount(dev))
1904                 return 0;
1905
1906         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1907         if (!fstype)
1908                 return 0;
1909
1910         dev->mount_path = join_paths(dev, mount_base(),
1911                                         dev->device_path);
1912
1913         if (pb_mkdir_recursive(dev->mount_path)) {
1914                 pb_log("couldn't create mount directory %s: %s\n",
1915                                 dev->mount_path, strerror(errno));
1916                 goto err_free;
1917         }
1918
1919         device_path = get_device_path(dev);
1920
1921         pb_log("mounting device %s read-only\n", dev->device_path);
1922         rc = try_mount(device_path, dev->mount_path, fstype,
1923                        MS_RDONLY | MS_SILENT, dev->ramdisk);
1924
1925         /* If mount fails clean up any snapshot and try again */
1926         if (rc && dev->ramdisk) {
1927                 pb_log("couldn't mount snapshot for %s: mount failed: %s\n",
1928                                 device_path, strerror(errno));
1929                 pb_log("falling back to actual device\n");
1930
1931                 devmapper_destroy_snapshot(dev);
1932
1933                 device_path = get_device_path(dev);
1934                 pb_log("mounting device %s read-only\n", dev->device_path);
1935                 rc = try_mount(device_path, dev->mount_path, fstype,
1936                                MS_RDONLY | MS_SILENT, dev->ramdisk);
1937         }
1938
1939         if (!rc) {
1940                 dev->mounted = true;
1941                 dev->mounted_rw = false;
1942                 dev->unmount = true;
1943                 dev->root_path = check_subvols(dev);
1944                 return 0;
1945         }
1946
1947         pb_log("couldn't mount device %s: mount failed: %s\n",
1948                         device_path, strerror(errno));
1949
1950         pb_rmdir_recursive(mount_base(), dev->mount_path);
1951 err_free:
1952         talloc_free(dev->mount_path);
1953         dev->mount_path = NULL;
1954         return -1;
1955 }
1956
1957 static int umount_device(struct discover_device *dev)
1958 {
1959         const char *device_path;
1960         int rc;
1961
1962         if (!dev->mounted || !dev->unmount)
1963                 return 0;
1964
1965         device_path = get_device_path(dev);
1966
1967         pb_log("unmounting device %s\n", device_path);
1968         rc = umount(dev->mount_path);
1969         if (rc)
1970                 return -1;
1971
1972         dev->mounted = false;
1973         devmapper_destroy_snapshot(dev);
1974
1975         pb_rmdir_recursive(mount_base(), dev->mount_path);
1976
1977         talloc_free(dev->mount_path);
1978         dev->mount_path = NULL;
1979         dev->root_path = NULL;
1980
1981         return 0;
1982 }
1983
1984 int device_request_write(struct discover_device *dev, bool *release)
1985 {
1986         const char *fstype, *device_path;
1987         const struct config *config;
1988         int rc;
1989
1990         *release = false;
1991
1992         config = config_get();
1993         if (!config->allow_writes)
1994                 return -1;
1995
1996         if (!dev->mounted)
1997                 return -1;
1998
1999         if (dev->mounted_rw)
2000                 return 0;
2001
2002         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
2003
2004         device_path = get_device_path(dev);
2005
2006         pb_log("remounting device %s read-write\n", device_path);
2007
2008         rc = umount(dev->mount_path);
2009         if (rc) {
2010                 pb_log("Failed to unmount %s: %s\n",
2011                        dev->mount_path, strerror(errno));
2012                 return -1;
2013         }
2014
2015         rc = try_mount(device_path, dev->mount_path, fstype,
2016                        MS_SILENT, dev->ramdisk);
2017         if (rc)
2018                 goto mount_ro;
2019
2020         dev->mounted_rw = true;
2021         *release = true;
2022         return 0;
2023
2024 mount_ro:
2025         pb_log("Unable to remount device %s read-write: %s\n",
2026                device_path, strerror(errno));
2027         rc = try_mount(device_path, dev->mount_path, fstype,
2028                        MS_RDONLY | MS_SILENT, dev->ramdisk);
2029         if (rc)
2030                 pb_log("Unable to recover mount for %s: %s\n",
2031                        device_path, strerror(errno));
2032         return -1;
2033 }
2034
2035 void device_release_write(struct discover_device *dev, bool release)
2036 {
2037         const char *fstype, *device_path;
2038
2039         if (!release)
2040                 return;
2041
2042         device_path = get_device_path(dev);
2043
2044         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
2045
2046         pb_log("remounting device %s read-only\n", device_path);
2047
2048         if (umount(dev->mount_path)) {
2049                 pb_log("Failed to unmount %s\n", dev->mount_path);
2050                 return;
2051         }
2052         dev->mounted_rw = dev->mounted = false;
2053
2054         if (dev->ramdisk) {
2055                 devmapper_merge_snapshot(dev);
2056                 /* device_path becomes stale after merge */
2057                 device_path = get_device_path(dev);
2058         }
2059
2060         if (try_mount(device_path, dev->mount_path, fstype,
2061                        MS_RDONLY | MS_SILENT, dev->ramdisk))
2062                 pb_log("Failed to remount %s read-only: %s\n",
2063                        device_path, strerror(errno));
2064         else
2065                 dev->mounted = true;
2066 }
2067
2068 void device_sync_snapshots(struct device_handler *handler, const char *device)
2069 {
2070         struct discover_device *dev = NULL;
2071         unsigned int i;
2072
2073         if (device) {
2074                 /* Find matching device and sync */
2075                 dev = device_lookup_by_name(handler, device);
2076                 if (!dev) {
2077                         pb_log("%s: device name '%s' unrecognised\n",
2078                                 __func__, device);
2079                         return;
2080                 }
2081                 if (dev->ramdisk)
2082                         device_release_write(dev, true);
2083                 else
2084                         pb_log("%s has no snapshot to merge, skipping\n",
2085                                 dev->device->id);
2086                 return;
2087         }
2088
2089         /* Otherwise sync all relevant devices */
2090         for (i = 0; i < handler->n_devices; i++) {
2091                 dev = handler->devices[i];
2092                 if (dev->device->type != DEVICE_TYPE_DISK &&
2093                         dev->device->type != DEVICE_TYPE_USB)
2094                         continue;
2095                 if (dev->ramdisk)
2096                         device_release_write(dev, true);
2097                 else
2098                         pb_log("%s has no snapshot to merge, skipping\n",
2099                                 dev->device->id);
2100         }
2101 }
2102
2103 #else
2104
2105 void device_handler_discover_context_commit(
2106                 struct device_handler *handler __attribute__((unused)),
2107                 struct discover_context *ctx __attribute__((unused)))
2108 {
2109         pb_log("%s stubbed out for test cases\n", __func__);
2110 }
2111
2112 static void device_handler_update_lang(const char *lang __attribute__((unused)))
2113 {
2114 }
2115
2116 static int device_handler_init_sources(
2117                 struct device_handler *handler __attribute__((unused)))
2118 {
2119         return 0;
2120 }
2121
2122 static void device_handler_reinit_sources(
2123                 struct device_handler *handler __attribute__((unused)))
2124 {
2125 }
2126
2127 static int umount_device(struct discover_device *dev __attribute__((unused)))
2128 {
2129         return 0;
2130 }
2131
2132 static int __attribute__((unused)) mount_device(
2133                 struct discover_device *dev __attribute__((unused)))
2134 {
2135         return 0;
2136 }
2137
2138 int device_request_write(struct discover_device *dev __attribute__((unused)),
2139                 bool *release)
2140 {
2141         *release = true;
2142         return 0;
2143 }
2144
2145 void device_release_write(struct discover_device *dev __attribute__((unused)),
2146         bool release __attribute__((unused)))
2147 {
2148 }
2149
2150 void device_sync_snapshots(
2151                 struct device_handler *handler __attribute__((unused)),
2152                 const char *device __attribute__((unused)))
2153 {
2154 }
2155
2156 #endif