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