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