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