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