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