]> git.ozlabs.org Git - petitboot/blob - discover/device-handler.c
discover/paths: Set suffix to default value on error.
[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
1195         handler = rqd->handler;
1196         device = rqd->device;
1197
1198         talloc_free(rqd);
1199
1200         /* network_requery_device may re-add a timeout, so clear the device
1201          * waiter here, so we can potentially start a new one. */
1202         device->requery_waiter = NULL;
1203
1204         /* We keep the device around, but get rid of the parsed boot
1205          * options on that device. That involves delaring out the lists,
1206          * and potentially cancelling a default.
1207          */
1208         list_for_each_entry_safe(&handler->unresolved_boot_options,
1209                         opt, tmp, list) {
1210                 if (opt->device != device)
1211                         continue;
1212                 list_remove(&opt->list);
1213                 talloc_free(opt);
1214         }
1215
1216         list_for_each_entry_safe(&device->boot_options, opt, tmp, list) {
1217                 if (opt == handler->default_boot_option) {
1218                         pb_log("Default option %s cancelled since device is being requeried",
1219                                         opt->option->name);
1220                         device_handler_cancel_default(handler);
1221                 }
1222                 list_remove(&opt->list);
1223                 talloc_free(opt);
1224         }
1225
1226         discover_server_notify_device_remove(handler->server, device->device);
1227         device->notified = false;
1228
1229         network_requery_device(handler->network, device);
1230
1231         return 0;
1232 }
1233
1234 /* Schedule a requery in timeout (seconds).
1235  *
1236  * Special values of timeout:
1237  *   0: no requery
1238  *  -1: use default
1239  */
1240 void device_handler_start_requery_timeout( struct device_handler *handler,
1241                 struct discover_device *dev, int timeout)
1242 {
1243         struct requery_data *rqd;
1244
1245         if (dev->requery_waiter)
1246                 return;
1247
1248         if (timeout == -1)
1249                 timeout = default_rescan_timeout;
1250         else if (timeout == 0)
1251                 return;
1252
1253         rqd = talloc(dev, struct requery_data);
1254         rqd->handler = handler;
1255         rqd->device = dev;
1256
1257         pb_debug("starting requery timeout for device %s, in %d sec\n",
1258                         dev->device->id, timeout);
1259
1260         dev->requery_waiter = waiter_register_timeout(handler->waitset,
1261                         timeout * 1000, device_handler_requery_timeout_fn, rqd);
1262 }
1263
1264 static int event_requery_timeout(struct event *event)
1265 {
1266         int timeout = -1;
1267         unsigned long x;
1268         const char *str;
1269         char *endp;
1270
1271         if (!event)
1272                 return timeout;
1273
1274         str = event_get_param(event, "reboottime");
1275         if (!str)
1276                 return timeout;
1277
1278         x = strtoul(str, &endp, 0);
1279         if (endp != str)
1280                 timeout = x;
1281
1282         return timeout;
1283 }
1284
1285
1286 /* Incoming dhcp event */
1287 int device_handler_dhcp(struct device_handler *handler,
1288                 struct discover_device *dev, struct event *event)
1289 {
1290         struct discover_context *ctx;
1291
1292         device_handler_status_dev_info(handler, dev,
1293                         _("Processing DHCP lease response (ip: %s)"),
1294                         event_get_param(event, "ip"));
1295
1296         pending_network_jobs_start();
1297
1298         /* create our context */
1299         ctx = device_handler_discover_context_create(handler, dev);
1300         talloc_steal(ctx, event);
1301         ctx->event = event;
1302
1303         device_handler_start_requery_timeout(handler, dev,
1304                         event_requery_timeout(event));
1305
1306         iterate_parsers(ctx);
1307
1308         device_handler_discover_context_commit(handler, ctx);
1309
1310         talloc_unlink(handler, ctx);
1311
1312         return 0;
1313 }
1314
1315 static struct discover_boot_option *find_boot_option_by_id(
1316                 struct device_handler *handler, const char *id)
1317 {
1318         unsigned int i;
1319
1320         for (i = 0; i < handler->n_devices; i++) {
1321                 struct discover_device *dev = handler->devices[i];
1322                 struct discover_boot_option *opt;
1323
1324                 list_for_each_entry(&dev->boot_options, opt, list)
1325                         if (!strcmp(opt->option->id, id))
1326                                 return opt;
1327         }
1328
1329         return NULL;
1330 }
1331
1332 void device_handler_boot(struct device_handler *handler,
1333                 struct boot_command *cmd)
1334 {
1335         struct discover_boot_option *opt = NULL;
1336
1337         if (cmd->option_id && strlen(cmd->option_id))
1338                 opt = find_boot_option_by_id(handler, cmd->option_id);
1339
1340         if (handler->pending_boot)
1341                 boot_cancel(handler->pending_boot);
1342
1343         platform_pre_boot();
1344
1345         handler->pending_boot = boot(handler, opt, cmd, handler->dry_run,
1346                         device_handler_boot_status_cb, handler);
1347         handler->pending_boot_is_default = false;
1348 }
1349
1350 void device_handler_cancel_default(struct device_handler *handler)
1351 {
1352         if (handler->timeout_waiter)
1353                 waiter_remove(handler->timeout_waiter);
1354
1355         handler->timeout_waiter = NULL;
1356         handler->autoboot_enabled = false;
1357
1358         /* we only send status if we had a default boot option queued */
1359         if (!handler->default_boot_option)
1360                 return;
1361
1362         pb_log("Cancelling default boot option\n");
1363
1364         if (handler->pending_boot && handler->pending_boot_is_default) {
1365                 boot_cancel(handler->pending_boot);
1366                 handler->pending_boot = NULL;
1367                 handler->pending_boot_is_default = false;
1368         }
1369
1370         handler->default_boot_option = NULL;
1371
1372         device_handler_status_info(handler, _("Default boot cancelled"));
1373 }
1374
1375 void device_handler_update_config(struct device_handler *handler,
1376                 struct config *config)
1377 {
1378         int rc;
1379
1380         rc = config_set(config);
1381         if (rc)
1382                 return;
1383
1384         discover_server_notify_config(handler->server, config);
1385         device_handler_update_lang(config->lang);
1386         device_handler_reinit(handler);
1387 }
1388
1389 static char *device_from_addr(void *ctx, struct pb_url *url)
1390 {
1391         char *ipaddr, *buf, *tok, *dev = NULL;
1392         const char *delim = " ";
1393         struct sockaddr_in *ip;
1394         struct sockaddr_in si;
1395         struct addrinfo *res;
1396         struct process *p;
1397         int rc;
1398
1399         /* Note: IPv4 only */
1400         rc = inet_pton(AF_INET, url->host, &(si.sin_addr));
1401         if (rc > 0) {
1402                 ipaddr = url->host;
1403         } else {
1404                 /* need to turn hostname into a valid IP */
1405                 rc = getaddrinfo(url->host, NULL, NULL, &res);
1406                 if (rc) {
1407                         pb_debug("%s: Invalid URL\n",__func__);
1408                         return NULL;
1409                 }
1410                 ipaddr = talloc_array(ctx,char,INET_ADDRSTRLEN);
1411                 ip = (struct sockaddr_in *) res->ai_addr;
1412                 inet_ntop(AF_INET, &(ip->sin_addr), ipaddr, INET_ADDRSTRLEN);
1413                 freeaddrinfo(res);
1414         }
1415
1416         const char *argv[] = {
1417                 pb_system_apps.ip,
1418                 "route", "show", "to", "match",
1419                 ipaddr,
1420                 NULL
1421         };
1422
1423         p = process_create(ctx);
1424
1425         p->path = pb_system_apps.ip;
1426         p->argv = argv;
1427         p->keep_stdout = true;
1428
1429         rc = process_run_sync(p);
1430
1431         if (rc || p->exit_status) {
1432                 /* ip has complained for some reason; most likely
1433                  * there is no route to the host - bail out */
1434                 pb_debug("%s: `ip` returns non-zero exit status\n", __func__);
1435                 pb_debug("ip buf: %s\n", p->stdout_buf);
1436                 process_release(p);
1437                 return NULL;
1438         }
1439
1440         buf = p->stdout_buf;
1441         /* If a route is found, ip-route output will be of the form
1442          * "... dev DEVNAME ... " */
1443         tok = strtok(buf, delim);
1444         while (tok) {
1445                 if (!strcmp(tok, "dev")) {
1446                         tok = strtok(NULL, delim);
1447                         dev = talloc_strdup(ctx, tok);
1448                         break;
1449                 }
1450                 tok = strtok(NULL, delim);
1451         }
1452
1453         process_release(p);
1454         if (dev)
1455                 pb_debug("%s: Found interface '%s'\n", __func__,dev);
1456         return dev;
1457 }
1458
1459 static void process_url_cb(struct load_url_result *result, void *data)
1460 {
1461         struct device_handler *handler;
1462         struct discover_context *ctx;
1463         struct discover_device *dev;
1464         struct event *event = data;
1465         const char *mac;
1466
1467         if (result->status != LOAD_OK) {
1468                 pb_log("%s: Load failed for %s\n", __func__, result->url->full);
1469                 return;
1470         }
1471
1472         if (!event)
1473                 return;
1474
1475         handler = talloc_parent(event);
1476         if (!handler)
1477                 return;
1478
1479         event->device = device_from_addr(event, result->url);
1480         if (!event->device) {
1481                 pb_log("Downloaded a file but can't find its interface - pretending it was local\n");
1482                 event->device = talloc_asprintf(event, "local");
1483         }
1484
1485         mac = event_get_param(event, "mac");
1486         char *url = talloc_asprintf(event, "file://%s", result->local);
1487         event_set_param(event, "pxeconffile-local", url);
1488
1489         dev = discover_device_create(handler, mac, event->device);
1490         ctx = device_handler_discover_context_create(handler, dev);
1491         talloc_steal(ctx, event);
1492         ctx->event = event;
1493
1494         iterate_parsers(ctx);
1495
1496         device_handler_discover_context_commit(handler, ctx);
1497
1498         talloc_unlink(handler, ctx);
1499 }
1500
1501 void device_handler_process_url(struct device_handler *handler,
1502                 const char *url, const char *mac, const char *ip)
1503 {
1504         struct discover_context *ctx;
1505         struct discover_device *dev;
1506         bool allow_async = false;
1507         struct pb_url *pb_url;
1508         struct event *event;
1509
1510         event = talloc_zero(handler, struct event);
1511         event->type = EVENT_TYPE_USER;
1512         event->action = EVENT_ACTION_URL;
1513
1514         pb_url = pb_url_parse(event, url);
1515         if (!pb_url || (pb_url->scheme != pb_url_file && !pb_url->host)) {
1516                 device_handler_status_err(handler, _("Invalid config URL!"));
1517                 talloc_free(event);
1518                 return;
1519         }
1520
1521         if (url[strlen(url) - 1] == '/') {
1522                 event_set_param(event, "pxepathprefix", url);
1523                 event_set_param(event, "mac", mac);
1524                 event_set_param(event, "ip", ip);
1525                 event->device = device_from_addr(event, pb_url);
1526                 if (!event->device) {
1527                         device_handler_status_err(handler,
1528                                         _("Unable to route to host %s"),
1529                                         pb_url->host);
1530                         talloc_free(event);
1531                         return;
1532                 }
1533         } else {
1534                 event_set_param(event, "pxeconffile", url);
1535                 allow_async = true;
1536         }
1537
1538         if (pb_url->scheme == pb_url_file)
1539                 event->device = talloc_asprintf(event, "local");
1540         else if (allow_async) {
1541                 /* If file is remote load asynchronously before passing to
1542                  * parser. This allows us to wait for network to be available */
1543                 if (!load_url_async(handler, pb_url, process_url_cb, event,
1544                                         NULL, handler)) {
1545                         pb_log("Failed to load url %s\n", pb_url->full);
1546                         device_handler_status_err(handler, _("Failed to load URL!"));
1547                         talloc_free(event);
1548                 }
1549                 return;
1550         }
1551
1552         /* If path is local we can parse straight away */
1553
1554         dev = discover_device_create(handler, mac, event->device);
1555         if (pb_url->scheme == pb_url_file)
1556                 dev->device->type = DEVICE_TYPE_ANY;
1557         ctx = device_handler_discover_context_create(handler, dev);
1558         talloc_steal(ctx, event);
1559         ctx->event = event;
1560
1561         iterate_parsers(ctx);
1562
1563         device_handler_discover_context_commit(handler, ctx);
1564
1565         talloc_unlink(handler, ctx);
1566 }
1567
1568 static void plugin_install_cb(struct process *process)
1569 {
1570         struct device_handler *handler = process->data;
1571
1572         if (!handler) {
1573                 pb_log("%s: Missing data!\n", __func__);
1574                 return;
1575         }
1576
1577         handler->plugin_installing = false;
1578         if (process->exit_status) {
1579                 device_handler_status_err(handler, "Plugin failed to install!");
1580                 pb_log("Failed to install plugin:\n%s\n", process->stdout_buf);
1581         }
1582 }
1583
1584 void device_handler_install_plugin(struct device_handler *handler,
1585                 const char *plugin_file)
1586 {
1587         struct process *p;
1588         int result;
1589
1590         if (handler->plugin_installing) {
1591                 pb_log("Plugin install cancelled - install already running");
1592                 return;
1593         }
1594
1595         p = process_create(handler);
1596         if (!p) {
1597                 pb_log("install_plugin: Failed to create process\n");
1598                 return;
1599         }
1600
1601         const char *argv[] = {
1602                 pb_system_apps.pb_plugin,
1603                 "install",
1604                 "auto",
1605                 plugin_file,
1606                 NULL
1607         };
1608
1609         p->path = pb_system_apps.pb_plugin;
1610         p->argv = argv;
1611         p->exit_cb = plugin_install_cb;
1612         p->data = handler;
1613         p->keep_stdout = true;
1614
1615         result = process_run_async(p);
1616
1617         if (result)
1618                 device_handler_status_err(handler, "Could not install plugin");
1619         else
1620                 handler->plugin_installing = true;
1621 }
1622
1623 #ifndef PETITBOOT_TEST
1624
1625 /**
1626  * context_commit - Commit a temporary discovery context to the handler,
1627  * and notify the clients about any new options / devices
1628  */
1629 void device_handler_discover_context_commit(struct device_handler *handler,
1630                 struct discover_context *ctx)
1631 {
1632         struct discover_device *dev = ctx->device;
1633         struct discover_boot_option *opt, *tmp;
1634
1635         if (!device_lookup_by_uuid(handler, dev->uuid))
1636                 device_handler_add_device(handler, dev);
1637
1638         /* move boot options from the context to the device */
1639         list_for_each_entry_safe(&ctx->boot_options, opt, tmp, list) {
1640                 list_remove(&opt->list);
1641
1642                 /* All boot options need at least a kernel image */
1643                 if (!opt->boot_image || !opt->boot_image->url) {
1644                         pb_log("boot option %s is missing boot image, ignoring\n",
1645                                 opt->option->id);
1646                         talloc_free(opt);
1647                         continue;
1648                 }
1649
1650                 if (boot_option_resolve(opt, handler)) {
1651                         pb_log("boot option %s is resolved, "
1652                                         "sending to clients\n",
1653                                         opt->option->id);
1654                         list_add_tail(&dev->boot_options, &opt->list);
1655                         talloc_steal(dev, opt);
1656                         boot_option_finalise(handler, opt);
1657                         notify_boot_option(handler, opt);
1658                 } else {
1659                         if (!opt->source->resolve_resource) {
1660                                 pb_log("parser %s gave us an unresolved "
1661                                         "resource (%s), but no way to "
1662                                         "resolve it\n",
1663                                         opt->source->name, opt->option->id);
1664                                 talloc_free(opt);
1665                         } else {
1666                                 pb_log("boot option %s is unresolved, "
1667                                                 "adding to queue\n",
1668                                                 opt->option->id);
1669                                 list_add(&handler->unresolved_boot_options,
1670                                                 &opt->list);
1671                                 talloc_steal(handler, opt);
1672                         }
1673                 }
1674         }
1675 }
1676
1677 void device_handler_add_plugin_option(struct device_handler *handler,
1678                 struct plugin_option *opt)
1679 {
1680         struct plugin_option *tmp;
1681         unsigned int i;
1682
1683         for (i = 0; i < handler->n_plugins; i++) {
1684                 tmp = handler->plugins[i];
1685                 /* If both id and version match, ignore */
1686                 if (strncmp(opt->id, tmp->id, strlen(opt->id)) == 0 &&
1687                                 strcmp(opt->version, tmp->version) == 0) {
1688                         pb_log("discover: Plugin '%s' already exists, ignoring\n",
1689                                         opt->id);
1690                         return;
1691                 }
1692         }
1693
1694         handler->plugins = talloc_realloc(handler, handler->plugins,
1695                         struct plugin_option *, handler->n_plugins + 1);
1696         if (!handler->plugins) {
1697                 pb_log("Failed to allocate memory for new plugin\n");
1698                 handler->n_plugins = 0;
1699                 return;
1700         }
1701
1702         handler->plugins[handler->n_plugins++] = opt;
1703         discover_server_notify_plugin_option_add(handler->server, opt);
1704 }
1705
1706 static void device_handler_update_lang(const char *lang)
1707 {
1708         const char *cur_lang;
1709
1710         if (!lang)
1711                 return;
1712
1713         cur_lang = setlocale(LC_ALL, NULL);
1714         if (cur_lang && !strcmp(cur_lang, lang))
1715                 return;
1716
1717         setlocale(LC_ALL, lang);
1718 }
1719
1720 static int device_handler_init_sources(struct device_handler *handler)
1721 {
1722         /* init our device sources: udev, network and user events */
1723         handler->user_event = user_event_init(handler, handler->waitset);
1724         if (!handler->user_event)
1725                 return -1;
1726
1727         handler->network = network_init(handler, handler->waitset,
1728                         handler->dry_run);
1729         if (!handler->network)
1730                 return -1;
1731
1732         handler->udev = udev_init(handler, handler->waitset);
1733         if (!handler->udev)
1734                 return -1;
1735
1736         return 0;
1737 }
1738
1739 static void device_handler_reinit_sources(struct device_handler *handler)
1740 {
1741         /* if we haven't initialised sources previously (becuase we started in
1742          * safe mode), then init once here. */
1743         if (!(handler->udev || handler->network || handler->user_event)) {
1744                 device_handler_init_sources(handler);
1745                 return;
1746         }
1747
1748         system_info_reinit();
1749
1750         network_shutdown(handler->network);
1751         handler->network = network_init(handler, handler->waitset,
1752                         handler->dry_run);
1753
1754         udev_reinit(handler->udev);
1755 }
1756
1757 static inline const char *get_device_path(struct discover_device *dev)
1758 {
1759         return dev->ramdisk ? dev->ramdisk->snapshot : dev->device_path;
1760 }
1761
1762 static char *check_subvols(struct discover_device *dev)
1763 {
1764         const char *fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1765         struct stat sb;
1766         char *path;
1767         int rc;
1768
1769         if (strncmp(fstype, "btrfs", strlen("btrfs")))
1770                 return dev->mount_path;
1771
1772         /* On btrfs a device's root may be under a subvolume path */
1773         path = join_paths(dev, dev->mount_path, "@");
1774         rc = stat(path, &sb);
1775         if (!rc && S_ISDIR(sb.st_mode)) {
1776                 pb_debug("Using '%s' for btrfs root path\n", path);
1777                 return path;
1778         }
1779
1780         talloc_free(path);
1781         return dev->mount_path;
1782 }
1783
1784 static bool check_existing_mount(struct discover_device *dev)
1785 {
1786         struct stat devstat, mntstat;
1787         const char *device_path;
1788         struct mntent *mnt;
1789         FILE *fp;
1790         int rc;
1791
1792         device_path = get_device_path(dev);
1793
1794         rc = stat(device_path, &devstat);
1795         if (rc) {
1796                 pb_debug("%s: stat failed: %s\n", __func__, strerror(errno));
1797                 return false;
1798         }
1799
1800         if (!S_ISBLK(devstat.st_mode)) {
1801                 pb_debug("%s: %s isn't a block device?\n", __func__,
1802                                 dev->device_path);
1803                 return false;
1804         }
1805
1806         fp = fopen("/proc/self/mounts", "r");
1807
1808         for (;;) {
1809                 mnt = getmntent(fp);
1810                 if (!mnt)
1811                         break;
1812
1813                 if (!mnt->mnt_fsname || mnt->mnt_fsname[0] != '/')
1814                         continue;
1815
1816                 rc = stat(mnt->mnt_fsname, &mntstat);
1817                 if (rc)
1818                         continue;
1819
1820                 if (!S_ISBLK(mntstat.st_mode))
1821                         continue;
1822
1823                 if (mntstat.st_rdev == devstat.st_rdev) {
1824                         dev->mount_path = talloc_strdup(dev, mnt->mnt_dir);
1825                         dev->root_path = check_subvols(dev);
1826                         dev->mounted_rw = !!hasmntopt(mnt, "rw");
1827                         dev->mounted = true;
1828                         dev->unmount = false;
1829
1830                         pb_debug("%s: %s is already mounted (r%c) at %s\n",
1831                                         __func__, dev->device_path,
1832                                         dev->mounted_rw ? 'w' : 'o',
1833                                         mnt->mnt_dir);
1834                         break;
1835                 }
1836         }
1837
1838         fclose(fp);
1839
1840         return mnt != NULL;
1841 }
1842
1843 /*
1844  * Attempt to mount a filesystem safely, while handling certain filesytem-
1845  * specific options
1846  */
1847 static int try_mount(const char *device_path, const char *mount_path,
1848                              const char *fstype, unsigned long flags,
1849                              bool have_snapshot)
1850 {
1851         const char *fs, *safe_opts;
1852         int rc;
1853
1854         /* Mount ext3 as ext4 instead so 'norecovery' can be used */
1855         if (strncmp(fstype, "ext3", strlen("ext3")) == 0) {
1856                 pb_debug("Mounting ext3 filesystem as ext4\n");
1857                 fs = "ext4";
1858         } else
1859                 fs = fstype;
1860
1861         if (strncmp(fs, "xfs", strlen("xfs")) == 0 ||
1862             strncmp(fs, "ext4", strlen("ext4")) == 0)
1863                 safe_opts = "norecovery";
1864         else
1865                 safe_opts = NULL;
1866
1867         errno = 0;
1868         /* If no snapshot is available don't attempt recovery */
1869         if (!have_snapshot)
1870                 return mount(device_path, mount_path, fs, flags, safe_opts);
1871
1872         rc = mount(device_path, mount_path, fs, flags, NULL);
1873
1874         if (!rc)
1875                 return rc;
1876
1877         /* Mounting failed; some filesystems will fail to mount if a recovery
1878          * journal exists (eg. cross-endian XFS), so try again with norecovery
1879          * where that option is available.
1880          * If mounting read-write just return the error as norecovery is not a
1881          * valid option */
1882         if ((flags & MS_RDONLY) != MS_RDONLY || !safe_opts)
1883                 return rc;
1884
1885         errno = 0;
1886         return mount(device_path, mount_path, fs, flags, safe_opts);
1887 }
1888
1889 static int mount_device(struct discover_device *dev)
1890 {
1891         const char *fstype, *device_path;
1892         int rc;
1893
1894         if (!dev->device_path)
1895                 return -1;
1896
1897         if (dev->mounted)
1898                 return 0;
1899
1900         if (check_existing_mount(dev))
1901                 return 0;
1902
1903         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1904         if (!fstype)
1905                 return 0;
1906
1907         dev->mount_path = join_paths(dev, mount_base(),
1908                                         dev->device_path);
1909
1910         if (pb_mkdir_recursive(dev->mount_path)) {
1911                 pb_log("couldn't create mount directory %s: %s\n",
1912                                 dev->mount_path, strerror(errno));
1913                 goto err_free;
1914         }
1915
1916         device_path = get_device_path(dev);
1917
1918         pb_log("mounting device %s read-only\n", dev->device_path);
1919         rc = try_mount(device_path, dev->mount_path, fstype,
1920                        MS_RDONLY | MS_SILENT, dev->ramdisk);
1921
1922         /* If mount fails clean up any snapshot and try again */
1923         if (rc && dev->ramdisk) {
1924                 pb_log("couldn't mount snapshot for %s: mount failed: %s\n",
1925                                 device_path, strerror(errno));
1926                 pb_log("falling back to actual device\n");
1927
1928                 devmapper_destroy_snapshot(dev);
1929
1930                 device_path = get_device_path(dev);
1931                 pb_log("mounting device %s read-only\n", dev->device_path);
1932                 rc = try_mount(device_path, dev->mount_path, fstype,
1933                                MS_RDONLY | MS_SILENT, dev->ramdisk);
1934         }
1935
1936         if (!rc) {
1937                 dev->mounted = true;
1938                 dev->mounted_rw = false;
1939                 dev->unmount = true;
1940                 dev->root_path = check_subvols(dev);
1941                 return 0;
1942         }
1943
1944         pb_log("couldn't mount device %s: mount failed: %s\n",
1945                         device_path, strerror(errno));
1946
1947         pb_rmdir_recursive(mount_base(), dev->mount_path);
1948 err_free:
1949         talloc_free(dev->mount_path);
1950         dev->mount_path = NULL;
1951         return -1;
1952 }
1953
1954 static int umount_device(struct discover_device *dev)
1955 {
1956         const char *device_path;
1957         int rc;
1958
1959         if (!dev->mounted || !dev->unmount)
1960                 return 0;
1961
1962         device_path = get_device_path(dev);
1963
1964         pb_log("unmounting device %s\n", device_path);
1965         rc = umount(dev->mount_path);
1966         if (rc)
1967                 return -1;
1968
1969         dev->mounted = false;
1970         devmapper_destroy_snapshot(dev);
1971
1972         pb_rmdir_recursive(mount_base(), dev->mount_path);
1973
1974         talloc_free(dev->mount_path);
1975         dev->mount_path = NULL;
1976         dev->root_path = NULL;
1977
1978         return 0;
1979 }
1980
1981 int device_request_write(struct discover_device *dev, bool *release)
1982 {
1983         const char *fstype, *device_path;
1984         const struct config *config;
1985         int rc;
1986
1987         *release = false;
1988
1989         config = config_get();
1990         if (!config->allow_writes)
1991                 return -1;
1992
1993         if (!dev->mounted)
1994                 return -1;
1995
1996         if (dev->mounted_rw)
1997                 return 0;
1998
1999         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
2000
2001         device_path = get_device_path(dev);
2002
2003         pb_log("remounting device %s read-write\n", device_path);
2004
2005         rc = umount(dev->mount_path);
2006         if (rc) {
2007                 pb_log("Failed to unmount %s: %s\n",
2008                        dev->mount_path, strerror(errno));
2009                 return -1;
2010         }
2011
2012         rc = try_mount(device_path, dev->mount_path, fstype,
2013                        MS_SILENT, dev->ramdisk);
2014         if (rc)
2015                 goto mount_ro;
2016
2017         dev->mounted_rw = true;
2018         *release = true;
2019         return 0;
2020
2021 mount_ro:
2022         pb_log("Unable to remount device %s read-write: %s\n",
2023                device_path, strerror(errno));
2024         rc = try_mount(device_path, dev->mount_path, fstype,
2025                        MS_RDONLY | MS_SILENT, dev->ramdisk);
2026         if (rc)
2027                 pb_log("Unable to recover mount for %s: %s\n",
2028                        device_path, strerror(errno));
2029         return -1;
2030 }
2031
2032 void device_release_write(struct discover_device *dev, bool release)
2033 {
2034         const char *fstype, *device_path;
2035
2036         if (!release)
2037                 return;
2038
2039         device_path = get_device_path(dev);
2040
2041         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
2042
2043         pb_log("remounting device %s read-only\n", device_path);
2044
2045         if (umount(dev->mount_path)) {
2046                 pb_log("Failed to unmount %s\n", dev->mount_path);
2047                 return;
2048         }
2049         dev->mounted_rw = dev->mounted = false;
2050
2051         if (dev->ramdisk) {
2052                 devmapper_merge_snapshot(dev);
2053                 /* device_path becomes stale after merge */
2054                 device_path = get_device_path(dev);
2055         }
2056
2057         if (try_mount(device_path, dev->mount_path, fstype,
2058                        MS_RDONLY | MS_SILENT, dev->ramdisk))
2059                 pb_log("Failed to remount %s read-only: %s\n",
2060                        device_path, strerror(errno));
2061         else
2062                 dev->mounted = true;
2063 }
2064
2065 void device_sync_snapshots(struct device_handler *handler, const char *device)
2066 {
2067         struct discover_device *dev = NULL;
2068         unsigned int i;
2069
2070         if (device) {
2071                 /* Find matching device and sync */
2072                 dev = device_lookup_by_name(handler, device);
2073                 if (!dev) {
2074                         pb_log("%s: device name '%s' unrecognised\n",
2075                                 __func__, device);
2076                         return;
2077                 }
2078                 if (dev->ramdisk)
2079                         device_release_write(dev, true);
2080                 else
2081                         pb_log("%s has no snapshot to merge, skipping\n",
2082                                 dev->device->id);
2083                 return;
2084         }
2085
2086         /* Otherwise sync all relevant devices */
2087         for (i = 0; i < handler->n_devices; i++) {
2088                 dev = handler->devices[i];
2089                 if (dev->device->type != DEVICE_TYPE_DISK &&
2090                         dev->device->type != DEVICE_TYPE_USB)
2091                         continue;
2092                 if (dev->ramdisk)
2093                         device_release_write(dev, true);
2094                 else
2095                         pb_log("%s has no snapshot to merge, skipping\n",
2096                                 dev->device->id);
2097         }
2098 }
2099
2100 #else
2101
2102 void device_handler_discover_context_commit(
2103                 struct device_handler *handler __attribute__((unused)),
2104                 struct discover_context *ctx __attribute__((unused)))
2105 {
2106         pb_log("%s stubbed out for test cases\n", __func__);
2107 }
2108
2109 static void device_handler_update_lang(const char *lang __attribute__((unused)))
2110 {
2111 }
2112
2113 static int device_handler_init_sources(
2114                 struct device_handler *handler __attribute__((unused)))
2115 {
2116         return 0;
2117 }
2118
2119 static void device_handler_reinit_sources(
2120                 struct device_handler *handler __attribute__((unused)))
2121 {
2122 }
2123
2124 static int umount_device(struct discover_device *dev __attribute__((unused)))
2125 {
2126         return 0;
2127 }
2128
2129 static int __attribute__((unused)) mount_device(
2130                 struct discover_device *dev __attribute__((unused)))
2131 {
2132         return 0;
2133 }
2134
2135 int device_request_write(struct discover_device *dev __attribute__((unused)),
2136                 bool *release)
2137 {
2138         *release = true;
2139         return 0;
2140 }
2141
2142 void device_release_write(struct discover_device *dev __attribute__((unused)),
2143         bool release __attribute__((unused)))
2144 {
2145 }
2146
2147 void device_sync_snapshots(
2148                 struct device_handler *handler __attribute__((unused)),
2149                 const char *device __attribute__((unused)))
2150 {
2151 }
2152
2153 #endif