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