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