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