]> git.ozlabs.org Git - petitboot/blob - discover/device-handler.c
discover/pxe: Format IPAPPEND mac addresses correctly
[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         ctx->network = handler->network;
630         list_init(&ctx->boot_options);
631
632         return ctx;
633 }
634
635 /**
636  * context_commit - Commit a temporary discovery context to the handler,
637  * and notify the clients about any new options / devices
638  */
639 void device_handler_discover_context_commit(struct device_handler *handler,
640                 struct discover_context *ctx)
641 {
642         struct discover_device *dev = ctx->device;
643         struct discover_boot_option *opt, *tmp;
644
645         if (!device_lookup_by_id(handler, dev->device->id))
646                 device_handler_add_device(handler, dev);
647
648         /* move boot options from the context to the device */
649         list_for_each_entry_safe(&ctx->boot_options, opt, tmp, list) {
650                 list_remove(&opt->list);
651
652                 if (boot_option_resolve(opt, handler)) {
653                         pb_log("boot option %s is resolved, "
654                                         "sending to clients\n",
655                                         opt->option->id);
656                         list_add_tail(&dev->boot_options, &opt->list);
657                         talloc_steal(dev, opt);
658                         boot_option_finalise(handler, opt);
659                         notify_boot_option(handler, opt);
660                 } else {
661                         if (!opt->source->resolve_resource) {
662                                 pb_log("parser %s gave us an unresolved "
663                                         "resource (%s), but no way to "
664                                         "resolve it\n",
665                                         opt->source->name, opt->option->id);
666                                 talloc_free(opt);
667                         } else {
668                                 pb_log("boot option %s is unresolved, "
669                                                 "adding to queue\n",
670                                                 opt->option->id);
671                                 list_add(&handler->unresolved_boot_options,
672                                                 &opt->list);
673                                 talloc_steal(handler, opt);
674                         }
675                 }
676         }
677 }
678
679 void device_handler_add_device(struct device_handler *handler,
680                 struct discover_device *device)
681 {
682         handler->n_devices++;
683         handler->devices = talloc_realloc(handler, handler->devices,
684                                 struct discover_device *, handler->n_devices);
685         handler->devices[handler->n_devices - 1] = device;
686
687         if (device->device->type == DEVICE_TYPE_NETWORK)
688                 network_register_device(handler->network, device);
689 }
690
691 /* Start discovery on a hotplugged device. The device will be in our devices
692  * array, but has only just been initialised by the hotplug source.
693  */
694 int device_handler_discover(struct device_handler *handler,
695                 struct discover_device *dev)
696 {
697         struct discover_context *ctx;
698         int rc;
699
700         process_boot_option_queue(handler);
701
702         /* create our context */
703         ctx = device_handler_discover_context_create(handler, dev);
704
705         rc = mount_device(dev);
706         if (rc)
707                 goto out;
708
709         /* add this device to our system info */
710         system_info_register_blockdev(dev->device->id, dev->uuid,
711                         dev->mount_path);
712
713         /* run the parsers. This will populate the ctx's boot_option list. */
714         iterate_parsers(ctx);
715
716         /* add discovered stuff to the handler */
717         device_handler_discover_context_commit(handler, ctx);
718
719 out:
720         talloc_free(ctx);
721
722         return 0;
723 }
724
725 /* Incoming dhcp event */
726 int device_handler_dhcp(struct device_handler *handler,
727                 struct discover_device *dev, struct event *event)
728 {
729         struct discover_context *ctx;
730
731         /* create our context */
732         ctx = device_handler_discover_context_create(handler, dev);
733         ctx->event = event;
734
735         iterate_parsers(ctx);
736
737         device_handler_discover_context_commit(handler, ctx);
738
739         talloc_free(ctx);
740
741         return 0;
742 }
743
744 /* incoming conf event */
745 int device_handler_conf(struct device_handler *handler,
746                 struct discover_device *dev, struct pb_url *url)
747 {
748         struct discover_context *ctx;
749
750         /* create our context */
751         ctx = device_handler_discover_context_create(handler, dev);
752         ctx->conf_url = url;
753
754         iterate_parsers(ctx);
755
756         device_handler_discover_context_commit(handler, ctx);
757
758         talloc_free(ctx);
759
760         return 0;
761 }
762
763 static struct discover_boot_option *find_boot_option_by_id(
764                 struct device_handler *handler, const char *id)
765 {
766         unsigned int i;
767
768         for (i = 0; i < handler->n_devices; i++) {
769                 struct discover_device *dev = handler->devices[i];
770                 struct discover_boot_option *opt;
771
772                 list_for_each_entry(&dev->boot_options, opt, list)
773                         if (!strcmp(opt->option->id, id))
774                                 return opt;
775         }
776
777         return NULL;
778 }
779
780 void device_handler_boot(struct device_handler *handler,
781                 struct boot_command *cmd)
782 {
783         struct discover_boot_option *opt = NULL;
784
785         if (cmd->option_id && strlen(cmd->option_id))
786                 opt = find_boot_option_by_id(handler, cmd->option_id);
787
788         if (handler->pending_boot)
789                 boot_cancel(handler->pending_boot);
790
791         platform_finalise_config();
792
793         handler->pending_boot = boot(handler, opt, cmd, handler->dry_run,
794                         boot_status, handler);
795         handler->pending_boot_is_default = false;
796 }
797
798 void device_handler_cancel_default(struct device_handler *handler)
799 {
800         struct boot_status status;
801
802         if (handler->timeout_waiter)
803                 waiter_remove(handler->timeout_waiter);
804
805         handler->timeout_waiter = NULL;
806         handler->autoboot_enabled = false;
807
808         /* we only send status if we had a default boot option queued */
809         if (!handler->default_boot_option)
810                 return;
811
812         pb_log("Cancelling default boot option\n");
813
814         if (handler->pending_boot && handler->pending_boot_is_default) {
815                 boot_cancel(handler->pending_boot);
816                 handler->pending_boot = NULL;
817                 handler->pending_boot_is_default = false;
818         }
819
820         handler->default_boot_option = NULL;
821
822         status.type = BOOT_STATUS_INFO;
823         status.progress = -1;
824         status.detail = NULL;
825         status.message = _("Default boot cancelled");
826
827         discover_server_notify_boot_status(handler->server, &status);
828 }
829
830 void device_handler_update_config(struct device_handler *handler,
831                 struct config *config)
832 {
833         int rc;
834
835         rc = config_set(config);
836         if (rc)
837                 return;
838
839         discover_server_notify_config(handler->server, config);
840         device_handler_update_lang(config->lang);
841         device_handler_reinit(handler);
842 }
843
844 static char *device_from_addr(void *ctx, struct pb_url *url)
845 {
846         char *ipaddr, *buf, *tok, *dev = NULL;
847         const char *delim = " ";
848         struct sockaddr_in *ip;
849         struct sockaddr_in si;
850         struct addrinfo *res;
851         struct process *p;
852         int rc;
853
854         /* Note: IPv4 only */
855         rc = inet_pton(AF_INET, url->host, &(si.sin_addr));
856         if (rc > 0) {
857                 ipaddr = url->host;
858         } else {
859                 /* need to turn hostname into a valid IP */
860                 rc = getaddrinfo(url->host, NULL, NULL, &res);
861                 if (rc) {
862                         pb_debug("%s: Invalid URL\n",__func__);
863                         return NULL;
864                 }
865                 ipaddr = talloc_array(ctx,char,INET_ADDRSTRLEN);
866                 ip = (struct sockaddr_in *) res->ai_addr;
867                 inet_ntop(AF_INET, &(ip->sin_addr), ipaddr, INET_ADDRSTRLEN);
868                 freeaddrinfo(res);
869         }
870
871         const char *argv[] = {
872                 pb_system_apps.ip,
873                 "route", "show", "to", "match",
874                 ipaddr,
875                 NULL
876         };
877
878         p = process_create(ctx);
879
880         p->path = pb_system_apps.ip;
881         p->argv = argv;
882         p->keep_stdout = true;
883
884         rc = process_run_sync(p);
885
886         if (rc) {
887                 /* ip has complained for some reason; most likely
888                  * there is no route to the host - bail out */
889                 pb_debug("%s: No route to %s\n",__func__,url->host);
890                 return NULL;
891         }
892
893         buf = p->stdout_buf;
894         /* If a route is found, ip-route output will be of the form
895          * "... dev DEVNAME ... " */
896         tok = strtok(buf, delim);
897         while (tok) {
898                 if (!strcmp(tok, "dev")) {
899                         tok = strtok(NULL, delim);
900                         dev = talloc_strdup(ctx, tok);
901                         break;
902                 }
903                 tok = strtok(NULL, delim);
904         }
905
906         process_release(p);
907         if (dev)
908                 pb_debug("%s: Found interface '%s'\n", __func__,dev);
909         return dev;
910 }
911
912
913 void device_handler_process_url(struct device_handler *handler,
914                 const char *url)
915 {
916         struct discover_context *ctx;
917         struct discover_device *dev;
918         struct boot_status *status;
919         struct pb_url *pb_url;
920         struct event *event;
921         struct param *param;
922
923         status = talloc(handler, struct boot_status);
924
925         status->type = BOOT_STATUS_ERROR;
926         status->progress = 0;
927         status->detail = talloc_asprintf(status,
928                         _("Received config URL %s"), url);
929
930         if (!handler->network) {
931                 status->message = talloc_asprintf(handler,
932                                         _("No network configured"));
933                 goto msg;
934         }
935
936         event = talloc(handler, struct event);
937         event->type = EVENT_TYPE_USER;
938         event->action = EVENT_ACTION_CONF;
939
940         event->params = talloc_array(event, struct param, 1);
941         param = &event->params[0];
942         param->name = talloc_strdup(event, "pxeconffile");
943         param->value = talloc_strdup(event, url);
944         event->n_params = 1;
945
946         pb_url = pb_url_parse(event, event->params->value);
947         if (!pb_url || !pb_url->host) {
948                 status->message = talloc_asprintf(handler,
949                                         _("Invalid config URL!"));
950                 goto msg;
951         }
952
953         event->device = device_from_addr(event, pb_url);
954         if (!event->device) {
955                 status->message = talloc_asprintf(status,
956                                         _("Unable to route to host %s"),
957                                         pb_url->host);
958                 goto msg;
959         }
960
961         dev = discover_device_create(handler, event->device);
962         ctx = device_handler_discover_context_create(handler, dev);
963         ctx->event = event;
964
965         iterate_parsers(ctx);
966
967         device_handler_discover_context_commit(handler, ctx);
968
969         talloc_free(ctx);
970
971         status->type = BOOT_STATUS_INFO;
972         status->message = talloc_asprintf(status, _("Config file %s parsed"),
973                                         pb_url->file);
974 msg:
975         boot_status(handler, status);
976         talloc_free(status);
977 }
978
979 #ifndef PETITBOOT_TEST
980
981 static void device_handler_update_lang(const char *lang)
982 {
983         const char *cur_lang;
984
985         if (!lang)
986                 return;
987
988         cur_lang = setlocale(LC_ALL, NULL);
989         if (cur_lang && !strcmp(cur_lang, lang))
990                 return;
991
992         setlocale(LC_ALL, lang);
993 }
994
995 static int device_handler_init_sources(struct device_handler *handler)
996 {
997         /* init our device sources: udev, network and user events */
998         handler->udev = udev_init(handler, handler->waitset);
999         if (!handler->udev)
1000                 return -1;
1001
1002         handler->network = network_init(handler, handler->waitset,
1003                         handler->dry_run);
1004         if (!handler->network)
1005                 return -1;
1006
1007         handler->user_event = user_event_init(handler, handler->waitset);
1008         if (!handler->user_event)
1009                 return -1;
1010
1011         return 0;
1012 }
1013
1014 static void device_handler_reinit_sources(struct device_handler *handler)
1015 {
1016         /* if we haven't initialised sources previously (becuase we started in
1017          * safe mode), then init once here. */
1018         if (!(handler->udev || handler->network || handler->user_event)) {
1019                 device_handler_init_sources(handler);
1020                 return;
1021         }
1022
1023         udev_reinit(handler->udev);
1024
1025         network_shutdown(handler->network);
1026         handler->network = network_init(handler, handler->waitset,
1027                         handler->dry_run);
1028 }
1029
1030 static bool check_existing_mount(struct discover_device *dev)
1031 {
1032         struct stat devstat, mntstat;
1033         struct mntent *mnt;
1034         FILE *fp;
1035         int rc;
1036
1037         rc = stat(dev->device_path, &devstat);
1038         if (rc) {
1039                 pb_debug("%s: stat failed: %s\n", __func__, strerror(errno));
1040                 return false;
1041         }
1042
1043         if (!S_ISBLK(devstat.st_mode)) {
1044                 pb_debug("%s: %s isn't a block device?\n", __func__,
1045                                 dev->device_path);
1046                 return false;
1047         }
1048
1049         fp = fopen("/proc/self/mounts", "r");
1050
1051         for (;;) {
1052                 mnt = getmntent(fp);
1053                 if (!mnt)
1054                         break;
1055
1056                 if (!mnt->mnt_fsname || mnt->mnt_fsname[0] != '/')
1057                         continue;
1058
1059                 rc = stat(mnt->mnt_fsname, &mntstat);
1060                 if (rc)
1061                         continue;
1062
1063                 if (!S_ISBLK(mntstat.st_mode))
1064                         continue;
1065
1066                 if (mntstat.st_rdev == devstat.st_rdev) {
1067                         dev->mount_path = talloc_strdup(dev, mnt->mnt_dir);
1068                         dev->mounted_rw = !!hasmntopt(mnt, "rw");
1069                         dev->mounted = true;
1070                         dev->unmount = false;
1071
1072                         pb_debug("%s: %s is already mounted (r%c) at %s\n",
1073                                         __func__, dev->device_path,
1074                                         dev->mounted_rw ? 'w' : 'o',
1075                                         mnt->mnt_dir);
1076                         break;
1077                 }
1078         }
1079
1080         fclose(fp);
1081
1082         return mnt != NULL;
1083 }
1084
1085 static int mount_device(struct discover_device *dev)
1086 {
1087         const char *fstype;
1088         int rc;
1089
1090         if (!dev->device_path)
1091                 return -1;
1092
1093         if (dev->mounted)
1094                 return 0;
1095
1096         if (check_existing_mount(dev))
1097                 return 0;
1098
1099         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1100         if (!fstype)
1101                 return 0;
1102
1103         dev->mount_path = join_paths(dev, mount_base(),
1104                                         dev->device_path);
1105
1106         if (pb_mkdir_recursive(dev->mount_path)) {
1107                 pb_log("couldn't create mount directory %s: %s\n",
1108                                 dev->mount_path, strerror(errno));
1109                 goto err_free;
1110         }
1111
1112         pb_log("mounting device %s read-only\n", dev->device_path);
1113         errno = 0;
1114         rc = mount(dev->device_path, dev->mount_path, fstype,
1115                         MS_RDONLY | MS_SILENT, "");
1116         if (!rc) {
1117                 dev->mounted = true;
1118                 dev->mounted_rw = false;
1119                 dev->unmount = true;
1120                 return 0;
1121         }
1122
1123         pb_log("couldn't mount device %s: mount failed: %s\n",
1124                         dev->device_path, strerror(errno));
1125
1126         pb_rmdir_recursive(mount_base(), dev->mount_path);
1127 err_free:
1128         talloc_free(dev->mount_path);
1129         dev->mount_path = NULL;
1130         return -1;
1131 }
1132
1133 static int umount_device(struct discover_device *dev)
1134 {
1135         int rc;
1136
1137         if (!dev->mounted || !dev->unmount)
1138                 return 0;
1139
1140         pb_log("unmounting device %s\n", dev->device_path);
1141         rc = umount(dev->mount_path);
1142         if (rc)
1143                 return -1;
1144
1145         dev->mounted = false;
1146
1147         pb_rmdir_recursive(mount_base(), dev->mount_path);
1148
1149         talloc_free(dev->mount_path);
1150         dev->mount_path = NULL;
1151
1152         return 0;
1153 }
1154
1155 int device_request_write(struct discover_device *dev, bool *release)
1156 {
1157         int rc;
1158
1159         *release = false;
1160
1161         if (!dev->mounted)
1162                 return -1;
1163
1164         if (dev->mounted_rw)
1165                 return 0;
1166
1167         pb_log("remounting device %s read-write\n", dev->device_path);
1168         rc = mount(dev->device_path, dev->mount_path, "",
1169                         MS_REMOUNT | MS_SILENT, "");
1170         if (rc)
1171                 return -1;
1172
1173         dev->mounted_rw = true;
1174         *release = true;
1175         return 0;
1176 }
1177
1178 void device_release_write(struct discover_device *dev, bool release)
1179 {
1180         if (!release)
1181                 return;
1182
1183         pb_log("remounting device %s read-only\n", dev->device_path);
1184         mount(dev->device_path, dev->mount_path, "",
1185                         MS_REMOUNT | MS_RDONLY | MS_SILENT, "");
1186         dev->mounted_rw = false;
1187 }
1188
1189 #else
1190
1191 static void device_handler_update_lang(const char *lang __attribute__((unused)))
1192 {
1193 }
1194
1195 static int device_handler_init_sources(
1196                 struct device_handler *handler __attribute__((unused)))
1197 {
1198         return 0;
1199 }
1200
1201 static void device_handler_reinit_sources(
1202                 struct device_handler *handler __attribute__((unused)))
1203 {
1204 }
1205
1206 static int umount_device(struct discover_device *dev __attribute__((unused)))
1207 {
1208         return 0;
1209 }
1210
1211 static int __attribute__((unused)) mount_device(
1212                 struct discover_device *dev __attribute__((unused)))
1213 {
1214         return 0;
1215 }
1216
1217 int device_request_write(struct discover_device *dev __attribute__((unused)),
1218                 bool *release)
1219 {
1220         *release = true;
1221         return 0;
1222 }
1223
1224 void device_release_write(struct discover_device *dev __attribute__((unused)),
1225         bool release __attribute__((unused)))
1226 {
1227 }
1228
1229 #endif
1230