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