Busybox: Upgrade to 1.21.1 (stable). lsof active.
[tomato.git] / release / src / router / hotplug2 / hotplug2_utils.c
blob402e19f57e41fc0de9fe0231442cbde359224666
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4 #include <fcntl.h>
5 #include <stdio.h>
6 #include <unistd.h>
7 #include <errno.h>
8 #include <sys/socket.h>
9 #include <sys/types.h>
10 #include <sys/un.h>
11 #include <sys/wait.h>
12 #include <linux/types.h>
13 #include <linux/netlink.h>
15 #include "hotplug2_utils.h"
17 /**
18 * A trivial function that reads kernel seqnum from sysfs.
20 * Returns: Seqnum as read from sysfs
22 inline event_seqnum_t get_kernel_seqnum() {
23 FILE *fp;
25 char filename[64];
26 char seqnum[64];
28 strcpy(filename, sysfs_seqnum_path);
30 fp = fopen(filename, "r");
31 if (fp == NULL)
32 return 0;
34 fread(seqnum, 1, 64, fp);
35 fclose(fp);
37 return strtoull(seqnum, NULL, 0);
40 /**
41 * Opens a PF_NETLINK socket into the kernel, to read uevents.
43 * @1 Specifies type of socket (whether we bind or whether we connect)
45 * Returns: Socket fd if succesful, -1 otherwise.
47 inline int init_netlink_socket(int type) {
48 int netlink_socket;
49 struct sockaddr_nl snl;
50 int buffersize = 16 * 1024 * 1024;
52 memset(&snl, 0x00, sizeof(struct sockaddr_nl));
53 snl.nl_family = AF_NETLINK;
54 snl.nl_pid = getpid();
55 snl.nl_groups = 1;
56 netlink_socket = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
57 if (netlink_socket == -1) {
58 ERROR("opening netlink","Failed socket: %s.", strerror(errno));
59 return -1;
63 * We're trying to override buffer size. If we fail, we attempt to set a big buffer and pray.
65 if (setsockopt(netlink_socket, SOL_SOCKET, SO_RCVBUFFORCE, &buffersize, sizeof(buffersize))) {
66 ERROR("opening netlink","Failed setsockopt: %s. (non-critical)", strerror(errno));
68 /* Somewhat safe default. */
69 buffersize = 106496;
71 if (setsockopt(netlink_socket, SOL_SOCKET, SO_RCVBUF, &buffersize, sizeof(buffersize))) {
72 ERROR("opening netlink","Failed setsockopt: %s. (critical)", strerror(errno));
77 * hotplug2-dnode performs connect, while hotplug2 daemon binds
79 switch (type) {
80 case NETLINK_CONNECT:
81 if (connect(netlink_socket, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl))) {
82 ERROR("opening netlink","Failed connect: %s.", strerror(errno));
83 close(netlink_socket);
84 return -1;
87 default:
88 if (bind(netlink_socket, (struct sockaddr *) &snl, sizeof(struct sockaddr_nl))) {
89 ERROR("opening netlink","Failed bind: %s.", strerror(errno));
90 close(netlink_socket);
91 return -1;
95 return netlink_socket;