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