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