]> git.ozlabs.org Git - petitboot/blob - discover/device-handler.c
discover: Update env vars at init and suppress LVM warnings
[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/sysmacros.h>
23 #include <sys/types.h>
24 #include <sys/socket.h>
25 #include <netdb.h>
26 #include <arpa/inet.h>
27
28 #include "device-handler.h"
29 #include "discover-server.h"
30 #include "devmapper.h"
31 #include "user-event.h"
32 #include "platform.h"
33 #include "event.h"
34 #include "parser.h"
35 #include "resource.h"
36 #include "paths.h"
37 #include "sysinfo.h"
38 #include "boot.h"
39 #include "udev.h"
40 #include "network.h"
41 #include "ipmi.h"
42
43 enum default_priority {
44         DEFAULT_PRIORITY_REMOTE         = 1,
45         DEFAULT_PRIORITY_LOCAL_FIRST    = 2,
46         DEFAULT_PRIORITY_LOCAL_LAST     = 0xfe,
47         DEFAULT_PRIORITY_DISABLED       = 0xff,
48 };
49
50 struct progress_info {
51         unsigned int                    percentage;
52         unsigned long                   size;           /* size in bytes */
53
54         const struct process_info       *procinfo;
55         struct list_item        list;
56 };
57
58 struct device_handler {
59         struct discover_server  *server;
60         int                     dry_run;
61
62         struct pb_udev          *udev;
63         struct network          *network;
64         struct user_event       *user_event;
65
66         struct discover_device  **devices;
67         unsigned int            n_devices;
68
69         struct ramdisk_device   **ramdisks;
70         unsigned int            n_ramdisks;
71
72         struct waitset          *waitset;
73         struct waiter           *timeout_waiter;
74         bool                    autoboot_enabled;
75         unsigned int            sec_to_boot;
76
77         struct discover_boot_option *default_boot_option;
78         int                     default_boot_option_priority;
79
80         struct list             unresolved_boot_options;
81
82         struct boot_task        *pending_boot;
83         bool                    pending_boot_is_default;
84
85         struct list             progress;
86         unsigned int            n_progress;
87
88         struct plugin_option    **plugins;
89         unsigned int            n_plugins;
90         bool                    plugin_installing;
91 };
92
93 static int mount_device(struct discover_device *dev);
94 static int umount_device(struct discover_device *dev);
95
96 static int device_handler_init_sources(struct device_handler *handler);
97 static void device_handler_reinit_sources(struct device_handler *handler);
98
99 static void device_handler_update_lang(const char *lang);
100
101 void discover_context_add_boot_option(struct discover_context *ctx,
102                 struct discover_boot_option *boot_option)
103 {
104         boot_option->source = ctx->parser;
105         list_add_tail(&ctx->boot_options, &boot_option->list);
106         talloc_steal(ctx, boot_option);
107 }
108
109 /**
110  * device_handler_get_device_count - Get the count of current handler devices.
111  */
112
113 int device_handler_get_device_count(const struct device_handler *handler)
114 {
115         return handler->n_devices;
116 }
117
118 /**
119  * device_handler_get_device - Get a handler device by index.
120  */
121
122 const struct discover_device *device_handler_get_device(
123         const struct device_handler *handler, unsigned int index)
124 {
125         if (index >= handler->n_devices) {
126                 assert(0 && "bad index");
127                 return NULL;
128         }
129
130         return handler->devices[index];
131 }
132
133 /**
134  * device_handler_get_plugin_count - Get the count of current handler plugins.
135  */
136 int device_handler_get_plugin_count(const struct device_handler *handler)
137 {
138         return handler->n_plugins;
139 }
140
141 /**
142  * discover_handler_get_plugin - Get a handler plugin by index.
143  */
144 const struct plugin_option *device_handler_get_plugin(
145         const struct device_handler *handler, unsigned int index)
146 {
147         if (index >= handler->n_plugins) {
148                 assert(0 && "bad index");
149                 return NULL;
150         }
151
152         return handler->plugins[index];
153 }
154
155 struct network *device_handler_get_network(
156                 const struct device_handler *handler)
157 {
158         return handler->network;
159 }
160
161 struct discover_boot_option *discover_boot_option_create(
162                 struct discover_context *ctx,
163                 struct discover_device *device)
164 {
165         struct discover_boot_option *opt;
166
167         opt = talloc_zero(ctx, struct discover_boot_option);
168         opt->option = talloc_zero(opt, struct boot_option);
169         opt->device = device;
170
171         return opt;
172 }
173
174 static int device_match_uuid(struct discover_device *dev, const char *uuid)
175 {
176         return dev->uuid && !strcmp(dev->uuid, uuid);
177 }
178
179 static int device_match_label(struct discover_device *dev, const char *label)
180 {
181         return dev->label && !strcmp(dev->label, label);
182 }
183
184 static int device_match_id(struct discover_device *dev, const char *id)
185 {
186         return !strcmp(dev->device->id, id);
187 }
188
189 static int device_match_serial(struct discover_device *dev, const char *serial)
190 {
191         const char *val = discover_device_get_param(dev, "ID_SERIAL");
192         return val && !strcmp(val, serial);
193 }
194
195 static struct discover_device *device_lookup(
196                 struct device_handler *device_handler,
197                 int (match_fn)(struct discover_device *, const char *),
198                 const char *str)
199 {
200         struct discover_device *dev;
201         unsigned int i;
202
203         if (!str)
204                 return NULL;
205
206         for (i = 0; i < device_handler->n_devices; i++) {
207                 dev = device_handler->devices[i];
208
209                 if (match_fn(dev, str))
210                         return dev;
211         }
212
213         return NULL;
214 }
215
216 struct discover_device *device_lookup_by_name(struct device_handler *handler,
217                 const char *name)
218 {
219         if (!strncmp(name, "/dev/", strlen("/dev/")))
220                 name += strlen("/dev/");
221
222         return device_lookup_by_id(handler, name);
223 }
224
225 struct discover_device *device_lookup_by_uuid(
226                 struct device_handler *device_handler,
227                 const char *uuid)
228 {
229         return device_lookup(device_handler, device_match_uuid, uuid);
230 }
231
232 struct discover_device *device_lookup_by_label(
233                 struct device_handler *device_handler,
234                 const char *label)
235 {
236         return device_lookup(device_handler, device_match_label, label);
237 }
238
239 struct discover_device *device_lookup_by_id(
240                 struct device_handler *device_handler,
241                 const char *id)
242 {
243         return device_lookup(device_handler, device_match_id, id);
244 }
245
246 struct discover_device *device_lookup_by_serial(
247                 struct device_handler *device_handler,
248                 const char *serial)
249 {
250         return device_lookup(device_handler, device_match_serial, serial);
251 }
252
253 void device_handler_destroy(struct device_handler *handler)
254 {
255         talloc_free(handler);
256 }
257
258 static int destroy_device(void *arg)
259 {
260         struct discover_device *dev = arg;
261
262         umount_device(dev);
263
264         return 0;
265 }
266
267 struct discover_device *discover_device_create(struct device_handler *handler,
268                 const char *uuid, const char *id)
269 {
270         struct discover_device *dev;
271
272         if (uuid)
273                 dev = device_lookup_by_uuid(handler, uuid);
274         else
275                 dev = device_lookup_by_id(handler, id);
276
277         if (dev)
278                 return dev;
279
280         dev = talloc_zero(handler, struct discover_device);
281         dev->device = talloc_zero(dev, struct device);
282         dev->device->id = talloc_strdup(dev->device, id);
283         dev->uuid = talloc_strdup(dev, uuid);
284         list_init(&dev->params);
285         list_init(&dev->boot_options);
286
287         talloc_set_destructor(dev, destroy_device);
288
289         return dev;
290 }
291
292 struct discover_device_param {
293         char                    *name;
294         char                    *value;
295         struct list_item        list;
296 };
297
298 void discover_device_set_param(struct discover_device *device,
299                 const char *name, const char *value)
300 {
301         struct discover_device_param *param;
302         bool found = false;
303
304         list_for_each_entry(&device->params, param, list) {
305                 if (!strcmp(param->name, name)) {
306                         found = true;
307                         break;
308                 }
309         }
310
311         if (!found) {
312                 if (!value)
313                         return;
314                 param = talloc(device, struct discover_device_param);
315                 param->name = talloc_strdup(param, name);
316                 list_add(&device->params, &param->list);
317         } else {
318                 if (!value) {
319                         list_remove(&param->list);
320                         talloc_free(param);
321                         return;
322                 }
323                 talloc_free(param->value);
324         }
325
326         param->value = talloc_strdup(param, value);
327 }
328
329 const char *discover_device_get_param(struct discover_device *device,
330                 const char *name)
331 {
332         struct discover_device_param *param;
333
334         list_for_each_entry(&device->params, param, list) {
335                 if (!strcmp(param->name, name))
336                         return param->value;
337         }
338         return NULL;
339 }
340
341 static void set_env_variables(const struct config *config)
342 {
343         if (config->http_proxy)
344                 setenv("http_proxy", config->http_proxy, 1);
345         else
346                 unsetenv("http_proxy");
347
348         if (config->https_proxy)
349                 setenv("https_proxy", config->https_proxy, 1);
350         else
351                 unsetenv("https_proxy");
352
353         /* Reduce noise in the log from LVM listing open file descriptors */
354         setenv("LVM_SUPPRESS_FD_WARNINGS", "1", 1);
355 }
356
357 struct device_handler *device_handler_init(struct discover_server *server,
358                 struct waitset *waitset, int dry_run)
359 {
360         struct device_handler *handler;
361         int rc;
362
363         handler = talloc_zero(NULL, struct device_handler);
364         handler->server = server;
365         handler->waitset = waitset;
366         handler->dry_run = dry_run;
367         handler->autoboot_enabled = config_autoboot_active(config_get());
368
369         list_init(&handler->unresolved_boot_options);
370
371         list_init(&handler->progress);
372
373         /* set up our mount point base */
374         pb_mkdir_recursive(mount_base());
375
376         parser_init();
377
378         if (config_get()->safe_mode)
379                 return handler;
380
381         set_env_variables(config_get());
382
383         rc = device_handler_init_sources(handler);
384         if (rc) {
385                 talloc_free(handler);
386                 return NULL;
387         }
388
389         return handler;
390 }
391
392 void device_handler_reinit(struct device_handler *handler)
393 {
394         struct discover_boot_option *opt, *tmp;
395         struct ramdisk_device *ramdisk;
396         unsigned int i;
397
398         device_handler_cancel_default(handler);
399         /* Cancel any pending non-default boot */
400         if (handler->pending_boot) {
401                 boot_cancel(handler->pending_boot);
402                 handler->pending_boot = NULL;
403                 handler->pending_boot_is_default = false;
404         }
405
406         /* Cancel any remaining async jobs */
407         process_stop_async_all();
408         pending_network_jobs_cancel();
409
410         /* free unresolved boot options */
411         list_for_each_entry_safe(&handler->unresolved_boot_options,
412                         opt, tmp, list)
413                 talloc_free(opt);
414         list_init(&handler->unresolved_boot_options);
415
416         /* drop all devices */
417         for (i = 0; i < handler->n_devices; i++) {
418                 discover_server_notify_device_remove(handler->server,
419                                 handler->devices[i]->device);
420                 ramdisk = handler->devices[i]->ramdisk;
421                 talloc_free(handler->devices[i]);
422                 talloc_free(ramdisk);
423         }
424
425         talloc_free(handler->devices);
426         handler->devices = NULL;
427         handler->n_devices = 0;
428         talloc_free(handler->ramdisks);
429         handler->ramdisks = NULL;
430         handler->n_ramdisks = 0;
431
432         /* drop any known plugins */
433         for (i = 0; i < handler->n_plugins; i++)
434                 talloc_free(handler->plugins[i]);
435         talloc_free(handler->plugins);
436         handler->plugins = NULL;
437         handler->n_plugins = 0;
438
439         discover_server_notify_plugins_remove(handler->server);
440
441         set_env_variables(config_get());
442
443         device_handler_reinit_sources(handler);
444 }
445
446 void device_handler_remove(struct device_handler *handler,
447                 struct discover_device *device)
448 {
449         struct discover_boot_option *opt, *tmp;
450         unsigned int i;
451
452         list_for_each_entry_safe(&device->boot_options, opt, tmp, list) {
453                 if (opt == handler->default_boot_option) {
454                         pb_log("Default option %s cancelled since device removed",
455                                         opt->option->name);
456                         device_handler_cancel_default(handler);
457                         break;
458                 }
459         }
460
461         for (i = 0; i < handler->n_devices; i++)
462                 if (handler->devices[i] == device)
463                         break;
464
465         if (i == handler->n_devices) {
466                 talloc_free(device);
467                 return;
468         }
469
470         /* Free any unresolved options, as they're currently allocated
471          * against the handler */
472         list_for_each_entry_safe(&handler->unresolved_boot_options,
473                         opt, tmp, list) {
474                 if (opt->device != device)
475                         continue;
476                 list_remove(&opt->list);
477                 talloc_free(opt);
478         }
479
480         /* if this is a network device, we have to unregister it from the
481          * network code */
482         if (device->device->type == DEVICE_TYPE_NETWORK)
483                 network_unregister_device(handler->network, device);
484
485         handler->n_devices--;
486         memmove(&handler->devices[i], &handler->devices[i + 1],
487                 (handler->n_devices - i) * sizeof(handler->devices[0]));
488         handler->devices = talloc_realloc(handler, handler->devices,
489                 struct discover_device *, handler->n_devices);
490
491         if (device->notified)
492                 discover_server_notify_device_remove(handler->server,
493                                                         device->device);
494
495         talloc_free(device);
496 }
497
498 void device_handler_status(struct device_handler *handler,
499                 struct status *status)
500 {
501         discover_server_notify_boot_status(handler->server, status);
502 }
503
504 static void _device_handler_vstatus(struct device_handler *handler,
505                 enum status_type type, const char *fmt, va_list ap)
506 {
507         struct status status;
508
509         status.type = type;
510         status.message = talloc_vasprintf(handler, fmt, ap);
511         status.backlog = false;
512
513         device_handler_status(handler, &status);
514
515         talloc_free(status.message);
516 }
517
518 static void _device_handler_vdevstatus(struct device_handler *handler,
519                 struct discover_device *device, enum status_type type,
520                 const char *fmt, va_list ap)
521 {
522         char *msg;
523
524         msg = talloc_asprintf(handler, "[%s] %s",
525                         device ? device->device->id : "unknown", fmt);
526         _device_handler_vstatus(handler, type, msg, ap);
527         talloc_free(msg);
528 }
529
530 void device_handler_status_dev_info(struct device_handler *handler,
531                 struct discover_device *dev, const char *fmt, ...)
532 {
533         va_list ap;
534
535         va_start(ap, fmt);
536         _device_handler_vdevstatus(handler, dev, STATUS_INFO, fmt, ap);
537         va_end(ap);
538 }
539
540 void device_handler_status_dev_err(struct device_handler *handler,
541                 struct discover_device *dev, const char *fmt, ...)
542 {
543         va_list ap;
544
545         va_start(ap, fmt);
546         _device_handler_vdevstatus(handler, dev, STATUS_ERROR, fmt, ap);
547         va_end(ap);
548 }
549
550 void device_handler_status_info(struct device_handler *handler,
551                 const char *fmt, ...)
552 {
553         va_list ap;
554
555         va_start(ap, fmt);
556         _device_handler_vstatus(handler, STATUS_INFO, fmt, ap);
557         va_end(ap);
558 }
559
560 void device_handler_status_err(struct device_handler *handler,
561                 const char *fmt, ...)
562 {
563         va_list ap;
564
565         va_start(ap, fmt);
566         _device_handler_vstatus(handler, STATUS_ERROR, fmt, ap);
567         va_end(ap);
568 }
569
570 void device_handler_status_download(struct device_handler *handler,
571                 const struct process_info *procinfo,
572                 unsigned int percentage, unsigned int size, char suffix)
573 {
574         struct progress_info *p, *progress = NULL;
575         uint64_t current_converted, current = 0;
576         const char *units = " kMGTP";
577         unsigned long size_bytes;
578         char *update = NULL;
579         double total = 0;
580         unsigned int i;
581         int unit = 0;
582
583         list_for_each_entry(&handler->progress, p, list)
584                 if (p->procinfo == procinfo)
585                         progress = p;
586
587         if (!progress) {
588                 pb_log("Registering new progress struct\n");
589                 progress = talloc_zero(handler, struct progress_info);
590                 if (!progress) {
591                         pb_log("Failed to allocate room for progress struct\n");
592                         return;
593                 }
594                 progress->procinfo = procinfo;
595                 list_add(&handler->progress, &progress->list);
596                 handler->n_progress++;
597         }
598
599         size_bytes = size;
600         for (i = 0; i < strlen(units); i++) {
601                 if (units[i] == suffix)
602                         break;
603         }
604
605         if (i >= strlen(units)) {
606             pb_log("Couldn't recognise suffix '%c'\n", suffix);
607             size_bytes = 0;
608         } else {
609                 while (i--)
610                         size_bytes <<= 10;
611         }
612
613         progress->percentage = percentage;
614         progress->size = size_bytes;
615
616         /*
617          * Aggregate the info we have and update status. If a progress struct
618          * has zero for both percentage and size we assume progress information
619          * is unavailable and fall back to a generic progress message.
620          */
621         list_for_each_entry(&handler->progress, p, list) {
622                 uint64_t c;
623                 double t;
624                 if (!p->percentage || !p->size) {
625                         update = talloc_asprintf(handler,
626                                         _("%u downloads in progress..."),
627                                         handler->n_progress);
628                         current = total = 0;
629                         break;
630                 }
631
632                 c = p->size;
633                 t = (100 * c) / p->percentage;
634
635                 current += c;
636                 total += t;
637         }
638
639         if (total) {
640                 current_converted = current;
641                 while (current_converted >= 1000) {
642                         current_converted >>= 10;
643                         unit++;
644                 }
645                 update = talloc_asprintf(handler,
646                                 _("%u %s downloading: %.0f%% - %lu%cB"),
647                                 handler->n_progress,
648                                 ngettext("item", "items", handler->n_progress),
649                                 (current / total) * 100, current_converted,
650                                 units[unit]);
651         }
652
653         if (!update) {
654                 pb_log("%s: failed to allocate new status\n", __func__);
655         } else {
656                 device_handler_status_info(handler, "%s\n", update);
657                 talloc_free(update);
658         }
659 }
660
661 static void device_handler_plugin_scan_device(struct device_handler *handler,
662                 struct discover_device *dev)
663 {
664         int rc;
665
666         pb_debug("Scanning %s for plugin files\n", dev->device->id);
667
668         rc = process_run_simple(handler, pb_system_apps.pb_plugin,
669                                 "scan", dev->mount_path,
670                                 NULL);
671         if (rc)
672                 pb_log("Error from pb-plugin scan %s\n",
673                                 dev->mount_path);
674 }
675
676 void device_handler_status_download_remove(struct device_handler *handler,
677                 struct process_info *procinfo)
678 {
679         struct progress_info *p, *tmp;
680
681         list_for_each_entry_safe(&handler->progress, p, tmp, list)
682                 if (p->procinfo == procinfo) {
683                         list_remove(&p->list);
684                         talloc_free(p);
685                         handler->n_progress--;
686                 }
687 }
688
689 static void device_handler_boot_status_cb(void *arg, struct status *status)
690 {
691         device_handler_status(arg, status);
692 }
693
694 static void countdown_status(struct device_handler *handler,
695                 struct discover_boot_option *opt, unsigned int sec)
696 {
697         struct status status;
698
699         status.type = STATUS_INFO;
700         status.message = talloc_asprintf(handler,
701                         _("Booting in %d sec: [%s] %s"), sec,
702                         opt->device->device->id, opt->option->name);
703         status.backlog = false;
704
705         device_handler_status(handler, &status);
706
707         talloc_free(status.message);
708 }
709
710 static int default_timeout(void *arg)
711 {
712         struct device_handler *handler = arg;
713         struct discover_boot_option *opt;
714
715         if (!handler->default_boot_option)
716                 return 0;
717
718         if (handler->pending_boot)
719                 return 0;
720
721         opt = handler->default_boot_option;
722
723         if (handler->sec_to_boot) {
724                 countdown_status(handler, opt, handler->sec_to_boot);
725                 handler->sec_to_boot--;
726                 handler->timeout_waiter = waiter_register_timeout(
727                                                 handler->waitset, 1000,
728                                                 default_timeout, handler);
729                 return 0;
730         }
731
732         handler->timeout_waiter = NULL;
733
734         pb_log("Timeout expired, booting default option %s\n", opt->option->id);
735
736         platform_pre_boot();
737
738         handler->pending_boot = boot(handler, handler->default_boot_option,
739                         NULL, handler->dry_run, device_handler_boot_status_cb,
740                         handler);
741         handler->pending_boot_is_default = true;
742         return 0;
743 }
744
745 struct {
746         enum ipmi_bootdev       ipmi_type;
747         enum device_type        device_type;
748 } device_type_map[] = {
749         { IPMI_BOOTDEV_NETWORK, DEVICE_TYPE_NETWORK },
750         { IPMI_BOOTDEV_DISK, DEVICE_TYPE_DISK },
751         { IPMI_BOOTDEV_DISK, DEVICE_TYPE_USB },
752         { IPMI_BOOTDEV_CDROM, DEVICE_TYPE_OPTICAL },
753 };
754
755 static bool ipmi_device_type_matches(enum ipmi_bootdev ipmi_type,
756                 enum device_type device_type)
757 {
758         unsigned int i;
759
760         for (i = 0; i < ARRAY_SIZE(device_type_map); i++) {
761                 if (device_type_map[i].device_type == device_type)
762                         return device_type_map[i].ipmi_type == ipmi_type;
763         }
764
765         return false;
766 }
767
768 static int autoboot_option_priority(const struct config *config,
769                                 struct discover_boot_option *opt)
770 {
771         enum device_type type = opt->device->device->type;
772         const char *uuid = opt->device->uuid;
773         struct autoboot_option *auto_opt;
774         unsigned int i;
775
776         for (i = 0; i < config->n_autoboot_opts; i++) {
777                 auto_opt = &config->autoboot_opts[i];
778                 if (auto_opt->boot_type == BOOT_DEVICE_UUID)
779                         if (!strcmp(auto_opt->uuid, uuid))
780                                 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
781
782                 if (auto_opt->boot_type == BOOT_DEVICE_TYPE)
783                         if (auto_opt->type == type ||
784                             auto_opt->type == DEVICE_TYPE_ANY)
785                                 return DEFAULT_PRIORITY_LOCAL_FIRST + i;
786         }
787
788         return -1;
789 }
790
791 /*
792  * We have different priorities to resolve conflicts between boot options that
793  * report to be the default for their device. This function assigns a priority
794  * for these options.
795  */
796 static enum default_priority default_option_priority(
797                 struct discover_boot_option *opt)
798 {
799         const struct config *config;
800
801         config = config_get();
802
803         /* We give highest priority to IPMI-configured boot options. If
804          * we have an IPMI bootdev configuration set, then we don't allow
805          * any other defaults */
806         if (config->ipmi_bootdev) {
807                 bool ipmi_match = ipmi_device_type_matches(config->ipmi_bootdev,
808                                 opt->device->device->type);
809                 if (ipmi_match)
810                         return DEFAULT_PRIORITY_REMOTE;
811
812                 pb_debug("handler: disabled default priority due to "
813                                 "non-matching IPMI type %x\n",
814                                 config->ipmi_bootdev);
815                 return DEFAULT_PRIORITY_DISABLED;
816         }
817
818         /* Next, try to match the option against the user-defined autoboot
819          * options, either by device UUID or type. */
820         if (config->n_autoboot_opts) {
821                 int boot_match = autoboot_option_priority(config, opt);
822                 if (boot_match > 0)
823                         return boot_match;
824         }
825
826         /* If the option didn't match any entry in the array, it is disabled */
827         pb_debug("handler: disabled default priority due to "
828                         "non-matching UUID or type\n");
829         return DEFAULT_PRIORITY_DISABLED;
830 }
831
832 static void set_default(struct device_handler *handler,
833                 struct discover_boot_option *opt)
834 {
835         enum default_priority cur_prio, new_prio;
836
837         if (!handler->autoboot_enabled)
838                 return;
839
840         pb_debug("handler: new default option: %s\n", opt->option->id);
841
842         new_prio = default_option_priority(opt);
843
844         /* Anything outside our range prevents a default boot */
845         if (new_prio >= DEFAULT_PRIORITY_DISABLED)
846                 return;
847
848         pb_debug("handler: calculated priority %d\n", new_prio);
849
850         /* Resolve any conflicts: if we have a new default option, it only
851          * replaces the current if it has a higher priority. */
852         if (handler->default_boot_option) {
853
854                 cur_prio = handler->default_boot_option_priority;
855
856                 if (new_prio < cur_prio) {
857                         pb_log("handler: new prio %d beats "
858                                         "old prio %d for %s\n",
859                                         new_prio, cur_prio,
860                                         handler->default_boot_option
861                                                 ->option->id);
862                         handler->default_boot_option = opt;
863                         handler->default_boot_option_priority = new_prio;
864                         /* extend the timeout a little, so the user sees some
865                          * indication of the change */
866                         handler->sec_to_boot += 2;
867                 }
868
869                 return;
870         }
871
872         handler->sec_to_boot = config_get()->autoboot_timeout_sec;
873         handler->default_boot_option = opt;
874         handler->default_boot_option_priority = new_prio;
875
876         pb_log("handler: boot option %s set as default, timeout %u sec.\n",
877                opt->option->id, handler->sec_to_boot);
878
879         default_timeout(handler);
880 }
881
882 static bool resource_is_resolved(struct resource *res)
883 {
884         return !res || res->resolved;
885 }
886
887 /* We only use this in an assert, which will disappear if we're compiling
888  * with NDEBUG, so we need the 'used' attribute for these builds */
889 static bool __attribute__((used)) boot_option_is_resolved(
890                 struct discover_boot_option *opt)
891 {
892         return resource_is_resolved(opt->boot_image) &&
893                 resource_is_resolved(opt->initrd) &&
894                 resource_is_resolved(opt->dtb) &&
895                 resource_is_resolved(opt->args_sig_file) &&
896                 resource_is_resolved(opt->icon);
897 }
898
899 static bool resource_resolve(struct resource *res, const char *name,
900                 struct discover_boot_option *opt,
901                 struct device_handler *handler)
902 {
903         struct parser *parser = opt->source;
904
905         if (resource_is_resolved(res))
906                 return true;
907
908         pb_debug("Attempting to resolve resource %s->%s with parser %s\n",
909                         opt->option->id, name, parser->name);
910         parser->resolve_resource(handler, res);
911
912         return res->resolved;
913 }
914
915 static bool boot_option_resolve(struct discover_boot_option *opt,
916                 struct device_handler *handler)
917 {
918         return resource_resolve(opt->boot_image, "boot_image", opt, handler) &&
919                 resource_resolve(opt->initrd, "initrd", opt, handler) &&
920                 resource_resolve(opt->dtb, "dtb", opt, handler) &&
921                 resource_resolve(opt->args_sig_file, "args_sig_file", opt,
922                         handler) &&
923                 resource_resolve(opt->icon, "icon", opt, handler);
924 }
925
926 static void boot_option_finalise(struct device_handler *handler,
927                 struct discover_boot_option *opt)
928 {
929         assert(boot_option_is_resolved(opt));
930
931         /* check that the parsers haven't set any of the final data */
932         assert(!opt->option->boot_image_file);
933         assert(!opt->option->initrd_file);
934         assert(!opt->option->dtb_file);
935         assert(!opt->option->icon_file);
936         assert(!opt->option->device_id);
937         assert(!opt->option->args_sig_file);
938
939         if (opt->boot_image)
940                 opt->option->boot_image_file = opt->boot_image->url->full;
941         if (opt->initrd)
942                 opt->option->initrd_file = opt->initrd->url->full;
943         if (opt->dtb)
944                 opt->option->dtb_file = opt->dtb->url->full;
945         if (opt->icon)
946                 opt->option->icon_file = opt->icon->url->full;
947         if (opt->args_sig_file)
948                 opt->option->args_sig_file = opt->args_sig_file->url->full;
949
950         opt->option->device_id = opt->device->device->id;
951
952         if (opt->option->is_default)
953                 set_default(handler, opt);
954 }
955
956 static void notify_boot_option(struct device_handler *handler,
957                 struct discover_boot_option *opt)
958 {
959         struct discover_device *dev = opt->device;
960
961         if (!dev->notified)
962                 discover_server_notify_device_add(handler->server,
963                                                   opt->device->device);
964         dev->notified = true;
965         discover_server_notify_boot_option_add(handler->server, opt->option);
966 }
967
968 static void process_boot_option_queue(struct device_handler *handler)
969 {
970         struct discover_boot_option *opt, *tmp;
971
972         list_for_each_entry_safe(&handler->unresolved_boot_options,
973                         opt, tmp, list) {
974
975                 pb_debug("queue: attempting resolution for %s\n",
976                                 opt->option->id);
977
978                 if (!boot_option_resolve(opt, handler))
979                         continue;
980
981                 pb_debug("\tresolved!\n");
982
983                 list_remove(&opt->list);
984                 list_add_tail(&opt->device->boot_options, &opt->list);
985                 talloc_steal(opt->device, opt);
986                 boot_option_finalise(handler, opt);
987                 notify_boot_option(handler, opt);
988         }
989 }
990
991 struct discover_context *device_handler_discover_context_create(
992                 struct device_handler *handler,
993                 struct discover_device *device)
994 {
995         struct discover_context *ctx;
996
997         ctx = talloc_zero(handler, struct discover_context);
998         ctx->handler = handler;
999         ctx->device = device;
1000         list_init(&ctx->boot_options);
1001
1002         return ctx;
1003 }
1004
1005 void device_handler_add_device(struct device_handler *handler,
1006                 struct discover_device *device)
1007 {
1008         handler->n_devices++;
1009         handler->devices = talloc_realloc(handler, handler->devices,
1010                                 struct discover_device *, handler->n_devices);
1011         handler->devices[handler->n_devices - 1] = device;
1012
1013         if (device->device->type == DEVICE_TYPE_NETWORK)
1014                 network_register_device(handler->network, device);
1015 }
1016
1017 void device_handler_add_ramdisk(struct device_handler *handler,
1018                 const char *path)
1019 {
1020         struct ramdisk_device *dev;
1021         unsigned int i;
1022
1023         if (!path)
1024                 return;
1025
1026         for (i = 0; i < handler->n_ramdisks; i++)
1027                 if (!strcmp(handler->ramdisks[i]->path, path))
1028                         return;
1029
1030         dev = talloc_zero(handler, struct ramdisk_device);
1031         if (!dev) {
1032                 pb_log("Failed to allocate memory to track %s\n", path);
1033                 return;
1034         }
1035
1036         dev->path = talloc_strdup(handler, path);
1037
1038         handler->ramdisks = talloc_realloc(handler, handler->ramdisks,
1039                                 struct ramdisk_device *,
1040                                 handler->n_ramdisks + 1);
1041         if (!handler->ramdisks) {
1042                 pb_log("Failed to reallocate memory"
1043                        "- ramdisk tracking inconsistent!\n");
1044                 return;
1045         }
1046
1047         handler->ramdisks[i] = dev;
1048         i = handler->n_ramdisks++;
1049 }
1050
1051 struct ramdisk_device *device_handler_get_ramdisk(
1052                 struct device_handler *handler)
1053 {
1054         unsigned int i;
1055         char *name;
1056         dev_t id;
1057
1058         /* Check if free ramdisk exists */
1059         for (i = 0; i < handler->n_ramdisks; i++)
1060                 if (!handler->ramdisks[i]->snapshot &&
1061                     !handler->ramdisks[i]->origin &&
1062                     !handler->ramdisks[i]->base)
1063                         return handler->ramdisks[i];
1064
1065         /* Otherwise create a new one */
1066         name = talloc_asprintf(handler, "/dev/ram%d",
1067                         handler->n_ramdisks);
1068         if (!name) {
1069                 pb_debug("Failed to allocate memory to name /dev/ram%d",
1070                         handler->n_ramdisks);
1071                 return NULL;
1072         }
1073
1074         id = makedev(1, handler->n_ramdisks);
1075         if (mknod(name, S_IFBLK, id)) {
1076                 if (errno == EEXIST) {
1077                         /* We haven't yet received updates for existing
1078                          * ramdisks - add and use this one */
1079                         pb_debug("Using untracked ramdisk %s\n", name);
1080                 } else {
1081                         pb_log("Failed to create new ramdisk %s: %s\n",
1082                                name, strerror(errno));
1083                         return NULL;
1084                 }
1085         }
1086         device_handler_add_ramdisk(handler, name);
1087         talloc_free(name);
1088
1089         return handler->ramdisks[i];
1090 }
1091
1092 void device_handler_release_ramdisk(struct discover_device *device)
1093 {
1094         struct ramdisk_device *ramdisk = device->ramdisk;
1095
1096         talloc_free(ramdisk->snapshot);
1097         talloc_free(ramdisk->origin);
1098         talloc_free(ramdisk->base);
1099
1100         ramdisk->snapshot = ramdisk->origin = ramdisk->base = NULL;
1101         ramdisk->sectors = 0;
1102
1103         device->ramdisk = NULL;
1104 }
1105
1106 /* Start discovery on a hotplugged device. The device will be in our devices
1107  * array, but has only just been initialised by the hotplug source.
1108  */
1109 int device_handler_discover(struct device_handler *handler,
1110                 struct discover_device *dev)
1111 {
1112         struct discover_context *ctx;
1113         int rc;
1114
1115         device_handler_status_dev_info(handler, dev,
1116                 /*
1117                  * TRANSLATORS: this string will be passed the type of the
1118                  * device (eg "disk" or "network"), which will be translated
1119                  * accordingly.
1120                  */
1121                 _("Processing new %s device"),
1122                 device_type_display_name(dev->device->type));
1123
1124         /* create our context */
1125         ctx = device_handler_discover_context_create(handler, dev);
1126
1127         rc = mount_device(dev);
1128         if (rc)
1129                 goto out;
1130
1131         /* add this device to our system info */
1132         system_info_register_blockdev(dev->device->id, dev->uuid,
1133                         dev->mount_path);
1134
1135         /* run the parsers. This will populate the ctx's boot_option list. */
1136         iterate_parsers(ctx);
1137
1138         /* add discovered stuff to the handler */
1139         device_handler_discover_context_commit(handler, ctx);
1140
1141         process_boot_option_queue(handler);
1142
1143         /* Check this device for pb-plugins */
1144         device_handler_plugin_scan_device(handler, dev);
1145 out:
1146         talloc_unlink(handler, ctx);
1147
1148         return 0;
1149 }
1150
1151 /* Incoming dhcp event */
1152 int device_handler_dhcp(struct device_handler *handler,
1153                 struct discover_device *dev, struct event *event)
1154 {
1155         struct discover_context *ctx;
1156
1157         device_handler_status_dev_info(handler, dev,
1158                         _("Processing DHCP lease response (ip: %s)"),
1159                         event_get_param(event, "ip"));
1160
1161         pending_network_jobs_start();
1162
1163         /* create our context */
1164         ctx = device_handler_discover_context_create(handler, dev);
1165         talloc_steal(ctx, event);
1166         ctx->event = event;
1167
1168         iterate_parsers(ctx);
1169
1170         device_handler_discover_context_commit(handler, ctx);
1171
1172         talloc_unlink(handler, ctx);
1173
1174         return 0;
1175 }
1176
1177 static struct discover_boot_option *find_boot_option_by_id(
1178                 struct device_handler *handler, const char *id)
1179 {
1180         unsigned int i;
1181
1182         for (i = 0; i < handler->n_devices; i++) {
1183                 struct discover_device *dev = handler->devices[i];
1184                 struct discover_boot_option *opt;
1185
1186                 list_for_each_entry(&dev->boot_options, opt, list)
1187                         if (!strcmp(opt->option->id, id))
1188                                 return opt;
1189         }
1190
1191         return NULL;
1192 }
1193
1194 void device_handler_boot(struct device_handler *handler,
1195                 struct boot_command *cmd)
1196 {
1197         struct discover_boot_option *opt = NULL;
1198
1199         if (cmd->option_id && strlen(cmd->option_id))
1200                 opt = find_boot_option_by_id(handler, cmd->option_id);
1201
1202         if (handler->pending_boot)
1203                 boot_cancel(handler->pending_boot);
1204
1205         platform_pre_boot();
1206
1207         handler->pending_boot = boot(handler, opt, cmd, handler->dry_run,
1208                         device_handler_boot_status_cb, handler);
1209         handler->pending_boot_is_default = false;
1210 }
1211
1212 void device_handler_cancel_default(struct device_handler *handler)
1213 {
1214         if (handler->timeout_waiter)
1215                 waiter_remove(handler->timeout_waiter);
1216
1217         handler->timeout_waiter = NULL;
1218         handler->autoboot_enabled = false;
1219
1220         /* we only send status if we had a default boot option queued */
1221         if (!handler->default_boot_option)
1222                 return;
1223
1224         pb_log("Cancelling default boot option\n");
1225
1226         if (handler->pending_boot && handler->pending_boot_is_default) {
1227                 boot_cancel(handler->pending_boot);
1228                 handler->pending_boot = NULL;
1229                 handler->pending_boot_is_default = false;
1230         }
1231
1232         handler->default_boot_option = NULL;
1233
1234         device_handler_status_info(handler, _("Default boot cancelled"));
1235 }
1236
1237 void device_handler_update_config(struct device_handler *handler,
1238                 struct config *config)
1239 {
1240         int rc;
1241
1242         rc = config_set(config);
1243         if (rc)
1244                 return;
1245
1246         discover_server_notify_config(handler->server, config);
1247         device_handler_update_lang(config->lang);
1248         device_handler_reinit(handler);
1249 }
1250
1251 static char *device_from_addr(void *ctx, struct pb_url *url)
1252 {
1253         char *ipaddr, *buf, *tok, *dev = NULL;
1254         const char *delim = " ";
1255         struct sockaddr_in *ip;
1256         struct sockaddr_in si;
1257         struct addrinfo *res;
1258         struct process *p;
1259         int rc;
1260
1261         /* Note: IPv4 only */
1262         rc = inet_pton(AF_INET, url->host, &(si.sin_addr));
1263         if (rc > 0) {
1264                 ipaddr = url->host;
1265         } else {
1266                 /* need to turn hostname into a valid IP */
1267                 rc = getaddrinfo(url->host, NULL, NULL, &res);
1268                 if (rc) {
1269                         pb_debug("%s: Invalid URL\n",__func__);
1270                         return NULL;
1271                 }
1272                 ipaddr = talloc_array(ctx,char,INET_ADDRSTRLEN);
1273                 ip = (struct sockaddr_in *) res->ai_addr;
1274                 inet_ntop(AF_INET, &(ip->sin_addr), ipaddr, INET_ADDRSTRLEN);
1275                 freeaddrinfo(res);
1276         }
1277
1278         const char *argv[] = {
1279                 pb_system_apps.ip,
1280                 "route", "show", "to", "match",
1281                 ipaddr,
1282                 NULL
1283         };
1284
1285         p = process_create(ctx);
1286
1287         p->path = pb_system_apps.ip;
1288         p->argv = argv;
1289         p->keep_stdout = true;
1290
1291         rc = process_run_sync(p);
1292
1293         if (rc || p->exit_status) {
1294                 /* ip has complained for some reason; most likely
1295                  * there is no route to the host - bail out */
1296                 pb_debug("%s: `ip` returns non-zero exit status\n", __func__);
1297                 pb_debug("ip buf: %s\n", p->stdout_buf);
1298                 process_release(p);
1299                 return NULL;
1300         }
1301
1302         buf = p->stdout_buf;
1303         /* If a route is found, ip-route output will be of the form
1304          * "... dev DEVNAME ... " */
1305         tok = strtok(buf, delim);
1306         while (tok) {
1307                 if (!strcmp(tok, "dev")) {
1308                         tok = strtok(NULL, delim);
1309                         dev = talloc_strdup(ctx, tok);
1310                         break;
1311                 }
1312                 tok = strtok(NULL, delim);
1313         }
1314
1315         process_release(p);
1316         if (dev)
1317                 pb_debug("%s: Found interface '%s'\n", __func__,dev);
1318         return dev;
1319 }
1320
1321 static void process_url_cb(struct load_url_result *result, void *data)
1322 {
1323         struct device_handler *handler;
1324         struct discover_context *ctx;
1325         struct discover_device *dev;
1326         struct event *event = data;
1327         const char *mac;
1328
1329         if (result->status != LOAD_OK) {
1330                 pb_log("%s: Load failed for %s\n", __func__, result->url->full);
1331                 return;
1332         }
1333
1334         if (!event)
1335                 return;
1336
1337         handler = talloc_parent(event);
1338         if (!handler)
1339                 return;
1340
1341         event->device = device_from_addr(event, result->url);
1342         if (!event->device) {
1343                 pb_log("Downloaded a file but can't find its interface - pretending it was local\n");
1344                 event->device = talloc_asprintf(event, "local");
1345         }
1346
1347         mac = event_get_param(event, "mac");
1348         char *url = talloc_asprintf(event, "file://%s", result->local);
1349         event_set_param(event, "pxeconffile", url);
1350
1351         dev = discover_device_create(handler, mac, event->device);
1352         ctx = device_handler_discover_context_create(handler, dev);
1353         talloc_steal(ctx, event);
1354         ctx->event = event;
1355
1356         iterate_parsers(ctx);
1357
1358         device_handler_discover_context_commit(handler, ctx);
1359
1360         talloc_unlink(handler, ctx);
1361 }
1362
1363 void device_handler_process_url(struct device_handler *handler,
1364                 const char *url, const char *mac, const char *ip)
1365 {
1366         struct discover_context *ctx;
1367         struct discover_device *dev;
1368         bool allow_async = false;
1369         struct pb_url *pb_url;
1370         struct event *event;
1371
1372         event = talloc_zero(handler, struct event);
1373         event->type = EVENT_TYPE_USER;
1374         event->action = EVENT_ACTION_URL;
1375
1376         pb_url = pb_url_parse(event, url);
1377         if (!pb_url || (pb_url->scheme != pb_url_file && !pb_url->host)) {
1378                 device_handler_status_err(handler, _("Invalid config URL!"));
1379                 talloc_free(event);
1380                 return;
1381         }
1382
1383         if (url[strlen(url) - 1] == '/') {
1384                 event_set_param(event, "pxepathprefix", url);
1385                 event_set_param(event, "mac", mac);
1386                 event_set_param(event, "ip", ip);
1387                 event->device = device_from_addr(event, pb_url);
1388                 if (!event->device) {
1389                         device_handler_status_err(handler,
1390                                         _("Unable to route to host %s"),
1391                                         pb_url->host);
1392                         talloc_free(event);
1393                         return;
1394                 }
1395         } else {
1396                 event_set_param(event, "pxeconffile", url);
1397                 allow_async = true;
1398         }
1399
1400         if (pb_url->scheme == pb_url_file)
1401                 event->device = talloc_asprintf(event, "local");
1402         else if (allow_async) {
1403                 /* If file is remote load asynchronously before passing to
1404                  * parser. This allows us to wait for network to be available */
1405                 if (!load_url_async(handler, pb_url, process_url_cb, event,
1406                                         NULL, handler)) {
1407                         pb_log("Failed to load url %s\n", pb_url->full);
1408                         device_handler_status_err(handler, _("Failed to load URL!"));
1409                         talloc_free(event);
1410                 }
1411                 return;
1412         }
1413
1414         /* If path is local we can parse straight away */
1415
1416         dev = discover_device_create(handler, mac, event->device);
1417         if (pb_url->scheme == pb_url_file)
1418                 dev->device->type = DEVICE_TYPE_ANY;
1419         ctx = device_handler_discover_context_create(handler, dev);
1420         talloc_steal(ctx, event);
1421         ctx->event = event;
1422
1423         iterate_parsers(ctx);
1424
1425         device_handler_discover_context_commit(handler, ctx);
1426
1427         talloc_unlink(handler, ctx);
1428 }
1429
1430 static void plugin_install_cb(struct process *process)
1431 {
1432         struct device_handler *handler = process->data;
1433
1434         if (!handler) {
1435                 pb_log("%s: Missing data!\n", __func__);
1436                 return;
1437         }
1438
1439         handler->plugin_installing = false;
1440         if (process->exit_status) {
1441                 device_handler_status_err(handler, "Plugin failed to install!");
1442                 pb_log("Failed to install plugin:\n%s\n", process->stdout_buf);
1443         }
1444 }
1445
1446 void device_handler_install_plugin(struct device_handler *handler,
1447                 const char *plugin_file)
1448 {
1449         struct process *p;
1450         int result;
1451
1452         if (handler->plugin_installing) {
1453                 pb_log("Plugin install cancelled - install already running");
1454                 return;
1455         }
1456
1457         p = process_create(handler);
1458         if (!p) {
1459                 pb_log("install_plugin: Failed to create process\n");
1460                 return;
1461         }
1462
1463         const char *argv[] = {
1464                 pb_system_apps.pb_plugin,
1465                 "install",
1466                 "auto",
1467                 plugin_file,
1468                 NULL
1469         };
1470
1471         p->path = pb_system_apps.pb_plugin;
1472         p->argv = argv;
1473         p->exit_cb = plugin_install_cb;
1474         p->data = handler;
1475         p->keep_stdout = true;
1476
1477         result = process_run_async(p);
1478
1479         if (result)
1480                 device_handler_status_err(handler, "Could not install plugin");
1481         else
1482                 handler->plugin_installing = true;
1483 }
1484
1485 #ifndef PETITBOOT_TEST
1486
1487 /**
1488  * context_commit - Commit a temporary discovery context to the handler,
1489  * and notify the clients about any new options / devices
1490  */
1491 void device_handler_discover_context_commit(struct device_handler *handler,
1492                 struct discover_context *ctx)
1493 {
1494         struct discover_device *dev = ctx->device;
1495         struct discover_boot_option *opt, *tmp;
1496
1497         if (!device_lookup_by_uuid(handler, dev->uuid))
1498                 device_handler_add_device(handler, dev);
1499
1500         /* move boot options from the context to the device */
1501         list_for_each_entry_safe(&ctx->boot_options, opt, tmp, list) {
1502                 list_remove(&opt->list);
1503
1504                 /* All boot options need at least a kernel image */
1505                 if (!opt->boot_image || !opt->boot_image->url) {
1506                         pb_log("boot option %s is missing boot image, ignoring\n",
1507                                 opt->option->id);
1508                         talloc_free(opt);
1509                         continue;
1510                 }
1511
1512                 if (boot_option_resolve(opt, handler)) {
1513                         pb_log("boot option %s is resolved, "
1514                                         "sending to clients\n",
1515                                         opt->option->id);
1516                         list_add_tail(&dev->boot_options, &opt->list);
1517                         talloc_steal(dev, opt);
1518                         boot_option_finalise(handler, opt);
1519                         notify_boot_option(handler, opt);
1520                 } else {
1521                         if (!opt->source->resolve_resource) {
1522                                 pb_log("parser %s gave us an unresolved "
1523                                         "resource (%s), but no way to "
1524                                         "resolve it\n",
1525                                         opt->source->name, opt->option->id);
1526                                 talloc_free(opt);
1527                         } else {
1528                                 pb_log("boot option %s is unresolved, "
1529                                                 "adding to queue\n",
1530                                                 opt->option->id);
1531                                 list_add(&handler->unresolved_boot_options,
1532                                                 &opt->list);
1533                                 talloc_steal(handler, opt);
1534                         }
1535                 }
1536         }
1537 }
1538
1539 void device_handler_add_plugin_option(struct device_handler *handler,
1540                 struct plugin_option *opt)
1541 {
1542         struct plugin_option *tmp;
1543         unsigned int i;
1544
1545         for (i = 0; i < handler->n_plugins; i++) {
1546                 tmp = handler->plugins[i];
1547                 /* If both id and version match, ignore */
1548                 if (strncmp(opt->id, tmp->id, strlen(opt->id)) == 0 &&
1549                                 strncmp(opt->version, tmp->version,
1550                                         strlen(opt->version) == 0)) {
1551                         pb_log("discover: Plugin '%s' already exists, ignoring\n",
1552                                         opt->id);
1553                         return;
1554                 }
1555         }
1556
1557         handler->plugins = talloc_realloc(handler, handler->plugins,
1558                         struct plugin_option *, handler->n_plugins + 1);
1559         if (!handler->plugins) {
1560                 pb_log("Failed to allocate memory for new plugin\n");
1561                 handler->n_plugins = 0;
1562                 return;
1563         }
1564
1565         handler->plugins[handler->n_plugins++] = opt;
1566         discover_server_notify_plugin_option_add(handler->server, opt);
1567 }
1568
1569 static void device_handler_update_lang(const char *lang)
1570 {
1571         const char *cur_lang;
1572
1573         if (!lang)
1574                 return;
1575
1576         cur_lang = setlocale(LC_ALL, NULL);
1577         if (cur_lang && !strcmp(cur_lang, lang))
1578                 return;
1579
1580         setlocale(LC_ALL, lang);
1581 }
1582
1583 static int device_handler_init_sources(struct device_handler *handler)
1584 {
1585         /* init our device sources: udev, network and user events */
1586         handler->user_event = user_event_init(handler, handler->waitset);
1587         if (!handler->user_event)
1588                 return -1;
1589
1590         handler->network = network_init(handler, handler->waitset,
1591                         handler->dry_run);
1592         if (!handler->network)
1593                 return -1;
1594
1595         handler->udev = udev_init(handler, handler->waitset);
1596         if (!handler->udev)
1597                 return -1;
1598
1599         return 0;
1600 }
1601
1602 static void device_handler_reinit_sources(struct device_handler *handler)
1603 {
1604         /* if we haven't initialised sources previously (becuase we started in
1605          * safe mode), then init once here. */
1606         if (!(handler->udev || handler->network || handler->user_event)) {
1607                 device_handler_init_sources(handler);
1608                 return;
1609         }
1610
1611         system_info_reinit();
1612
1613         network_shutdown(handler->network);
1614         handler->network = network_init(handler, handler->waitset,
1615                         handler->dry_run);
1616
1617         udev_reinit(handler->udev);
1618 }
1619
1620 static inline const char *get_device_path(struct discover_device *dev)
1621 {
1622         return dev->ramdisk ? dev->ramdisk->snapshot : dev->device_path;
1623 }
1624
1625 static char *check_subvols(struct discover_device *dev)
1626 {
1627         const char *fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1628         struct stat sb;
1629         char *path;
1630         int rc;
1631
1632         if (strncmp(fstype, "btrfs", strlen("btrfs")))
1633                 return dev->mount_path;
1634
1635         /* On btrfs a device's root may be under a subvolume path */
1636         path = join_paths(dev, dev->mount_path, "@");
1637         rc = stat(path, &sb);
1638         if (!rc && S_ISDIR(sb.st_mode)) {
1639                 pb_debug("Using '%s' for btrfs root path\n", path);
1640                 return path;
1641         }
1642
1643         talloc_free(path);
1644         return dev->mount_path;
1645 }
1646
1647 static bool check_existing_mount(struct discover_device *dev)
1648 {
1649         struct stat devstat, mntstat;
1650         const char *device_path;
1651         struct mntent *mnt;
1652         FILE *fp;
1653         int rc;
1654
1655         device_path = get_device_path(dev);
1656
1657         rc = stat(device_path, &devstat);
1658         if (rc) {
1659                 pb_debug("%s: stat failed: %s\n", __func__, strerror(errno));
1660                 return false;
1661         }
1662
1663         if (!S_ISBLK(devstat.st_mode)) {
1664                 pb_debug("%s: %s isn't a block device?\n", __func__,
1665                                 dev->device_path);
1666                 return false;
1667         }
1668
1669         fp = fopen("/proc/self/mounts", "r");
1670
1671         for (;;) {
1672                 mnt = getmntent(fp);
1673                 if (!mnt)
1674                         break;
1675
1676                 if (!mnt->mnt_fsname || mnt->mnt_fsname[0] != '/')
1677                         continue;
1678
1679                 rc = stat(mnt->mnt_fsname, &mntstat);
1680                 if (rc)
1681                         continue;
1682
1683                 if (!S_ISBLK(mntstat.st_mode))
1684                         continue;
1685
1686                 if (mntstat.st_rdev == devstat.st_rdev) {
1687                         dev->mount_path = talloc_strdup(dev, mnt->mnt_dir);
1688                         dev->root_path = check_subvols(dev);
1689                         dev->mounted_rw = !!hasmntopt(mnt, "rw");
1690                         dev->mounted = true;
1691                         dev->unmount = false;
1692
1693                         pb_debug("%s: %s is already mounted (r%c) at %s\n",
1694                                         __func__, dev->device_path,
1695                                         dev->mounted_rw ? 'w' : 'o',
1696                                         mnt->mnt_dir);
1697                         break;
1698                 }
1699         }
1700
1701         fclose(fp);
1702
1703         return mnt != NULL;
1704 }
1705
1706 /*
1707  * Attempt to mount a filesystem safely, while handling certain filesytem-
1708  * specific options
1709  */
1710 static int try_mount(const char *device_path, const char *mount_path,
1711                              const char *fstype, unsigned long flags,
1712                              bool have_snapshot)
1713 {
1714         const char *fs, *safe_opts;
1715         int rc;
1716
1717         /* Mount ext3 as ext4 instead so 'norecovery' can be used */
1718         if (strncmp(fstype, "ext3", strlen("ext3")) == 0) {
1719                 pb_debug("Mounting ext3 filesystem as ext4\n");
1720                 fs = "ext4";
1721         } else
1722                 fs = fstype;
1723
1724         if (strncmp(fs, "xfs", strlen("xfs")) == 0 ||
1725             strncmp(fs, "ext4", strlen("ext4")) == 0)
1726                 safe_opts = "norecovery";
1727         else
1728                 safe_opts = NULL;
1729
1730         errno = 0;
1731         /* If no snapshot is available don't attempt recovery */
1732         if (!have_snapshot)
1733                 return mount(device_path, mount_path, fs, flags, safe_opts);
1734
1735         rc = mount(device_path, mount_path, fs, flags, NULL);
1736
1737         if (!rc)
1738                 return rc;
1739
1740         /* Mounting failed; some filesystems will fail to mount if a recovery
1741          * journal exists (eg. cross-endian XFS), so try again with norecovery
1742          * where that option is available.
1743          * If mounting read-write just return the error as norecovery is not a
1744          * valid option */
1745         if ((flags & MS_RDONLY) != MS_RDONLY || !safe_opts)
1746                 return rc;
1747
1748         errno = 0;
1749         return mount(device_path, mount_path, fs, flags, safe_opts);
1750 }
1751
1752 static int mount_device(struct discover_device *dev)
1753 {
1754         const char *fstype, *device_path;
1755         int rc;
1756
1757         if (!dev->device_path)
1758                 return -1;
1759
1760         if (dev->mounted)
1761                 return 0;
1762
1763         if (check_existing_mount(dev))
1764                 return 0;
1765
1766         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1767         if (!fstype)
1768                 return 0;
1769
1770         dev->mount_path = join_paths(dev, mount_base(),
1771                                         dev->device_path);
1772
1773         if (pb_mkdir_recursive(dev->mount_path)) {
1774                 pb_log("couldn't create mount directory %s: %s\n",
1775                                 dev->mount_path, strerror(errno));
1776                 goto err_free;
1777         }
1778
1779         device_path = get_device_path(dev);
1780
1781         pb_log("mounting device %s read-only\n", dev->device_path);
1782         rc = try_mount(device_path, dev->mount_path, fstype,
1783                        MS_RDONLY | MS_SILENT, dev->ramdisk);
1784
1785         if (!rc) {
1786                 dev->mounted = true;
1787                 dev->mounted_rw = false;
1788                 dev->unmount = true;
1789                 dev->root_path = check_subvols(dev);
1790                 return 0;
1791         }
1792
1793         pb_log("couldn't mount device %s: mount failed: %s\n",
1794                         device_path, strerror(errno));
1795
1796         /* If mount fails clean up any snapshot */
1797         devmapper_destroy_snapshot(dev);
1798
1799         pb_rmdir_recursive(mount_base(), dev->mount_path);
1800 err_free:
1801         talloc_free(dev->mount_path);
1802         dev->mount_path = NULL;
1803         return -1;
1804 }
1805
1806 static int umount_device(struct discover_device *dev)
1807 {
1808         const char *device_path;
1809         int rc;
1810
1811         if (!dev->mounted || !dev->unmount)
1812                 return 0;
1813
1814         device_path = get_device_path(dev);
1815
1816         pb_log("unmounting device %s\n", device_path);
1817         rc = umount(dev->mount_path);
1818         if (rc)
1819                 return -1;
1820
1821         dev->mounted = false;
1822         devmapper_destroy_snapshot(dev);
1823
1824         pb_rmdir_recursive(mount_base(), dev->mount_path);
1825
1826         talloc_free(dev->mount_path);
1827         dev->mount_path = NULL;
1828         dev->root_path = NULL;
1829
1830         return 0;
1831 }
1832
1833 int device_request_write(struct discover_device *dev, bool *release)
1834 {
1835         const char *fstype, *device_path;
1836         const struct config *config;
1837         int rc;
1838
1839         *release = false;
1840
1841         config = config_get();
1842         if (!config->allow_writes)
1843                 return -1;
1844
1845         if (!dev->mounted)
1846                 return -1;
1847
1848         if (dev->mounted_rw)
1849                 return 0;
1850
1851         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1852
1853         device_path = get_device_path(dev);
1854
1855         pb_log("remounting device %s read-write\n", device_path);
1856
1857         rc = umount(dev->mount_path);
1858         if (rc) {
1859                 pb_log("Failed to unmount %s: %s\n",
1860                        dev->mount_path, strerror(errno));
1861                 return -1;
1862         }
1863
1864         rc = try_mount(device_path, dev->mount_path, fstype,
1865                        MS_SILENT, dev->ramdisk);
1866         if (rc)
1867                 goto mount_ro;
1868
1869         dev->mounted_rw = true;
1870         *release = true;
1871         return 0;
1872
1873 mount_ro:
1874         pb_log("Unable to remount device %s read-write: %s\n",
1875                device_path, strerror(errno));
1876         rc = try_mount(device_path, dev->mount_path, fstype,
1877                        MS_RDONLY | MS_SILENT, dev->ramdisk);
1878         if (rc)
1879                 pb_log("Unable to recover mount for %s: %s\n",
1880                        device_path, strerror(errno));
1881         return -1;
1882 }
1883
1884 void device_release_write(struct discover_device *dev, bool release)
1885 {
1886         const char *fstype, *device_path;
1887
1888         if (!release)
1889                 return;
1890
1891         device_path = get_device_path(dev);
1892
1893         fstype = discover_device_get_param(dev, "ID_FS_TYPE");
1894
1895         pb_log("remounting device %s read-only\n", device_path);
1896
1897         if (umount(dev->mount_path)) {
1898                 pb_log("Failed to unmount %s\n", dev->mount_path);
1899                 return;
1900         }
1901         dev->mounted_rw = dev->mounted = false;
1902
1903         if (dev->ramdisk) {
1904                 devmapper_merge_snapshot(dev);
1905                 /* device_path becomes stale after merge */
1906                 device_path = get_device_path(dev);
1907         }
1908
1909         if (try_mount(device_path, dev->mount_path, fstype,
1910                        MS_RDONLY | MS_SILENT, dev->ramdisk))
1911                 pb_log("Failed to remount %s read-only: %s\n",
1912                        device_path, strerror(errno));
1913         else
1914                 dev->mounted = true;
1915 }
1916
1917 void device_sync_snapshots(struct device_handler *handler, const char *device)
1918 {
1919         struct discover_device *dev = NULL;
1920         unsigned int i;
1921
1922         if (device) {
1923                 /* Find matching device and sync */
1924                 dev = device_lookup_by_name(handler, device);
1925                 if (!dev) {
1926                         pb_log("%s: device name '%s' unrecognised\n",
1927                                 __func__, device);
1928                         return;
1929                 }
1930                 if (dev->ramdisk)
1931                         device_release_write(dev, true);
1932                 else
1933                         pb_log("%s has no snapshot to merge, skipping\n",
1934                                 dev->device->id);
1935                 return;
1936         }
1937
1938         /* Otherwise sync all relevant devices */
1939         for (i = 0; i < handler->n_devices; i++) {
1940                 dev = handler->devices[i];
1941                 if (dev->device->type != DEVICE_TYPE_DISK &&
1942                         dev->device->type != DEVICE_TYPE_USB)
1943                         continue;
1944                 if (dev->ramdisk)
1945                         device_release_write(dev, true);
1946                 else
1947                         pb_log("%s has no snapshot to merge, skipping\n",
1948                                 dev->device->id);
1949         }
1950 }
1951
1952 #else
1953
1954 void device_handler_discover_context_commit(
1955                 struct device_handler *handler __attribute__((unused)),
1956                 struct discover_context *ctx __attribute__((unused)))
1957 {
1958         pb_log("%s stubbed out for test cases\n", __func__);
1959 }
1960
1961 static void device_handler_update_lang(const char *lang __attribute__((unused)))
1962 {
1963 }
1964
1965 static int device_handler_init_sources(
1966                 struct device_handler *handler __attribute__((unused)))
1967 {
1968         return 0;
1969 }
1970
1971 static void device_handler_reinit_sources(
1972                 struct device_handler *handler __attribute__((unused)))
1973 {
1974 }
1975
1976 static int umount_device(struct discover_device *dev __attribute__((unused)))
1977 {
1978         return 0;
1979 }
1980
1981 static int __attribute__((unused)) mount_device(
1982                 struct discover_device *dev __attribute__((unused)))
1983 {
1984         return 0;
1985 }
1986
1987 int device_request_write(struct discover_device *dev __attribute__((unused)),
1988                 bool *release)
1989 {
1990         *release = true;
1991         return 0;
1992 }
1993
1994 void device_release_write(struct discover_device *dev __attribute__((unused)),
1995         bool release __attribute__((unused)))
1996 {
1997 }
1998
1999 void device_sync_snapshots(
2000                 struct device_handler *handler __attribute__((unused)),
2001                 const char *device __attribute__((unused)))
2002 {
2003 }
2004
2005 #endif