]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/libudev/libudev-monitor.c
libudev-monitor: add missing error checks in udev_monitor_enable_receiving()
[thirdparty/systemd.git] / src / libudev / libudev-monitor.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <linux/filter.h>
5 #include <linux/netlink.h>
6 #include <poll.h>
7 #include <stddef.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <sys/socket.h>
12 #include <unistd.h>
13
14 #include "libudev.h"
15
16 #include "alloc-util.h"
17 #include "device-private.h"
18 #include "device-util.h"
19 #include "fd-util.h"
20 #include "fileio.h"
21 #include "format-util.h"
22 #include "hashmap.h"
23 #include "libudev-device-internal.h"
24 #include "libudev-private.h"
25 #include "missing.h"
26 #include "mount-util.h"
27 #include "set.h"
28 #include "socket-util.h"
29 #include "string-util.h"
30 #include "strv.h"
31
32 /**
33 * SECTION:libudev-monitor
34 * @short_description: device event source
35 *
36 * Connects to a device event source.
37 */
38
39 /**
40 * udev_monitor:
41 *
42 * Opaque object handling an event source.
43 */
44 struct udev_monitor {
45 struct udev *udev;
46 unsigned n_ref;
47 int sock;
48 union sockaddr_union snl;
49 union sockaddr_union snl_trusted_sender;
50 union sockaddr_union snl_destination;
51 socklen_t addrlen;
52 Hashmap *subsystem_filter;
53 Set *tag_filter;
54 bool bound;
55 };
56
57 enum udev_monitor_netlink_group {
58 UDEV_MONITOR_NONE,
59 UDEV_MONITOR_KERNEL,
60 UDEV_MONITOR_UDEV,
61 };
62
63 #define UDEV_MONITOR_MAGIC 0xfeedcafe
64 struct udev_monitor_netlink_header {
65 /* "libudev" prefix to distinguish libudev and kernel messages */
66 char prefix[8];
67 /*
68 * magic to protect against daemon <-> library message format mismatch
69 * used in the kernel from socket filter rules; needs to be stored in network order
70 */
71 unsigned magic;
72 /* total length of header structure known to the sender */
73 unsigned header_size;
74 /* properties string buffer */
75 unsigned properties_off;
76 unsigned properties_len;
77 /*
78 * hashes of primary device properties strings, to let libudev subscribers
79 * use in-kernel socket filters; values need to be stored in network order
80 */
81 unsigned filter_subsystem_hash;
82 unsigned filter_devtype_hash;
83 unsigned filter_tag_bloom_hi;
84 unsigned filter_tag_bloom_lo;
85 };
86
87 static int udev_monitor_set_nl_address(struct udev_monitor *udev_monitor) {
88 union sockaddr_union snl;
89 socklen_t addrlen;
90
91 assert(udev_monitor);
92
93 /* Get the address the kernel has assigned us.
94 * It is usually, but not necessarily the pid. */
95 addrlen = sizeof(struct sockaddr_nl);
96 if (getsockname(udev_monitor->sock, &snl.sa, &addrlen) < 0)
97 return -errno;
98
99 udev_monitor->snl.nl.nl_pid = snl.nl.nl_pid;
100 return 0;
101 }
102
103 struct udev_monitor *udev_monitor_new_from_netlink_fd(struct udev *udev, const char *name, int fd) {
104 _cleanup_(udev_monitor_unrefp) struct udev_monitor *udev_monitor = NULL;
105 _cleanup_close_ int sock = -1;
106 unsigned group;
107 int r;
108
109 assert_return_errno(!name || STR_IN_SET(name, "udev", "kernel"), NULL, EINVAL);
110
111 if (!name)
112 group = UDEV_MONITOR_NONE;
113 else if (streq(name, "udev")) {
114 /*
115 * We do not support subscribing to uevents if no instance of
116 * udev is running. Uevents would otherwise broadcast the
117 * processing data of the host into containers, which is not
118 * desired.
119 *
120 * Containers will currently not get any udev uevents, until
121 * a supporting infrastructure is available.
122 *
123 * We do not set a netlink multicast group here, so the socket
124 * will not receive any messages.
125 */
126 if (access("/run/udev/control", F_OK) < 0 && dev_is_devtmpfs() <= 0) {
127 log_debug("The udev service seems not to be active, disabling the monitor");
128 group = UDEV_MONITOR_NONE;
129 } else
130 group = UDEV_MONITOR_UDEV;
131 } else {
132 assert(streq(name, "kernel"));
133 group = UDEV_MONITOR_KERNEL;
134 }
135
136 if (fd < 0) {
137 sock = socket(PF_NETLINK, SOCK_RAW|SOCK_CLOEXEC|SOCK_NONBLOCK, NETLINK_KOBJECT_UEVENT);
138 if (sock < 0) {
139 log_debug_errno(errno, "Failed to create socket: %m");
140 return NULL;
141 }
142 }
143
144 udev_monitor = new(struct udev_monitor, 1);
145 if (!udev_monitor) {
146 errno = ENOMEM;
147 return NULL;
148 }
149
150 *udev_monitor = (struct udev_monitor) {
151 .udev = udev,
152 .n_ref = 1,
153 .sock = fd >= 0 ? fd : TAKE_FD(sock),
154 .bound = fd >= 0,
155 .snl.nl.nl_family = AF_NETLINK,
156 .snl.nl.nl_groups = group,
157
158 /* default destination for sending */
159 .snl_destination.nl.nl_family = AF_NETLINK,
160 .snl_destination.nl.nl_groups = UDEV_MONITOR_UDEV,
161 };
162
163 if (fd >= 0) {
164 r = udev_monitor_set_nl_address(udev_monitor);
165 if (r < 0) {
166 log_debug_errno(r, "Failed to set netlink address: %m");
167 return NULL;
168 }
169 }
170
171 return TAKE_PTR(udev_monitor);
172 }
173
174 /**
175 * udev_monitor_new_from_netlink:
176 * @udev: udev library context
177 * @name: name of event source
178 *
179 * Create new udev monitor and connect to a specified event
180 * source. Valid sources identifiers are "udev" and "kernel".
181 *
182 * Applications should usually not connect directly to the
183 * "kernel" events, because the devices might not be useable
184 * at that time, before udev has configured them, and created
185 * device nodes. Accessing devices at the same time as udev,
186 * might result in unpredictable behavior. The "udev" events
187 * are sent out after udev has finished its event processing,
188 * all rules have been processed, and needed device nodes are
189 * created.
190 *
191 * The initial refcount is 1, and needs to be decremented to
192 * release the resources of the udev monitor.
193 *
194 * Returns: a new udev monitor, or #NULL, in case of an error
195 **/
196 _public_ struct udev_monitor *udev_monitor_new_from_netlink(struct udev *udev, const char *name) {
197 return udev_monitor_new_from_netlink_fd(udev, name, -1);
198 }
199
200 static void bpf_stmt(struct sock_filter *ins, unsigned *i,
201 unsigned short code, unsigned data) {
202 ins[(*i)++] = (struct sock_filter) {
203 .code = code,
204 .k = data,
205 };
206 }
207
208 static void bpf_jmp(struct sock_filter *ins, unsigned *i,
209 unsigned short code, unsigned data,
210 unsigned short jt, unsigned short jf) {
211 ins[(*i)++] = (struct sock_filter) {
212 .code = code,
213 .jt = jt,
214 .jf = jf,
215 .k = data,
216 };
217 }
218
219 /**
220 * udev_monitor_filter_update:
221 * @udev_monitor: monitor
222 *
223 * Update the installed socket filter. This is only needed,
224 * if the filter was removed or changed.
225 *
226 * Returns: 0 on success, otherwise a negative error value.
227 */
228 _public_ int udev_monitor_filter_update(struct udev_monitor *udev_monitor) {
229 struct sock_filter ins[512] = {};
230 struct sock_fprog filter;
231 const char *subsystem, *devtype, *tag;
232 unsigned i = 0;
233 Iterator it;
234
235 assert_return(udev_monitor, -EINVAL);
236
237 if (hashmap_isempty(udev_monitor->subsystem_filter) &&
238 set_isempty(udev_monitor->tag_filter))
239 return 0;
240
241 /* load magic in A */
242 bpf_stmt(ins, &i, BPF_LD|BPF_W|BPF_ABS, offsetof(struct udev_monitor_netlink_header, magic));
243 /* jump if magic matches */
244 bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, UDEV_MONITOR_MAGIC, 1, 0);
245 /* wrong magic, pass packet */
246 bpf_stmt(ins, &i, BPF_RET|BPF_K, 0xffffffff);
247
248 if (!set_isempty(udev_monitor->tag_filter)) {
249 int tag_matches = set_size(udev_monitor->tag_filter);
250
251 /* add all tags matches */
252 SET_FOREACH(tag, udev_monitor->tag_filter, it) {
253 uint64_t tag_bloom_bits = util_string_bloom64(tag);
254 uint32_t tag_bloom_hi = tag_bloom_bits >> 32;
255 uint32_t tag_bloom_lo = tag_bloom_bits & 0xffffffff;
256
257 /* load device bloom bits in A */
258 bpf_stmt(ins, &i, BPF_LD|BPF_W|BPF_ABS, offsetof(struct udev_monitor_netlink_header, filter_tag_bloom_hi));
259 /* clear bits (tag bits & bloom bits) */
260 bpf_stmt(ins, &i, BPF_ALU|BPF_AND|BPF_K, tag_bloom_hi);
261 /* jump to next tag if it does not match */
262 bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, tag_bloom_hi, 0, 3);
263
264 /* load device bloom bits in A */
265 bpf_stmt(ins, &i, BPF_LD|BPF_W|BPF_ABS, offsetof(struct udev_monitor_netlink_header, filter_tag_bloom_lo));
266 /* clear bits (tag bits & bloom bits) */
267 bpf_stmt(ins, &i, BPF_ALU|BPF_AND|BPF_K, tag_bloom_lo);
268 /* jump behind end of tag match block if tag matches */
269 tag_matches--;
270 bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, tag_bloom_lo, 1 + (tag_matches * 6), 0);
271 }
272
273 /* nothing matched, drop packet */
274 bpf_stmt(ins, &i, BPF_RET|BPF_K, 0);
275 }
276
277 /* add all subsystem matches */
278 if (!hashmap_isempty(udev_monitor->subsystem_filter)) {
279 HASHMAP_FOREACH_KEY(devtype, subsystem, udev_monitor->subsystem_filter, it) {
280 uint32_t hash = util_string_hash32(subsystem);
281
282 /* load device subsystem value in A */
283 bpf_stmt(ins, &i, BPF_LD|BPF_W|BPF_ABS, offsetof(struct udev_monitor_netlink_header, filter_subsystem_hash));
284 if (!devtype) {
285 /* jump if subsystem does not match */
286 bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, hash, 0, 1);
287 } else {
288 hash = util_string_hash32(devtype);
289
290 /* jump if subsystem does not match */
291 bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, hash, 0, 3);
292 /* load device devtype value in A */
293 bpf_stmt(ins, &i, BPF_LD|BPF_W|BPF_ABS, offsetof(struct udev_monitor_netlink_header, filter_devtype_hash));
294 /* jump if value does not match */
295 bpf_jmp(ins, &i, BPF_JMP|BPF_JEQ|BPF_K, hash, 0, 1);
296 }
297
298 /* matched, pass packet */
299 bpf_stmt(ins, &i, BPF_RET|BPF_K, 0xffffffff);
300
301 if (i+1 >= ELEMENTSOF(ins))
302 return -E2BIG;
303 }
304
305 /* nothing matched, drop packet */
306 bpf_stmt(ins, &i, BPF_RET|BPF_K, 0);
307 }
308
309 /* matched, pass packet */
310 bpf_stmt(ins, &i, BPF_RET|BPF_K, 0xffffffff);
311
312 /* install filter */
313 filter = (struct sock_fprog) {
314 .len = i,
315 .filter = ins,
316 };
317 if (setsockopt(udev_monitor->sock, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)) < 0)
318 return -errno;
319
320 return 0;
321 }
322
323 int udev_monitor_allow_unicast_sender(struct udev_monitor *udev_monitor, struct udev_monitor *sender)
324 {
325 udev_monitor->snl_trusted_sender.nl.nl_pid = sender->snl.nl.nl_pid;
326 return 0;
327 }
328
329 /**
330 * udev_monitor_enable_receiving:
331 * @udev_monitor: the monitor which should receive events
332 *
333 * Binds the @udev_monitor socket to the event source.
334 *
335 * Returns: 0 on success, otherwise a negative error value.
336 */
337 _public_ int udev_monitor_enable_receiving(struct udev_monitor *udev_monitor) {
338 const int on = 1;
339 int r;
340
341 assert_return(udev_monitor, -EINVAL);
342
343 r = udev_monitor_filter_update(udev_monitor);
344 if (r < 0)
345 return log_debug_errno(r, "Failed to update filter: %m");
346
347 if (!udev_monitor->bound) {
348 if (bind(udev_monitor->sock, &udev_monitor->snl.sa, sizeof(struct sockaddr_nl)) < 0)
349 return log_debug_errno(errno, "Failed to bind udev monitor socket to event source: %m");
350
351 udev_monitor->bound = true;
352 }
353
354 r = udev_monitor_set_nl_address(udev_monitor);
355 if (r < 0)
356 return log_debug_errno(r, "Failed to set address: %m");
357
358 /* enable receiving of sender credentials */
359 if (setsockopt(udev_monitor->sock, SOL_SOCKET, SO_PASSCRED, &on, sizeof(on)) < 0)
360 return log_debug_errno(errno, "Failed to set socket option SO_PASSCRED: %m");
361
362 return 0;
363 }
364
365 /**
366 * udev_monitor_set_receive_buffer_size:
367 * @udev_monitor: the monitor which should receive events
368 * @size: the size in bytes
369 *
370 * Set the size of the kernel socket buffer. This call needs the
371 * appropriate privileges to succeed.
372 *
373 * Returns: 0 on success, otherwise -1 on error.
374 */
375 _public_ int udev_monitor_set_receive_buffer_size(struct udev_monitor *udev_monitor, int size)
376 {
377 if (udev_monitor == NULL)
378 return -EINVAL;
379 if (setsockopt(udev_monitor->sock, SOL_SOCKET, SO_RCVBUFFORCE, &size, sizeof(size)) < 0)
380 return -errno;
381
382 return 0;
383 }
384
385 int udev_monitor_disconnect(struct udev_monitor *udev_monitor) {
386 assert(udev_monitor);
387
388 udev_monitor->sock = safe_close(udev_monitor->sock);
389 return 0;
390 }
391
392 static struct udev_monitor *udev_monitor_free(struct udev_monitor *udev_monitor) {
393 assert(udev_monitor);
394
395 udev_monitor_disconnect(udev_monitor);
396 hashmap_free_free_free(udev_monitor->subsystem_filter);
397 set_free_free(udev_monitor->tag_filter);
398 return mfree(udev_monitor);
399 }
400
401 /**
402 * udev_monitor_ref:
403 * @udev_monitor: udev monitor
404 *
405 * Take a reference of a udev monitor.
406 *
407 * Returns: the passed udev monitor
408 **/
409
410 /**
411 * udev_monitor_unref:
412 * @udev_monitor: udev monitor
413 *
414 * Drop a reference of a udev monitor. If the refcount reaches zero,
415 * the bound socket will be closed, and the resources of the monitor
416 * will be released.
417 *
418 * Returns: #NULL
419 **/
420 DEFINE_PUBLIC_TRIVIAL_REF_UNREF_FUNC(struct udev_monitor, udev_monitor, udev_monitor_free);
421
422 /**
423 * udev_monitor_get_udev:
424 * @udev_monitor: udev monitor
425 *
426 * Retrieve the udev library context the monitor was created with.
427 *
428 * Returns: the udev library context
429 **/
430 _public_ struct udev *udev_monitor_get_udev(struct udev_monitor *udev_monitor)
431 {
432 if (udev_monitor == NULL)
433 return NULL;
434 return udev_monitor->udev;
435 }
436
437 /**
438 * udev_monitor_get_fd:
439 * @udev_monitor: udev monitor
440 *
441 * Retrieve the socket file descriptor associated with the monitor.
442 *
443 * Returns: the socket file descriptor
444 **/
445 _public_ int udev_monitor_get_fd(struct udev_monitor *udev_monitor)
446 {
447 if (udev_monitor == NULL)
448 return -EINVAL;
449 return udev_monitor->sock;
450 }
451
452 static int passes_filter(struct udev_monitor *udev_monitor, sd_device *device) {
453 const char *tag, *subsystem, *devtype, *s, *d = NULL;
454 Iterator i;
455 int r;
456
457 assert_return(udev_monitor, -EINVAL);
458 assert_return(device, -EINVAL);
459
460 if (hashmap_isempty(udev_monitor->subsystem_filter))
461 goto tag;
462
463 r = sd_device_get_subsystem(device, &s);
464 if (r < 0)
465 return r;
466
467 r = sd_device_get_devtype(device, &d);
468 if (r < 0 && r != -ENOENT)
469 return r;
470
471 HASHMAP_FOREACH_KEY(devtype, subsystem, udev_monitor->subsystem_filter, i) {
472 if (!streq(s, subsystem))
473 continue;
474
475 if (!devtype)
476 goto tag;
477
478 if (!d)
479 continue;
480
481 if (streq(d, devtype))
482 goto tag;
483 }
484
485 return 0;
486
487 tag:
488 if (set_isempty(udev_monitor->tag_filter))
489 return 1;
490
491 SET_FOREACH(tag, udev_monitor->tag_filter, i)
492 if (sd_device_has_tag(device, tag) > 0)
493 return 1;
494
495 return 0;
496 }
497
498 static int udev_monitor_receive_device_one(struct udev_monitor *udev_monitor, sd_device **ret) {
499 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
500 union {
501 struct udev_monitor_netlink_header nlh;
502 char raw[8192];
503 } buf;
504 struct iovec iov = {
505 .iov_base = &buf,
506 .iov_len = sizeof(buf)
507 };
508 char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
509 union sockaddr_union snl;
510 struct msghdr smsg = {
511 .msg_iov = &iov,
512 .msg_iovlen = 1,
513 .msg_control = cred_msg,
514 .msg_controllen = sizeof(cred_msg),
515 .msg_name = &snl,
516 .msg_namelen = sizeof(snl),
517 };
518 struct cmsghdr *cmsg;
519 struct ucred *cred;
520 ssize_t buflen, bufpos;
521 bool is_initialized = false;
522 int r;
523
524 assert(ret);
525
526 buflen = recvmsg(udev_monitor->sock, &smsg, 0);
527 if (buflen < 0) {
528 if (errno != EINTR)
529 log_debug_errno(errno, "Failed to receive message: %m");
530 return -errno;
531 }
532
533 if (buflen < 32 || (smsg.msg_flags & MSG_TRUNC))
534 return log_debug_errno(EINVAL, "Invalid message length.");
535
536 if (snl.nl.nl_groups == UDEV_MONITOR_NONE) {
537 /* unicast message, check if we trust the sender */
538 if (udev_monitor->snl_trusted_sender.nl.nl_pid == 0 ||
539 snl.nl.nl_pid != udev_monitor->snl_trusted_sender.nl.nl_pid)
540 return log_debug_errno(EAGAIN, "Unicast netlink message ignored.");
541
542 } else if (snl.nl.nl_groups == UDEV_MONITOR_KERNEL) {
543 if (snl.nl.nl_pid > 0)
544 return log_debug_errno(EAGAIN, "Multicast kernel netlink message from PID %"PRIu32" ignored.", snl.nl.nl_pid);
545 }
546
547 cmsg = CMSG_FIRSTHDR(&smsg);
548 if (!cmsg || cmsg->cmsg_type != SCM_CREDENTIALS)
549 return log_debug_errno(EAGAIN, "No sender credentials received, message ignored.");
550
551 cred = (struct ucred*) CMSG_DATA(cmsg);
552 if (cred->uid != 0)
553 return log_debug_errno(EAGAIN, "Sender uid="UID_FMT", message ignored.", cred->uid);
554
555 if (streq(buf.raw, "libudev")) {
556 /* udev message needs proper version magic */
557 if (buf.nlh.magic != htobe32(UDEV_MONITOR_MAGIC))
558 return log_debug_errno(EAGAIN, "Invalid message signature (%x != %x)",
559 buf.nlh.magic, htobe32(UDEV_MONITOR_MAGIC));
560
561 if (buf.nlh.properties_off+32 > (size_t) buflen)
562 return log_debug_errno(EAGAIN, "Invalid message length (%u > %zd)",
563 buf.nlh.properties_off+32, buflen);
564
565 bufpos = buf.nlh.properties_off;
566
567 /* devices received from udev are always initialized */
568 is_initialized = true;
569
570 } else {
571 /* kernel message with header */
572 bufpos = strlen(buf.raw) + 1;
573 if ((size_t) bufpos < sizeof("a@/d") || bufpos >= buflen)
574 return log_debug_errno(EAGAIN, "Invalid message length");
575
576 /* check message header */
577 if (!strstr(buf.raw, "@/"))
578 return log_debug_errno(EAGAIN, "Invalid message header");
579 }
580
581 r = device_new_from_nulstr(&device, (uint8_t*) &buf.raw[bufpos], buflen - bufpos);
582 if (r < 0)
583 return log_debug_errno(r, "Failed to create device: %m");
584
585 if (is_initialized)
586 device_set_is_initialized(device);
587
588 /* skip device, if it does not pass the current filter */
589 if (passes_filter(udev_monitor, device) <= 0)
590 return 0;
591
592 *ret = TAKE_PTR(device);
593 return 1;
594 }
595
596 int udev_monitor_receive_sd_device(struct udev_monitor *udev_monitor, sd_device **ret) {
597 struct pollfd pfd = {
598 .fd = udev_monitor->sock,
599 .events = POLLIN,
600 };
601 int r;
602
603 assert(udev_monitor);
604 assert(ret);
605
606 for (;;) {
607 /* r == 0 means a device is received but it does not pass the current filter. */
608 r = udev_monitor_receive_device_one(udev_monitor, ret);
609 if (r != 0)
610 return r;
611
612 for (;;) {
613 /* wait next message */
614 r = poll(&pfd, 1, 0);
615 if (r < 0) {
616 if (IN_SET(errno, EINTR, EAGAIN))
617 continue;
618
619 return -errno;
620 } else if (r == 0)
621 return -EAGAIN;
622
623 /* receive next message */
624 break;
625 }
626 }
627 }
628
629 /**
630 * udev_monitor_receive_device:
631 * @udev_monitor: udev monitor
632 *
633 * Receive data from the udev monitor socket, allocate a new udev
634 * device, fill in the received data, and return the device.
635 *
636 * Only socket connections with uid=0 are accepted.
637 *
638 * The monitor socket is by default set to NONBLOCK. A variant of poll() on
639 * the file descriptor returned by udev_monitor_get_fd() should to be used to
640 * wake up when new devices arrive, or alternatively the file descriptor
641 * switched into blocking mode.
642 *
643 * The initial refcount is 1, and needs to be decremented to
644 * release the resources of the udev device.
645 *
646 * Returns: a new udev device, or #NULL, in case of an error
647 **/
648 _public_ struct udev_device *udev_monitor_receive_device(struct udev_monitor *udev_monitor) {
649 _cleanup_(sd_device_unrefp) sd_device *device = NULL;
650 int r;
651
652 assert_return(udev_monitor, NULL);
653
654 r = udev_monitor_receive_sd_device(udev_monitor, &device);
655 if (r < 0) {
656 errno = -r;
657 return NULL;
658 }
659
660 return udev_device_new(udev_monitor->udev, device);
661 }
662
663 static int udev_monitor_send_sd_device(
664 struct udev_monitor *udev_monitor,
665 struct udev_monitor *destination,
666 sd_device *device) {
667
668 struct udev_monitor_netlink_header nlh = {
669 .prefix = "libudev",
670 .magic = htobe32(UDEV_MONITOR_MAGIC),
671 .header_size = sizeof nlh,
672 };
673 struct iovec iov[2] = {
674 { .iov_base = &nlh, .iov_len = sizeof nlh },
675 };
676 struct msghdr smsg = {
677 .msg_iov = iov,
678 .msg_iovlen = 2,
679 };
680 uint64_t tag_bloom_bits;
681 const char *buf, *val;
682 ssize_t count;
683 size_t blen;
684 int r;
685
686 assert(udev_monitor);
687 assert(device);
688
689 r = device_get_properties_nulstr(device, (const uint8_t **) &buf, &blen);
690 if (r < 0)
691 return log_debug_errno(r, "Failed to get device properties: %m");
692 if (blen < 32) {
693 log_debug("Device buffer is too small to contain a valid device");
694 return -EINVAL;
695 }
696
697 /* fill in versioned header */
698 r = sd_device_get_subsystem(device, &val);
699 if (r < 0)
700 return log_debug_errno(r, "Failed to get device subsystem: %m");
701 nlh.filter_subsystem_hash = htobe32(util_string_hash32(val));
702
703 if (sd_device_get_devtype(device, &val) >= 0 && val)
704 nlh.filter_devtype_hash = htobe32(util_string_hash32(val));
705
706 /* add tag bloom filter */
707 tag_bloom_bits = 0;
708 FOREACH_DEVICE_TAG(device, val)
709 tag_bloom_bits |= util_string_bloom64(val);
710
711 if (tag_bloom_bits > 0) {
712 nlh.filter_tag_bloom_hi = htobe32(tag_bloom_bits >> 32);
713 nlh.filter_tag_bloom_lo = htobe32(tag_bloom_bits & 0xffffffff);
714 }
715
716 /* add properties list */
717 nlh.properties_off = iov[0].iov_len;
718 nlh.properties_len = blen;
719 iov[1] = (struct iovec) {
720 .iov_base = (char*) buf,
721 .iov_len = blen,
722 };
723
724 /*
725 * Use custom address for target, or the default one.
726 *
727 * If we send to a multicast group, we will get
728 * ECONNREFUSED, which is expected.
729 */
730 smsg.msg_name = destination ? &destination->snl : &udev_monitor->snl_destination;
731 smsg.msg_namelen = sizeof(struct sockaddr_nl);
732 count = sendmsg(udev_monitor->sock, &smsg, 0);
733 if (count < 0) {
734 if (!destination && errno == ECONNREFUSED) {
735 log_debug("Passed device to netlink monitor %p", udev_monitor);
736 return 0;
737 } else
738 return log_debug_errno(errno, "Failed to send device to netlink monitor %p", udev_monitor);
739 }
740
741 log_debug("Passed %zi byte device to netlink monitor %p", count, udev_monitor);
742 return count;
743 }
744
745 int udev_monitor_send_device(
746 struct udev_monitor *udev_monitor,
747 struct udev_monitor *destination,
748 struct udev_device *udev_device) {
749 assert(udev_device);
750
751 return udev_monitor_send_sd_device(udev_monitor, destination, udev_device->device);
752 }
753
754 /**
755 * udev_monitor_filter_add_match_subsystem_devtype:
756 * @udev_monitor: the monitor
757 * @subsystem: the subsystem value to match the incoming devices against
758 * @devtype: the devtype value to match the incoming devices against
759 *
760 * This filter is efficiently executed inside the kernel, and libudev subscribers
761 * will usually not be woken up for devices which do not match.
762 *
763 * The filter must be installed before the monitor is switched to listening mode.
764 *
765 * Returns: 0 on success, otherwise a negative error value.
766 */
767 _public_ int udev_monitor_filter_add_match_subsystem_devtype(struct udev_monitor *udev_monitor, const char *subsystem, const char *devtype) {
768 _cleanup_free_ char *s = NULL, *d = NULL;
769 int r;
770
771 assert_return(udev_monitor, -EINVAL);
772 assert_return(subsystem, -EINVAL);
773
774 s = strdup(subsystem);
775 if (!s)
776 return -ENOMEM;
777
778 if (devtype) {
779 d = strdup(devtype);
780 if (!d)
781 return -ENOMEM;
782 }
783
784 r = hashmap_ensure_allocated(&udev_monitor->subsystem_filter, NULL);
785 if (r < 0)
786 return r;
787
788 r = hashmap_put(udev_monitor->subsystem_filter, s, d);
789 if (r < 0)
790 return r;
791
792 s = d = NULL;
793 return 0;
794 }
795
796 /**
797 * udev_monitor_filter_add_match_tag:
798 * @udev_monitor: the monitor
799 * @tag: the name of a tag
800 *
801 * This filter is efficiently executed inside the kernel, and libudev subscribers
802 * will usually not be woken up for devices which do not match.
803 *
804 * The filter must be installed before the monitor is switched to listening mode.
805 *
806 * Returns: 0 on success, otherwise a negative error value.
807 */
808 _public_ int udev_monitor_filter_add_match_tag(struct udev_monitor *udev_monitor, const char *tag) {
809 _cleanup_free_ char *t = NULL;
810 int r;
811
812 assert_return(udev_monitor, -EINVAL);
813 assert_return(tag, -EINVAL);
814
815 t = strdup(tag);
816 if (!t)
817 return -ENOMEM;
818
819 r = set_ensure_allocated(&udev_monitor->tag_filter, &string_hash_ops);
820 if (r < 0)
821 return r;
822
823 r = set_put(udev_monitor->tag_filter, t);
824 if (r == -EEXIST)
825 return 0;
826 if (r < 0)
827 return r;
828
829 TAKE_PTR(t);
830 return 0;
831 }
832
833 /**
834 * udev_monitor_filter_remove:
835 * @udev_monitor: monitor
836 *
837 * Remove all filters from monitor.
838 *
839 * Returns: 0 on success, otherwise a negative error value.
840 */
841 _public_ int udev_monitor_filter_remove(struct udev_monitor *udev_monitor) {
842 static const struct sock_fprog filter = { 0, NULL };
843
844 assert_return(udev_monitor, -EINVAL);
845
846 udev_monitor->subsystem_filter = hashmap_free_free_free(udev_monitor->subsystem_filter);
847 udev_monitor->tag_filter = set_free_free(udev_monitor->tag_filter);
848
849 if (setsockopt(udev_monitor->sock, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)) < 0)
850 return -errno;
851
852 return 0;
853 }