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