discover: Recognise and open LUKS encrypted partitions
[petitboot] / discover / udev.c
1
2 #if defined(HAVE_CONFIG_H)
3 #include "config.h"
4 #endif
5
6 #include <assert.h>
7 #include <errno.h>
8 #include <libudev.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <unistd.h>
13 #include <sys/socket.h>
14 #include <sys/types.h>
15 #include <sys/un.h>
16
17 #include <log/log.h>
18 #include <types/types.h>
19 #include <talloc/talloc.h>
20 #include <waiter/waiter.h>
21 #include <system/system.h>
22 #include <process/process.h>
23
24 #include "event.h"
25 #include "udev.h"
26 #include "pb-discover.h"
27 #include "device-handler.h"
28 #include "cdrom.h"
29 #include "devmapper.h"
30 #include "network.h"
31
32 /* We set a default monitor buffer size, as we may not process monitor
33  * events while performing device discvoery. systemd uses a 128M buffer, so
34  * we'll do the same here */
35 static const int monitor_bufsize = 128 * 1024 * 1024;
36
37 struct pb_udev {
38         struct udev *udev;
39         struct udev_monitor *monitor;
40         struct device_handler *handler;
41 };
42
43 static int udev_destructor(void *p)
44 {
45         struct pb_udev *udev = p;
46
47         if (udev->monitor) {
48                 udev_monitor_unref(udev->monitor);
49                 udev->monitor = NULL;
50         }
51
52         if (udev->udev) {
53                 udev_unref(udev->udev);
54                 udev->udev = NULL;
55         }
56
57         return 0;
58 }
59
60 static void udev_setup_device_params(struct udev_device *udev,
61                 struct discover_device *dev)
62 {
63         struct udev_list_entry *list, *entry;
64
65         list = udev_device_get_properties_list_entry(udev);
66         if (!list)
67                 return;
68
69         udev_list_entry_foreach(entry, list)
70                 discover_device_set_param(dev,
71                                 udev_list_entry_get_name(entry),
72                                 udev_list_entry_get_value(entry));
73 }
74
75 /*
76  * Search for LVM logical volumes. If any exist they should be recognised
77  * by udev as normal.
78  * Normally this is handled in an init script, but on some platforms
79  * disks are slow enough to come up that we need to check again.
80  */
81 static void lvm_vg_search(struct device_handler *handler)
82 {
83         if (process_run_simple(handler, pb_system_apps.vgscan, "-qq", NULL))
84                 pb_log_fn("Failed to execute vgscan\n");
85
86         if (process_run_simple(handler, pb_system_apps.vgchange, "-ay", "-qq",
87                                 NULL))
88                 pb_log_fn("Failed to execute vgchange\n");
89 }
90
91 static int udev_handle_block_add(struct pb_udev *udev, struct udev_device *dev,
92                 const char *name)
93 {
94         char *devlinks = NULL, *link, *saveptr = NULL;
95         struct discover_device *ddev;
96         unsigned int i = 0;
97         const char *typestr;
98         const char *uuid;
99         const char *path;
100         const char *node;
101         const char *prop;
102         const char *type;
103         const char *devname;
104         const char *ignored_types[] = {
105                 "linux_raid_member",
106                 "swap",
107                 NULL,
108         };
109         bool cdrom, usb, luks = false;
110
111         typestr = udev_device_get_devtype(dev);
112         if (!typestr) {
113                 pb_debug("udev_device_get_devtype failed\n");
114                 return -1;
115         }
116
117         if (!(!strcmp(typestr, "disk") || !strcmp(typestr, "partition"))) {
118                 pb_log("SKIP %s: invalid type %s\n", name, typestr);
119                 return 0;
120         }
121
122         node = udev_device_get_devnode(dev);
123         path = udev_device_get_devpath(dev);
124         if (path && strstr(path, "virtual/block/loop")) {
125                 pb_log("SKIP: %s: ignored (path=%s)\n", name, path);
126                 return 0;
127         }
128
129         if (path && strstr(path, "virtual/block/ram")) {
130                 device_handler_add_ramdisk(udev->handler, node);
131                 return 0;
132         }
133
134         cdrom = node && !!udev_device_get_property_value(dev, "ID_CDROM");
135         if (cdrom) {
136                 /* CDROMs require a little initialisation, to get
137                  * petitboot-compatible tray behaviour */
138                 cdrom_init(node);
139                 if (!cdrom_media_present(node)) {
140                         pb_log("SKIP: %s: no media present\n", name);
141                         return 0;
142                 }
143         }
144
145         /*
146          * Ignore any device mapper devices that aren't logical volumes or
147          * opened encrypted devices
148          */
149         devname = udev_device_get_property_value(dev, "DM_NAME");
150         if (devname) {
151                 if (device_handler_found_crypt_device(udev->handler, devname)) {
152                         luks = true;
153                 } else if (!udev_device_get_property_value(dev, "DM_LV_NAME")) {
154                         pb_debug("SKIP: dm-device %s\n", devname);
155                         return 0;
156                 }
157         }
158
159         type = udev_device_get_property_value(dev, "ID_FS_TYPE");
160         if (!type) {
161                 pb_log("SKIP: %s: no ID_FS_TYPE property\n", name);
162                 return 0;
163         }
164
165         while (ignored_types[i]) {
166                 if (!strncmp(type, ignored_types[i], strlen(ignored_types[i]))) {
167                         pb_log("SKIP: %s: ignore '%s' filesystem\n", name, type);
168                         return 0;
169                 }
170                 i++;
171         }
172
173         /* Search for LVM logical volumes if we see an LVM member */
174         if (strncmp(type, "LVM2_member", strlen("LVM2_member")) == 0) {
175                 lvm_vg_search(udev->handler);
176                 return 0;
177         }
178
179         /* We may see multipath devices; they'll have the same uuid as an
180          * existing device, so only parse the first. */
181         uuid = udev_device_get_property_value(dev, "ID_FS_UUID");
182         if (uuid) {
183                 ddev = device_lookup_by_uuid(udev->handler, uuid);
184                 if (ddev) {
185                         pb_log("SKIP: %s UUID [%s] already present (as %s)\n",
186                                         name, uuid, ddev->device->id);
187                         return 0;
188                 }
189         }
190
191         /* Use DM_NAME for logical volumes, or the device name otherwise */
192         ddev = discover_device_create(udev->handler, uuid, devname ?: name);
193
194         if (devname) {
195                 /*
196                  * For logical volumes udev_device_get_devnode() returns a path
197                  * of the form "/dev/dm-xx". These nodes names are not
198                  * persistent and are opaque to the user. Instead use the more
199                  * recognisable "/dev/mapper/lv-name" node if it is available.
200                  */
201                 devlinks = talloc_strdup(ddev,
202                                 udev_device_get_property_value(dev, "DEVLINKS"));
203                 link = devlinks ? strtok_r(devlinks, " ", &saveptr) : NULL;
204                 while (link) {
205                         if (strncmp(link, "/dev/mapper/",
206                                         strlen("/dev/mapper/")) == 0) {
207                                 node = link;
208                                 break;
209                         }
210                         link = strtok_r(NULL, " ", &saveptr);
211                 }
212         }
213
214         ddev->device_path = talloc_strdup(ddev, node);
215         talloc_free(devlinks);
216
217         if (uuid)
218                 ddev->uuid = talloc_strdup(ddev, uuid);
219         prop = udev_device_get_property_value(dev, "ID_FS_LABEL");
220         if (prop)
221                 ddev->label = talloc_strdup(ddev, prop);
222
223         usb = !!udev_device_get_property_value(dev, "ID_USB_DRIVER");
224         if (cdrom)
225                 ddev->device->type = DEVICE_TYPE_OPTICAL;
226         else if (strncmp(type, "crypto_LUKS", strlen("crypto_LUKS")) == 0)
227                 ddev->device->type = DEVICE_TYPE_LUKS;
228         else
229                 ddev->device->type = usb ? DEVICE_TYPE_USB : DEVICE_TYPE_DISK;
230
231         udev_setup_device_params(dev, ddev);
232
233         /*
234          * Don't perform discovery on encrypted devices, just register and
235          * notify clients.
236          */
237         if (ddev->device->type == DEVICE_TYPE_LUKS) {
238                 pb_log("Notifying clients about encrypted device %s\n",
239                                 name);
240                 device_handler_add_encrypted_dev(udev->handler, ddev);
241                 return 0;
242         }
243
244         /* Create a snapshot for all disk devices */
245         if ((ddev->device->type == DEVICE_TYPE_DISK ||
246              ddev->device->type == DEVICE_TYPE_USB))
247                 devmapper_init_snapshot(udev->handler, ddev);
248
249         /* Note if this is an opened LUKS device */
250         ddev->crypt_device = luks;
251
252         device_handler_discover(udev->handler, ddev);
253
254         return 0;
255 }
256
257 /*
258  * Mark valid interfaces as 'ready'.
259  * The udev_enumerate_add_match_is_initialized() filter in udev_enumerate()
260  * ensures that any device we see is properly initialized by udev (eg. interface
261  * names); here we check that the properties are sane and mark the interface
262  * as ready for configuration in discover/network.
263  */
264 static int udev_check_interface_ready(struct device_handler *handler,
265                 struct udev_device *dev)
266 {
267         const char *name, *ifindex, *interface, *mac_name;
268         uint8_t *mac;
269         char byte[3];
270         unsigned int i, j;
271
272
273         name = udev_device_get_sysname(dev);
274         if (!name) {
275                 pb_debug("udev_device_get_sysname failed\n");
276                 return -1;
277         }
278
279         ifindex = udev_device_get_property_value(dev, "IFINDEX");
280         interface = udev_device_get_property_value(dev, "INTERFACE");
281         mac_name = udev_device_get_property_value(dev, "ID_NET_NAME_MAC");
282
283         /* Physical interfaces should have all of these properties */
284         if (!ifindex || !interface || !mac_name) {
285                 pb_debug("%s: interface %s missing properties\n",
286                                 __func__, name);
287                 return -1;
288         }
289
290         /* ID_NET_NAME_MAC format is enxMACADDR */
291         if (strlen(mac_name) < 15) {
292                 pb_debug("%s: Unexpected MAC format: %s\n",
293                                 __func__, mac_name);
294                 return -1;
295         }
296
297         mac = talloc_array(handler, uint8_t, HWADDR_SIZE);
298         if (!mac)
299                 return -1;
300
301         /*
302          * ID_NET_NAME_MAC is not a conventionally formatted MAC
303          * string - convert it before passing it to network.c
304          */
305         byte[2] = '\0';
306         for (i = strlen("enx"), j = 0;
307                         i < strlen(mac_name) && j < HWADDR_SIZE; i += 2) {
308                 memcpy(byte, &mac_name[i], 2);
309                 mac[j++] = strtoul(byte, NULL, 16);
310         }
311
312         network_mark_interface_ready(handler,
313                         atoi(ifindex), interface, mac, HWADDR_SIZE);
314
315         talloc_free(mac);
316         return 0;
317 }
318
319 static int udev_handle_dev_add(struct pb_udev *udev, struct udev_device *dev)
320 {
321         const char *subsys;
322         const char *name;
323
324         name = udev_device_get_sysname(dev);
325         if (!name) {
326                 pb_debug("udev_device_get_sysname failed\n");
327                 return -1;
328         }
329
330         subsys = udev_device_get_subsystem(dev);
331         if (!subsys) {
332                 pb_debug("udev_device_get_subsystem failed\n");
333                 return -1;
334         }
335
336         /* If we see a net device, check if it is ready to be used */
337         if (!strncmp(subsys, "net", strlen("net")))
338                 return udev_check_interface_ready(udev->handler, dev);
339
340         if (device_lookup_by_id(udev->handler, name)) {
341                 pb_debug("device %s is already present?\n", name);
342                 return -1;
343         }
344
345         if (!strcmp(subsys, "block")) {
346                 return udev_handle_block_add(udev, dev, name);
347         }
348
349         pb_log("SKIP %s: unknown subsystem %s\n", name, subsys);
350         return -1;
351 }
352
353
354 static int udev_handle_dev_remove(struct pb_udev *udev, struct udev_device *dev)
355 {
356         struct discover_device *ddev;
357         const char *name;
358
359         name = udev_device_get_sysname(dev);
360         if (!name) {
361                 pb_debug("udev_device_get_sysname failed\n");
362                 return -1;
363         }
364
365         ddev = device_lookup_by_id(udev->handler, name);
366         if (!ddev)
367                 return 0;
368
369         device_handler_remove(udev->handler, ddev);
370
371         return 0;
372 }
373
374 /* returns true if further event processing should stop (eg., we've
375  * ejected the cdrom)
376  */
377 static bool udev_handle_cdrom_events(struct pb_udev *udev,
378                 struct udev_device *dev, struct discover_device *ddev)
379 {
380         const char *node;
381         bool eject = false;
382
383         node = udev_device_get_devnode(dev);
384
385         /* handle CDROM eject requests */
386         if (udev_device_get_property_value(dev, "DISK_EJECT_REQUEST")) {
387                 pb_debug("udev: eject request\n");
388
389                 /* If the device is mounted, cdrom_id's own eject request may
390                  * have failed. So, we'll need to do our own here.
391                  */
392                 if (ddev) {
393                         eject = ddev->mounted;
394                         udev_handle_dev_remove(udev, dev);
395                 }
396
397                 if (eject)
398                         cdrom_eject(node);
399
400                 return true;
401         }
402
403         if (udev_device_get_property_value(dev, "DISK_MEDIA_CHANGE")) {
404                 if (cdrom_media_present(node))
405                         udev_handle_dev_add(udev, dev);
406                 else
407                         udev_handle_dev_remove(udev, dev);
408                 return true;
409         }
410
411         return false;
412 }
413
414 static int udev_handle_dev_change(struct pb_udev *udev, struct udev_device *dev)
415 {
416         struct discover_device *ddev;
417         const char *subsys;
418         const char *name;
419         int rc = 0;
420
421         name = udev_device_get_sysname(dev);
422         subsys = udev_device_get_subsystem(dev);
423
424         /* If we see a net device, check if it is ready to be used */
425         if (!strncmp(subsys, "net", strlen("net")))
426                 return udev_check_interface_ready(udev->handler, dev);
427
428         ddev = device_lookup_by_id(udev->handler, name);
429
430         /* if this is a CDROM device, process eject & media change requests;
431          * these may stop further processing */
432         if (!udev_device_get_property_value(dev, "ID_CDROM")) {
433                 if (udev_handle_cdrom_events(udev, dev, ddev))
434                         return 0;
435         }
436
437         /* if this is a new device, treat it as an add */
438         if (!ddev)
439                 rc = udev_handle_dev_add(udev, dev);
440
441         return rc;
442 }
443
444 static int udev_handle_dev_action(struct udev_device *dev, const char *action)
445 {
446         struct pb_udev *udev = udev_get_userdata(udev_device_get_udev(dev));
447         struct udev_list_entry *list;
448         const char *name;
449
450         list = udev_device_get_properties_list_entry(dev);
451         name = udev_device_get_sysname(dev);
452
453         pb_debug("udev: action %s, device %s\n", action, name);
454         pb_debug("udev: properties:\n");
455
456         for (; list; list = udev_list_entry_get_next(list))
457                 pb_debug("\t%-20s: %s\n", udev_list_entry_get_name(list),
458                                 udev_list_entry_get_value(list));
459
460         if (!strcmp(action, "add"))
461                 return udev_handle_dev_add(udev, dev);
462
463         else if (!strcmp(action, "remove"))
464                 return udev_handle_dev_remove(udev, dev);
465
466         else if (!strcmp(action, "change"))
467                 return udev_handle_dev_change(udev, dev);
468
469         return 0;
470 }
471
472 static int udev_enumerate(struct udev *udev)
473 {
474         int result;
475         struct udev_list_entry *list, *entry;
476         struct udev_enumerate *enumerate;
477
478         enumerate = udev_enumerate_new(udev);
479
480         if (!enumerate) {
481                 pb_log("udev_enumerate_new failed\n");
482                 return -1;
483         }
484
485         result = udev_enumerate_add_match_subsystem(enumerate, "block");
486         if (result) {
487                 pb_log("udev_enumerate_add_match_subsystem failed\n");
488                 goto fail;
489         }
490
491         result = udev_enumerate_add_match_subsystem(enumerate, "net");
492         if (result) {
493                 pb_log("udev_enumerate_add_match_subsystem failed\n");
494                 goto fail;
495         }
496
497         result = udev_enumerate_add_match_is_initialized(enumerate);
498         if (result) {
499                 pb_log("udev_enumerate_add_match_is_initialised failed\n");
500                 goto fail;
501         }
502
503         udev_enumerate_scan_devices(enumerate);
504
505         list = udev_enumerate_get_list_entry(enumerate);
506
507         udev_list_entry_foreach(entry, list) {
508                 const char *syspath;
509                 struct udev_device *dev;
510
511                 syspath = udev_list_entry_get_name(entry);
512                 dev = udev_device_new_from_syspath(udev, syspath);
513
514                 udev_handle_dev_action(dev, "add");
515
516                 udev_device_unref(dev);
517         }
518
519         udev_enumerate_unref(enumerate);
520         return 0;
521
522 fail:
523         udev_enumerate_unref(enumerate);
524         return -1;
525 }
526
527 static int udev_setup_monitor(struct udev *udev, struct udev_monitor **monitor)
528 {
529         int result;
530         struct udev_monitor *m;
531
532         *monitor = NULL;
533         m = udev_monitor_new_from_netlink(udev, "udev");
534
535         if (!m) {
536                 pb_log("udev_monitor_new_from_netlink failed\n");
537                 goto out_err;
538         }
539
540         result = udev_monitor_set_receive_buffer_size(m, monitor_bufsize);
541         if (result) {
542                 pb_log("udev_monitor_set_rx_bufsize(%d) failed\n",
543                         monitor_bufsize);
544         }
545
546         result = udev_monitor_filter_add_match_subsystem_devtype(m, "block",
547                 NULL);
548
549         if (result) {
550                 pb_log("udev_monitor_filter_add_match_subsystem_devtype failed\n");
551                 goto out_err;
552         }
553
554         result = udev_monitor_filter_add_match_subsystem_devtype(m, "net",
555                 NULL);
556
557         if (result) {
558                 pb_log("udev_monitor_filter_add_match_subsystem_devtype failed\n");
559                 goto out_err;
560         }
561
562         result = udev_monitor_enable_receiving(m);
563
564         if (result) {
565                 pb_log("udev_monitor_enable_receiving failed\n");
566                 goto out_err;
567         }
568
569         *monitor = m;
570         return 0;
571
572 out_err:
573         udev_monitor_unref(m);
574         return -1;
575 }
576
577 /*
578  * udev_process - waiter callback for monitor netlink.
579  */
580
581 static int udev_process(void *arg)
582 {
583         struct udev_monitor *monitor = arg;
584         struct udev_device *dev;
585         const char *action;
586
587         dev = udev_monitor_receive_device(monitor);
588         if (!dev) {
589                 pb_log("udev_monitor_receive_device failed\n");
590                 return -1;
591         }
592
593         action = udev_device_get_action(dev);
594
595         if (!action) {
596                 pb_log("udev_device_get_action failed\n");
597         } else {
598                 udev_handle_dev_action(dev, action);
599         }
600
601         udev_device_unref(dev);
602         return 0;
603 }
604
605 #ifdef UDEV_LOGGING
606 static void udev_log_fn(struct udev __attribute__((unused)) *udev,
607         int __attribute__((unused)) priority, const char *file, int line,
608         const char *fn, const char *format, va_list args)
609 {
610       pb_log("libudev: %s %s:%d: ", fn, file, line);
611       vfprintf(pb_log_get_stream(), format, args);
612 }
613 #endif
614
615 struct pb_udev *udev_init(struct device_handler *handler,
616                 struct waitset *waitset)
617 {
618         struct pb_udev *udev;
619         int result;
620
621         udev = talloc_zero(handler, struct pb_udev);
622         talloc_set_destructor(udev, udev_destructor);
623         udev->handler = handler;
624
625         udev->udev = udev_new();
626
627         if (!udev->udev) {
628                 pb_log("udev_new failed\n");
629                 goto fail;
630         }
631
632         udev_set_userdata(udev->udev, udev);
633
634 #ifdef UDEV_LOGGING
635         udev_set_log_fn(udev->udev, udev_log_fn);
636 #endif
637
638         result = udev_setup_monitor(udev->udev, &udev->monitor);
639         if (result)
640                 goto fail;
641
642         result = udev_enumerate(udev->udev);
643         if (result)
644                 goto fail;
645
646         waiter_register_io(waitset, udev_monitor_get_fd(udev->monitor), WAIT_IN,
647                 udev_process, udev->monitor);
648
649         pb_debug("%s: waiting on udev\n", __func__);
650
651         return udev;
652
653 fail:
654         talloc_free(udev);
655         return NULL;
656 }
657
658 void udev_reinit(struct pb_udev *udev)
659 {
660         pb_log("udev: reinit requested, starting enumeration\n");
661         udev_enumerate(udev->udev);
662 }