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