]> git.ozlabs.org Git - petitboot/blob - discover/device-handler.c
discover/device-handler: Allow process_url request to be pending
[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 static void process_url_cb(struct load_url_result *result, void *data)
1248 {
1249         struct device_handler *handler;
1250         struct discover_context *ctx;
1251         struct discover_device *dev;
1252         struct event *event = data;
1253         const char *mac;
1254
1255         if (result->status != LOAD_OK) {
1256                 pb_log("%s: Load failed for %s\n", __func__, result->url->full);
1257                 return;
1258         }
1259
1260         if (!event)
1261                 return;
1262
1263         handler = talloc_parent(event);
1264         if (!handler)
1265                 return;
1266
1267         event->device = device_from_addr(event, result->url);
1268         if (!event->device) {
1269                 pb_log("Downloaded a file but can't find its interface - pretending it was local\n");
1270                 event->device = talloc_asprintf(event, "local");
1271         }
1272
1273         mac = event_get_param(event, "mac");
1274         char *url = talloc_asprintf(event, "file://%s", result->local);
1275         event_set_param(event, "pxeconffile", url);
1276
1277         dev = discover_device_create(handler, mac, event->device);
1278         ctx = device_handler_discover_context_create(handler, dev);
1279         talloc_steal(ctx, event);
1280         ctx->event = event;
1281
1282         iterate_parsers(ctx);
1283
1284         device_handler_discover_context_commit(handler, ctx);
1285
1286         talloc_unlink(handler, ctx);
1287 }
1288
1289 void device_handler_process_url(struct device_handler *handler,
1290                 const char *url, const char *mac, const char *ip)
1291 {
1292         struct discover_context *ctx;
1293         struct discover_device *dev;
1294         bool allow_async = false;
1295         struct pb_url *pb_url;
1296         struct event *event;
1297
1298         event = talloc_zero(handler, struct event);
1299         event->type = EVENT_TYPE_USER;
1300         event->action = EVENT_ACTION_URL;
1301
1302         pb_url = pb_url_parse(event, url);
1303         if (!pb_url || (pb_url->scheme != pb_url_file && !pb_url->host)) {
1304                 device_handler_status_err(handler, _("Invalid config URL!"));
1305                 talloc_free(event);
1306                 return;
1307         }
1308
1309         if (url[strlen(url) - 1] == '/') {
1310                 event_set_param(event, "pxepathprefix", url);
1311                 event_set_param(event, "mac", mac);
1312                 event_set_param(event, "ip", ip);
1313                 event->device = device_from_addr(event, pb_url);
1314                 if (!event->device) {
1315                         device_handler_status_err(handler,
1316                                         _("Unable to route to host %s"),
1317                                         pb_url->host);
1318                         talloc_free(event);
1319                         return;
1320                 }
1321         } else {
1322                 event_set_param(event, "pxeconffile", url);
1323                 allow_async = true;
1324         }
1325
1326         if (pb_url->scheme == pb_url_file)
1327                 event->device = talloc_asprintf(event, "local");
1328         else if (allow_async) {
1329                 /* If file is remote load asynchronously before passing to
1330                  * parser. This allows us to wait for network to be available */
1331                 if (!load_url_async(handler, pb_url, process_url_cb, event,
1332                                         NULL, handler)) {
1333                         pb_log("Failed to load url %s\n", pb_url->full);
1334                         device_handler_status_err(handler, _("Failed to load URL!"));
1335                         talloc_free(event);
1336                 }
1337                 return;
1338         }
1339
1340         /* If path is local we can parse straight away */
1341
1342         dev = discover_device_create(handler, mac, event->device);
1343         if (pb_url->scheme == pb_url_file)
1344                 dev->device->type = DEVICE_TYPE_ANY;
1345         ctx = device_handler_discover_context_create(handler, dev);
1346         talloc_steal(ctx, event);
1347         ctx->event = event;
1348
1349         iterate_parsers(ctx);
1350
1351         device_handler_discover_context_commit(handler, ctx);
1352
1353         talloc_unlink(handler, ctx);
1354 }
1355
1356 #ifndef PETITBOOT_TEST
1357
1358 /**
1359  * context_commit - Commit a temporary discovery context to the handler,
1360  * and notify the clients about any new options / devices
1361  */
1362 void device_handler_discover_context_commit(struct device_handler *handler,
1363                 struct discover_context *ctx)
1364 {
1365         struct discover_device *dev = ctx->device;
1366         struct discover_boot_option *opt, *tmp;
1367
1368         if (!device_lookup_by_uuid(handler, dev->uuid))
1369                 device_handler_add_device(handler, dev);
1370
1371         /* move boot options from the context to the device */
1372         list_for_each_entry_safe(&ctx->boot_options, opt, tmp, list) {
1373                 list_remove(&opt->list);
1374
1375                 /* All boot options need at least a kernel image */
1376                 if (!opt->boot_image || !opt->boot_image->url) {
1377                         pb_log("boot option %s is missing boot image, ignoring\n",
1378                                 opt->option->id);
1379                         talloc_free(opt);
1380                         continue;
1381                 }
1382
1383                 if (boot_option_resolve(opt, handler)) {
1384                         pb_log("boot option %s is resolved, "
1385                                         "sending to clients\n",
1386                                         opt->option->id);
1387                         list_add_tail(&dev->boot_options, &opt->list);
1388                         talloc_steal(dev, opt);
1389                         boot_option_finalise(handler, opt);
1390                         notify_boot_option(handler, opt);
1391                 } else {
1392                         if (!opt->source->resolve_resource) {
1393                                 pb_log("parser %s gave us an unresolved "
1394                                         "resource (%s), but no way to "
1395                                         "resolve it\n",
1396                                         opt->source->name, opt->option->id);
1397                                 talloc_free(opt);
1398                         } else {
1399                                 pb_log("boot option %s is unresolved, "
1400                                                 "adding to queue\n",
1401                                                 opt->option->id);
1402                                 list_add(&handler->unresolved_boot_options,
1403                                                 &opt->list);
1404                                 talloc_steal(handler, opt);
1405                         }
1406                 }
1407         }
1408 }
1409
1410 static void device_handler_update_lang(const char *lang)
1411 {
1412         const char *cur_lang;
1413
1414         if (!lang)
1415                 return;
1416
1417         cur_lang = setlocale(LC_ALL, NULL);
1418         if (cur_lang && !strcmp(cur_lang, lang))
1419                 return;
1420
1421         setlocale(LC_ALL, lang);
1422 }
1423
1424 static int device_handler_init_sources(struct device_handler *handler)
1425 {
1426         /* init our device sources: udev, network and user events */
1427         handler->udev = udev_init(handler, handler->waitset);
1428         if (!handler->udev)
1429                 return -1;
1430
1431         handler->network = network_init(handler, handler->waitset,
1432                         handler->dry_run);
1433         if (!handler->network)
1434                 return -1;
1435
1436         handler->user_event = user_event_init(handler, handler->waitset);
1437         if (!handler->user_event)
1438                 return -1;
1439
1440         return 0;
1441 }
1442
1443 static void device_handler_reinit_sources(struct device_handler *handler)
1444 {
1445         /* if we haven't initialised sources previously (becuase we started in
1446          * safe mode), then init once here. */
1447         if (!(handler->udev || handler->network || handler->user_event)) {
1448                 device_handler_init_sources(handler);
1449                 return;
1450         }
1451
1452         system_info_reinit();
1453
1454         udev_reinit(handler->udev);
1455
1456         network_shutdown(handler->network);
1457         handler->network = network_init(handler, handler->waitset,
1458                         handler->dry_run);
1459 }
1460
1461 static inline const char *get_device_path(struct discover_device *dev)
1462 {
1463         return dev->ramdisk ? dev->ramdisk->snapshot : dev->device_path;
1464 }
1465
1466 static char *check_subvols(struct discover_device *dev)
1467 {
1468         const char *fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1469         struct stat sb;
1470         char *path;
1471         int rc;
1472
1473         if (strncmp(fstype, "btrfs", strlen("btrfs")))
1474                 return dev->mount_path;
1475
1476         /* On btrfs a device's root may be under a subvolume path */
1477         path = join_paths(dev, dev->mount_path, "@");
1478         rc = stat(path, &sb);
1479         if (!rc && S_ISDIR(sb.st_mode)) {
1480                 pb_debug("Using '%s' for btrfs root path\n", path);
1481                 return path;
1482         }
1483
1484         talloc_free(path);
1485         return dev->mount_path;
1486 }
1487
1488 static bool check_existing_mount(struct discover_device *dev)
1489 {
1490         struct stat devstat, mntstat;
1491         const char *device_path;
1492         struct mntent *mnt;
1493         FILE *fp;
1494         int rc;
1495
1496         device_path = get_device_path(dev);
1497
1498         rc = stat(device_path, &devstat);
1499         if (rc) {
1500                 pb_debug("%s: stat failed: %s\n", __func__, strerror(errno));
1501                 return false;
1502         }
1503
1504         if (!S_ISBLK(devstat.st_mode)) {
1505                 pb_debug("%s: %s isn't a block device?\n", __func__,
1506                                 dev->device_path);
1507                 return false;
1508         }
1509
1510         fp = fopen("/proc/self/mounts", "r");
1511
1512         for (;;) {
1513                 mnt = getmntent(fp);
1514                 if (!mnt)
1515                         break;
1516
1517                 if (!mnt->mnt_fsname || mnt->mnt_fsname[0] != '/')
1518                         continue;
1519
1520                 rc = stat(mnt->mnt_fsname, &mntstat);
1521                 if (rc)
1522                         continue;
1523
1524                 if (!S_ISBLK(mntstat.st_mode))
1525                         continue;
1526
1527                 if (mntstat.st_rdev == devstat.st_rdev) {
1528                         dev->mount_path = talloc_strdup(dev, mnt->mnt_dir);
1529                         dev->root_path = check_subvols(dev);
1530                         dev->mounted_rw = !!hasmntopt(mnt, "rw");
1531                         dev->mounted = true;
1532                         dev->unmount = false;
1533
1534                         pb_debug("%s: %s is already mounted (r%c) at %s\n",
1535                                         __func__, dev->device_path,
1536                                         dev->mounted_rw ? 'w' : 'o',
1537                                         mnt->mnt_dir);
1538                         break;
1539                 }
1540         }
1541
1542         fclose(fp);
1543
1544         return mnt != NULL;
1545 }
1546
1547 /*
1548  * Attempt to mount a filesystem safely, while handling certain filesytem-
1549  * specific options
1550  */
1551 static int try_mount(const char *device_path, const char *mount_path,
1552                              const char *fstype, unsigned long flags,
1553                              bool have_snapshot)
1554 {
1555         const char *fs, *safe_opts;
1556         int rc;
1557
1558         /* Mount ext3 as ext4 instead so 'norecovery' can be used */
1559         if (strncmp(fstype, "ext3", strlen("ext3")) == 0) {
1560                 pb_debug("Mounting ext3 filesystem as ext4\n");
1561                 fs = "ext4";
1562         } else
1563                 fs = fstype;
1564
1565         if (strncmp(fs, "xfs", strlen("xfs")) == 0 ||
1566             strncmp(fs, "ext4", strlen("ext4")) == 0)
1567                 safe_opts = "norecovery";
1568         else
1569                 safe_opts = NULL;
1570
1571         errno = 0;
1572         /* If no snapshot is available don't attempt recovery */
1573         if (!have_snapshot)
1574                 return mount(device_path, mount_path, fs, flags, safe_opts);
1575
1576         rc = mount(device_path, mount_path, fs, flags, NULL);
1577
1578         if (!rc)
1579                 return rc;
1580
1581         /* Mounting failed; some filesystems will fail to mount if a recovery
1582          * journal exists (eg. cross-endian XFS), so try again with norecovery
1583          * where that option is available.
1584          * If mounting read-write just return the error as norecovery is not a
1585          * valid option */
1586         if ((flags & MS_RDONLY) != MS_RDONLY || !safe_opts)
1587                 return rc;
1588
1589         errno = 0;
1590         return mount(device_path, mount_path, fs, flags, safe_opts);
1591 }
1592
1593 static int mount_device(struct discover_device *dev)
1594 {
1595         const char *fstype, *device_path;
1596         int rc;
1597
1598         if (!dev->device_path)
1599                 return -1;
1600
1601         if (dev->mounted)
1602                 return 0;
1603
1604         if (check_existing_mount(dev))
1605                 return 0;
1606
1607         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1608         if (!fstype)
1609                 return 0;
1610
1611         dev->mount_path = join_paths(dev, mount_base(),
1612                                         dev->device_path);
1613
1614         if (pb_mkdir_recursive(dev->mount_path)) {
1615                 pb_log("couldn't create mount directory %s: %s\n",
1616                                 dev->mount_path, strerror(errno));
1617                 goto err_free;
1618         }
1619
1620         device_path = get_device_path(dev);
1621
1622         pb_log("mounting device %s read-only\n", dev->device_path);
1623         rc = try_mount(device_path, dev->mount_path, fstype,
1624                        MS_RDONLY | MS_SILENT, dev->ramdisk);
1625
1626         if (!rc) {
1627                 dev->mounted = true;
1628                 dev->mounted_rw = false;
1629                 dev->unmount = true;
1630                 dev->root_path = check_subvols(dev);
1631                 return 0;
1632         }
1633
1634         pb_log("couldn't mount device %s: mount failed: %s\n",
1635                         device_path, strerror(errno));
1636
1637         /* If mount fails clean up any snapshot */
1638         devmapper_destroy_snapshot(dev);
1639
1640         pb_rmdir_recursive(mount_base(), dev->mount_path);
1641 err_free:
1642         talloc_free(dev->mount_path);
1643         dev->mount_path = NULL;
1644         return -1;
1645 }
1646
1647 static int umount_device(struct discover_device *dev)
1648 {
1649         const char *device_path;
1650         int rc;
1651
1652         if (!dev->mounted || !dev->unmount)
1653                 return 0;
1654
1655         device_path = get_device_path(dev);
1656
1657         pb_log("unmounting device %s\n", device_path);
1658         rc = umount(dev->mount_path);
1659         if (rc)
1660                 return -1;
1661
1662         dev->mounted = false;
1663         devmapper_destroy_snapshot(dev);
1664
1665         pb_rmdir_recursive(mount_base(), dev->mount_path);
1666
1667         talloc_free(dev->mount_path);
1668         dev->mount_path = NULL;
1669         dev->root_path = NULL;
1670
1671         return 0;
1672 }
1673
1674 int device_request_write(struct discover_device *dev, bool *release)
1675 {
1676         const char *fstype, *device_path;
1677         const struct config *config;
1678         int rc;
1679
1680         *release = false;
1681
1682         config = config_get();
1683         if (!config->allow_writes)
1684                 return -1;
1685
1686         if (!dev->mounted)
1687                 return -1;
1688
1689         if (dev->mounted_rw)
1690                 return 0;
1691
1692         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1693
1694         device_path = get_device_path(dev);
1695
1696         pb_log("remounting device %s read-write\n", device_path);
1697
1698         rc = umount(dev->mount_path);
1699         if (rc) {
1700                 pb_log("Failed to unmount %s: %s\n",
1701                        dev->mount_path, strerror(errno));
1702                 return -1;
1703         }
1704
1705         rc = try_mount(device_path, dev->mount_path, fstype,
1706                        MS_SILENT, dev->ramdisk);
1707         if (rc)
1708                 goto mount_ro;
1709
1710         dev->mounted_rw = true;
1711         *release = true;
1712         return 0;
1713
1714 mount_ro:
1715         pb_log("Unable to remount device %s read-write: %s\n",
1716                device_path, strerror(errno));
1717         rc = try_mount(device_path, dev->mount_path, fstype,
1718                        MS_RDONLY | MS_SILENT, dev->ramdisk);
1719         if (rc)
1720                 pb_log("Unable to recover mount for %s: %s\n",
1721                        device_path, strerror(errno));
1722         return -1;
1723 }
1724
1725 void device_release_write(struct discover_device *dev, bool release)
1726 {
1727         const char *fstype, *device_path;
1728
1729         if (!release)
1730                 return;
1731
1732         device_path = get_device_path(dev);
1733
1734         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1735
1736         pb_log("remounting device %s read-only\n", device_path);
1737
1738         if (umount(dev->mount_path)) {
1739                 pb_log("Failed to unmount %s\n", dev->mount_path);
1740                 return;
1741         }
1742         dev->mounted_rw = dev->mounted = false;
1743
1744         if (dev->ramdisk) {
1745                 devmapper_merge_snapshot(dev);
1746                 /* device_path becomes stale after merge */
1747                 device_path = get_device_path(dev);
1748         }
1749
1750         if (try_mount(device_path, dev->mount_path, fstype,
1751                        MS_RDONLY | MS_SILENT, dev->ramdisk))
1752                 pb_log("Failed to remount %s read-only: %s\n",
1753                        device_path, strerror(errno));
1754         else
1755                 dev->mounted = true;
1756 }
1757
1758 void device_sync_snapshots(struct device_handler *handler, const char *device)
1759 {
1760         struct discover_device *dev = NULL;
1761         unsigned int i;
1762
1763         if (device) {
1764                 /* Find matching device and sync */
1765                 dev = device_lookup_by_name(handler, device);
1766                 if (!dev) {
1767                         pb_log("%s: device name '%s' unrecognised\n",
1768                                 __func__, device);
1769                         return;
1770                 }
1771                 if (dev->ramdisk)
1772                         device_release_write(dev, true);
1773                 else
1774                         pb_log("%s has no snapshot to merge, skipping\n",
1775                                 dev->device->id);
1776                 return;
1777         }
1778
1779         /* Otherwise sync all relevant devices */
1780         for (i = 0; i < handler->n_devices; i++) {
1781                 dev = handler->devices[i];
1782                 if (dev->device->type != DEVICE_TYPE_DISK &&
1783                         dev->device->type != DEVICE_TYPE_USB)
1784                         continue;
1785                 if (dev->ramdisk)
1786                         device_release_write(dev, true);
1787                 else
1788                         pb_log("%s has no snapshot to merge, skipping\n",
1789                                 dev->device->id);
1790         }
1791 }
1792
1793 #else
1794
1795 void device_handler_discover_context_commit(
1796                 struct device_handler *handler __attribute__((unused)),
1797                 struct discover_context *ctx __attribute__((unused)))
1798 {
1799         pb_log("%s stubbed out for test cases\n", __func__);
1800 }
1801
1802 static void device_handler_update_lang(const char *lang __attribute__((unused)))
1803 {
1804 }
1805
1806 static int device_handler_init_sources(
1807                 struct device_handler *handler __attribute__((unused)))
1808 {
1809         return 0;
1810 }
1811
1812 static void device_handler_reinit_sources(
1813                 struct device_handler *handler __attribute__((unused)))
1814 {
1815 }
1816
1817 static int umount_device(struct discover_device *dev __attribute__((unused)))
1818 {
1819         return 0;
1820 }
1821
1822 static int __attribute__((unused)) mount_device(
1823                 struct discover_device *dev __attribute__((unused)))
1824 {
1825         return 0;
1826 }
1827
1828 int device_request_write(struct discover_device *dev __attribute__((unused)),
1829                 bool *release)
1830 {
1831         *release = true;
1832         return 0;
1833 }
1834
1835 void device_release_write(struct discover_device *dev __attribute__((unused)),
1836         bool release __attribute__((unused)))
1837 {
1838 }
1839
1840 void device_sync_snapshots(
1841                 struct device_handler *handler __attribute__((unused)),
1842                 const char *device __attribute__((unused)))
1843 {
1844 }
1845
1846 #endif