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