2 * uevent.c - trigger upon netlink uevents from the kernel
4 * Only kernels from version 2.6.10* on provide the uevent netlink socket.
5 * Until the libc-kernel-headers are updated, you need to compile with:
7 * gcc -I /lib/modules/`uname -r`/build/include -o uevent_listen uevent_listen.c
9 * Copyright (C) 2004 Kay Sievers <kay.sievers@vrfy.org>
11 * This program is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License as published by the
13 * Free Software Foundation version 2 of the License.
15 * This program is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 675 Mass Ave, Cambridge, MA 02139, USA.
32 #include <sys/socket.h>
34 #include <asm/types.h>
35 #include <linux/netlink.h>
41 struct uevent * alloc_uevent (void)
43 return (struct uevent *)MALLOC(sizeof(struct uevent));
46 int uevent_listen(int (*uev_trigger)(struct uevent *, void * trigger_data),
50 struct sockaddr_nl snl;
53 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
54 snl.nl_family = AF_NETLINK;
55 snl.nl_pid = getpid();
56 snl.nl_groups = 0xffffffff;
58 sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
60 condlog(0, "error getting socket, exit\n");
64 retval = bind(sock, (struct sockaddr *) &snl,
65 sizeof(struct sockaddr_nl));
67 condlog(0, "bind failed, exit\n");
72 static char buffer[HOTPLUG_BUFFER_SIZE + OBJECT_SIZE];
79 buflen = recv(sock, &buffer, sizeof(buffer), 0);
81 condlog(0, "error receiving message\n");
85 if ((size_t)buflen > sizeof(buffer)-1)
86 buflen = sizeof(buffer)-1;
88 buffer[buflen] = '\0';
92 condlog(1, "lost uevent, oom");
96 /* save start of payload */
97 bufpos = strlen(buffer) + 1;
100 uev->action = buffer;
101 pos = strchr(buffer, '@');
107 uev->devpath = &pos[1];
109 /* hotplug events have the environment attached - reconstruct envp[] */
110 for (i = 0; (bufpos < (size_t)buflen) && (i < HOTPLUG_NUM_ENVP-1); i++) {
114 key = &buffer[bufpos];
115 keylen = strlen(key);
117 bufpos += keylen + 1;
121 condlog(3, "uevent '%s' from '%s'\n", uev->action, uev->devpath);
123 /* print payload environment */
124 for (i = 0; uev->envp[i] != NULL; i++)
125 condlog(3, "%s\n", uev->envp[i]);
127 if (uev_trigger && uev_trigger(uev, trigger_data))
128 condlog(0, "uevent trigger error");