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