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