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