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