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