discover: Mount snapshots for all eligible disk devices
[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/types.h>
23 #include <sys/socket.h>
24 #include <netdb.h>
25 #include <arpa/inet.h>
26
27 #include "device-handler.h"
28 #include "discover-server.h"
29 #include "devmapper.h"
30 #include "user-event.h"
31 #include "platform.h"
32 #include "event.h"
33 #include "parser.h"
34 #include "resource.h"
35 #include "paths.h"
36 #include "sysinfo.h"
37 #include "boot.h"
38 #include "udev.h"
39 #include "network.h"
40 #include "ipmi.h"
41
42 enum default_priority {
43         DEFAULT_PRIORITY_REMOTE         = 1,
44         DEFAULT_PRIORITY_LOCAL_FIRST    = 2,
45         DEFAULT_PRIORITY_LOCAL_LAST     = 0xfe,
46         DEFAULT_PRIORITY_DISABLED       = 0xff,
47 };
48
49 struct device_handler {
50         struct discover_server  *server;
51         int                     dry_run;
52
53         struct pb_udev          *udev;
54         struct network          *network;
55         struct user_event       *user_event;
56
57         struct discover_device  **devices;
58         unsigned int            n_devices;
59
60         struct ramdisk_device   **ramdisks;
61         unsigned int            n_ramdisks;
62
63         struct waitset          *waitset;
64         struct waiter           *timeout_waiter;
65         bool                    autoboot_enabled;
66         unsigned int            sec_to_boot;
67
68         struct discover_boot_option *default_boot_option;
69         int                     default_boot_option_priority;
70
71         struct list             unresolved_boot_options;
72
73         struct boot_task        *pending_boot;
74         bool                    pending_boot_is_default;
75 };
76
77 static int mount_device(struct discover_device *dev);
78 static int umount_device(struct discover_device *dev);
79
80 static int device_handler_init_sources(struct device_handler *handler);
81 static void device_handler_reinit_sources(struct device_handler *handler);
82
83 static void device_handler_update_lang(const char *lang);
84
85 void discover_context_add_boot_option(struct discover_context *ctx,
86                 struct discover_boot_option *boot_option)
87 {
88         boot_option->source = ctx->parser;
89         list_add_tail(&ctx->boot_options, &boot_option->list);
90         talloc_steal(ctx, boot_option);
91 }
92
93 /**
94  * device_handler_get_device_count - Get the count of current handler devices.
95  */
96
97 int device_handler_get_device_count(const struct device_handler *handler)
98 {
99         return handler->n_devices;
100 }
101
102 /**
103  * device_handler_get_device - Get a handler device by index.
104  */
105
106 const struct discover_device *device_handler_get_device(
107         const struct device_handler *handler, unsigned int index)
108 {
109         if (index >= handler->n_devices) {
110                 assert(0 && "bad index");
111                 return NULL;
112         }
113
114         return handler->devices[index];
115 }
116
117 struct discover_boot_option *discover_boot_option_create(
118                 struct discover_context *ctx,
119                 struct discover_device *device)
120 {
121         struct discover_boot_option *opt;
122
123         opt = talloc_zero(ctx, struct discover_boot_option);
124         opt->option = talloc_zero(opt, struct boot_option);
125         opt->device = device;
126
127         return opt;
128 }
129
130 static int device_match_uuid(struct discover_device *dev, const char *uuid)
131 {
132         return dev->uuid && !strcmp(dev->uuid, uuid);
133 }
134
135 static int device_match_label(struct discover_device *dev, const char *label)
136 {
137         return dev->label && !strcmp(dev->label, label);
138 }
139
140 static int device_match_id(struct discover_device *dev, const char *id)
141 {
142         return !strcmp(dev->device->id, id);
143 }
144
145 static int device_match_serial(struct discover_device *dev, const char *serial)
146 {
147         const char *val = discover_device_get_param(dev, "ID_SERIAL");
148         return val && !strcmp(val, serial);
149 }
150
151 static struct discover_device *device_lookup(
152                 struct device_handler *device_handler,
153                 int (match_fn)(struct discover_device *, const char *),
154                 const char *str)
155 {
156         struct discover_device *dev;
157         unsigned int i;
158
159         if (!str)
160                 return NULL;
161
162         for (i = 0; i < device_handler->n_devices; i++) {
163                 dev = device_handler->devices[i];
164
165                 if (match_fn(dev, str))
166                         return dev;
167         }
168
169         return NULL;
170 }
171
172 struct discover_device *device_lookup_by_name(struct device_handler *handler,
173                 const char *name)
174 {
175         if (!strncmp(name, "/dev/", strlen("/dev/")))
176                 name += strlen("/dev/");
177
178         return device_lookup_by_id(handler, name);
179 }
180
181 struct discover_device *device_lookup_by_uuid(
182                 struct device_handler *device_handler,
183                 const char *uuid)
184 {
185         return device_lookup(device_handler, device_match_uuid, uuid);
186 }
187
188 struct discover_device *device_lookup_by_label(
189                 struct device_handler *device_handler,
190                 const char *label)
191 {
192         return device_lookup(device_handler, device_match_label, label);
193 }
194
195 struct discover_device *device_lookup_by_id(
196                 struct device_handler *device_handler,
197                 const char *id)
198 {
199         return device_lookup(device_handler, device_match_id, id);
200 }
201
202 struct discover_device *device_lookup_by_serial(
203                 struct device_handler *device_handler,
204                 const char *serial)
205 {
206         return device_lookup(device_handler, device_match_serial, serial);
207 }
208
209 void device_handler_destroy(struct device_handler *handler)
210 {
211         talloc_free(handler);
212 }
213
214 static int destroy_device(void *arg)
215 {
216         struct discover_device *dev = arg;
217
218         umount_device(dev);
219
220         return 0;
221 }
222
223 struct discover_device *discover_device_create(struct device_handler *handler,
224                 const char *id)
225 {
226         struct discover_device *dev;
227
228         dev = device_lookup_by_id(handler, id);
229         if (dev)
230                 return dev;
231
232         dev = talloc_zero(handler, struct discover_device);
233         dev->device = talloc_zero(dev, struct device);
234         dev->device->id = talloc_strdup(dev->device, id);
235         list_init(&dev->params);
236         list_init(&dev->boot_options);
237
238         talloc_set_destructor(dev, destroy_device);
239
240         return dev;
241 }
242
243 struct discover_device_param {
244         char                    *name;
245         char                    *value;
246         struct list_item        list;
247 };
248
249 void discover_device_set_param(struct discover_device *device,
250                 const char *name, const char *value)
251 {
252         struct discover_device_param *param;
253         bool found = false;
254
255         list_for_each_entry(&device->params, param, list) {
256                 if (!strcmp(param->name, name)) {
257                         found = true;
258                         break;
259                 }
260         }
261
262         if (!found) {
263                 if (!value)
264                         return;
265                 param = talloc(device, struct discover_device_param);
266                 param->name = talloc_strdup(param, name);
267                 list_add(&device->params, &param->list);
268         } else {
269                 if (!value) {
270                         list_remove(&param->list);
271                         talloc_free(param);
272                         return;
273                 }
274                 talloc_free(param->value);
275         }
276
277         param->value = talloc_strdup(param, value);
278 }
279
280 const char *discover_device_get_param(struct discover_device *device,
281                 const char *name)
282 {
283         struct discover_device_param *param;
284
285         list_for_each_entry(&device->params, param, list) {
286                 if (!strcmp(param->name, name))
287                         return param->value;
288         }
289         return NULL;
290 }
291
292 struct device_handler *device_handler_init(struct discover_server *server,
293                 struct waitset *waitset, int dry_run)
294 {
295         struct device_handler *handler;
296         int rc;
297
298         handler = talloc_zero(NULL, struct device_handler);
299         handler->server = server;
300         handler->waitset = waitset;
301         handler->dry_run = dry_run;
302         handler->autoboot_enabled = config_get()->autoboot_enabled;
303
304         list_init(&handler->unresolved_boot_options);
305
306         /* set up our mount point base */
307         pb_mkdir_recursive(mount_base());
308
309         parser_init();
310
311         if (config_get()->safe_mode)
312                 return handler;
313
314         rc = device_handler_init_sources(handler);
315         if (rc) {
316                 talloc_free(handler);
317                 return NULL;
318         }
319
320         return handler;
321 }
322
323 void device_handler_reinit(struct device_handler *handler)
324 {
325         struct discover_boot_option *opt, *tmp;
326         struct ramdisk_device *ramdisk;
327         unsigned int i;
328
329         device_handler_cancel_default(handler);
330
331         /* free unresolved boot options */
332         list_for_each_entry_safe(&handler->unresolved_boot_options,
333                         opt, tmp, list)
334                 talloc_free(opt);
335         list_init(&handler->unresolved_boot_options);
336
337         /* drop all devices */
338         for (i = 0; i < handler->n_devices; i++) {
339                 discover_server_notify_device_remove(handler->server,
340                                 handler->devices[i]->device);
341                 ramdisk = handler->devices[i]->ramdisk;
342                 talloc_free(handler->devices[i]);
343                 talloc_free(ramdisk);
344         }
345
346         talloc_free(handler->devices);
347         handler->devices = NULL;
348         handler->n_devices = 0;
349         talloc_free(handler->ramdisks);
350         handler->ramdisks = NULL;
351         handler->n_ramdisks = 0;
352
353         device_handler_reinit_sources(handler);
354 }
355
356 void device_handler_remove(struct device_handler *handler,
357                 struct discover_device *device)
358 {
359         struct discover_boot_option *opt, *tmp;
360         unsigned int i;
361
362         for (i = 0; i < handler->n_devices; i++)
363                 if (handler->devices[i] == device)
364                         break;
365
366         if (i == handler->n_devices) {
367                 talloc_free(device);
368                 return;
369         }
370
371         /* Free any unresolved options, as they're currently allocated
372          * against the handler */
373         list_for_each_entry_safe(&handler->unresolved_boot_options,
374                         opt, tmp, list) {
375                 if (opt->device != device)
376                         continue;
377                 list_remove(&opt->list);
378                 talloc_free(opt);
379         }
380
381         /* if this is a network device, we have to unregister it from the
382          * network code */
383         if (device->device->type == DEVICE_TYPE_NETWORK)
384                 network_unregister_device(handler->network, device);
385
386         handler->n_devices--;
387         memmove(&handler->devices[i], &handler->devices[i + 1],
388                 (handler->n_devices - i) * sizeof(handler->devices[0]));
389         handler->devices = talloc_realloc(handler, handler->devices,
390                 struct discover_device *, handler->n_devices);
391
392         if (device->notified)
393                 discover_server_notify_device_remove(handler->server,
394                                                         device->device);
395
396         talloc_free(device);
397 }
398
399 static void boot_status(void *arg, struct boot_status *status)
400 {
401         struct device_handler *handler = arg;
402
403         discover_server_notify_boot_status(handler->server, status);
404 }
405
406 static void countdown_status(struct device_handler *handler,
407                 struct discover_boot_option *opt, unsigned int sec)
408 {
409         struct boot_status status;
410
411         status.type = BOOT_STATUS_INFO;
412         status.progress = -1;
413         status.detail = NULL;
414         status.message = talloc_asprintf(handler,
415                         _("Booting in %d sec: %s"), sec, opt->option->name);
416
417         discover_server_notify_boot_status(handler->server, &status);
418
419         talloc_free(status.message);
420 }
421
422 static int default_timeout(void *arg)
423 {
424         struct device_handler *handler = arg;
425         struct discover_boot_option *opt;
426
427         if (!handler->default_boot_option)
428                 return 0;
429
430         if (handler->pending_boot)
431                 return 0;
432
433         opt = handler->default_boot_option;
434
435         if (handler->sec_to_boot) {
436                 countdown_status(handler, opt, handler->sec_to_boot);
437                 handler->sec_to_boot--;
438                 handler->timeout_waiter = waiter_register_timeout(
439                                                 handler->waitset, 1000,
440                                                 default_timeout, handler);
441                 return 0;
442         }
443
444         handler->timeout_waiter = NULL;
445
446         pb_log("Timeout expired, booting default option %s\n", opt->option->id);
447
448         handler->pending_boot = boot(handler, handler->default_boot_option,
449                         NULL, handler->dry_run, boot_status, handler);
450         handler->pending_boot_is_default = true;
451         return 0;
452 }
453
454 struct {
455         enum ipmi_bootdev       ipmi_type;
456         enum device_type        device_type;
457 } device_type_map[] = {
458         { IPMI_BOOTDEV_NETWORK, DEVICE_TYPE_NETWORK },
459         { IPMI_BOOTDEV_DISK, DEVICE_TYPE_DISK },
460         { IPMI_BOOTDEV_CDROM, DEVICE_TYPE_OPTICAL },
461 };
462
463 static bool ipmi_device_type_matches(enum ipmi_bootdev ipmi_type,
464                 enum device_type device_type)
465 {
466         unsigned int i;
467
468         for (i = 0; i < ARRAY_SIZE(device_type_map); i++) {
469                 if (device_type_map[i].device_type == device_type)
470                         return device_type_map[i].ipmi_type == ipmi_type;
471         }
472
473         return false;
474 }
475
476 static int autoboot_option_priority(const struct config *config,
477                                 struct discover_boot_option *opt)
478 {
479         enum device_type type = opt->device->device->type;
480         const char *uuid = opt->device->uuid;
481         struct autoboot_option *auto_opt;
482         unsigned int i;
483
484         for (i = 0; i < config->n_autoboot_opts; i++) {
485                 auto_opt = &config->autoboot_opts[i];
486                 if (auto_opt->boot_type == BOOT_DEVICE_UUID)
487                         if (!strcmp(auto_opt->uuid, uuid))
488                                 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
489
490                 if (auto_opt->boot_type == BOOT_DEVICE_TYPE)
491                         if (auto_opt->type == type ||
492                             auto_opt->type == DEVICE_TYPE_ANY)
493                                 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
494         }
495
496         return -1;
497 }
498
499 /*
500  * We have different priorities to resolve conflicts between boot options that
501  * report to be the default for their device. This function assigns a priority
502  * for these options.
503  */
504 static enum default_priority default_option_priority(
505                 struct discover_boot_option *opt)
506 {
507         const struct config *config;
508
509         config = config_get();
510
511         /* We give highest priority to IPMI-configured boot options. If
512          * we have an IPMI bootdev configuration set, then we don't allow
513          * any other defaults */
514         if (config->ipmi_bootdev) {
515                 bool ipmi_match = ipmi_device_type_matches(config->ipmi_bootdev,
516                                 opt->device->device->type);
517                 if (ipmi_match)
518                         return DEFAULT_PRIORITY_REMOTE;
519
520                 pb_debug("handler: disabled default priority due to "
521                                 "non-matching IPMI type %x\n",
522                                 config->ipmi_bootdev);
523                 return DEFAULT_PRIORITY_DISABLED;
524         }
525
526         /* Next, try to match the option against the user-defined autoboot
527          * options, either by device UUID or type. */
528         if (config->n_autoboot_opts) {
529                 int boot_match = autoboot_option_priority(config, opt);
530                 if (boot_match > 0)
531                         return boot_match;
532         }
533
534         /* If the option didn't match any entry in the array, it is disabled */
535         pb_debug("handler: disabled default priority due to "
536                         "non-matching UUID or type\n");
537         return DEFAULT_PRIORITY_DISABLED;
538 }
539
540 static void set_default(struct device_handler *handler,
541                 struct discover_boot_option *opt)
542 {
543         enum default_priority cur_prio, new_prio;
544
545         if (!handler->autoboot_enabled)
546                 return;
547
548         pb_debug("handler: new default option: %s\n", opt->option->id);
549
550         new_prio = default_option_priority(opt);
551
552         /* Anything outside our range prevents a default boot */
553         if (new_prio >= DEFAULT_PRIORITY_DISABLED)
554                 return;
555
556         pb_debug("handler: calculated priority %d\n", new_prio);
557
558         /* Resolve any conflicts: if we have a new default option, it only
559          * replaces the current if it has a higher priority. */
560         if (handler->default_boot_option) {
561
562                 cur_prio = handler->default_boot_option_priority;
563
564                 if (new_prio < cur_prio) {
565                         pb_log("handler: new prio %d beats "
566                                         "old prio %d for %s\n",
567                                         new_prio, cur_prio,
568                                         handler->default_boot_option
569                                                 ->option->id);
570                         handler->default_boot_option = opt;
571                         handler->default_boot_option_priority = new_prio;
572                         /* extend the timeout a little, so the user sees some
573                          * indication of the change */
574                         handler->sec_to_boot += 2;
575                 }
576
577                 return;
578         }
579
580         handler->sec_to_boot = config_get()->autoboot_timeout_sec;
581         handler->default_boot_option = opt;
582         handler->default_boot_option_priority = new_prio;
583
584         pb_log("handler: boot option %s set as default, timeout %u sec.\n",
585                opt->option->id, handler->sec_to_boot);
586
587         default_timeout(handler);
588 }
589
590 static bool resource_is_resolved(struct resource *res)
591 {
592         return !res || res->resolved;
593 }
594
595 /* We only use this in an assert, which will disappear if we're compiling
596  * with NDEBUG, so we need the 'used' attribute for these builds */
597 static bool __attribute__((used)) boot_option_is_resolved(
598                 struct discover_boot_option *opt)
599 {
600         return resource_is_resolved(opt->boot_image) &&
601                 resource_is_resolved(opt->initrd) &&
602                 resource_is_resolved(opt->dtb) &&
603                 resource_is_resolved(opt->icon);
604 }
605
606 static bool resource_resolve(struct resource *res, const char *name,
607                 struct discover_boot_option *opt,
608                 struct device_handler *handler)
609 {
610         struct parser *parser = opt->source;
611
612         if (resource_is_resolved(res))
613                 return true;
614
615         pb_debug("Attempting to resolve resource %s->%s with parser %s\n",
616                         opt->option->id, name, parser->name);
617         parser->resolve_resource(handler, res);
618
619         return res->resolved;
620 }
621
622 static bool boot_option_resolve(struct discover_boot_option *opt,
623                 struct device_handler *handler)
624 {
625         return resource_resolve(opt->boot_image, "boot_image", opt, handler) &&
626                 resource_resolve(opt->initrd, "initrd", opt, handler) &&
627                 resource_resolve(opt->dtb, "dtb", opt, handler) &&
628                 resource_resolve(opt->icon, "icon", opt, handler);
629 }
630
631 static void boot_option_finalise(struct device_handler *handler,
632                 struct discover_boot_option *opt)
633 {
634         assert(boot_option_is_resolved(opt));
635
636         /* check that the parsers haven't set any of the final data */
637         assert(!opt->option->boot_image_file);
638         assert(!opt->option->initrd_file);
639         assert(!opt->option->dtb_file);
640         assert(!opt->option->icon_file);
641         assert(!opt->option->device_id);
642
643         if (opt->boot_image)
644                 opt->option->boot_image_file = opt->boot_image->url->full;
645         if (opt->initrd)
646                 opt->option->initrd_file = opt->initrd->url->full;
647         if (opt->dtb)
648                 opt->option->dtb_file = opt->dtb->url->full;
649         if (opt->icon)
650                 opt->option->icon_file = opt->icon->url->full;
651
652         opt->option->device_id = opt->device->device->id;
653
654         if (opt->option->is_default)
655                 set_default(handler, opt);
656 }
657
658 static void notify_boot_option(struct device_handler *handler,
659                 struct discover_boot_option *opt)
660 {
661         struct discover_device *dev = opt->device;
662
663         if (!dev->notified)
664                 discover_server_notify_device_add(handler->server,
665                                                   opt->device->device);
666         dev->notified = true;
667         discover_server_notify_boot_option_add(handler->server, opt->option);
668 }
669
670 static void process_boot_option_queue(struct device_handler *handler)
671 {
672         struct discover_boot_option *opt, *tmp;
673
674         list_for_each_entry_safe(&handler->unresolved_boot_options,
675                         opt, tmp, list) {
676
677                 pb_debug("queue: attempting resolution for %s\n",
678                                 opt->option->id);
679
680                 if (!boot_option_resolve(opt, handler))
681                         continue;
682
683                 pb_debug("\tresolved!\n");
684
685                 list_remove(&opt->list);
686                 list_add_tail(&opt->device->boot_options, &opt->list);
687                 talloc_steal(opt->device, opt);
688                 boot_option_finalise(handler, opt);
689                 notify_boot_option(handler, opt);
690         }
691 }
692
693 struct discover_context *device_handler_discover_context_create(
694                 struct device_handler *handler,
695                 struct discover_device *device)
696 {
697         struct discover_context *ctx;
698
699         ctx = talloc_zero(handler, struct discover_context);
700         ctx->device = device;
701         ctx->network = handler->network;
702         list_init(&ctx->boot_options);
703
704         return ctx;
705 }
706
707 /**
708  * context_commit - Commit a temporary discovery context to the handler,
709  * and notify the clients about any new options / devices
710  */
711 void device_handler_discover_context_commit(struct device_handler *handler,
712                 struct discover_context *ctx)
713 {
714         struct discover_device *dev = ctx->device;
715         struct discover_boot_option *opt, *tmp;
716
717         if (!device_lookup_by_id(handler, dev->device->id))
718                 device_handler_add_device(handler, dev);
719
720         /* move boot options from the context to the device */
721         list_for_each_entry_safe(&ctx->boot_options, opt, tmp, list) {
722                 list_remove(&opt->list);
723
724                 if (boot_option_resolve(opt, handler)) {
725                         pb_log("boot option %s is resolved, "
726                                         "sending to clients\n",
727                                         opt->option->id);
728                         list_add_tail(&dev->boot_options, &opt->list);
729                         talloc_steal(dev, opt);
730                         boot_option_finalise(handler, opt);
731                         notify_boot_option(handler, opt);
732                 } else {
733                         if (!opt->source->resolve_resource) {
734                                 pb_log("parser %s gave us an unresolved "
735                                         "resource (%s), but no way to "
736                                         "resolve it\n",
737                                         opt->source->name, opt->option->id);
738                                 talloc_free(opt);
739                         } else {
740                                 pb_log("boot option %s is unresolved, "
741                                                 "adding to queue\n",
742                                                 opt->option->id);
743                                 list_add(&handler->unresolved_boot_options,
744                                                 &opt->list);
745                                 talloc_steal(handler, opt);
746                         }
747                 }
748         }
749 }
750
751 void device_handler_add_device(struct device_handler *handler,
752                 struct discover_device *device)
753 {
754         handler->n_devices++;
755         handler->devices = talloc_realloc(handler, handler->devices,
756                                 struct discover_device *, handler->n_devices);
757         handler->devices[handler->n_devices - 1] = device;
758
759         if (device->device->type == DEVICE_TYPE_NETWORK)
760                 network_register_device(handler->network, device);
761 }
762
763 void device_handler_add_ramdisk(struct device_handler *handler,
764                 const char *path)
765 {
766         struct ramdisk_device *dev;
767         unsigned int i;
768
769         if (!path)
770                 return;
771
772         for (i = 0; i < handler->n_ramdisks; i++)
773                 if (!strcmp(handler->ramdisks[i]->path, path))
774                         return;
775
776         dev = talloc_zero(handler, struct ramdisk_device);
777         if (!dev) {
778                 pb_log("Failed to allocate memory to track %s\n", path);
779                 return;
780         }
781
782         dev->path = talloc_strdup(handler, path);
783
784         handler->ramdisks = talloc_realloc(handler, handler->ramdisks,
785                                 struct ramdisk_device *,
786                                 handler->n_ramdisks + 1);
787         if (!handler->ramdisks) {
788                 pb_log("Failed to reallocate memory"
789                        "- ramdisk tracking inconsistent!\n");
790                 return;
791         }
792
793         handler->ramdisks[i] = dev;
794         i = handler->n_ramdisks++;
795 }
796
797 struct ramdisk_device *device_handler_get_ramdisk(
798                 struct device_handler *handler)
799 {
800         unsigned int i;
801         char *name;
802         dev_t id;
803
804         /* Check if free ramdisk exists */
805         for (i = 0; i < handler->n_ramdisks; i++)
806                 if (!handler->ramdisks[i]->snapshot &&
807                     !handler->ramdisks[i]->origin &&
808                     !handler->ramdisks[i]->base)
809                         return handler->ramdisks[i];
810
811         /* Otherwise create a new one */
812         name = talloc_asprintf(handler, "/dev/ram%d",
813                         handler->n_ramdisks);
814         if (!name) {
815                 pb_debug("Failed to allocate memory to name /dev/ram%d",
816                         handler->n_ramdisks);
817                 return NULL;
818         }
819
820         id = makedev(1, handler->n_ramdisks);
821         if (mknod(name, S_IFBLK, id)) {
822                 if (errno == EEXIST) {
823                         /* We haven't yet received updates for existing
824                          * ramdisks - add and use this one */
825                         pb_debug("Using untracked ramdisk %s\n", name);
826                 } else {
827                         pb_log("Failed to create new ramdisk %s: %s\n",
828                                name, strerror(errno));
829                         return NULL;
830                 }
831         }
832         device_handler_add_ramdisk(handler, name);
833         talloc_free(name);
834
835         return handler->ramdisks[i];
836 }
837
838 void device_handler_release_ramdisk(struct discover_device *device)
839 {
840         struct ramdisk_device *ramdisk = device->ramdisk;
841
842         talloc_free(ramdisk->snapshot);
843         talloc_free(ramdisk->origin);
844         talloc_free(ramdisk->base);
845
846         ramdisk->snapshot = ramdisk->origin = ramdisk->base = NULL;
847         ramdisk->sectors = 0;
848
849         device->ramdisk = NULL;
850 }
851
852 /* Start discovery on a hotplugged device. The device will be in our devices
853  * array, but has only just been initialised by the hotplug source.
854  */
855 int device_handler_discover(struct device_handler *handler,
856                 struct discover_device *dev)
857 {
858         struct discover_context *ctx;
859         struct boot_status *status;
860         int rc;
861
862         status = talloc_zero(handler, struct boot_status);
863         status->type = BOOT_STATUS_INFO;
864         status->message = talloc_asprintf(status, "Processing %s device %s",
865                                 device_type_display_name(dev->device->type),
866                                 dev->device->id);
867         boot_status(handler, status);
868
869         process_boot_option_queue(handler);
870
871         /* create our context */
872         ctx = device_handler_discover_context_create(handler, dev);
873
874         rc = mount_device(dev);
875         if (rc)
876                 goto out;
877
878         /* add this device to our system info */
879         system_info_register_blockdev(dev->device->id, dev->uuid,
880                         dev->mount_path);
881
882         /* run the parsers. This will populate the ctx's boot_option list. */
883         iterate_parsers(ctx);
884
885         /* add discovered stuff to the handler */
886         device_handler_discover_context_commit(handler, ctx);
887
888 out:
889         status->message = talloc_asprintf(status,"Processing %s complete\n",
890                                 dev->device->id);
891         boot_status(handler, status);
892
893         talloc_free(status);
894         talloc_free(ctx);
895
896         return 0;
897 }
898
899 /* Incoming dhcp event */
900 int device_handler_dhcp(struct device_handler *handler,
901                 struct discover_device *dev, struct event *event)
902 {
903         struct discover_context *ctx;
904         struct boot_status *status;
905
906         status = talloc_zero(handler, struct boot_status);
907         status->type = BOOT_STATUS_INFO;
908         status->message = talloc_asprintf(status, "Processing dhcp event on %s",
909                                 dev->device->id);
910         boot_status(handler, status);
911
912         /* create our context */
913         ctx = device_handler_discover_context_create(handler, dev);
914         ctx->event = event;
915
916         iterate_parsers(ctx);
917
918         device_handler_discover_context_commit(handler, ctx);
919
920         status->message = talloc_asprintf(status,"Processing %s complete\n",
921                                 dev->device->id);
922         boot_status(handler, status);
923
924         talloc_free(status);
925         talloc_free(ctx);
926
927         return 0;
928 }
929
930 /* incoming conf event */
931 int device_handler_conf(struct device_handler *handler,
932                 struct discover_device *dev, struct pb_url *url)
933 {
934         struct discover_context *ctx;
935         struct boot_status *status;
936
937         status = talloc_zero(handler, struct boot_status);
938         status->type = BOOT_STATUS_INFO;
939         status->message = talloc_asprintf(status, "Processing user config");
940         boot_status(handler, status);
941
942         /* create our context */
943         ctx = device_handler_discover_context_create(handler, dev);
944         ctx->conf_url = url;
945
946         iterate_parsers(ctx);
947
948         device_handler_discover_context_commit(handler, ctx);
949
950         status->message = talloc_asprintf(status,
951                                 "Processing user config complete");
952         boot_status(handler, status);
953
954         talloc_free(status);
955         talloc_free(ctx);
956
957         return 0;
958 }
959
960 static struct discover_boot_option *find_boot_option_by_id(
961                 struct device_handler *handler, const char *id)
962 {
963         unsigned int i;
964
965         for (i = 0; i < handler->n_devices; i++) {
966                 struct discover_device *dev = handler->devices[i];
967                 struct discover_boot_option *opt;
968
969                 list_for_each_entry(&dev->boot_options, opt, list)
970                         if (!strcmp(opt->option->id, id))
971                                 return opt;
972         }
973
974         return NULL;
975 }
976
977 void device_handler_boot(struct device_handler *handler,
978                 struct boot_command *cmd)
979 {
980         struct discover_boot_option *opt = NULL;
981
982         if (cmd->option_id && strlen(cmd->option_id))
983                 opt = find_boot_option_by_id(handler, cmd->option_id);
984
985         if (handler->pending_boot)
986                 boot_cancel(handler->pending_boot);
987
988         platform_pre_boot();
989
990         handler->pending_boot = boot(handler, opt, cmd, handler->dry_run,
991                         boot_status, handler);
992         handler->pending_boot_is_default = false;
993 }
994
995 void device_handler_cancel_default(struct device_handler *handler)
996 {
997         struct boot_status status;
998
999         if (handler->timeout_waiter)
1000                 waiter_remove(handler->timeout_waiter);
1001
1002         handler->timeout_waiter = NULL;
1003         handler->autoboot_enabled = false;
1004
1005         /* we only send status if we had a default boot option queued */
1006         if (!handler->default_boot_option)
1007                 return;
1008
1009         pb_log("Cancelling default boot option\n");
1010
1011         if (handler->pending_boot && handler->pending_boot_is_default) {
1012                 boot_cancel(handler->pending_boot);
1013                 handler->pending_boot = NULL;
1014                 handler->pending_boot_is_default = false;
1015         }
1016
1017         handler->default_boot_option = NULL;
1018
1019         status.type = BOOT_STATUS_INFO;
1020         status.progress = -1;
1021         status.detail = NULL;
1022         status.message = _("Default boot cancelled");
1023
1024         discover_server_notify_boot_status(handler->server, &status);
1025 }
1026
1027 void device_handler_update_config(struct device_handler *handler,
1028                 struct config *config)
1029 {
1030         int rc;
1031
1032         rc = config_set(config);
1033         if (rc)
1034                 return;
1035
1036         discover_server_notify_config(handler->server, config);
1037         device_handler_update_lang(config->lang);
1038         device_handler_reinit(handler);
1039 }
1040
1041 static char *device_from_addr(void *ctx, struct pb_url *url)
1042 {
1043         char *ipaddr, *buf, *tok, *dev = NULL;
1044         const char *delim = " ";
1045         struct sockaddr_in *ip;
1046         struct sockaddr_in si;
1047         struct addrinfo *res;
1048         struct process *p;
1049         int rc;
1050
1051         /* Note: IPv4 only */
1052         rc = inet_pton(AF_INET, url->host, &(si.sin_addr));
1053         if (rc > 0) {
1054                 ipaddr = url->host;
1055         } else {
1056                 /* need to turn hostname into a valid IP */
1057                 rc = getaddrinfo(url->host, NULL, NULL, &res);
1058                 if (rc) {
1059                         pb_debug("%s: Invalid URL\n",__func__);
1060                         return NULL;
1061                 }
1062                 ipaddr = talloc_array(ctx,char,INET_ADDRSTRLEN);
1063                 ip = (struct sockaddr_in *) res->ai_addr;
1064                 inet_ntop(AF_INET, &(ip->sin_addr), ipaddr, INET_ADDRSTRLEN);
1065                 freeaddrinfo(res);
1066         }
1067
1068         const char *argv[] = {
1069                 pb_system_apps.ip,
1070                 "route", "show", "to", "match",
1071                 ipaddr,
1072                 NULL
1073         };
1074
1075         p = process_create(ctx);
1076
1077         p->path = pb_system_apps.ip;
1078         p->argv = argv;
1079         p->keep_stdout = true;
1080
1081         rc = process_run_sync(p);
1082
1083         if (rc) {
1084                 /* ip has complained for some reason; most likely
1085                  * there is no route to the host - bail out */
1086                 pb_debug("%s: No route to %s\n",__func__,url->host);
1087                 return NULL;
1088         }
1089
1090         buf = p->stdout_buf;
1091         /* If a route is found, ip-route output will be of the form
1092          * "... dev DEVNAME ... " */
1093         tok = strtok(buf, delim);
1094         while (tok) {
1095                 if (!strcmp(tok, "dev")) {
1096                         tok = strtok(NULL, delim);
1097                         dev = talloc_strdup(ctx, tok);
1098                         break;
1099                 }
1100                 tok = strtok(NULL, delim);
1101         }
1102
1103         process_release(p);
1104         if (dev)
1105                 pb_debug("%s: Found interface '%s'\n", __func__,dev);
1106         return dev;
1107 }
1108
1109
1110 void device_handler_process_url(struct device_handler *handler,
1111                 const char *url)
1112 {
1113         struct discover_context *ctx;
1114         struct discover_device *dev;
1115         struct boot_status *status;
1116         struct pb_url *pb_url;
1117         struct event *event;
1118         struct param *param;
1119
1120         status = talloc(handler, struct boot_status);
1121
1122         status->type = BOOT_STATUS_ERROR;
1123         status->progress = 0;
1124         status->detail = talloc_asprintf(status,
1125                         _("Received config URL %s"), url);
1126
1127         if (!handler->network) {
1128                 status->message = talloc_asprintf(handler,
1129                                         _("No network configured"));
1130                 goto msg;
1131         }
1132
1133         event = talloc(handler, struct event);
1134         event->type = EVENT_TYPE_USER;
1135         event->action = EVENT_ACTION_CONF;
1136
1137         event->params = talloc_array(event, struct param, 1);
1138         param = &event->params[0];
1139         param->name = talloc_strdup(event, "pxeconffile");
1140         param->value = talloc_strdup(event, url);
1141         event->n_params = 1;
1142
1143         pb_url = pb_url_parse(event, event->params->value);
1144         if (!pb_url || !pb_url->host) {
1145                 status->message = talloc_asprintf(handler,
1146                                         _("Invalid config URL!"));
1147                 goto msg;
1148         }
1149
1150         event->device = device_from_addr(event, pb_url);
1151         if (!event->device) {
1152                 status->message = talloc_asprintf(status,
1153                                         _("Unable to route to host %s"),
1154                                         pb_url->host);
1155                 goto msg;
1156         }
1157
1158         dev = discover_device_create(handler, event->device);
1159         ctx = device_handler_discover_context_create(handler, dev);
1160         ctx->event = event;
1161
1162         iterate_parsers(ctx);
1163
1164         device_handler_discover_context_commit(handler, ctx);
1165
1166         talloc_free(ctx);
1167
1168         status->type = BOOT_STATUS_INFO;
1169         status->message = talloc_asprintf(status, _("Config file %s parsed"),
1170                                         pb_url->file);
1171 msg:
1172         boot_status(handler, status);
1173         talloc_free(status);
1174 }
1175
1176 #ifndef PETITBOOT_TEST
1177
1178 static void device_handler_update_lang(const char *lang)
1179 {
1180         const char *cur_lang;
1181
1182         if (!lang)
1183                 return;
1184
1185         cur_lang = setlocale(LC_ALL, NULL);
1186         if (cur_lang && !strcmp(cur_lang, lang))
1187                 return;
1188
1189         setlocale(LC_ALL, lang);
1190 }
1191
1192 static int device_handler_init_sources(struct device_handler *handler)
1193 {
1194         /* init our device sources: udev, network and user events */
1195         handler->udev = udev_init(handler, handler->waitset);
1196         if (!handler->udev)
1197                 return -1;
1198
1199         handler->network = network_init(handler, handler->waitset,
1200                         handler->dry_run);
1201         if (!handler->network)
1202                 return -1;
1203
1204         handler->user_event = user_event_init(handler, handler->waitset);
1205         if (!handler->user_event)
1206                 return -1;
1207
1208         return 0;
1209 }
1210
1211 static void device_handler_reinit_sources(struct device_handler *handler)
1212 {
1213         /* if we haven't initialised sources previously (becuase we started in
1214          * safe mode), then init once here. */
1215         if (!(handler->udev || handler->network || handler->user_event)) {
1216                 device_handler_init_sources(handler);
1217                 return;
1218         }
1219
1220         udev_reinit(handler->udev);
1221
1222         network_shutdown(handler->network);
1223         handler->network = network_init(handler, handler->waitset,
1224                         handler->dry_run);
1225 }
1226
1227 static const char *fs_parameters(unsigned int rw_flags, const char *fstype)
1228 {
1229         if ((rw_flags | MS_RDONLY) != MS_RDONLY)
1230                 return "";
1231
1232         /* Avoid writing back to the disk on journaled filesystems */
1233         if (!strncmp(fstype, "ext4", strlen("ext4")))
1234                 return "norecovery";
1235         if (!strncmp(fstype, "xfs", strlen("xfs")))
1236                 return "norecovery";
1237
1238         return "";
1239 }
1240
1241 static inline const char *get_device_path(struct discover_device *dev)
1242 {
1243         return dev->ramdisk ? dev->ramdisk->snapshot : dev->device_path;
1244 }
1245
1246 static bool check_existing_mount(struct discover_device *dev)
1247 {
1248         struct stat devstat, mntstat;
1249         const char *device_path;
1250         struct mntent *mnt;
1251         FILE *fp;
1252         int rc;
1253
1254         device_path = get_device_path(dev);
1255
1256         rc = stat(device_path, &devstat);
1257         if (rc) {
1258                 pb_debug("%s: stat failed: %s\n", __func__, strerror(errno));
1259                 return false;
1260         }
1261
1262         if (!S_ISBLK(devstat.st_mode)) {
1263                 pb_debug("%s: %s isn't a block device?\n", __func__,
1264                                 dev->device_path);
1265                 return false;
1266         }
1267
1268         fp = fopen("/proc/self/mounts", "r");
1269
1270         for (;;) {
1271                 mnt = getmntent(fp);
1272                 if (!mnt)
1273                         break;
1274
1275                 if (!mnt->mnt_fsname || mnt->mnt_fsname[0] != '/')
1276                         continue;
1277
1278                 rc = stat(mnt->mnt_fsname, &mntstat);
1279                 if (rc)
1280                         continue;
1281
1282                 if (!S_ISBLK(mntstat.st_mode))
1283                         continue;
1284
1285                 if (mntstat.st_rdev == devstat.st_rdev) {
1286                         dev->mount_path = talloc_strdup(dev, mnt->mnt_dir);
1287                         dev->mounted_rw = !!hasmntopt(mnt, "rw");
1288                         dev->mounted = true;
1289                         dev->unmount = false;
1290
1291                         pb_debug("%s: %s is already mounted (r%c) at %s\n",
1292                                         __func__, dev->device_path,
1293                                         dev->mounted_rw ? 'w' : 'o',
1294                                         mnt->mnt_dir);
1295                         break;
1296                 }
1297         }
1298
1299         fclose(fp);
1300
1301         return mnt != NULL;
1302 }
1303
1304 static int mount_device(struct discover_device *dev)
1305 {
1306         const char *fstype, *device_path;
1307         int rc;
1308
1309         if (!dev->device_path)
1310                 return -1;
1311
1312         if (dev->mounted)
1313                 return 0;
1314
1315         if (check_existing_mount(dev))
1316                 return 0;
1317
1318         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1319         if (!fstype)
1320                 return 0;
1321
1322         /* ext3 treats the norecovery option as an error, so mount the device
1323          * as an ext4 filesystem instead */
1324         if (!strncmp(fstype, "ext3", strlen("ext3"))) {
1325                 pb_debug("Mounting ext3 filesystem as ext4\n");
1326                 fstype = talloc_asprintf(dev, "ext4");
1327         }
1328
1329         dev->mount_path = join_paths(dev, mount_base(),
1330                                         dev->device_path);
1331
1332         if (pb_mkdir_recursive(dev->mount_path)) {
1333                 pb_log("couldn't create mount directory %s: %s\n",
1334                                 dev->mount_path, strerror(errno));
1335                 goto err_free;
1336         }
1337
1338         device_path = get_device_path(dev);
1339
1340         pb_log("mounting device %s read-only\n", dev->device_path);
1341         errno = 0;
1342         rc = mount(device_path, dev->mount_path, fstype,
1343                         MS_RDONLY | MS_SILENT,
1344                         fs_parameters(MS_RDONLY, fstype));
1345         if (!rc) {
1346                 dev->mounted = true;
1347                 dev->mounted_rw = false;
1348                 dev->unmount = true;
1349                 return 0;
1350         }
1351
1352         pb_log("couldn't mount device %s: mount failed: %s\n",
1353                         device_path, strerror(errno));
1354
1355         /* If mount fails clean up any snapshot */
1356         devmapper_destroy_snapshot(dev);
1357
1358         pb_rmdir_recursive(mount_base(), dev->mount_path);
1359 err_free:
1360         talloc_free(dev->mount_path);
1361         dev->mount_path = NULL;
1362         return -1;
1363 }
1364
1365 static int umount_device(struct discover_device *dev)
1366 {
1367         const char *device_path;
1368         int rc;
1369
1370         if (!dev->mounted || !dev->unmount)
1371                 return 0;
1372
1373         device_path = get_device_path(dev);
1374
1375         pb_log("unmounting device %s\n", device_path);
1376         rc = umount(dev->mount_path);
1377         if (rc)
1378                 return -1;
1379
1380         dev->mounted = false;
1381         devmapper_destroy_snapshot(dev);
1382
1383         pb_rmdir_recursive(mount_base(), dev->mount_path);
1384
1385         talloc_free(dev->mount_path);
1386         dev->mount_path = NULL;
1387
1388         return 0;
1389 }
1390
1391 int device_request_write(struct discover_device *dev, bool *release)
1392 {
1393         const char *fstype, *device_path;
1394         int rc;
1395
1396         *release = false;
1397
1398         if (!dev->mounted)
1399                 return -1;
1400
1401         if (dev->mounted_rw)
1402                 return 0;
1403
1404         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1405
1406         device_path = get_device_path(dev);
1407
1408         pb_log("remounting device %s read-write\n", device_path);
1409
1410         rc = umount(dev->mount_path);
1411         if (rc) {
1412                 pb_log("Failed to unmount %s: %s\n",
1413                        dev->mount_path, strerror(errno));
1414                 return -1;
1415         }
1416
1417         rc = mount(device_path, dev->mount_path, fstype,
1418                         MS_SILENT,
1419                         fs_parameters(MS_REMOUNT, fstype));
1420         if (rc)
1421                 goto mount_ro;
1422
1423         dev->mounted_rw = true;
1424         *release = true;
1425         return 0;
1426
1427 mount_ro:
1428         pb_log("Unable to remount device %s read-write: %s\n",
1429                device_path, strerror(errno));
1430         if (mount(device_path, dev->mount_path, fstype,
1431                         MS_RDONLY | MS_SILENT,
1432                         fs_parameters(MS_RDONLY, fstype)))
1433                 pb_log("Unable to recover mount for %s: %s\n",
1434                        device_path, strerror(errno));
1435         return -1;
1436 }
1437
1438 void device_release_write(struct discover_device *dev, bool release)
1439 {
1440         const char *fstype, *device_path;
1441         int rc = 0;
1442
1443         if (!release)
1444                 return;
1445
1446         device_path = get_device_path(dev);
1447
1448         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1449
1450         pb_log("remounting device %s read-only\n", device_path);
1451
1452         if (umount(dev->mount_path)) {
1453                 pb_log("Failed to unmount %s\n", dev->mount_path);
1454                 return;
1455         }
1456         dev->mounted_rw = dev->mounted = false;
1457
1458         if (dev->ramdisk) {
1459                 devmapper_merge_snapshot(dev);
1460                 /* device_path becomes stale after merge */
1461                 device_path = get_device_path(dev);
1462         }
1463
1464         mount(device_path, dev->mount_path, fstype,
1465                         MS_RDONLY | MS_SILENT,
1466                         fs_parameters(MS_RDONLY, fstype));
1467         if (rc)
1468                 pb_log("Failed to remount %s read-only: %s\n",
1469                        device_path, strerror(errno));
1470         else
1471                 dev->mounted = true;
1472 }
1473
1474 #else
1475
1476 static void device_handler_update_lang(const char *lang __attribute__((unused)))
1477 {
1478 }
1479
1480 static int device_handler_init_sources(
1481                 struct device_handler *handler __attribute__((unused)))
1482 {
1483         return 0;
1484 }
1485
1486 static void device_handler_reinit_sources(
1487                 struct device_handler *handler __attribute__((unused)))
1488 {
1489 }
1490
1491 static int umount_device(struct discover_device *dev __attribute__((unused)))
1492 {
1493         return 0;
1494 }
1495
1496 static int __attribute__((unused)) mount_device(
1497                 struct discover_device *dev __attribute__((unused)))
1498 {
1499         return 0;
1500 }
1501
1502 int device_request_write(struct discover_device *dev __attribute__((unused)),
1503                 bool *release)
1504 {
1505         *release = true;
1506         return 0;
1507 }
1508
1509 void device_release_write(struct discover_device *dev __attribute__((unused)),
1510         bool release __attribute__((unused)))
1511 {
1512 }
1513
1514 #endif
1515