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