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