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