]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/libsystemd/sd-device/device-monitor.c
Merge pull request #16145 from poettering/qrcode-dlopen
[thirdparty/systemd.git] / src / libsystemd / sd-device / device-monitor.c
CommitLineData
b1c097af
YW
1/* SPDX-License-Identifier: LGPL-2.1+ */
2
3#include <errno.h>
4#include <linux/filter.h>
5#include <linux/netlink.h>
f6dbcebd
LP
6#include <linux/sockios.h>
7#include <sys/ioctl.h>
f5947a5e 8#include <unistd.h>
b1c097af
YW
9
10#include "sd-device.h"
11#include "sd-event.h"
12
13#include "MurmurHash2.h"
14#include "alloc-util.h"
15#include "device-monitor-private.h"
16#include "device-private.h"
17#include "device-util.h"
f6dbcebd 18#include "errno-util.h"
b1c097af
YW
19#include "fd-util.h"
20#include "format-util.h"
21#include "hashmap.h"
cb310866 22#include "io-util.h"
f6dbcebd 23#include "missing_socket.h"
049af8ad 24#include "mountpoint-util.h"
b1c097af
YW
25#include "set.h"
26#include "socket-util.h"
27#include "string-util.h"
28#include "strv.h"
29
30struct sd_device_monitor {
31 unsigned n_ref;
32
33 int sock;
34 union sockaddr_union snl;
35 union sockaddr_union snl_trusted_sender;
36 bool bound;
37
38 Hashmap *subsystem_filter;
39 Set *tag_filter;
40 bool filter_uptodate;
41
42 sd_event *event;
43 sd_event_source *event_source;
b1c097af
YW
44 sd_device_monitor_handler_t callback;
45 void *userdata;
46};
47
48#define UDEV_MONITOR_MAGIC 0xfeedcafe
49
50typedef struct monitor_netlink_header {
51 /* "libudev" prefix to distinguish libudev and kernel messages */
52 char prefix[8];
53 /* Magic to protect against daemon <-> Library message format mismatch
54 * Used in the kernel from socket filter rules; needs to be stored in network order */
55 unsigned magic;
56 /* Total length of header structure known to the sender */
57 unsigned header_size;
58 /* Properties string buffer */
59 unsigned properties_off;
60 unsigned properties_len;
61 /* Hashes of primary device properties strings, to let libudev subscribers
62 * use in-kernel socket filters; values need to be stored in network order */
63 unsigned filter_subsystem_hash;
64 unsigned filter_devtype_hash;
65 unsigned filter_tag_bloom_hi;
66 unsigned filter_tag_bloom_lo;
67} monitor_netlink_header;
68
69static int monitor_set_nl_address(sd_device_monitor *m) {
70 union sockaddr_union snl;
71 socklen_t addrlen;
72
73 assert(m);
74
75 /* Get the address the kernel has assigned us.
76 * It is usually, but not necessarily the pid. */
77 addrlen = sizeof(struct sockaddr_nl);
78 if (getsockname(m->sock, &snl.sa, &addrlen) < 0)
79 return -errno;
80
81 m->snl.nl.nl_pid = snl.nl.nl_pid;
82 return 0;
83}
84
85int device_monitor_allow_unicast_sender(sd_device_monitor *m, sd_device_monitor *sender) {
86 assert_return(m, -EINVAL);
87 assert_return(sender, -EINVAL);
88
89 m->snl_trusted_sender.nl.nl_pid = sender->snl.nl.nl_pid;
90 return 0;
91}
92
93_public_ int sd_device_monitor_set_receive_buffer_size(sd_device_monitor *m, size_t size) {
9e5b6496 94 int r, n = (int) size;
b1c097af
YW
95
96 assert_return(m, -EINVAL);
dcdc2f61 97 assert_return((size_t) n == size, -EINVAL);
b1c097af 98
ee0b9e72
YW
99 if (setsockopt_int(m->sock, SOL_SOCKET, SO_RCVBUFFORCE, n) < 0) {
100 r = setsockopt_int(m->sock, SOL_SOCKET, SO_RCVBUF, n);
9e5b6496
YW
101 if (r < 0)
102 return r;
103 }
b1c097af
YW
104
105 return 0;
106}
107
108int device_monitor_disconnect(sd_device_monitor *m) {
109 assert(m);
110
111 m->sock = safe_close(m->sock);
112 return 0;
113}
114
115int device_monitor_get_fd(sd_device_monitor *m) {
116 assert_return(m, -EINVAL);
117
118 return m->sock;
119}
120
121int device_monitor_new_full(sd_device_monitor **ret, MonitorNetlinkGroup group, int fd) {
122 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *m = NULL;
123 _cleanup_close_ int sock = -1;
124 int r;
125
126 assert_return(ret, -EINVAL);
127 assert_return(group >= 0 && group < _MONITOR_NETLINK_GROUP_MAX, -EINVAL);
128
129 if (group == MONITOR_GROUP_UDEV &&
130 access("/run/udev/control", F_OK) < 0 &&
131 dev_is_devtmpfs() <= 0) {
132
133 /*
134 * We do not support subscribing to uevents if no instance of
135 * udev is running. Uevents would otherwise broadcast the
136 * processing data of the host into containers, which is not
137 * desired.
138 *
139 * Containers will currently not get any udev uevents, until
140 * a supporting infrastructure is available.
141 *
142 * We do not set a netlink multicast group here, so the socket
143 * will not receive any messages.
144 */
145
c7d54dae 146 log_debug("sd-device-monitor: The udev service seems not to be active, disabling the monitor");
b1c097af
YW
147 group = MONITOR_GROUP_NONE;
148 }
149
150 if (fd < 0) {
151 sock = socket(PF_NETLINK, SOCK_RAW|SOCK_CLOEXEC|SOCK_NONBLOCK, NETLINK_KOBJECT_UEVENT);
152 if (sock < 0)
c7d54dae 153 return log_debug_errno(errno, "sd-device-monitor: Failed to create socket: %m");
b1c097af
YW
154 }
155
156 m = new(sd_device_monitor, 1);
157 if (!m)
158 return -ENOMEM;
159
160 *m = (sd_device_monitor) {
161 .n_ref = 1,
162 .sock = fd >= 0 ? fd : TAKE_FD(sock),
163 .bound = fd >= 0,
164 .snl.nl.nl_family = AF_NETLINK,
165 .snl.nl.nl_groups = group,
166 };
167
168 if (fd >= 0) {
169 r = monitor_set_nl_address(m);
f6dbcebd
LP
170 if (r < 0) {
171 log_debug_errno(r, "sd-device-monitor: Failed to set netlink address: %m");
172 goto fail;
173 }
174 }
175
176 if (DEBUG_LOGGING) {
177 _cleanup_close_ int netns = -1;
178
179 /* So here's the thing: only AF_NETLINK sockets from the main network namespace will get
180 * hardware events. Let's check if ours is from there, and if not generate a debug message,
181 * since we cannot possibly work correctly otherwise. This is just a safety check to make
182 * things easier to debug. */
183
184 netns = ioctl(m->sock, SIOCGSKNS);
185 if (netns < 0)
186 log_debug_errno(errno, "sd-device-monitor: Unable to get network namespace of udev netlink socket, unable to determine if we are in host netns: %m");
187 else {
188 struct stat a, b;
189
190 if (fstat(netns, &a) < 0) {
191 r = log_debug_errno(errno, "sd-device-monitor: Failed to stat netns of udev netlink socket: %m");
192 goto fail;
193 }
194
195 if (stat("/proc/1/ns/net", &b) < 0) {
196 if (ERRNO_IS_PRIVILEGE(errno))
197 /* If we can't access PID1's netns info due to permissions, it's fine, this is a
198 * safety check only after all. */
199 log_debug_errno(errno, "sd-device-monitor: No permission to stat PID1's netns, unable to determine if we are in host netns: %m");
200 else
201 log_debug_errno(errno, "sd-device-monitor: Failed to stat PID1's netns: %m");
202
203 } else if (a.st_dev != b.st_dev || a.st_ino != b.st_ino)
204 log_debug("sd-device-monitor: Netlink socket we listen on is not from host netns, we won't see device events.");
205 }
b1c097af
YW
206 }
207
208 *ret = TAKE_PTR(m);
209 return 0;
f6dbcebd
LP
210
211fail:
212 /* Let's unset the socket fd in the monitor object before we destroy it so that the fd passed in is
213 * not closed on failure. */
214 if (fd >= 0)
215 m->sock = -1;
216
217 return r;
b1c097af
YW
218}
219
220_public_ int sd_device_monitor_new(sd_device_monitor **ret) {
221 return device_monitor_new_full(ret, MONITOR_GROUP_UDEV, -1);
222}
223
224_public_ int sd_device_monitor_stop(sd_device_monitor *m) {
225 assert_return(m, -EINVAL);
226
227 m->event_source = sd_event_source_unref(m->event_source);
228 (void) device_monitor_disconnect(m);
229
230 return 0;
231}
232
233static int device_monitor_event_handler(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
234 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
235 sd_device_monitor *m = userdata;
236
237 assert(m);
238
239 if (device_monitor_receive_device(m, &device) <= 0)
240 return 0;
241
242 if (m->callback)
243 return m->callback(m, device, m->userdata);
244
245 return 0;
246}
247
deb2b734 248_public_ int sd_device_monitor_start(sd_device_monitor *m, sd_device_monitor_handler_t callback, void *userdata) {
b1c097af
YW
249 int r;
250
251 assert_return(m, -EINVAL);
252
253 if (!m->event) {
deb2b734 254 r = sd_device_monitor_attach_event(m, NULL);
b1c097af
YW
255 if (r < 0)
256 return r;
257 }
258
a153a1de
YW
259 r = device_monitor_enable_receiving(m);
260 if (r < 0)
261 return r;
b1c097af
YW
262
263 m->callback = callback;
264 m->userdata = userdata;
265
deb2b734 266 r = sd_event_add_io(m->event, &m->event_source, m->sock, EPOLLIN, device_monitor_event_handler, m);
b1c097af
YW
267 if (r < 0)
268 return r;
269
deb2b734 270 (void) sd_event_source_set_description(m->event_source, "sd-device-monitor");
b1c097af
YW
271
272 return 0;
273}
274
275_public_ int sd_device_monitor_detach_event(sd_device_monitor *m) {
276 assert_return(m, -EINVAL);
277
278 (void) sd_device_monitor_stop(m);
279 m->event = sd_event_unref(m->event);
280
281 return 0;
282}
283
deb2b734 284_public_ int sd_device_monitor_attach_event(sd_device_monitor *m, sd_event *event) {
b1c097af
YW
285 int r;
286
287 assert_return(m, -EINVAL);
288 assert_return(!m->event, -EBUSY);
289
290 if (event)
291 m->event = sd_event_ref(event);
292 else {
293 r = sd_event_default(&m->event);
294 if (r < 0)
779c9234 295 return r;
b1c097af
YW
296 }
297
b1c097af
YW
298 return 0;
299}
300
301_public_ sd_event *sd_device_monitor_get_event(sd_device_monitor *m) {
302 assert_return(m, NULL);
303
304 return m->event;
305}
306
bf7712b6
YW
307_public_ sd_event_source *sd_device_monitor_get_event_source(sd_device_monitor *m) {
308 assert_return(m, NULL);
309
310 return m->event_source;
311}
312
b1c097af
YW
313int device_monitor_enable_receiving(sd_device_monitor *m) {
314 int r;
315
316 assert_return(m, -EINVAL);
317
f1d7b787
YW
318 r = sd_device_monitor_filter_update(m);
319 if (r < 0)
320 return log_debug_errno(r, "sd-device-monitor: Failed to update filter: %m");
b1c097af
YW
321
322 if (!m->bound) {
c821e84a
YW
323 /* enable receiving of sender credentials */
324 r = setsockopt_int(m->sock, SOL_SOCKET, SO_PASSCRED, true);
325 if (r < 0)
326 return log_debug_errno(r, "sd-device-monitor: Failed to set socket option SO_PASSCRED: %m");
327
b1c097af 328 if (bind(m->sock, &m->snl.sa, sizeof(struct sockaddr_nl)) < 0)
5cee547a 329 return log_debug_errno(errno, "sd-device-monitor: Failed to bind monitoring socket: %m");
b1c097af
YW
330
331 m->bound = true;
b1c097af 332
c821e84a
YW
333 r = monitor_set_nl_address(m);
334 if (r < 0)
335 return log_debug_errno(r, "sd-device-monitor: Failed to set address: %m");
336 }
b1c097af
YW
337
338 return 0;
339}
340
341static sd_device_monitor *device_monitor_free(sd_device_monitor *m) {
342 assert(m);
343
344 (void) sd_device_monitor_detach_event(m);
345
346 hashmap_free_free_free(m->subsystem_filter);
347 set_free_free(m->tag_filter);
348
349 return mfree(m);
350}
351
352DEFINE_PUBLIC_TRIVIAL_REF_UNREF_FUNC(sd_device_monitor, sd_device_monitor, device_monitor_free);
353
354static int passes_filter(sd_device_monitor *m, sd_device *device) {
355 const char *tag, *subsystem, *devtype, *s, *d = NULL;
356 Iterator i;
357 int r;
358
359 assert_return(m, -EINVAL);
360 assert_return(device, -EINVAL);
361
362 if (hashmap_isempty(m->subsystem_filter))
363 goto tag;
364
365 r = sd_device_get_subsystem(device, &s);
366 if (r < 0)
367 return r;
368
369 r = sd_device_get_devtype(device, &d);
370 if (r < 0 && r != -ENOENT)
371 return r;
372
373 HASHMAP_FOREACH_KEY(devtype, subsystem, m->subsystem_filter, i) {
374 if (!streq(s, subsystem))
375 continue;
376
377 if (!devtype)
378 goto tag;
379
380 if (!d)
381 continue;
382
383 if (streq(d, devtype))
384 goto tag;
385 }
386
387 return 0;
388
389tag:
390 if (set_isempty(m->tag_filter))
391 return 1;
392
393 SET_FOREACH(tag, m->tag_filter, i)
394 if (sd_device_has_tag(device, tag) > 0)
395 return 1;
396
397 return 0;
398}
399
400int device_monitor_receive_device(sd_device_monitor *m, sd_device **ret) {
401 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
402 union {
403 monitor_netlink_header nlh;
404 char raw[8192];
405 } buf;
406 struct iovec iov = {
407 .iov_base = &buf,
408 .iov_len = sizeof(buf)
409 };
fb29cdbe 410 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred))) control;
b1c097af
YW
411 union sockaddr_union snl;
412 struct msghdr smsg = {
413 .msg_iov = &iov,
414 .msg_iovlen = 1,
fb29cdbe
LP
415 .msg_control = &control,
416 .msg_controllen = sizeof(control),
b1c097af
YW
417 .msg_name = &snl,
418 .msg_namelen = sizeof(snl),
419 };
420 struct cmsghdr *cmsg;
421 struct ucred *cred;
422 ssize_t buflen, bufpos;
423 bool is_initialized = false;
424 int r;
425
426 assert(ret);
427
428 buflen = recvmsg(m->sock, &smsg, 0);
429 if (buflen < 0) {
430 if (errno != EINTR)
c7d54dae 431 log_debug_errno(errno, "sd-device-monitor: Failed to receive message: %m");
b1c097af
YW
432 return -errno;
433 }
434
435 if (buflen < 32 || (smsg.msg_flags & MSG_TRUNC))
886cf317
ZJS
436 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
437 "sd-device-monitor: Invalid message length.");
b1c097af
YW
438
439 if (snl.nl.nl_groups == MONITOR_GROUP_NONE) {
440 /* unicast message, check if we trust the sender */
441 if (m->snl_trusted_sender.nl.nl_pid == 0 ||
442 snl.nl.nl_pid != m->snl_trusted_sender.nl.nl_pid)
886cf317
ZJS
443 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
444 "sd-device-monitor: Unicast netlink message ignored.");
b1c097af
YW
445
446 } else if (snl.nl.nl_groups == MONITOR_GROUP_KERNEL) {
447 if (snl.nl.nl_pid > 0)
886cf317
ZJS
448 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
449 "sd-device-monitor: Multicast kernel netlink message from PID %"PRIu32" ignored.", snl.nl.nl_pid);
b1c097af
YW
450 }
451
452 cmsg = CMSG_FIRSTHDR(&smsg);
453 if (!cmsg || cmsg->cmsg_type != SCM_CREDENTIALS)
886cf317
ZJS
454 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
455 "sd-device-monitor: No sender credentials received, message ignored.");
b1c097af
YW
456
457 cred = (struct ucred*) CMSG_DATA(cmsg);
458 if (cred->uid != 0)
886cf317
ZJS
459 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
460 "sd-device-monitor: Sender uid="UID_FMT", message ignored.", cred->uid);
b1c097af
YW
461
462 if (streq(buf.raw, "libudev")) {
463 /* udev message needs proper version magic */
464 if (buf.nlh.magic != htobe32(UDEV_MONITOR_MAGIC))
886cf317
ZJS
465 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
466 "sd-device-monitor: Invalid message signature (%x != %x)",
b1c097af
YW
467 buf.nlh.magic, htobe32(UDEV_MONITOR_MAGIC));
468
469 if (buf.nlh.properties_off+32 > (size_t) buflen)
886cf317
ZJS
470 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
471 "sd-device-monitor: Invalid message length (%u > %zd)",
b1c097af
YW
472 buf.nlh.properties_off+32, buflen);
473
474 bufpos = buf.nlh.properties_off;
475
476 /* devices received from udev are always initialized */
477 is_initialized = true;
478
479 } else {
480 /* kernel message with header */
481 bufpos = strlen(buf.raw) + 1;
482 if ((size_t) bufpos < sizeof("a@/d") || bufpos >= buflen)
886cf317
ZJS
483 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
484 "sd-device-monitor: Invalid message length");
b1c097af
YW
485
486 /* check message header */
487 if (!strstr(buf.raw, "@/"))
886cf317
ZJS
488 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
489 "sd-device-monitor: Invalid message header");
b1c097af
YW
490 }
491
492 r = device_new_from_nulstr(&device, (uint8_t*) &buf.raw[bufpos], buflen - bufpos);
493 if (r < 0)
c7d54dae 494 return log_debug_errno(r, "sd-device-monitor: Failed to create device from received message: %m");
b1c097af
YW
495
496 if (is_initialized)
497 device_set_is_initialized(device);
498
499 /* Skip device, if it does not pass the current filter */
500 r = passes_filter(m, device);
501 if (r < 0)
c7d54dae 502 return log_device_debug_errno(device, r, "sd-device-monitor: Failed to check received device passing filter: %m");
b1c097af 503 if (r == 0)
c7d54dae 504 log_device_debug(device, "sd-device-monitor: Received device does not pass filter, ignoring");
b1c097af
YW
505 else
506 *ret = TAKE_PTR(device);
507
508 return r;
509}
510
511static uint32_t string_hash32(const char *str) {
512 return MurmurHash2(str, strlen(str), 0);
513}
514
515/* Get a bunch of bit numbers out of the hash, and set the bits in our bit field */
516static uint64_t string_bloom64(const char *str) {
517 uint64_t bits = 0;
518 uint32_t hash = string_hash32(str);
519
520 bits |= 1LLU << (hash & 63);
521 bits |= 1LLU << ((hash >> 6) & 63);
522 bits |= 1LLU << ((hash >> 12) & 63);
523 bits |= 1LLU << ((hash >> 18) & 63);
524 return bits;
525}
526
527int device_monitor_send_device(
528 sd_device_monitor *m,
529 sd_device_monitor *destination,
530 sd_device *device) {
531
532 monitor_netlink_header nlh = {
533 .prefix = "libudev",
534 .magic = htobe32(UDEV_MONITOR_MAGIC),
535 .header_size = sizeof nlh,
536 };
537 struct iovec iov[2] = {
538 { .iov_base = &nlh, .iov_len = sizeof nlh },
539 };
540 struct msghdr smsg = {
541 .msg_iov = iov,
542 .msg_iovlen = 2,
543 };
544 /* default destination for sending */
545 union sockaddr_union default_destination = {
546 .nl.nl_family = AF_NETLINK,
547 .nl.nl_groups = MONITOR_GROUP_UDEV,
548 };
549 uint64_t tag_bloom_bits;
550 const char *buf, *val;
551 ssize_t count;
552 size_t blen;
553 int r;
554
555 assert(m);
556 assert(device);
557
558 r = device_get_properties_nulstr(device, (const uint8_t **) &buf, &blen);
559 if (r < 0)
c7d54dae 560 return log_device_debug_errno(device, r, "sd-device-monitor: Failed to get device properties: %m");
9e791238
ZJS
561 if (blen < 32)
562 log_device_debug_errno(device, SYNTHETIC_ERRNO(EINVAL),
563 "sd-device-monitor: Length of device property nulstr is too small to contain valid device information");
b1c097af
YW
564
565 /* fill in versioned header */
566 r = sd_device_get_subsystem(device, &val);
567 if (r < 0)
c7d54dae 568 return log_device_debug_errno(device, r, "sd-device-monitor: Failed to get device subsystem: %m");
b1c097af
YW
569 nlh.filter_subsystem_hash = htobe32(string_hash32(val));
570
a537eafe 571 if (sd_device_get_devtype(device, &val) >= 0)
b1c097af
YW
572 nlh.filter_devtype_hash = htobe32(string_hash32(val));
573
574 /* add tag bloom filter */
575 tag_bloom_bits = 0;
576 FOREACH_DEVICE_TAG(device, val)
577 tag_bloom_bits |= string_bloom64(val);
578
579 if (tag_bloom_bits > 0) {
580 nlh.filter_tag_bloom_hi = htobe32(tag_bloom_bits >> 32);
581 nlh.filter_tag_bloom_lo = htobe32(tag_bloom_bits & 0xffffffff);
582 }
583
584 /* add properties list */
585 nlh.properties_off = iov[0].iov_len;
586 nlh.properties_len = blen;
cb310866 587 iov[1] = IOVEC_MAKE((char*) buf, blen);
b1c097af
YW
588
589 /*
590 * Use custom address for target, or the default one.
591 *
592 * If we send to a multicast group, we will get
593 * ECONNREFUSED, which is expected.
594 */
595 smsg.msg_name = destination ? &destination->snl : &default_destination;
596 smsg.msg_namelen = sizeof(struct sockaddr_nl);
597 count = sendmsg(m->sock, &smsg, 0);
598 if (count < 0) {
599 if (!destination && errno == ECONNREFUSED) {
c7d54dae 600 log_device_debug(device, "sd-device-monitor: Passed to netlink monitor");
b1c097af
YW
601 return 0;
602 } else
c7d54dae 603 return log_device_debug_errno(device, errno, "sd-device-monitor: Failed to send device to netlink monitor: %m");
b1c097af
YW
604 }
605
c7d54dae 606 log_device_debug(device, "sd-device-monitor: Passed %zi byte to netlink monitor", count);
b1c097af
YW
607 return count;
608}
609
610static void bpf_stmt(struct sock_filter *ins, unsigned *i,
611 unsigned short code, unsigned data) {
612 ins[(*i)++] = (struct sock_filter) {
613 .code = code,
614 .k = data,
615 };
616}
617
618static void bpf_jmp(struct sock_filter *ins, unsigned *i,
619 unsigned short code, unsigned data,
620 unsigned short jt, unsigned short jf) {
621 ins[(*i)++] = (struct sock_filter) {
622 .code = code,
623 .jt = jt,
624 .jf = jf,
625 .k = data,
626 };
627}
628
629_public_ int sd_device_monitor_filter_update(sd_device_monitor *m) {
630 struct sock_filter ins[512] = {};
631 struct sock_fprog filter;
632 const char *subsystem, *devtype, *tag;
633 unsigned i = 0;
634 Iterator it;
635
636 assert_return(m, -EINVAL);
637
f1d7b787
YW
638 if (m->filter_uptodate)
639 return 0;
640
b1c097af
YW
641 if (hashmap_isempty(m->subsystem_filter) &&
642 set_isempty(m->tag_filter)) {
643 m->filter_uptodate = true;
644 return 0;
645 }
646
647 /* load magic in A */
648 bpf_stmt(ins, &i, BPF_LD|BPF_W|BPF_ABS, offsetof(monitor_netlink_header, magic));
649 /* jump if magic matches */
650 bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, UDEV_MONITOR_MAGIC, 1, 0);
651 /* wrong magic, pass packet */
652 bpf_stmt(ins, &i, BPF_RET|BPF_K, 0xffffffff);
653
654 if (!set_isempty(m->tag_filter)) {
655 int tag_matches = set_size(m->tag_filter);
656
657 /* add all tags matches */
658 SET_FOREACH(tag, m->tag_filter, it) {
659 uint64_t tag_bloom_bits = string_bloom64(tag);
660 uint32_t tag_bloom_hi = tag_bloom_bits >> 32;
661 uint32_t tag_bloom_lo = tag_bloom_bits & 0xffffffff;
662
663 /* load device bloom bits in A */
664 bpf_stmt(ins, &i, BPF_LD|BPF_W|BPF_ABS, offsetof(monitor_netlink_header, filter_tag_bloom_hi));
665 /* clear bits (tag bits & bloom bits) */
666 bpf_stmt(ins, &i, BPF_ALU|BPF_AND|BPF_K, tag_bloom_hi);
667 /* jump to next tag if it does not match */
668 bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, tag_bloom_hi, 0, 3);
669
670 /* load device bloom bits in A */
671 bpf_stmt(ins, &i, BPF_LD|BPF_W|BPF_ABS, offsetof(monitor_netlink_header, filter_tag_bloom_lo));
672 /* clear bits (tag bits & bloom bits) */
673 bpf_stmt(ins, &i, BPF_ALU|BPF_AND|BPF_K, tag_bloom_lo);
674 /* jump behind end of tag match block if tag matches */
675 tag_matches--;
676 bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, tag_bloom_lo, 1 + (tag_matches * 6), 0);
677 }
678
679 /* nothing matched, drop packet */
680 bpf_stmt(ins, &i, BPF_RET|BPF_K, 0);
681 }
682
683 /* add all subsystem matches */
684 if (!hashmap_isempty(m->subsystem_filter)) {
685 HASHMAP_FOREACH_KEY(devtype, subsystem, m->subsystem_filter, it) {
686 uint32_t hash = string_hash32(subsystem);
687
688 /* load device subsystem value in A */
689 bpf_stmt(ins, &i, BPF_LD|BPF_W|BPF_ABS, offsetof(monitor_netlink_header, filter_subsystem_hash));
690 if (!devtype) {
691 /* jump if subsystem does not match */
692 bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, hash, 0, 1);
693 } else {
b1c097af
YW
694 /* jump if subsystem does not match */
695 bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, hash, 0, 3);
696 /* load device devtype value in A */
697 bpf_stmt(ins, &i, BPF_LD|BPF_W|BPF_ABS, offsetof(monitor_netlink_header, filter_devtype_hash));
698 /* jump if value does not match */
65fe9c31 699 hash = string_hash32(devtype);
b1c097af
YW
700 bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, hash, 0, 1);
701 }
702
703 /* matched, pass packet */
704 bpf_stmt(ins, &i, BPF_RET|BPF_K, 0xffffffff);
705
706 if (i+1 >= ELEMENTSOF(ins))
707 return -E2BIG;
708 }
709
710 /* nothing matched, drop packet */
711 bpf_stmt(ins, &i, BPF_RET|BPF_K, 0);
712 }
713
714 /* matched, pass packet */
715 bpf_stmt(ins, &i, BPF_RET|BPF_K, 0xffffffff);
716
717 /* install filter */
718 filter = (struct sock_fprog) {
719 .len = i,
720 .filter = ins,
721 };
722 if (setsockopt(m->sock, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)) < 0)
723 return -errno;
724
725 m->filter_uptodate = true;
726 return 0;
727}
728
729_public_ int sd_device_monitor_filter_add_match_subsystem_devtype(sd_device_monitor *m, const char *subsystem, const char *devtype) {
730 _cleanup_free_ char *s = NULL, *d = NULL;
731 int r;
732
733 assert_return(m, -EINVAL);
734 assert_return(subsystem, -EINVAL);
735
736 s = strdup(subsystem);
737 if (!s)
738 return -ENOMEM;
739
740 if (devtype) {
741 d = strdup(devtype);
742 if (!d)
743 return -ENOMEM;
744 }
745
746 r = hashmap_ensure_allocated(&m->subsystem_filter, NULL);
747 if (r < 0)
748 return r;
749
750 r = hashmap_put(m->subsystem_filter, s, d);
751 if (r < 0)
752 return r;
753
754 s = d = NULL;
755 m->filter_uptodate = false;
756
757 return 0;
758}
759
760_public_ int sd_device_monitor_filter_add_match_tag(sd_device_monitor *m, const char *tag) {
b1c097af
YW
761 assert_return(m, -EINVAL);
762 assert_return(tag, -EINVAL);
763
aaffd349
ZJS
764 int r = set_put_strdup(&m->tag_filter, tag);
765 if (r > 0)
766 m->filter_uptodate = false;
767 return r;
b1c097af
YW
768}
769
770_public_ int sd_device_monitor_filter_remove(sd_device_monitor *m) {
771 static const struct sock_fprog filter = { 0, NULL };
772
773 assert_return(m, -EINVAL);
774
775 m->subsystem_filter = hashmap_free_free_free(m->subsystem_filter);
776 m->tag_filter = set_free_free(m->tag_filter);
777
b0757173 778 if (setsockopt(m->sock, SOL_SOCKET, SO_DETACH_FILTER, &filter, sizeof(filter)) < 0)
b1c097af
YW
779 return -errno;
780
781 m->filter_uptodate = true;
782 return 0;
783}