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