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