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