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