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