Debian Codegraph @

src/libsystemd/sd-device/device-monitor.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <linux/filter.h>
4 #include <linux/netlink.h>
5 #include <linux/sockios.h>
6 #include <sys/ioctl.h>
7 #include <unistd.h>
8
9 #include "sd-device.h"
10 #include "sd-event.h"
11
12 #include "MurmurHash2.h"
13 #include "alloc-util.h"
14 #include "device-filter.h"
15 #include "device-monitor-private.h"
16 #include "device-private.h"
17 #include "device-util.h"
18 #include "errno-util.h"
19 #include "fd-util.h"
20 #include "format-util.h"
21 #include "hashmap.h"
22 #include "io-util.h"
23 #include "iovec-util.h"
24 #include "log.h"
25 #include "log-context.h"
26 #include "mountpoint-util.h"
27 #include "set.h"
28 #include "socket-util.h"
29 #include "stat-util.h"
30 #include "string-util.h"
31 #include "uid-range.h"
32
33 #define log_monitor(m, format, ...) \
34 log_debug("sd-device-monitor(%s): " format, strna(m ? m->description : NULL), ##__VA_ARGS__)
35 #define log_monitor_errno(m, r, format, ...) \
36 log_debug_errno(r, "sd-device-monitor(%s): " format, strna(m ? m->description : NULL), ##__VA_ARGS__)
37 #define log_device_monitor(d, m, format, ...) \
38 log_device_debug(d, "sd-device-monitor(%s): " format, strna(m ? m->description : NULL), ##__VA_ARGS__)
39 #define log_device_monitor_errno(d, m, r, format, ...) \
40 log_device_debug_errno(d, r, "sd-device-monitor(%s): " format, strna(m ? m->description : NULL), ##__VA_ARGS__)
41
42 struct sd_device_monitor {
43 unsigned n_ref;
44
45 int sock;
46 union sockaddr_union snl;
47 union sockaddr_union snl_trusted_sender;
48
49 UIDRange *mapped_userns_uid_range;
50
51 Hashmap *subsystem_filter;
52 Set *tag_filter;
53 Hashmap *match_sysattr_filter;
54 Hashmap *nomatch_sysattr_filter;
55 Set *match_parent_filter;
56 Set *nomatch_parent_filter;
57 bool filter_uptodate;
58
59 bool multicast_group_dropped;
60 size_t multicast_group_len;
61 uint32_t *multicast_groups;
62
63 sd_event *event;
64 sd_event_source *event_source;
65 char *description;
66 sd_device_monitor_handler_t callback;
67 void *userdata;
68 };
69
70 #define UDEV_MONITOR_MAGIC 0xfeedcafe
71
72 typedef struct monitor_netlink_header {
73 /* "libudev" prefix to distinguish libudev and kernel messages */
74 char prefix[8];
75 /* Magic to protect against daemon <-> Library message format mismatch
76 * Used in the kernel from socket filter rules; needs to be stored in network order */
77 unsigned magic;
78 /* Total length of header structure known to the sender */
79 unsigned header_size;
80 /* Properties string buffer */
81 unsigned properties_off;
82 unsigned properties_len;
83 /* Hashes of primary device properties strings, to let libudev subscribers
84 * use in-kernel socket filters; values need to be stored in network order */
85 unsigned filter_subsystem_hash;
86 unsigned filter_devtype_hash;
87 unsigned filter_tag_bloom_hi;
88 unsigned filter_tag_bloom_lo;
89 } monitor_netlink_header;
90
91 static int monitor_set_nl_address(sd_device_monitor *m) {
92 union sockaddr_union snl;
93 socklen_t addrlen;
94
95 assert(m);
96
97 /* Get the address the kernel has assigned us.
98 * It is usually, but not necessarily the pid. */
99 addrlen = sizeof(struct sockaddr_nl);
100 if (getsockname(m->sock, &snl.sa, &addrlen) < 0)
101 return -errno;
102
103 m->snl.nl.nl_pid = snl.nl.nl_pid;
104 return 0;
105 }
106
107 int device_monitor_get_address(sd_device_monitor *m, union sockaddr_union *ret) {
108 assert(m);
109 assert(ret);
110
111 *ret = m->snl;
112 return 0;
113 }
114
115 int device_monitor_allow_unicast_sender(sd_device_monitor *m, sd_device_monitor *sender) {
116 assert(m);
117 assert(sender);
118
119 return device_monitor_get_address(sender, &m->snl_trusted_sender);
120 }
121
122 _public_ int sd_device_monitor_set_receive_buffer_size(sd_device_monitor *m, size_t size) {
123 assert_return(m, -EINVAL);
124
125 return fd_set_rcvbuf(m->sock, size, false);
126 }
127
128 _public_ int sd_device_monitor_get_fd(sd_device_monitor *m) {
129 assert_return(m, -EINVAL);
130
131 return m->sock;
132 }
133
134 _public_ int sd_device_monitor_get_events(sd_device_monitor *m) {
135 assert_return(m, -EINVAL);
136 assert_return(m->sock >= 0, -ESTALE);
137
138 return EPOLLIN;
139 }
140
141 _public_ int sd_device_monitor_get_timeout(sd_device_monitor *m, uint64_t *ret) {
142 assert_return(m, -EINVAL);
143 assert_return(m->sock >= 0, -ESTALE);
144
145 if (ret)
146 *ret = USEC_INFINITY;
147 return 0;
148 }
149
150 int device_monitor_new_full(sd_device_monitor **ret, MonitorNetlinkGroup group, int fd) {
151 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *m = NULL;
152 _cleanup_close_ int sock = -EBADF;
153 int r;
154
155 assert(group >= 0 && group < _MONITOR_NETLINK_GROUP_MAX);
156 assert_return(ret, -EINVAL);
157
158 if (group == MONITOR_GROUP_UDEV &&
159 access("/run/udev/control", F_OK) < 0 &&
160 dev_is_devtmpfs() <= 0) {
161
162 /*
163 * We do not support subscribing to uevents if no instance of
164 * udev is running. Uevents would otherwise broadcast the
165 * processing data of the host into containers, which is not
166 * desired.
167 *
168 * Containers will currently not get any udev uevents, until
169 * a supporting infrastructure is available.
170 *
171 * We do not set a netlink multicast group here, so the socket
172 * will not receive any messages.
173 */
174
175 log_monitor(m, "The udev service seems not to be active, disabling the monitor.");
176 group = MONITOR_GROUP_NONE;
177 }
178
179 if (fd < 0) {
180 sock = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC|SOCK_NONBLOCK, NETLINK_KOBJECT_UEVENT);
181 if (sock < 0)
182 return log_monitor_errno(m, errno, "Failed to create socket: %m");
183 }
184
185 m = new(sd_device_monitor, 1);
186 if (!m)
187 return -ENOMEM;
188
189 *m = (sd_device_monitor) {
190 .n_ref = 1,
191 .sock = fd >= 0 ? fd : TAKE_FD(sock),
192 .snl.nl.nl_family = AF_NETLINK,
193 .snl.nl.nl_groups = group,
194 };
195
196 if (fd < 0) {
197 /* enable receiving of sender credentials */
198 r = setsockopt_int(m->sock, SOL_SOCKET, SO_PASSCRED, true);
199 if (r < 0)
200 return log_monitor_errno(m, r, "Failed to set socket option SO_PASSCRED: %m");
201
202 if (bind(m->sock, &m->snl.sa, sizeof(struct sockaddr_nl)) < 0)
203 return log_monitor_errno(m, errno, "Failed to bind monitoring socket: %m");
204 }
205
206 r = monitor_set_nl_address(m);
207 if (r < 0) {
208 log_monitor_errno(m, r, "Failed to set netlink address: %m");
209 goto fail;
210 }
211
212 if (DEBUG_LOGGING) {
213 _cleanup_close_ int netns = -EBADF;
214
215 /* So here's the thing: only AF_NETLINK sockets from the main network namespace will get
216 * hardware events. Let's check if ours is from there, and if not generate a debug message,
217 * since we cannot possibly work correctly otherwise. This is just a safety check to make
218 * things easier to debug. */
219
220 netns = ioctl(m->sock, SIOCGSKNS);
221 if (netns < 0)
222 log_monitor_errno(m, errno, "Unable to get network namespace of udev netlink socket, unable to determine if we are in host netns, ignoring: %m");
223 else {
224 struct stat a, b;
225
226 if (fstat(netns, &a) < 0) {
227 r = log_monitor_errno(m, errno, "Failed to stat netns of udev netlink socket: %m");
228 goto fail;
229 }
230
231 if (stat("/proc/1/ns/net", &b) < 0) {
232 if (ERRNO_IS_PRIVILEGE(errno))
233 /* If we can't access PID1's netns info due to permissions, it's fine, this is a
234 * safety check only after all. */
235 log_monitor_errno(m, errno, "No permission to stat PID1's netns, unable to determine if we are in host netns, ignoring: %m");
236 else
237 log_monitor_errno(m, errno, "Failed to stat PID1's netns, ignoring: %m");
238
239 } else if (!stat_inode_same(&a, &b))
240 log_monitor(m, "Netlink socket we listen on is not from host netns, we won't see device events.");
241 }
242 }
243
244 /* Let's bump the receive buffer size, but only if we are not called via socket activation, as in
245 * that case the service manager sets the receive buffer size for us, and the value in the .socket
246 * unit should take full effect. */
247 if (fd < 0) {
248 r = sd_device_monitor_set_receive_buffer_size(m, 128*1024*1024);
249 if (r < 0)
250 log_monitor_errno(m, r, "Failed to increase receive buffer size, ignoring: %m");
251 }
252
253 *ret = TAKE_PTR(m);
254 return 0;
255
256 fail:
257 /* Let's unset the socket fd in the monitor object before we destroy it so that the fd passed in is
258 * not closed on failure. */
259 if (fd >= 0)
260 m->sock = -EBADF;
261
262 return r;
263 }
264
265 _public_ int sd_device_monitor_new(sd_device_monitor **ret) {
266 return device_monitor_new_full(ret, MONITOR_GROUP_UDEV, -EBADF);
267 }
268
269 _public_ int sd_device_monitor_is_running(sd_device_monitor *m) {
270 if (!m)
271 return 0;
272
273 return sd_event_source_get_enabled(m->event_source, NULL);
274 }
275
276 static int device_monitor_update_multicast_groups(sd_device_monitor *m, bool add) {
277 int r, opt = add ? NETLINK_ADD_MEMBERSHIP : NETLINK_DROP_MEMBERSHIP;
278
279 assert(m);
280 assert(m->sock >= 0);
281
282 for (size_t i = 0; i < m->multicast_group_len; i++)
283 for (unsigned j = 0; j < sizeof(uint32_t) * 8; j++)
284 if (m->multicast_groups[i] & (1U << j)) {
285 unsigned group = i * sizeof(uint32_t) * 8 + j + 1;
286
287 /* group is "unsigned", but netlink(7) says the argument is "int". */
288 r = setsockopt_int(m->sock, SOL_NETLINK, opt, group);
289 if (r < 0)
290 return r;
291 }
292
293 return 0;
294 }
295
296 _public_ int sd_device_monitor_stop(sd_device_monitor *m) {
297 int r;
298
299 assert_return(m, -EINVAL);
300 assert_return(m->sock >= 0, -ESTALE);
301
302 if (!m->multicast_group_dropped) {
303 m->multicast_group_len = 0;
304 m->multicast_groups = mfree(m->multicast_groups);
305
306 /* Save multicast groups. */
307 r = netlink_socket_get_multicast_groups(m->sock, &m->multicast_group_len, &m->multicast_groups);
308 if (r < 0)
309 return r;
310
311 /* Leave from all multicast groups to prevent the buffer is filled. */
312 r = device_monitor_update_multicast_groups(m, /* add= */ false);
313 if (r < 0)
314 return r;
315
316 m->multicast_group_dropped = true;
317 }
318
319 return sd_event_source_set_enabled(m->event_source, SD_EVENT_OFF);
320 }
321
322 static int device_monitor_event_handler(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
323 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
324 _unused_ _cleanup_(log_context_unrefp) LogContext *c = NULL;
325 sd_device_monitor *m = ASSERT_PTR(userdata);
326
327 if (sd_device_monitor_receive(m, &device) <= 0)
328 return 0;
329
330 if (log_context_enabled())
331 c = log_context_new_strv_consume(device_make_log_fields(device));
332
333 if (m->callback)
334 return m->callback(m, device, m->userdata);
335
336 return 0;
337 }
338
339 _public_ int sd_device_monitor_start(sd_device_monitor *m, sd_device_monitor_handler_t callback, void *userdata) {
340 int r;
341
342 assert_return(m, -EINVAL);
343 assert_return(m->sock >= 0, -ESTALE);
344
345 if (!m->event) {
346 r = sd_device_monitor_attach_event(m, NULL);
347 if (r < 0)
348 return r;
349 }
350
351 r = sd_device_monitor_filter_update(m);
352 if (r < 0)
353 return log_monitor_errno(m, r, "Failed to update filter: %m");
354
355 m->callback = callback;
356 m->userdata = userdata;
357
358 if (!m->event_source) {
359 /* The monitor has never started. Add IO event source. */
360 r = sd_event_add_io(m->event, &m->event_source, m->sock, EPOLLIN, device_monitor_event_handler, m);
361 if (r < 0)
362 return r;
363
364 (void) sd_event_source_set_description(m->event_source, m->description ?: "sd-device-monitor");
365 return 0;
366 }
367
368 r = sd_device_monitor_is_running(m);
369 if (r < 0)
370 return r;
371 if (r == 0) {
372 /* If the monitor was previously started but now it is stopped, flush anything queued during
373 * the monitor is stopped. */
374 r = flush_fd(m->sock);
375 if (r < 0)
376 return r;
377
378 /* Then, join the saved broadcast groups again. */
379 r = device_monitor_update_multicast_groups(m, /* add= */ true);
380 if (r < 0)
381 return r;
382
383 m->multicast_group_dropped = false;
384 }
385
386 return sd_event_source_set_enabled(m->event_source, SD_EVENT_ON);
387 }
388
389 _public_ int sd_device_monitor_detach_event(sd_device_monitor *m) {
390 assert_return(m, -EINVAL);
391
392 m->event_source = sd_event_source_unref(m->event_source);
393 m->event = sd_event_unref(m->event);
394
395 return 0;
396 }
397
398 _public_ int sd_device_monitor_attach_event(sd_device_monitor *m, sd_event *event) {
399 int r;
400
401 assert_return(m, -EINVAL);
402 assert_return(!m->event, -EBUSY);
403
404 if (event)
405 m->event = sd_event_ref(event);
406 else {
407 r = sd_event_default(&m->event);
408 if (r < 0)
409 return r;
410 }
411
412 return 0;
413 }
414
415 _public_ sd_event* sd_device_monitor_get_event(sd_device_monitor *m) {
416 assert_return(m, NULL);
417
418 return m->event;
419 }
420
421 _public_ sd_event_source* sd_device_monitor_get_event_source(sd_device_monitor *m) {
422 assert_return(m, NULL);
423
424 return m->event_source;
425 }
426
427 _public_ int sd_device_monitor_set_description(sd_device_monitor *m, const char *description) {
428 int r;
429
430 assert_return(m, -EINVAL);
431
432 r = free_and_strdup(&m->description, description);
433 if (r <= 0)
434 return r;
435
436 if (m->event_source)
437 (void) sd_event_source_set_description(m->event_source, description);
438
439 return r;
440 }
441
442 _public_ int sd_device_monitor_get_description(sd_device_monitor *m, const char **ret) {
443 assert_return(m, -EINVAL);
444 assert_return(ret, -EINVAL);
445
446 *ret = m->description;
447 return 0;
448 }
449
450 static sd_device_monitor* device_monitor_free(sd_device_monitor *m) {
451 assert(m);
452
453 (void) sd_device_monitor_detach_event(m);
454 m->sock = safe_close(m->sock);
455
456 uid_range_free(m->mapped_userns_uid_range);
457 free(m->description);
458 hashmap_free(m->subsystem_filter);
459 set_free(m->tag_filter);
460 hashmap_free(m->match_sysattr_filter);
461 hashmap_free(m->nomatch_sysattr_filter);
462 set_free(m->match_parent_filter);
463 set_free(m->nomatch_parent_filter);
464 free(m->multicast_groups);
465
466 return mfree(m);
467 }
468
469 DEFINE_PUBLIC_TRIVIAL_REF_UNREF_FUNC(sd_device_monitor, sd_device_monitor, device_monitor_free);
470
471 static int check_subsystem_filter(sd_device_monitor *m, sd_device *device) {
472 const char *s, *d;
473 int r;
474
475 assert(m);
476 assert(device);
477
478 if (hashmap_isempty(m->subsystem_filter))
479 return true;
480
481 HASHMAP_FOREACH_KEY(d, s, m->subsystem_filter) {
482 r = device_is_subsystem_devtype(device, s, d);
483 if (r != 0)
484 return r;
485 }
486
487 return false;
488 }
489
490 static bool check_tag_filter(sd_device_monitor *m, sd_device *device) {
491 const char *tag;
492
493 assert(m);
494 assert(device);
495
496 if (set_isempty(m->tag_filter))
497 return true;
498
499 SET_FOREACH(tag, m->tag_filter)
500 if (sd_device_has_tag(device, tag) > 0)
501 return true;
502
503 return false;
504 }
505
506 static int passes_filter(sd_device_monitor *m, sd_device *device) {
507 int r;
508
509 assert(m);
510 assert(device);
511
512 r = check_subsystem_filter(m, device);
513 if (r <= 0)
514 return r;
515
516 if (!check_tag_filter(m, device))
517 return false;
518
519 if (!device_match_sysattr(device, m->match_sysattr_filter, m->nomatch_sysattr_filter))
520 return false;
521
522 return device_match_parent(device, m->match_parent_filter, m->nomatch_parent_filter);
523 }
524
525 static bool check_sender_uid(sd_device_monitor *m, uid_t uid) {
526 int r;
527
528 assert(m);
529
530 /* Always trust messages from uid 0. */
531 if (uid == 0)
532 return true;
533
534 /* Trust messages sent by the same UID we are running. Currently, such situation happens only for
535 * unicast messages. */
536 if (uid == getuid() || uid == geteuid())
537 return true;
538
539 if (!m->mapped_userns_uid_range) {
540 r = uid_range_load_userns(/* path= */ NULL, UID_RANGE_USERNS_INSIDE, &m->mapped_userns_uid_range);
541 if (r < 0)
542 log_monitor_errno(m, r, "Failed to load UID ranges mapped to the current user namespace, ignoring: %m");
543 }
544
545 /* Trust messages come from outside of the current user namespace. */
546 if (!uid_range_contains(m->mapped_userns_uid_range, uid))
547 return true;
548
549 /* Otherwise, refuse messages. */
550 return false;
551 }
552
553 _public_ int sd_device_monitor_receive(sd_device_monitor *m, sd_device **ret) {
554 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
555 _cleanup_free_ uint8_t *buf_alloc = NULL;
556 union {
557 monitor_netlink_header *nlh;
558 char *nulstr;
559 uint8_t *buf;
560 } message;
561 struct iovec iov;
562 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred))) control;
563 union sockaddr_union snl;
564 struct msghdr smsg = {
565 .msg_iov = &iov,
566 .msg_iovlen = 1,
567 .msg_control = &control,
568 .msg_controllen = sizeof(control),
569 .msg_name = &snl,
570 .msg_namelen = sizeof(snl),
571 };
572 struct ucred *cred;
573 size_t offset;
574 ssize_t n;
575 bool is_initialized = false;
576 int r;
577
578 assert_return(m, -EINVAL);
579 assert_return(ret, -EINVAL);
580
581 n = next_datagram_size_fd(m->sock);
582 if (n < 0) {
583 if (!ERRNO_IS_TRANSIENT(n))
584 log_monitor_errno(m, n, "Failed to get the received message size: %m");
585 return n;
586 }
587
588 if ((size_t) n < ALLOCA_MAX / sizeof(uint8_t) / 2)
589 message.buf = newa(uint8_t, n);
590 else {
591 buf_alloc = new(uint8_t, n);
592 if (!buf_alloc)
593 return log_oom_debug();
594
595 message.buf = buf_alloc;
596 }
597
598 iov = IOVEC_MAKE(message.buf, n);
599
600 n = recvmsg_safe(m->sock, &smsg, 0);
601 if (n < 0) {
602 if (!ERRNO_IS_NEG_TRANSIENT(n))
603 log_monitor_errno(m, n, "Failed to receive message: %s",
604 n == -ECHRNG ? "got truncated control data" :
605 n == -EXFULL ? "got truncated payload data" :
606 STRERROR((int) n));
607 return n;
608 }
609 if (n < 32)
610 return log_monitor_errno(m, SYNTHETIC_ERRNO(EINVAL), "Invalid message length (%zi), ignoring message.", n);
611
612 if (snl.nl.nl_groups == MONITOR_GROUP_NONE) {
613 /* unicast message, check if we trust the sender */
614 if (m->snl_trusted_sender.nl.nl_pid == 0 ||
615 snl.nl.nl_pid != m->snl_trusted_sender.nl.nl_pid)
616 return log_monitor_errno(m, SYNTHETIC_ERRNO(EAGAIN),
617 "Unicast netlink message ignored.");
618
619 } else if (snl.nl.nl_groups == MONITOR_GROUP_KERNEL) {
620 if (snl.nl.nl_pid > 0)
621 return log_monitor_errno(m, SYNTHETIC_ERRNO(EAGAIN),
622 "Multicast kernel netlink message from PID %"PRIu32" ignored.",
623 snl.nl.nl_pid);
624 }
625
626 cred = CMSG_FIND_DATA(&smsg, SOL_SOCKET, SCM_CREDENTIALS, struct ucred);
627 if (!cred)
628 return log_monitor_errno(m, SYNTHETIC_ERRNO(EAGAIN),
629 "No sender credentials received, ignoring message.");
630
631 if (!check_sender_uid(m, cred->uid))
632 return log_monitor_errno(m, SYNTHETIC_ERRNO(EAGAIN),
633 "Sender uid="UID_FMT", message ignored.", cred->uid);
634
635 if (!memchr(message.buf, 0, n))
636 return log_monitor_errno(m, SYNTHETIC_ERRNO(EAGAIN), "Received message without NUL, ignoring message.");
637
638 if (streq(message.nulstr, "libudev")) {
639 /* udev message needs proper version magic */
640 if (message.nlh->magic != htobe32(UDEV_MONITOR_MAGIC))
641 return log_monitor_errno(m, SYNTHETIC_ERRNO(EAGAIN),
642 "Invalid message signature (%x != %x).",
643 message.nlh->magic, htobe32(UDEV_MONITOR_MAGIC));
644
645 if (message.nlh->properties_off + 32 > (size_t) n)
646 return log_monitor_errno(m, SYNTHETIC_ERRNO(EAGAIN),
647 "Invalid offset for properties (%u > %zi).",
648 message.nlh->properties_off + 32, n);
649
650 offset = message.nlh->properties_off;
651
652 /* devices received from udev are always initialized */
653 is_initialized = true;
654
655 } else {
656 /* check kernel message header */
657 if (!strstr(message.nulstr, "@/"))
658 return log_monitor_errno(m, SYNTHETIC_ERRNO(EAGAIN), "Invalid message header.");
659
660 offset = strlen(message.nulstr) + 1;
661 if (offset >= (size_t) n)
662 return log_monitor_errno(m, SYNTHETIC_ERRNO(EAGAIN), "Invalid message length.");
663 }
664
665 r = device_new_from_nulstr(&device, message.nulstr + offset, n - offset);
666 if (r < 0)
667 return log_monitor_errno(m, r, "Failed to create device from received message: %m");
668
669 if (is_initialized)
670 device_set_is_initialized(device);
671
672 /* Skip device, if it does not pass the current filter */
673 r = passes_filter(m, device);
674 if (r < 0)
675 return log_device_monitor_errno(device, m, r, "Failed to check received device passing filter: %m");
676 if (r == 0) {
677 log_device_monitor(device, m, "Received device does not pass filter, ignoring.");
678 *ret = NULL;
679 } else
680 *ret = TAKE_PTR(device);
681
682 return r;
683 }
684
685 static uint32_t string_hash32(const char *str) {
686 return MurmurHash2(str, strlen(str), 0);
687 }
688
689 /* Get a bunch of bit numbers out of the hash, and set the bits in our bit field */
690 static uint64_t string_bloom64(const char *str) {
691 uint64_t bits = 0;
692 uint32_t hash = string_hash32(str);
693
694 bits |= UINT64_C(1) << (hash & 63);
695 bits |= UINT64_C(1) << ((hash >> 6) & 63);
696 bits |= UINT64_C(1) << ((hash >> 12) & 63);
697 bits |= UINT64_C(1) << ((hash >> 18) & 63);
698 return bits;
699 }
700
701 int device_monitor_send(
702 sd_device_monitor *m,
703 const union sockaddr_union *destination,
704 sd_device *device) {
705
706 monitor_netlink_header nlh = {
707 .prefix = "libudev",
708 .magic = htobe32(UDEV_MONITOR_MAGIC),
709 .header_size = sizeof nlh,
710 };
711 struct iovec iov[2] = {
712 { .iov_base = &nlh, .iov_len = sizeof nlh },
713 };
714 struct msghdr smsg = {
715 .msg_iov = iov,
716 .msg_iovlen = 2,
717 };
718 /* default destination for sending */
719 static const union sockaddr_union default_destination = {
720 .nl.nl_family = AF_NETLINK,
721 .nl.nl_groups = MONITOR_GROUP_UDEV,
722 };
723 uint64_t tag_bloom_bits;
724 const char *buf, *val;
725 ssize_t count;
726 size_t blen;
727 int r;
728
729 assert(m);
730 assert(device);
731
732 r = device_get_properties_nulstr(device, &buf, &blen);
733 if (r < 0)
734 return log_device_monitor_errno(device, m, r, "Failed to get device properties: %m");
735 if (blen < 32)
736 return log_device_monitor_errno(device, m, SYNTHETIC_ERRNO(EINVAL),
737 "Length of device property nulstr is too small to contain valid device information.");
738
739 /* fill in versioned header */
740 r = sd_device_get_subsystem(device, &val);
741 if (r < 0)
742 return log_device_monitor_errno(device, m, r, "Failed to get device subsystem: %m");
743 nlh.filter_subsystem_hash = htobe32(string_hash32(val));
744
745 if (sd_device_get_devtype(device, &val) >= 0)
746 nlh.filter_devtype_hash = htobe32(string_hash32(val));
747
748 /* add tag bloom filter */
749 tag_bloom_bits = 0;
750 FOREACH_DEVICE_TAG(device, tag)
751 tag_bloom_bits |= string_bloom64(tag);
752
753 if (tag_bloom_bits > 0) {
754 nlh.filter_tag_bloom_hi = htobe32(tag_bloom_bits >> 32);
755 nlh.filter_tag_bloom_lo = htobe32(tag_bloom_bits & 0xffffffff);
756 }
757
758 /* add properties list */
759 nlh.properties_off = iov[0].iov_len;
760 nlh.properties_len = blen;
761 iov[1] = IOVEC_MAKE((char*) buf, blen);
762
763 /*
764 * Use custom address for target, or the default one.
765 *
766 * If we send to a multicast group, we will get
767 * ECONNREFUSED, which is expected.
768 */
769 smsg.msg_name = (struct sockaddr_nl*) &(destination ?: &default_destination)->nl;
770 smsg.msg_namelen = sizeof(struct sockaddr_nl);
771 count = sendmsg(m->sock, &smsg, 0);
772 if (count < 0) {
773 if (!destination && errno == ECONNREFUSED) {
774 log_device_monitor(device, m, "Passed to netlink monitor.");
775 return 0;
776 } else
777 return log_device_monitor_errno(device, m, errno, "Failed to send device to netlink monitor: %m");
778 }
779
780 log_device_monitor(device, m, "Passed %zi byte to netlink monitor.", count);
781 return count;
782 }
783
784 static void bpf_stmt(struct sock_filter *ins, unsigned *i,
785 unsigned short code, unsigned data) {
786 assert(i);
787
788 ins[(*i)++] = (struct sock_filter) {
789 .code = code,
790 .k = data,
791 };
792 }
793
794 static void bpf_jmp(struct sock_filter *ins, unsigned *i,
795 unsigned short code, unsigned data,
796 unsigned short jt, unsigned short jf) {
797 assert(i);
798
799 ins[(*i)++] = (struct sock_filter) {
800 .code = code,
801 .jt = jt,
802 .jf = jf,
803 .k = data,
804 };
805 }
806
807 _public_ int sd_device_monitor_filter_update(sd_device_monitor *m) {
808 struct sock_filter ins[512] = {};
809 struct sock_fprog filter;
810 const char *subsystem, *devtype, *tag;
811 unsigned i = 0;
812
813 assert_return(m, -EINVAL);
814
815 if (m->filter_uptodate)
816 return 0;
817
818 if (m->snl.nl.nl_groups == MONITOR_GROUP_KERNEL ||
819 (hashmap_isempty(m->subsystem_filter) &&
820 set_isempty(m->tag_filter))) {
821 m->filter_uptodate = true;
822 return 0;
823 }
824
825 /* load magic in A */
826 bpf_stmt(ins, &i, BPF_LD|BPF_W|BPF_ABS, offsetof(monitor_netlink_header, magic));
827 /* jump if magic matches */
828 bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, UDEV_MONITOR_MAGIC, 1, 0);
829 /* wrong magic, pass packet */
830 bpf_stmt(ins, &i, BPF_RET|BPF_K, 0xffffffff);
831
832 if (!set_isempty(m->tag_filter)) {
833 int tag_matches = set_size(m->tag_filter);
834
835 /* add all tags matches */
836 SET_FOREACH(tag, m->tag_filter) {
837 uint64_t tag_bloom_bits = string_bloom64(tag);
838 uint32_t tag_bloom_hi = tag_bloom_bits >> 32;
839 uint32_t tag_bloom_lo = tag_bloom_bits & 0xffffffff;
840
841 /* load device bloom bits in A */
842 bpf_stmt(ins, &i, BPF_LD|BPF_W|BPF_ABS, offsetof(monitor_netlink_header, filter_tag_bloom_hi));
843 /* clear bits (tag bits & bloom bits) */
844 bpf_stmt(ins, &i, BPF_ALU|BPF_AND|BPF_K, tag_bloom_hi);
845 /* jump to next tag if it does not match */
846 bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, tag_bloom_hi, 0, 3);
847
848 /* load device bloom bits in A */
849 bpf_stmt(ins, &i, BPF_LD|BPF_W|BPF_ABS, offsetof(monitor_netlink_header, filter_tag_bloom_lo));
850 /* clear bits (tag bits & bloom bits) */
851 bpf_stmt(ins, &i, BPF_ALU|BPF_AND|BPF_K, tag_bloom_lo);
852 /* jump behind end of tag match block if tag matches */
853 tag_matches--;
854 bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, tag_bloom_lo, 1 + (tag_matches * 6), 0);
855 }
856
857 /* nothing matched, drop packet */
858 bpf_stmt(ins, &i, BPF_RET|BPF_K, 0);
859 }
860
861 /* add all subsystem matches */
862 if (!hashmap_isempty(m->subsystem_filter)) {
863 HASHMAP_FOREACH_KEY(devtype, subsystem, m->subsystem_filter) {
864 uint32_t hash = string_hash32(subsystem);
865
866 /* load device subsystem value in A */
867 bpf_stmt(ins, &i, BPF_LD|BPF_W|BPF_ABS, offsetof(monitor_netlink_header, filter_subsystem_hash));
868 if (!devtype) {
869 /* jump if subsystem does not match */
870 bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, hash, 0, 1);
871 } else {
872 /* jump if subsystem does not match */
873 bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, hash, 0, 3);
874 /* load device devtype value in A */
875 bpf_stmt(ins, &i, BPF_LD|BPF_W|BPF_ABS, offsetof(monitor_netlink_header, filter_devtype_hash));
876 /* jump if value does not match */
877 hash = string_hash32(devtype);
878 bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, hash, 0, 1);
879 }
880
881 /* matched, pass packet */
882 bpf_stmt(ins, &i, BPF_RET|BPF_K, 0xffffffff);
883
884 if (i+1 >= ELEMENTSOF(ins))
885 return -E2BIG;
886 }
887
888 /* nothing matched, drop packet */
889 bpf_stmt(ins, &i, BPF_RET|BPF_K, 0);
890 }
891
892 /* matched, pass packet */
893 bpf_stmt(ins, &i, BPF_RET|BPF_K, 0xffffffff);
894
895 /* install filter */
896 filter = (struct sock_fprog) {
897 .len = i,
898 .filter = ins,
899 };
900 if (setsockopt(m->sock, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)) < 0)
901 return -errno;
902
903 m->filter_uptodate = true;
904 return 0;
905 }
906
907 _public_ int sd_device_monitor_filter_add_match_subsystem_devtype(sd_device_monitor *m, const char *subsystem, const char *devtype) {
908 int r;
909
910 assert_return(m, -EINVAL);
911 assert_return(subsystem, -EINVAL);
912
913 /* Do not use string_has_ops_free_free or hashmap_put_strdup() here, as this may be called
914 * multiple times with the same subsystem but different devtypes. */
915 r = hashmap_put_strdup_full(&m->subsystem_filter, &trivial_hash_ops_free_free, subsystem, devtype);
916 if (r <= 0)
917 return r;
918
919 m->filter_uptodate = false;
920 return r;
921 }
922
923 _public_ int sd_device_monitor_filter_add_match_tag(sd_device_monitor *m, const char *tag) {
924 int r;
925
926 assert_return(m, -EINVAL);
927 assert_return(tag, -EINVAL);
928
929 r = set_put_strdup(&m->tag_filter, tag);
930 if (r <= 0)
931 return r;
932
933 m->filter_uptodate = false;
934 return r;
935 }
936
937 _public_ int sd_device_monitor_filter_add_match_sysattr(sd_device_monitor *m, const char *sysattr, const char *value, int match) {
938 Hashmap **hashmap;
939
940 assert_return(m, -EINVAL);
941 assert_return(sysattr, -EINVAL);
942
943 if (match)
944 hashmap = &m->match_sysattr_filter;
945 else
946 hashmap = &m->nomatch_sysattr_filter;
947
948 /* TODO: unset m->filter_uptodate on success when we support this filter on BPF. */
949 return update_match_strv(hashmap, sysattr, value, /* clear_on_null= */ true);
950 }
951
952 _public_ int sd_device_monitor_filter_add_match_parent(sd_device_monitor *m, sd_device *device, int match) {
953 const char *syspath;
954 Set **set;
955 int r;
956
957 assert_return(m, -EINVAL);
958 assert_return(device, -EINVAL);
959
960 r = sd_device_get_syspath(device, &syspath);
961 if (r < 0)
962 return r;
963
964 if (match)
965 set = &m->match_parent_filter;
966 else
967 set = &m->nomatch_parent_filter;
968
969 /* TODO: unset m->filter_uptodate on success when we support this filter on BPF. */
970 return set_put_strdup(set, syspath);
971 }
972
973 _public_ int sd_device_monitor_filter_remove(sd_device_monitor *m) {
974 static const struct sock_fprog filter = { 0, NULL };
975
976 assert_return(m, -EINVAL);
977
978 m->subsystem_filter = hashmap_free(m->subsystem_filter);
979 m->tag_filter = set_free(m->tag_filter);
980 m->match_sysattr_filter = hashmap_free(m->match_sysattr_filter);
981 m->nomatch_sysattr_filter = hashmap_free(m->nomatch_sysattr_filter);
982 m->match_parent_filter = set_free(m->match_parent_filter);
983 m->nomatch_parent_filter = set_free(m->nomatch_parent_filter);
984
985 if (setsockopt(m->sock, SOL_SOCKET, SO_DETACH_FILTER, &filter, sizeof(filter)) < 0)
986 return -errno;
987
988 m->filter_uptodate = true;
989 return 0;
990 }