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