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