summaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/Makefile74
-rw-r--r--lib/addr.c883
-rw-r--r--lib/attr.c787
-rw-r--r--lib/cache.c805
-rw-r--r--lib/cache_mngr.c392
-rw-r--r--lib/cache_mngt.c266
-rw-r--r--lib/data.c172
-rw-r--r--lib/defs.h29
-rw-r--r--lib/defs.h.in28
-rw-r--r--lib/doc.c106
-rw-r--r--lib/family.c62
-rw-r--r--lib/fib_lookup/lookup.c353
-rw-r--r--lib/fib_lookup/request.c187
-rw-r--r--lib/genl/ctrl.c319
-rw-r--r--lib/genl/family.c285
-rw-r--r--lib/genl/genl.c210
-rw-r--r--lib/genl/mngt.c285
-rw-r--r--lib/handlers.c447
-rw-r--r--lib/msg.c931
-rw-r--r--lib/netfilter/ct.c465
-rw-r--r--lib/netfilter/ct_obj.c667
-rw-r--r--lib/netfilter/log.c349
-rw-r--r--lib/netfilter/log_obj.c425
-rw-r--r--lib/netfilter/nfnl.c246
-rw-r--r--lib/nl.c798
-rw-r--r--lib/object.c386
-rw-r--r--lib/route/addr.c1130
-rw-r--r--lib/route/class.c230
-rw-r--r--lib/route/class_api.c102
-rw-r--r--lib/route/class_obj.c287
-rw-r--r--lib/route/classifier.c343
-rw-r--r--lib/route/cls/fw.c251
-rw-r--r--lib/route/cls/police.c67
-rw-r--r--lib/route/cls/u32.c602
-rw-r--r--lib/route/cls_api.c103
-rw-r--r--lib/route/cls_obj.c203
-rw-r--r--lib/route/link.c1313
-rw-r--r--lib/route/neigh.c1023
-rw-r--r--lib/route/neightbl.c825
-rw-r--r--lib/route/nexthop.c151
-rw-r--r--lib/route/qdisc.c478
-rw-r--r--lib/route/qdisc_api.c98
-rw-r--r--lib/route/qdisc_obj.c273
-rw-r--r--lib/route/route.c444
-rw-r--r--lib/route/route_obj.c908
-rw-r--r--lib/route/route_utils.c183
-rw-r--r--lib/route/rtnl.c125
-rw-r--r--lib/route/rule.c900
-rw-r--r--lib/route/sch/blackhole.c38
-rw-r--r--lib/route/sch/cbq.c306
-rw-r--r--lib/route/sch/dsmark.c459
-rw-r--r--lib/route/sch/fifo.c205
-rw-r--r--lib/route/sch/htb.c553
-rw-r--r--lib/route/sch/netem.c603
-rw-r--r--lib/route/sch/prio.c332
-rw-r--r--lib/route/sch/red.c219
-rw-r--r--lib/route/sch/sfq.c294
-rw-r--r--lib/route/sch/tbf.c540
-rw-r--r--lib/route/tc.c585
-rw-r--r--lib/socket.c548
-rw-r--r--lib/utils.c701
61 files changed, 25379 insertions, 0 deletions
diff --git a/lib/Makefile b/lib/Makefile
new file mode 100644
index 0000000..a654242
--- /dev/null
+++ b/lib/Makefile
@@ -0,0 +1,74 @@
+#
+# lib/Makefile
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation version 2.1
+# of the License.
+#
+# Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+#
+
+ifeq ($(shell [ ! -r ../Makefile.opts ] && echo 1),)
+ include ../Makefile.opts
+endif
+
+# Core
+CIN := $(wildcard *.c)
+# NETLINK_ROUTE
+CIN += $(wildcard route/*.c)
+# Schedulers
+CIN += $(wildcard route/sch/*.c)
+# Classifiers
+CIN += $(wildcard route/cls/*.c)
+# NETLINK_GENERIC
+CIN += $(wildcard genl/*.c)
+# fib lookup
+CIN += $(wildcard fib_lookup/*.c)
+# Netfilter
+CIN += $(wildcard netfilter/*.c)
+
+DEPS := $(CIN:%.c=%.d)
+OBJ := $(CIN:%.c=%.o)
+CFLAGS += -fPIC
+OUT_SLIB := $(PACKAGE_NAME).so.$(PACKAGE_VERSION)
+LN_SLIB := $(PACKAGE_NAME).so
+LN1_SLIB := $(LN_SLIB).1
+
+export
+
+.PHONY: all clean install librtn.a $(OUT_SLIB)
+
+
+all:
+ @echo " MAKE $(OUT_SLIB)"; \
+ $(MAKE) $(OUT_SLIB)
+
+$(OUT_SLIB): ../Makefile.opts $(OBJ)
+ @echo " LD $(OUT_SLIB)"; \
+ $(CC) -shared -Wl,-soname,libnl.so.1 -o $(OUT_SLIB) $(OBJ) $(LIBNL_LIB) -lc
+ @echo " LN $(OUT_SLIB) $(LN1_SLIB)"; \
+ rm -f $(LN1_SLIB) ; $(LN) -s $(OUT_SLIB) $(LN1_SLIB)
+ @echo " LN $(LN1_SLIB) $(LN_SLIB)"; \
+ rm -f $(LN_SLIB) ; $(LN) -s $(LN1_SLIB) $(LN_SLIB)
+
+clean:
+ @echo " CLEAN lib"; \
+ $(RM) -f $(OBJ) $(OUT_SLIB) $(LN_SLIB) $(LN1_SLIB); \
+ $(RM) -f $(DEPS) $(OUT_SLIB) $(LN_SLIB) $(LN1_SLIB)
+
+distclean:
+ @echo " DISTCLEAN lib"; \
+ $(RM) -f $(DEPS)
+
+install:
+ mkdir -p $(DESTDIR)$(libdir)/
+ install -m 0644 $(OUT_SLIB) $(DESTDIR)$(libdir)
+ rm -f $(DESTDIR)$(libdir)/$(LN1_SLIB)
+ $(LN) -s $(OUT_SLIB) $(DESTDIR)$(libdir)/$(LN1_SLIB)
+ rm -f $(DESTDIR)$(libdir)/$(LN_SLIB)
+ $(LN) -s $(LN1_SLIB) $(DESTDIR)$(libdir)/$(LN_SLIB)
+
+$(DEPS): ../Makefile.opts
+
+include ../Makefile.rules
diff --git a/lib/addr.c b/lib/addr.c
new file mode 100644
index 0000000..7fe3781
--- /dev/null
+++ b/lib/addr.c
@@ -0,0 +1,883 @@
+/*
+ * lib/addr.c Abstract Address
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup utils
+ * @defgroup addr Abstract Address
+ *
+ * @par 1) Transform character string to abstract address
+ * @code
+ * struct nl_addr *a = nl_addr_parse("::1", AF_UNSPEC);
+ * printf("Address family: %s\n", nl_af2str(nl_addr_get_family(a)));
+ * nl_addr_put(a);
+ * a = nl_addr_parse("11:22:33:44:55:66", AF_UNSPEC);
+ * printf("Address family: %s\n", nl_af2str(nl_addr_get_family(a)));
+ * nl_addr_put(a);
+ * @endcode
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/addr.h>
+#include <linux/socket.h>
+
+/* All this DECnet stuff is stolen from iproute2, thanks to whoever wrote
+ * this, probably Alexey. */
+static inline uint16_t dn_ntohs(uint16_t addr)
+{
+ union {
+ uint8_t byte[2];
+ uint16_t word;
+ } u = {
+ .word = addr,
+ };
+
+ return ((uint16_t) u.byte[0]) | (((uint16_t) u.byte[1]) << 8);
+}
+
+static inline int do_digit(char *str, uint16_t *addr, uint16_t scale,
+ size_t *pos, size_t len, int *started)
+{
+ uint16_t tmp = *addr / scale;
+
+ if (*pos == len)
+ return 1;
+
+ if (((tmp) > 0) || *started || (scale == 1)) {
+ *str = tmp + '0';
+ *started = 1;
+ (*pos)++;
+ *addr -= (tmp * scale);
+ }
+
+ return 0;
+}
+
+static const char *dnet_ntop(char *addrbuf, size_t addrlen, char *str,
+ size_t len)
+{
+ uint16_t addr = dn_ntohs(*(uint16_t *)addrbuf);
+ uint16_t area = addr >> 10;
+ size_t pos = 0;
+ int started = 0;
+
+ if (addrlen != 2)
+ return NULL;
+
+ addr &= 0x03ff;
+
+ if (len == 0)
+ return str;
+
+ if (do_digit(str + pos, &area, 10, &pos, len, &started))
+ return str;
+
+ if (do_digit(str + pos, &area, 1, &pos, len, &started))
+ return str;
+
+ if (pos == len)
+ return str;
+
+ *(str + pos) = '.';
+ pos++;
+ started = 0;
+
+ if (do_digit(str + pos, &addr, 1000, &pos, len, &started))
+ return str;
+
+ if (do_digit(str + pos, &addr, 100, &pos, len, &started))
+ return str;
+
+ if (do_digit(str + pos, &addr, 10, &pos, len, &started))
+ return str;
+
+ if (do_digit(str + pos, &addr, 1, &pos, len, &started))
+ return str;
+
+ if (pos == len)
+ return str;
+
+ *(str + pos) = 0;
+
+ return str;
+}
+
+static int dnet_num(const char *src, uint16_t * dst)
+{
+ int rv = 0;
+ int tmp;
+ *dst = 0;
+
+ while ((tmp = *src++) != 0) {
+ tmp -= '0';
+ if ((tmp < 0) || (tmp > 9))
+ return rv;
+
+ rv++;
+ (*dst) *= 10;
+ (*dst) += tmp;
+ }
+
+ return rv;
+}
+
+static inline int dnet_pton(const char *src, char *addrbuf)
+{
+ uint16_t area = 0;
+ uint16_t node = 0;
+ int pos;
+
+ pos = dnet_num(src, &area);
+ if ((pos == 0) || (area > 63) ||
+ ((*(src + pos) != '.') && (*(src + pos) != ',')))
+ return -EINVAL;
+
+ pos = dnet_num(src + pos + 1, &node);
+ if ((pos == 0) || (node > 1023))
+ return -EINVAL;
+
+ *(uint16_t *)addrbuf = dn_ntohs((area << 10) | node);
+
+ return 1;
+}
+
+/**
+ * @name Creating Abstract Addresses
+ * @{
+ */
+
+/**
+ * Allocate new abstract address object.
+ * @arg maxsize Maximum size of the binary address.
+ * @return Newly allocated address object or NULL
+ */
+struct nl_addr *nl_addr_alloc(size_t maxsize)
+{
+ struct nl_addr *addr;
+
+ addr = calloc(1, sizeof(*addr) + maxsize);
+ if (!addr) {
+ nl_errno(ENOMEM);
+ return NULL;
+ }
+
+ addr->a_refcnt = 1;
+ addr->a_maxsize = maxsize;
+
+ return addr;
+}
+
+/**
+ * Allocate new abstract address object based on a binary address.
+ * @arg family Address family.
+ * @arg buf Buffer containing the binary address.
+ * @arg size Length of binary address buffer.
+ * @return Newly allocated address handle or NULL
+ */
+struct nl_addr *nl_addr_build(int family, void *buf, size_t size)
+{
+ struct nl_addr *addr;
+
+ addr = nl_addr_alloc(size);
+ if (!addr)
+ return NULL;
+
+ addr->a_family = family;
+ addr->a_len = size;
+ addr->a_prefixlen = size*8;
+
+ if (size)
+ memcpy(addr->a_addr, buf, size);
+
+ return addr;
+}
+
+/**
+ * Allocate abstract address object based on a character string
+ * @arg addrstr Address represented as character string.
+ * @arg hint Address family hint or AF_UNSPEC.
+ *
+ * Regognizes the following address formats:
+ *@code
+ * Format Len Family
+ * ----------------------------------------------------------------
+ * IPv6 address format 16 AF_INET6
+ * ddd.ddd.ddd.ddd 4 AF_INET
+ * HH:HH:HH:HH:HH:HH 6 AF_LLC
+ * AA{.|,}NNNN 2 AF_DECnet
+ * HH:HH:HH:... variable AF_UNSPEC
+ * @endcode
+ *
+ * Special values:
+ * - none: All bits and length set to 0.
+ * - {default|all|any}: All bits set to 0, length based on hint or
+ * AF_INET if no hint is given.
+ *
+ * The prefix length may be appened at the end prefixed with a
+ * slash, e.g. 10.0.0.0/8.
+ *
+ * @return Newly allocated abstract address object or NULL.
+ */
+struct nl_addr *nl_addr_parse(const char *addrstr, int hint)
+{
+ int err, copy = 0, len = 0, family = AF_UNSPEC;
+ char *str, *prefix, buf[32];
+ struct nl_addr *addr = NULL; /* gcc ain't that smart */
+
+ str = strdup(addrstr);
+ if (!str) {
+ err = nl_errno(ENOMEM);
+ goto errout;
+ }
+
+ prefix = strchr(str, '/');
+ if (prefix)
+ *prefix = '\0';
+
+ if (!strcasecmp(str, "none")) {
+ family = hint;
+ goto prefix;
+ }
+
+ if (!strcasecmp(str, "default") ||
+ !strcasecmp(str, "all") ||
+ !strcasecmp(str, "any")) {
+
+ switch (hint) {
+ case AF_INET:
+ case AF_UNSPEC:
+ /* Kind of a hack, we assume that if there is
+ * no hint given the user wants to have a IPv4
+ * address given back. */
+ family = AF_INET;
+ len = 4;
+ goto prefix;
+
+ case AF_INET6:
+ family = AF_INET6;
+ len = 16;
+ goto prefix;
+
+ case AF_LLC:
+ family = AF_LLC;
+ len = 6;
+ goto prefix;
+
+ default:
+ err = nl_error(EINVAL, "Unsuported address" \
+ "family for default address");
+ goto errout;
+ }
+ }
+
+ copy = 1;
+
+ if (hint == AF_INET || hint == AF_UNSPEC) {
+ if (inet_pton(AF_INET, str, buf) > 0) {
+ family = AF_INET;
+ len = 4;
+ goto prefix;
+ }
+ if (hint == AF_INET) {
+ err = nl_error(EINVAL, "Invalid IPv4 address");
+ goto errout;
+ }
+ }
+
+ if (hint == AF_INET6 || hint == AF_UNSPEC) {
+ if (inet_pton(AF_INET6, str, buf) > 0) {
+ family = AF_INET6;
+ len = 16;
+ goto prefix;
+ }
+ if (hint == AF_INET6) {
+ err = nl_error(EINVAL, "Invalid IPv6 address");
+ goto errout;
+ }
+ }
+
+ if ((hint == AF_LLC || hint == AF_UNSPEC) && strchr(str, ':')) {
+ unsigned int a, b, c, d, e, f;
+
+ if (sscanf(str, "%02x:%02x:%02x:%02x:%02x:%02x",
+ &a, &b, &c, &d, &e, &f) == 6) {
+ family = AF_LLC;
+ len = 6;
+ buf[0] = (unsigned char) a;
+ buf[1] = (unsigned char) b;
+ buf[2] = (unsigned char) c;
+ buf[3] = (unsigned char) d;
+ buf[4] = (unsigned char) e;
+ buf[5] = (unsigned char) f;
+ goto prefix;
+ }
+
+ if (hint == AF_LLC) {
+ err = nl_error(EINVAL, "Invalid link layer address");
+ goto errout;
+ }
+ }
+
+ if ((hint == AF_DECnet || hint == AF_UNSPEC) &&
+ (strchr(str, '.') || strchr(str, ','))) {
+ if (dnet_pton(str, buf) > 0) {
+ family = AF_DECnet;
+ len = 2;
+ goto prefix;
+ }
+ if (hint == AF_DECnet) {
+ err = nl_error(EINVAL, "Invalid DECnet address");
+ goto errout;
+ }
+ }
+
+ if (hint == AF_UNSPEC && strchr(str, ':')) {
+ int i = 0;
+ char *s = str, *p;
+ for (;;) {
+ long l = strtol(s, &p, 16);
+
+ if (s == p || l > 0xff || i >= sizeof(buf)) {
+ err = -EINVAL;
+ goto errout;
+ }
+
+ buf[i++] = (unsigned char) l;
+ if (*p == '\0')
+ break;
+ s = ++p;
+ }
+
+ len = i;
+ family = AF_UNSPEC;
+ goto prefix;
+ }
+
+ err = nl_error(EINVAL, "Invalid address");
+ goto errout;
+
+prefix:
+ addr = nl_addr_alloc(len);
+ if (!addr) {
+ err = nl_errno(ENOMEM);
+ goto errout;
+ }
+
+ nl_addr_set_family(addr, family);
+
+ if (copy)
+ nl_addr_set_binary_addr(addr, buf, len);
+
+ if (prefix) {
+ char *p;
+ long pl = strtol(++prefix, &p, 0);
+ if (p == prefix) {
+ nl_addr_destroy(addr);
+ err = -EINVAL;
+ goto errout;
+ }
+ nl_addr_set_prefixlen(addr, pl);
+ } else
+ nl_addr_set_prefixlen(addr, len * 8);
+
+ err = 0;
+errout:
+ free(str);
+
+ return err ? NULL : addr;
+}
+
+/**
+ * Clone existing abstract address object.
+ * @arg addr Abstract address object.
+ * @return Newly allocated abstract address object being a duplicate of the
+ * specified address object or NULL if a failure occured.
+ */
+struct nl_addr *nl_addr_clone(struct nl_addr *addr)
+{
+ struct nl_addr *new;
+
+ new = nl_addr_build(addr->a_family, addr->a_addr, addr->a_len);
+ if (new)
+ new->a_prefixlen = addr->a_prefixlen;
+
+ return new;
+}
+
+/** @} */
+
+/**
+ * @name Destroying Abstract Addresses
+ * @{
+ */
+
+/**
+ * Destroy abstract address object.
+ * @arg addr Abstract address object.
+ */
+void nl_addr_destroy(struct nl_addr *addr)
+{
+ if (!addr)
+ return;
+
+ if (addr->a_refcnt != 1)
+ BUG();
+
+ free(addr);
+}
+
+/** @} */
+
+/**
+ * @name Managing Usage References
+ * @{
+ */
+
+struct nl_addr *nl_addr_get(struct nl_addr *addr)
+{
+ addr->a_refcnt++;
+
+ return addr;
+}
+
+void nl_addr_put(struct nl_addr *addr)
+{
+ if (!addr)
+ return;
+
+ if (addr->a_refcnt == 1)
+ nl_addr_destroy(addr);
+ else
+ addr->a_refcnt--;
+}
+
+/**
+ * Check whether an abstract address object is shared.
+ * @arg addr Abstract address object.
+ * @return Non-zero if the abstract address object is shared, otherwise 0.
+ */
+int nl_addr_shared(struct nl_addr *addr)
+{
+ return addr->a_refcnt > 1;
+}
+
+/** @} */
+
+/**
+ * @name Miscellaneous
+ * @{
+ */
+
+/**
+ * Compares two abstract address objects.
+ * @arg a A abstract address object.
+ * @arg b Another abstract address object.
+ *
+ * @return Integer less than, equal to or greather than zero if \c is found,
+ * respectively to be less than, to, or be greater than \c b.
+ */
+int nl_addr_cmp(struct nl_addr *a, struct nl_addr *b)
+{
+ int d = a->a_family - b->a_family;
+
+ if (d == 0) {
+ d = a->a_len - b->a_len;
+
+ if (a->a_len && d == 0)
+ return memcmp(a->a_addr, b->a_addr, a->a_len);
+ }
+
+ return d;
+}
+
+/**
+ * Compares the prefix of two abstract address objects.
+ * @arg a A abstract address object.
+ * @arg b Another abstract address object.
+ *
+ * @return Integer less than, equal to or greather than zero if \c is found,
+ * respectively to be less than, to, or be greater than \c b.
+ */
+int nl_addr_cmp_prefix(struct nl_addr *a, struct nl_addr *b)
+{
+ int d = a->a_family - b->a_family;
+
+ if (d == 0) {
+ int len = min(a->a_prefixlen, b->a_prefixlen);
+ int bytes = len / 8;
+
+ d = memcmp(a->a_addr, b->a_addr, bytes);
+ if (d == 0) {
+ int mask = (1UL << (len % 8)) - 1UL;
+
+ d = (a->a_addr[bytes] & mask) -
+ (b->a_addr[bytes] & mask);
+ }
+ }
+
+ return d;
+}
+
+/**
+ * Check if an address matches a certain family.
+ * @arg addr Address represented as character string.
+ * @arg family Desired address family.
+ *
+ * @return 1 if the address is of the desired address family,
+ * otherwise 0 is returned.
+ */
+int nl_addr_valid(char *addr, int family)
+{
+ int ret;
+ char buf[32];
+
+ switch (family) {
+ case AF_INET:
+ case AF_INET6:
+ ret = inet_pton(family, addr, buf);
+ if (ret <= 0)
+ return 0;
+ break;
+
+ case AF_DECnet:
+ ret = dnet_pton(addr, buf);
+ if (ret <= 0)
+ return 0;
+ break;
+
+ case AF_LLC:
+ if (sscanf(addr, "%*02x:%*02x:%*02x:%*02x:%*02x:%*02x") != 6)
+ return 0;
+ break;
+ }
+
+ return 1;
+}
+
+/**
+ * Guess address family of an abstract address object based on address size.
+ * @arg addr Abstract address object.
+ * @return Address family or AF_UNSPEC if guessing wasn't successful.
+ */
+int nl_addr_guess_family(struct nl_addr *addr)
+{
+ switch (addr->a_len) {
+ case 4:
+ return AF_INET;
+ case 6:
+ return AF_LLC;
+ case 16:
+ return AF_INET6;
+ default:
+ return AF_UNSPEC;
+ }
+}
+
+/**
+ * Fill out sockaddr structure with values from abstract address object.
+ * @arg addr Abstract address object.
+ * @arg sa Destination sockaddr structure buffer.
+ * @arg salen Length of sockaddr structure buffer.
+ *
+ * Fills out the specified sockaddr structure with the data found in the
+ * specified abstract address. The salen argument needs to be set to the
+ * size of sa but will be modified to the actual size used during before
+ * the function exits.
+ *
+ * @return 0 on success or a negative error code
+ */
+int nl_addr_fill_sockaddr(struct nl_addr *addr, struct sockaddr *sa,
+ socklen_t *salen)
+{
+ switch (addr->a_family) {
+ case AF_INET: {
+ struct sockaddr_in *sai = (struct sockaddr_in *) sa;
+
+ if (*salen < sizeof(*sai))
+ return -EINVAL;
+
+ sai->sin_family = addr->a_family;
+ memcpy(&sai->sin_addr, addr->a_addr, 4);
+ *salen = sizeof(*sai);
+ }
+ break;
+
+ case AF_INET6: {
+ struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *) sa;
+
+ if (*salen < sizeof(*sa6))
+ return -EINVAL;
+
+ sa6->sin6_family = addr->a_family;
+ memcpy(&sa6->sin6_addr, addr->a_addr, 16);
+ *salen = sizeof(*sa6);
+ }
+ break;
+
+ default:
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+
+/** @} */
+
+/**
+ * @name Getting Information About Addresses
+ * @{
+ */
+
+/**
+ * Call getaddrinfo() for an abstract address object.
+ * @arg addr Abstract address object.
+ *
+ * Calls getaddrinfo() for the specified abstract address in AI_NUMERICHOST
+ * mode.
+ *
+ * @note The caller is responsible for freeing the linked list using the
+ * interface provided by getaddrinfo(3).
+ *
+ * @return A linked list of addrinfo handles or NULL with an error message
+ * associated.
+ */
+struct addrinfo *nl_addr_info(struct nl_addr *addr)
+{
+ int err;
+ struct addrinfo *res;
+ char buf[INET6_ADDRSTRLEN+5];
+ struct addrinfo hint = {
+ .ai_flags = AI_NUMERICHOST,
+ .ai_family = addr->a_family,
+ };
+
+ nl_addr2str(addr, buf, sizeof(buf));
+
+ err = getaddrinfo(buf, NULL, &hint, &res);
+ if (err != 0) {
+ nl_error(err, gai_strerror(err));
+ return NULL;
+ }
+
+ return res;
+}
+
+/**
+ * Resolve abstract address object to a name using getnameinfo().
+ * @arg addr Abstract address object.
+ * @arg host Destination buffer for host name.
+ * @arg hostlen Length of destination buffer.
+ *
+ * Resolves the abstract address to a name and writes the looked up result
+ * into the host buffer. getnameinfo() is used to perform the lookup and
+ * is put into NI_NAMEREQD mode so the function will fail if the lookup
+ * couldn't be performed.
+ *
+ * @return 0 on success or a negative error code.
+ */
+int nl_addr_resolve(struct nl_addr *addr, char *host, size_t hostlen)
+{
+ int err;
+ struct sockaddr_in6 buf;
+ socklen_t salen = sizeof(buf);
+
+ err = nl_addr_fill_sockaddr(addr, (struct sockaddr *) &buf, &salen);
+ if (err < 0)
+ return err;
+
+ return getnameinfo((struct sockaddr *) &buf, salen,
+ host, hostlen, NULL, 0, NI_NAMEREQD);
+}
+
+/** @} */
+
+/**
+ * @name Attributes
+ * @{
+ */
+
+void nl_addr_set_family(struct nl_addr *addr, int family)
+{
+ addr->a_family = family;
+}
+
+int nl_addr_get_family(struct nl_addr *addr)
+{
+ return addr->a_family;
+}
+
+/**
+ * Set binary address of abstract address object.
+ * @arg addr Abstract address object.
+ * @arg buf Buffer containing binary address.
+ * @arg len Length of buffer containing binary address.
+ */
+int nl_addr_set_binary_addr(struct nl_addr *addr, void *buf, size_t len)
+{
+ if (len > addr->a_maxsize)
+ return -ERANGE;
+
+ addr->a_len = len;
+ memcpy(addr->a_addr, buf, len);
+
+ return 0;
+}
+
+/**
+ * Get binary address of abstract address object.
+ * @arg addr Abstract address object.
+ */
+void *nl_addr_get_binary_addr(struct nl_addr *addr)
+{
+ return addr->a_addr;
+}
+
+/**
+ * Get length of binary address of abstract address object.
+ * @arg addr Abstract address object.
+ */
+unsigned int nl_addr_get_len(struct nl_addr *addr)
+{
+ return addr->a_len;
+}
+
+void nl_addr_set_prefixlen(struct nl_addr *addr, int prefixlen)
+{
+ addr->a_prefixlen = prefixlen;
+}
+
+/**
+ * Get prefix length of abstract address object.
+ * @arg addr Abstract address object.
+ */
+unsigned int nl_addr_get_prefixlen(struct nl_addr *addr)
+{
+ return addr->a_prefixlen;
+}
+
+/** @} */
+
+/**
+ * @name Translations to Strings
+ * @{
+ */
+
+/**
+ * Convert abstract address object to character string.
+ * @arg addr Abstract address object.
+ * @arg buf Destination buffer.
+ * @arg size Size of destination buffer.
+ *
+ * Converts an abstract address to a character string and stores
+ * the result in the specified destination buffer.
+ *
+ * @return Address represented in ASCII stored in destination buffer.
+ */
+char *nl_addr2str(struct nl_addr *addr, char *buf, size_t size)
+{
+ int i;
+ char tmp[16];
+
+ if (!addr->a_len) {
+ snprintf(buf, size, "none");
+ goto prefix;
+ }
+
+ switch (addr->a_family) {
+ case AF_INET:
+ inet_ntop(AF_INET, addr->a_addr, buf, size);
+ break;
+
+ case AF_INET6:
+ inet_ntop(AF_INET6, addr->a_addr, buf, size);
+ break;
+
+ case AF_DECnet:
+ dnet_ntop(addr->a_addr, addr->a_len, buf, size);
+ break;
+
+ case AF_LLC:
+ default:
+ snprintf(buf, size, "%02x",
+ (unsigned char) addr->a_addr[0]);
+ for (i = 1; i < addr->a_len; i++) {
+ snprintf(tmp, sizeof(tmp), ":%02x",
+ (unsigned char) addr->a_addr[i]);
+ strncat(buf, tmp, size - strlen(buf) - 1);
+ }
+ break;
+ }
+
+prefix:
+ if (addr->a_prefixlen != (8 * addr->a_len)) {
+ snprintf(tmp, sizeof(tmp), "/%u", addr->a_prefixlen);
+ strncat(buf, tmp, size - strlen(buf) - 1);
+ }
+
+ return buf;
+}
+
+/** @} */
+
+/**
+ * @name Address Family Transformations
+ * @{
+ */
+
+static struct trans_tbl afs[] = {
+ __ADD(AF_UNSPEC,unspec)
+ __ADD(AF_UNIX,unix)
+ __ADD(AF_LOCAL,local)
+ __ADD(AF_INET,inet)
+ __ADD(AF_AX25,ax25)
+ __ADD(AF_IPX,ipx)
+ __ADD(AF_APPLETALK,appletalk)
+ __ADD(AF_NETROM,netrom)
+ __ADD(AF_BRIDGE,bridge)
+ __ADD(AF_ATMPVC,atmpvc)
+ __ADD(AF_X25,x25)
+ __ADD(AF_INET6,inet6)
+ __ADD(AF_ROSE,rose)
+ __ADD(AF_DECnet,decnet)
+ __ADD(AF_NETBEUI,netbeui)
+ __ADD(AF_SECURITY,security)
+ __ADD(AF_KEY,key)
+ __ADD(AF_NETLINK,netlink)
+ __ADD(AF_ROUTE,route)
+ __ADD(AF_PACKET,packet)
+ __ADD(AF_ASH,ash)
+ __ADD(AF_ECONET,econet)
+ __ADD(AF_ATMSVC,atmsvc)
+ __ADD(AF_SNA,sna)
+ __ADD(AF_IRDA,irda)
+ __ADD(AF_PPPOX,pppox)
+ __ADD(AF_WANPIPE,wanpipe)
+ __ADD(AF_LLC,llc)
+ __ADD(AF_BLUETOOTH,bluetooth)
+};
+
+char *nl_af2str(int family, char *buf, size_t size)
+{
+ return __type2str(family, buf, size, afs, ARRAY_SIZE(afs));
+}
+
+int nl_str2af(const char *name)
+{
+ int fam = __str2type(name, afs, ARRAY_SIZE(afs));
+ return fam >= 0 ? fam : AF_UNSPEC;
+}
+
+/** @} */
+
+/** @} */
diff --git a/lib/attr.c b/lib/attr.c
new file mode 100644
index 0000000..fbce4ac
--- /dev/null
+++ b/lib/attr.c
@@ -0,0 +1,787 @@
+/*
+ * lib/attr.c Netlink Attributes
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/addr.h>
+#include <netlink/attr.h>
+#include <netlink/msg.h>
+#include <linux/socket.h>
+
+/**
+ * @ingroup msg
+ * @defgroup attr Attributes
+ * Netlink Attributes Construction/Parsing Interface
+ * @par 0) Introduction
+ * Netlink attributes are chained together following each other:
+ * @code
+ * <------- nla_total_size(payload) ------->
+ * <---- nla_attr_size(payload) ----->
+ * +----------+- - -+- - - - - - - - - +- - -+-------- - -
+ * | Header | Pad | Payload | Pad | Header
+ * +----------+- - -+- - - - - - - - - +- - -+-------- - -
+ * <- nla_len(nla) -> ^
+ * nla_data(nla)----^ |
+ * nla_next(nla)-----------------------------'
+ * @endcode
+ *
+ * @par
+ * The attribute header and payload must be aligned properly:
+ * @code
+ * <------- NLA_HDRLEN ------> <-- NLA_ALIGN(payload)-->
+ * +---------------------+- - -+- - - - - - - - - -+- - -+
+ * | Header | Pad | Payload | Pad |
+ * | (struct nlattr) | ing | | ing |
+ * +---------------------+- - -+- - - - - - - - - -+- - -+
+ * <-------------- nlattr->nla_len -------------->
+ * @endcode
+ *
+ * @par Nested TLVs:
+ * Nested TLVs are an array of TLVs nested into another TLV. This can be useful
+ * to allow subsystems to have their own formatting rules without the need to
+ * make the underlying layer be aware of it. It can also be useful to transfer
+ * arrays, lists and flattened trees.
+ * \code
+ * <-------------------- NLA_ALIGN(...) ------------------->
+ * +---------------+- - - - - - - - - - - - - - - - - -+- - -+
+ * | |+---------+---------+- - -+-------+| |
+ * | TLV Header || TLV 1 | TLV 2 | | TLV n || Pad |
+ * | |+---------+---------+- - -+-------+| |
+ * +---------------+- - - - - - - - - - - - - - - - - -+- - -+
+ * <--------- nla_data(nla) --------->
+ * \endcode
+ *
+ * @par 1) Constructing a message with attributes
+ * @code
+ * int param1 = 10;
+ * char *param2 = "parameter text";
+ * struct nlmsghdr hdr = {
+ * .nlmsg_type = MY_ACTION,
+ * };
+ * struct nl_msg *m = nlmsg_build(&hdr);
+ * nla_put_u32(m, 1, param1);
+ * nla_put_string(m, 2, param2);
+ *
+ * nl_send_auto_complete(handle, nl_msg_get(m));
+ * nlmsg_free(m);
+ * @endcode
+ *
+ * @par 2) Constructing nested attributes
+ * @code
+ * struct nl_msg * nested_config(void)
+ * {
+ * int a = 5, int b = 10;
+ * struct nl_msg *n = nlmsg_build(NULL);
+ * nla_put_u32(n, 10, a);
+ * nla_put_u32(n, 20, b);
+ * return n;
+ * }
+ *
+ * ...
+ * struct nl_msg *m = nlmsg_build(&hdr);
+ * struct nl_msg *nest = nested_config();
+ * nla_put_nested(m, 1, nest);
+ *
+ * nl_send_auto_complete(handle, nl_msg_get(m));
+ * nlmsg_free(nest);
+ * nlmsg_free(m);
+ * @endcode
+ * @{
+ */
+
+/**
+ * @name Size Calculations
+ * @{
+ */
+
+/**
+ * length of attribute not including padding
+ * @arg payload length of payload
+ */
+int nla_attr_size(int payload)
+{
+ return NLA_HDRLEN + payload;
+}
+
+/**
+ * total length of attribute including padding
+ * @arg payload length of payload
+ */
+int nla_total_size(int payload)
+{
+ return NLA_ALIGN(nla_attr_size(payload));
+}
+
+/**
+ * length of padding at the tail of the attribute
+ * @arg payload length of payload
+ */
+int nla_padlen(int payload)
+{
+ return nla_total_size(payload) - nla_attr_size(payload);
+}
+
+/** @} */
+
+/**
+ * @name Payload Access
+ * @{
+ */
+
+/**
+ * attribute type
+ * @arg nla netlink attribute
+ */
+int nla_type(const struct nlattr *nla)
+{
+ return nla->nla_type & NLA_TYPE_MASK;
+}
+
+/**
+ * head of payload
+ * @arg nla netlink attribute
+ */
+void *nla_data(const struct nlattr *nla)
+{
+ return (char *) nla + NLA_HDRLEN;
+}
+
+/**
+ * length of payload
+ * @arg nla netlink attribute
+ */
+int nla_len(const struct nlattr *nla)
+{
+ return nla->nla_len - NLA_HDRLEN;
+}
+
+/** @} */
+
+/**
+ * @name Attribute Parsing
+ * @{
+ */
+
+/**
+ * check if the netlink attribute fits into the remaining bytes
+ * @arg nla netlink attribute
+ * @arg remaining number of bytes remaining in attribute stream
+ */
+int nla_ok(const struct nlattr *nla, int remaining)
+{
+ return remaining >= sizeof(*nla) &&
+ nla->nla_len >= sizeof(*nla) &&
+ nla->nla_len <= remaining;
+}
+
+/**
+ * next netlink attribte in attribute stream
+ * @arg nla netlink attribute
+ * @arg remaining number of bytes remaining in attribute stream
+ *
+ * @return the next netlink attribute in the attribute stream and
+ * decrements remaining by the size of the current attribute.
+ */
+struct nlattr *nla_next(const struct nlattr *nla, int *remaining)
+{
+ int totlen = NLA_ALIGN(nla->nla_len);
+
+ *remaining -= totlen;
+ return (struct nlattr *) ((char *) nla + totlen);
+}
+
+static uint16_t nla_attr_minlen[NLA_TYPE_MAX+1] = {
+ [NLA_U8] = sizeof(uint8_t),
+ [NLA_U16] = sizeof(uint16_t),
+ [NLA_U32] = sizeof(uint32_t),
+ [NLA_U64] = sizeof(uint64_t),
+ [NLA_STRING] = 1,
+ [NLA_NESTED] = NLA_HDRLEN,
+};
+
+static int validate_nla(struct nlattr *nla, int maxtype,
+ struct nla_policy *policy)
+{
+ struct nla_policy *pt;
+ int minlen = 0, type = nla_type(nla);
+
+ if (type <= 0 || type > maxtype)
+ return 0;
+
+ pt = &policy[type];
+
+ if (pt->type > NLA_TYPE_MAX)
+ BUG();
+
+ if (pt->minlen)
+ minlen = pt->minlen;
+ else if (pt->type != NLA_UNSPEC)
+ minlen = nla_attr_minlen[pt->type];
+
+ if (pt->type == NLA_FLAG && nla_len(nla) > 0)
+ return nl_errno(ERANGE);
+
+ if (nla_len(nla) < minlen)
+ return nl_errno(ERANGE);
+
+ if (pt->maxlen && nla_len(nla) > pt->maxlen)
+ return nl_errno(ERANGE);
+
+ if (pt->type == NLA_STRING) {
+ char *data = nla_data(nla);
+ if (data[nla_len(nla) - 1] != '\0')
+ return nl_errno(EINVAL);
+ }
+
+ return 0;
+}
+
+
+/**
+ * Parse a stream of attributes into a tb buffer
+ * @arg tb destination array with maxtype+1 elements
+ * @arg maxtype maximum attribute type to be expected
+ * @arg head head of attribute stream
+ * @arg len length of attribute stream
+ * @arg policy validation policy
+ *
+ * Parses a stream of attributes and stores a pointer to each attribute in
+ * the tb array accessable via the attribute type. Attributes with a type
+ * exceeding maxtype will be silently ignored for backwards compatibility
+ * reasons. policy may be set to NULL if no validation is required.
+ *
+ * @return 0 on success or a negative error code.
+ */
+int nla_parse(struct nlattr *tb[], int maxtype, struct nlattr *head, int len,
+ struct nla_policy *policy)
+{
+ struct nlattr *nla;
+ int rem, err;
+
+ memset(tb, 0, sizeof(struct nlattr *) * (maxtype + 1));
+
+ nla_for_each_attr(nla, head, len, rem) {
+ int type = nla_type(nla);
+
+ if (type == 0) {
+ fprintf(stderr, "Illegal nla->nla_type == 0\n");
+ continue;
+ }
+
+ if (type <= maxtype) {
+ if (policy) {
+ err = validate_nla(nla, maxtype, policy);
+ if (err < 0)
+ goto errout;
+ }
+
+ tb[type] = nla;
+ }
+ }
+
+ if (rem > 0)
+ fprintf(stderr, "netlink: %d bytes leftover after parsing "
+ "attributes.\n", rem);
+
+ err = 0;
+errout:
+ return err;
+}
+
+
+/**
+ * parse nested attributes
+ * @arg tb destination array with maxtype+1 elements
+ * @arg maxtype maximum attribute type to be expected
+ * @arg nla attribute containing the nested attributes
+ * @arg policy validation policy
+ *
+ * @see nla_parse()
+ */
+int nla_parse_nested(struct nlattr *tb[], int maxtype, struct nlattr *nla,
+ struct nla_policy *policy)
+{
+ return nla_parse(tb, maxtype, nla_data(nla), nla_len(nla), policy);
+}
+
+/**
+ * Validate a stream of attributes
+ * @arg head head of attribute stream
+ * @arg len length of attribute stream
+ * @arg maxtype maximum attribute type to be expected
+ * @arg policy validation policy
+ *
+ * Validates all attributes in the specified attribute stream
+ * against the specified policy. Attributes with a type exceeding
+ * maxtype will be ignored. See documenation of struct nla_policy
+ * for more details.
+ *
+ * @return 0 on success or a negative error code.
+ */
+int nla_validate(struct nlattr *head, int len, int maxtype,
+ struct nla_policy *policy)
+{
+ struct nlattr *nla;
+ int rem, err;
+
+ nla_for_each_attr(nla, head, len, rem) {
+ err = validate_nla(nla, maxtype, policy);
+ if (err < 0)
+ goto errout;
+ }
+
+ err = 0;
+errout:
+ return err;
+}
+
+/**
+ * Find a specific attribute in a stream of attributes
+ * @arg head head of attribute stream
+ * @arg len length of attribute stream
+ * @arg attrtype type of attribute to look for
+ *
+ * @return the first attribute in the stream matching the specified type.
+ */
+struct nlattr *nla_find(struct nlattr *head, int len, int attrtype)
+{
+ struct nlattr *nla;
+ int rem;
+
+ nla_for_each_attr(nla, head, len, rem)
+ if (nla_type(nla) == attrtype)
+ return nla;
+
+ return NULL;
+}
+
+/** @} */
+
+/**
+ * @name Utilities
+ * @{
+ */
+
+/**
+ * Copy a netlink attribute into another memory area
+ * @arg dest where to copy to memcpy
+ * @arg src netlink attribute to copy from
+ * @arg count size of the destination area
+ *
+ * Note: The number of bytes copied is limited by the length of
+ * attribute's payload. memcpy
+ *
+ * @return the number of bytes copied.
+ */
+int nla_memcpy(void *dest, struct nlattr *src, int count)
+{
+ int minlen;
+
+ if (!src)
+ return 0;
+
+ minlen = min_t(int, count, nla_len(src));
+ memcpy(dest, nla_data(src), minlen);
+
+ return minlen;
+}
+
+/**
+ * Copy string attribute payload into a sized buffer
+ * @arg dst where to copy the string to
+ * @arg nla attribute to copy the string from
+ * @arg dstsize size of destination buffer
+ *
+ * Copies at most dstsize - 1 bytes into the destination buffer.
+ * The result is always a valid NUL-terminated string. Unlike
+ * strlcpy the destination buffer is always padded out.
+ *
+ * @return the length of the source buffer.
+ */
+size_t nla_strlcpy(char *dst, const struct nlattr *nla, size_t dstsize)
+{
+ size_t srclen = nla_len(nla);
+ char *src = nla_data(nla);
+
+ if (srclen > 0 && src[srclen - 1] == '\0')
+ srclen--;
+
+ if (dstsize > 0) {
+ size_t len = (srclen >= dstsize) ? dstsize - 1 : srclen;
+
+ memset(dst, 0, dstsize);
+ memcpy(dst, src, len);
+ }
+
+ return srclen;
+}
+
+/**
+ * Compare an attribute with sized memory area
+ * @arg nla netlink attribute
+ * @arg data memory area
+ * @arg size size of memory area
+ */
+int nla_memcmp(const struct nlattr *nla, const void *data,
+ size_t size)
+{
+ int d = nla_len(nla) - size;
+
+ if (d == 0)
+ d = memcmp(nla_data(nla), data, size);
+
+ return d;
+}
+
+/**
+ * Compare a string attribute against a string
+ * @arg nla netlink string attribute
+ * @arg str another string
+ */
+int nla_strcmp(const struct nlattr *nla, const char *str)
+{
+ int len = strlen(str) + 1;
+ int d = nla_len(nla) - len;
+
+ if (d == 0)
+ d = memcmp(nla_data(nla), str, len);
+
+ return d;
+}
+
+/** @} */
+
+/**
+ * @name Attribute Construction
+ * @{
+ */
+
+/**
+ * reserve room for attribute on the skb
+ * @arg n netlink message
+ * @arg attrtype attribute type
+ * @arg attrlen length of attribute payload
+ *
+ * Adds a netlink attribute header to a netlink message and reserves
+ * room for the payload but does not copy it.
+ */
+struct nlattr *nla_reserve(struct nl_msg *n, int attrtype, int attrlen)
+{
+ struct nlattr *nla;
+ int tlen;
+
+ tlen = NLMSG_ALIGN(n->nm_nlh->nlmsg_len) + nla_total_size(attrlen);
+
+ n->nm_nlh = realloc(n->nm_nlh, tlen);
+ if (!n->nm_nlh) {
+ nl_errno(ENOMEM);
+ return NULL;
+ }
+
+ nla = (struct nlattr *) nlmsg_tail(n->nm_nlh);
+ nla->nla_type = attrtype;
+ nla->nla_len = nla_attr_size(attrlen);
+
+ memset((unsigned char *) nla + nla->nla_len, 0, nla_padlen(attrlen));
+ n->nm_nlh->nlmsg_len = tlen;
+
+ NL_DBG(2, "msg %p: Reserved %d bytes at offset +%d for attr %d "
+ "nlmsg_len=%d\n", n, attrlen,
+ (void *) nla - nlmsg_data(n->nm_nlh),
+ attrtype, n->nm_nlh->nlmsg_len);
+
+ return nla;
+}
+
+/**
+ * Add a netlink attribute to a netlink message
+ * @arg n netlink message
+ * @arg attrtype attribute type
+ * @arg attrlen length of attribute payload
+ * @arg data head of attribute payload
+ *
+ * @return -1 if the tailroom of the skb is insufficient to store
+ * the attribute header and payload.
+ */
+int nla_put(struct nl_msg *n, int attrtype, int attrlen, const void *data)
+{
+ struct nlattr *nla;
+
+ nla = nla_reserve(n, attrtype, attrlen);
+ if (!nla)
+ return nl_errno(ENOMEM);
+
+ memcpy(nla_data(nla), data, attrlen);
+ NL_DBG(2, "msg %p: Wrote %d bytes at offset +%d for attr %d\n",
+ n, attrlen, (void *) nla - nlmsg_data(n->nm_nlh), attrtype);
+
+ return 0;
+}
+
+/**
+ * Add a nested netlink attribute to a netlink message
+ * @arg n netlink message
+ * @arg attrtype attribute type
+ * @arg nested netlink attribute to nest
+ *
+ * @return -1 if the tailroom of the skb is insufficient to store
+ * the attribute header and payload.
+ */
+int nla_put_nested(struct nl_msg *n, int attrtype, struct nl_msg *nested)
+{
+ return nla_put(n, attrtype, nlmsg_len(nested->nm_nlh),
+ nlmsg_data(nested->nm_nlh));
+}
+
+/**
+ * Add a u16 netlink attribute to a netlink message
+ * @arg n netlink message
+ * @arg attrtype attribute type
+ * @arg value numeric value
+ */
+int nla_put_u8(struct nl_msg *n, int attrtype, uint8_t value)
+{
+ return nla_put(n, attrtype, sizeof(uint8_t), &value);
+}
+
+/**
+ * Add a u16 netlink attribute to a netlink message
+ * @arg n netlink message
+ * @arg attrtype attribute type
+ * @arg value numeric value
+ */
+int nla_put_u16(struct nl_msg *n, int attrtype, uint16_t value)
+{
+ return nla_put(n, attrtype, sizeof(uint16_t), &value);
+}
+
+/**
+ * Add a u32 netlink attribute to a netlink message
+ * @arg n netlink message
+ * @arg attrtype attribute type
+ * @arg value numeric value
+ */
+int nla_put_u32(struct nl_msg *n, int attrtype, uint32_t value)
+{
+ return nla_put(n, attrtype, sizeof(uint32_t), &value);
+}
+
+/**
+ * Add a u64 netlink attribute to a netlink message
+ * @arg n netlink message
+ * @arg attrtype attribute type
+ * @arg value numeric value
+ */
+int nla_put_u64(struct nl_msg *n, int attrtype, uint64_t value)
+{
+ return nla_put(n, attrtype, sizeof(uint64_t), &value);
+}
+
+/**
+ * Add a string netlink attribute to a netlink message
+ * @arg n netlink message
+ * @arg attrtype attribute type
+ * @arg str NUL terminated string
+ */
+int nla_put_string(struct nl_msg *n, int attrtype, const char *str)
+{
+ return nla_put(n, attrtype, strlen(str) + 1, str);
+}
+
+/**
+ * Add a flag netlink attribute to a netlink message
+ * @arg n netlink message
+ * @arg attrtype attribute type
+ */
+int nla_put_flag(struct nl_msg *n, int attrtype)
+{
+ return nla_put(n, attrtype, 0, NULL);
+}
+
+/**
+ * Add a msecs netlink attribute to a netlink message
+ * @arg n netlink message
+ * @arg attrtype attribute type
+ * @arg msecs number of msecs
+ */
+int nla_put_msecs(struct nl_msg *n, int attrtype, unsigned long msecs)
+{
+ return nla_put_u64(n, attrtype, msecs);
+}
+
+/**
+ * Add an abstract data netlink attribute to a netlink message
+ * @arg n netlink message
+ * @arg attrtype attribute type
+ * @arg data abstract data
+ */
+int nla_put_data(struct nl_msg *n, int attrtype, struct nl_data *data)
+{
+ return nla_put(n, attrtype, nl_data_get_size(data),
+ nl_data_get(data));
+}
+
+/**
+ * Add an abstract address netlink attribute to a netlink message
+ * @arg n netlink message
+ * @arg attrtype attribute type
+ * @arg addr abstract address
+ */
+int nla_put_addr(struct nl_msg *n, int attrtype, struct nl_addr *addr)
+{
+ return nla_put(n, attrtype, nl_addr_get_len(addr),
+ nl_addr_get_binary_addr(addr));
+}
+
+/** @} */
+
+/**
+ * @name Attribute Nesting
+ * @{
+ */
+
+/**
+ * Start a new level of nested attributes
+ * @arg n netlink message
+ * @arg attrtype attribute type of container
+ *
+ * @return the container attribute
+ */
+struct nlattr *nla_nest_start(struct nl_msg *n, int attrtype)
+{
+ struct nlattr *start = (struct nlattr *) nlmsg_tail(n->nm_nlh);
+
+ if (nla_put(n, attrtype, 0, NULL) < 0)
+ return NULL;
+
+ return start;
+}
+
+/**
+ * Finalize nesting of attributes
+ * @arg n netlink message
+ * @arg start container attribute
+ *
+ * Corrects the container attribute header to include the all
+ * appeneded attributes.
+ *
+ * @return the total data length of the skb.
+ */
+int nla_nest_end(struct nl_msg *n, struct nlattr *start)
+{
+ start->nla_len = (unsigned char *) nlmsg_tail(n->nm_nlh) -
+ (unsigned char *) start;
+ return 0;
+}
+
+/** @} */
+
+/**
+ * @name Attribute Reading
+ * @{
+ */
+
+/**
+ * Return payload of u32 attribute
+ * @arg nla u32 netlink attribute
+ */
+uint32_t nla_get_u32(struct nlattr *nla)
+{
+ return *(uint32_t *) nla_data(nla);
+}
+
+/**
+ * Return payload of u16 attribute
+ * @arg nla u16 netlink attribute
+ */
+uint16_t nla_get_u16(struct nlattr *nla)
+{
+ return *(uint16_t *) nla_data(nla);
+}
+
+/**
+ * Return payload of u8 attribute
+ * @arg nla u8 netlink attribute
+ */
+uint8_t nla_get_u8(struct nlattr *nla)
+{
+ return *(uint8_t *) nla_data(nla);
+}
+
+/**
+ * Return payload of u64 attribute
+ * @arg nla u64 netlink attribute
+ */
+uint64_t nla_get_u64(struct nlattr *nla)
+{
+ uint64_t tmp;
+
+ nla_memcpy(&tmp, nla, sizeof(tmp));
+
+ return tmp;
+}
+
+/**
+ * return payload of string attribute
+ * @arg nla string netlink attribute
+ */
+char *nla_get_string(struct nlattr *nla)
+{
+ return (char *) nla_data(nla);
+}
+
+/**
+ * Return payload of flag attribute
+ * @arg nla flag netlink attribute
+ */
+int nla_get_flag(struct nlattr *nla)
+{
+ return !!nla;
+}
+
+/**
+ * Return payload of msecs attribute
+ * @arg nla msecs netlink attribute
+ *
+ * @return the number of milliseconds.
+ */
+unsigned long nla_get_msecs(struct nlattr *nla)
+{
+ return nla_get_u64(nla);
+}
+
+/**
+ * Return payload of address attribute
+ * @arg nla address netlink attribute
+ * @arg family address family
+ *
+ * @return Newly allocated address handle or NULL
+ */
+struct nl_addr *nla_get_addr(struct nlattr *nla, int family)
+{
+ return nl_addr_build(family, nla_data(nla), nla_len(nla));
+}
+
+/**
+ * Return payload of abstract data attribute
+ * @arg nla abstract data netlink attribute
+ *
+ * @return Newly allocated abstract data handle or NULL
+ */
+struct nl_data *nla_get_data(struct nlattr *nla)
+{
+ return nl_data_alloc(nla_data(nla), nla_len(nla));
+}
+
+/** @} */
+
+/** @} */
diff --git a/lib/cache.c b/lib/cache.c
new file mode 100644
index 0000000..577b2ba
--- /dev/null
+++ b/lib/cache.c
@@ -0,0 +1,805 @@
+/*
+ * lib/cache.c Caching Module
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup cache_mngt
+ * @defgroup cache Cache
+ *
+ * @code
+ * Cache Management | | Type Specific Cache Operations
+ *
+ * | | +----------------+ +------------+
+ * | request update | | msg_parser |
+ * | | +----------------+ +------------+
+ * +- - - - -^- - - - - - - -^- -|- - - -
+ * nl_cache_update: | | | |
+ * 1) --------- co_request_update ------+ | |
+ * | | |
+ * 2) destroy old cache +----------- pp_cb ---------|---+
+ * | | |
+ * 3) ---------- nl_recvmsgs ----------+ +- cb_valid -+
+ * +--------------+ | | | |
+ * | nl_cache_add |<-----+ + - - -v- -|- - - - - - - - - - -
+ * +--------------+ | | +-------------+
+ * | nl_recvmsgs |
+ * | | +-----|-^-----+
+ * +---v-|---+
+ * | | | nl_recv |
+ * +---------+
+ * | | Core Netlink
+ * @endcode
+ *
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/cache.h>
+#include <netlink/object.h>
+#include <netlink/utils.h>
+
+/**
+ * @name Access Functions
+ * @{
+ */
+
+/**
+ * Return the number of items in the cache
+ * @arg cache cache handle
+ */
+int nl_cache_nitems(struct nl_cache *cache)
+{
+ return cache->c_nitems;
+}
+
+/**
+ * Return the number of items matching a filter in the cache
+ * @arg cache Cache object.
+ * @arg filter Filter object.
+ */
+int nl_cache_nitems_filter(struct nl_cache *cache, struct nl_object *filter)
+{
+ struct nl_object_ops *ops;
+ struct nl_object *obj;
+ int nitems = 0;
+
+ if (cache->c_ops == NULL)
+ BUG();
+
+ ops = cache->c_ops->co_obj_ops;
+
+ nl_list_for_each_entry(obj, &cache->c_items, ce_list) {
+ if (filter && !nl_object_match_filter(obj, filter))
+ continue;
+
+ nitems++;
+ }
+
+ return nitems;
+}
+
+/**
+ * Returns \b true if the cache is empty.
+ * @arg cache Cache to check
+ * @return \a true if the cache is empty, otherwise \b false is returned.
+ */
+int nl_cache_is_empty(struct nl_cache *cache)
+{
+ return nl_list_empty(&cache->c_items);
+}
+
+/**
+ * Return the operations set of the cache
+ * @arg cache cache handle
+ */
+struct nl_cache_ops *nl_cache_get_ops(struct nl_cache *cache)
+{
+ return cache->c_ops;
+}
+
+/**
+ * Return the first element in the cache
+ * @arg cache cache handle
+ */
+struct nl_object *nl_cache_get_first(struct nl_cache *cache)
+{
+ if (nl_list_empty(&cache->c_items))
+ return NULL;
+
+ return nl_list_entry(cache->c_items.next,
+ struct nl_object, ce_list);
+}
+
+/**
+ * Return the last element in the cache
+ * @arg cache cache handle
+ */
+struct nl_object *nl_cache_get_last(struct nl_cache *cache)
+{
+ if (nl_list_empty(&cache->c_items))
+ return NULL;
+
+ return nl_list_entry(cache->c_items.prev,
+ struct nl_object, ce_list);
+}
+
+/**
+ * Return the next element in the cache
+ * @arg obj current object
+ */
+struct nl_object *nl_cache_get_next(struct nl_object *obj)
+{
+ if (nl_list_at_tail(obj, &obj->ce_cache->c_items, ce_list))
+ return NULL;
+ else
+ return nl_list_entry(obj->ce_list.next,
+ struct nl_object, ce_list);
+}
+
+/**
+ * Return the previous element in the cache
+ * @arg obj current object
+ */
+struct nl_object *nl_cache_get_prev(struct nl_object *obj)
+{
+ if (nl_list_at_head(obj, &obj->ce_cache->c_items, ce_list))
+ return NULL;
+ else
+ return nl_list_entry(obj->ce_list.prev,
+ struct nl_object, ce_list);
+}
+
+/** @} */
+
+/**
+ * @name Cache Creation/Deletion
+ * @{
+ */
+
+/**
+ * Allocate an empty cache
+ * @arg ops cache operations to base the cache on
+ *
+ * @return A newly allocated and initialized cache.
+ */
+struct nl_cache *nl_cache_alloc(struct nl_cache_ops *ops)
+{
+ struct nl_cache *cache;
+
+ cache = calloc(1, sizeof(*cache));
+ if (!cache) {
+ nl_errno(ENOMEM);
+ return NULL;
+ }
+
+ nl_init_list_head(&cache->c_items);
+ cache->c_ops = ops;
+
+ NL_DBG(2, "Allocated cache %p <%s>.\n", cache, nl_cache_name(cache));
+
+ return cache;
+}
+
+/**
+ * Allocate an empty cache based on type name
+ * @arg kind Name of cache type
+ * @return A newly allocated and initialized cache.
+ */
+struct nl_cache *nl_cache_alloc_name(const char *kind)
+{
+ struct nl_cache_ops *ops;
+
+ ops = nl_cache_ops_lookup(kind);
+ if (!ops) {
+ nl_error(ENOENT, "Unable to lookup cache \"%s\"", kind);
+ return NULL;
+ }
+
+ return nl_cache_alloc(ops);
+}
+
+/**
+ * Allocate a new cache containing a subset of a cache
+ * @arg orig Original cache to be based on
+ * @arg filter Filter defining the subset to be filled into new cache
+ * @return A newly allocated cache or NULL.
+ */
+struct nl_cache *nl_cache_subset(struct nl_cache *orig,
+ struct nl_object *filter)
+{
+ struct nl_cache *cache;
+ struct nl_object_ops *ops;
+ struct nl_object *obj;
+
+ if (!filter)
+ BUG();
+
+ cache = nl_cache_alloc(orig->c_ops);
+ if (!cache)
+ return NULL;
+
+ ops = orig->c_ops->co_obj_ops;
+
+ nl_list_for_each_entry(obj, &orig->c_items, ce_list) {
+ if (!nl_object_match_filter(obj, filter))
+ continue;
+
+ nl_cache_add(cache, obj);
+ }
+
+ return cache;
+}
+
+/**
+ * Clear a cache.
+ * @arg cache cache to clear
+ *
+ * Removes all elements of a cache.
+ */
+void nl_cache_clear(struct nl_cache *cache)
+{
+ struct nl_object *obj, *tmp;
+
+ NL_DBG(1, "Clearing cache %p <%s>...\n", cache, nl_cache_name(cache));
+
+ nl_list_for_each_entry_safe(obj, tmp, &cache->c_items, ce_list)
+ nl_cache_remove(obj);
+}
+
+/**
+ * Free a cache.
+ * @arg cache Cache to free.
+ *
+ * Removes all elements of a cache and frees all memory.
+ *
+ * @note Use this function if you are working with allocated caches.
+ */
+void nl_cache_free(struct nl_cache *cache)
+{
+ nl_cache_clear(cache);
+ NL_DBG(1, "Freeing cache %p <%s>...\n", cache, nl_cache_name(cache));
+ free(cache);
+}
+
+/** @} */
+
+/**
+ * @name Cache Modifications
+ * @{
+ */
+
+static int __cache_add(struct nl_cache *cache, struct nl_object *obj)
+{
+ obj->ce_cache = cache;
+
+ nl_list_add_tail(&obj->ce_list, &cache->c_items);
+ cache->c_nitems++;
+
+ NL_DBG(1, "Added %p to cache %p <%s>.\n",
+ obj, cache, nl_cache_name(cache));
+
+ return 0;
+}
+
+/**
+ * Add object to a cache.
+ * @arg cache Cache to add object to
+ * @arg obj Object to be added to the cache
+ *
+ * Adds the given object to the specified cache. The object is cloned
+ * if it has been added to another cache already.
+ *
+ * @return 0 or a negative error code.
+ */
+int nl_cache_add(struct nl_cache *cache, struct nl_object *obj)
+{
+ struct nl_object *new;
+
+ if (cache->c_ops->co_obj_ops != obj->ce_ops)
+ return nl_error(EINVAL, "Object mismatches cache type");
+
+ if (!nl_list_empty(&obj->ce_list)) {
+ new = nl_object_clone(obj);
+ if (!new)
+ return nl_errno(ENOMEM);
+ } else {
+ nl_object_get(obj);
+ new = obj;
+ }
+
+ return __cache_add(cache, new);
+}
+
+/**
+ * Move object from one cache to another
+ * @arg cache Cache to move object to.
+ * @arg obj Object subject to be moved
+ *
+ * Removes the given object from its associated cache if needed
+ * and adds it to the new cache.
+ *
+ * @return 0 on success or a negative error code.
+ */
+int nl_cache_move(struct nl_cache *cache, struct nl_object *obj)
+{
+ if (cache->c_ops->co_obj_ops != obj->ce_ops)
+ return nl_error(EINVAL, "Object mismatches cache type");
+
+ NL_DBG(3, "Moving object %p to cache %p\n", obj, cache);
+
+ /* Acquire reference, if already in a cache this will be
+ * reverted during removal */
+ nl_object_get(obj);
+
+ if (!nl_list_empty(&obj->ce_list))
+ nl_cache_remove(obj);
+
+ return __cache_add(cache, obj);
+}
+
+/**
+ * Removes an object from a cache.
+ * @arg obj Object to remove from its cache
+ *
+ * Removes the object \c obj from the cache it is assigned to, since
+ * an object can only be assigned to one cache at a time, the cache
+ * must ne be passed along with it.
+ */
+void nl_cache_remove(struct nl_object *obj)
+{
+ struct nl_cache *cache = obj->ce_cache;
+
+ if (cache == NULL)
+ return;
+
+ nl_list_del(&obj->ce_list);
+ obj->ce_cache = NULL;
+ nl_object_put(obj);
+ cache->c_nitems--;
+
+ NL_DBG(1, "Deleted %p from cache %p <%s>.\n",
+ obj, cache, nl_cache_name(cache));
+}
+
+/**
+ * Search for an object in a cache
+ * @arg cache Cache to search in.
+ * @arg needle Object to look for.
+ *
+ * Iterates over the cache and looks for an object with identical
+ * identifiers as the needle.
+ *
+ * @return Reference to object or NULL if not found.
+ * @note The returned object must be returned via nl_object_put().
+ */
+struct nl_object *nl_cache_search(struct nl_cache *cache,
+ struct nl_object *needle)
+{
+ struct nl_object *obj;
+
+ nl_list_for_each_entry(obj, &cache->c_items, ce_list) {
+ if (nl_object_identical(obj, needle)) {
+ nl_object_get(obj);
+ return obj;
+ }
+ }
+
+ return NULL;
+}
+
+
+/** @} */
+
+/**
+ * @name Synchronization
+ * @{
+ */
+
+/**
+ * Request a full dump from the kernel to fill a cache
+ * @arg handle Netlink handle
+ * @arg cache Cache subjected to be filled.
+ *
+ * Send a dumping request to the kernel causing it to dump all objects
+ * related to the specified cache to the netlink socket.
+ *
+ * Use nl_cache_pickup() to read the objects from the socket and fill them
+ * into a cache.
+ */
+int nl_cache_request_full_dump(struct nl_handle *handle, struct nl_cache *cache)
+{
+ NL_DBG(2, "Requesting dump from kernel for cache %p <%s>...\n",
+ cache, nl_cache_name(cache));
+
+ return cache->c_ops->co_request_update(cache, handle);
+}
+
+/** @cond SKIP */
+struct update_xdata {
+ struct nl_cache_ops *ops;
+ struct nl_parser_param *params;
+};
+
+static int update_msg_parser(struct nl_msg *msg, void *arg)
+{
+ struct update_xdata *x = arg;
+
+ return nl_cache_parse(x->ops, &msg->nm_src, msg->nm_nlh, x->params);
+}
+/** @endcond */
+
+int __cache_pickup(struct nl_handle *handle, struct nl_cache *cache,
+ struct nl_parser_param *param)
+{
+ int err;
+ struct nl_cb *cb;
+ struct update_xdata x = {
+ .ops = cache->c_ops,
+ .params = param,
+ };
+
+ NL_DBG(1, "Picking up answer for cache %p <%s>...\n",
+ cache, nl_cache_name(cache));
+
+ cb = nl_cb_clone(handle->h_cb);
+ if (cb == NULL)
+ return nl_get_errno();
+
+ nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, update_msg_parser, &x);
+
+ err = nl_recvmsgs(handle, cb);
+ if (err < 0)
+ NL_DBG(2, "While picking up for %p <%s>, recvmsgs() returned " \
+ "%d: %s", cache, nl_cache_name(cache),
+ err, nl_geterror());
+
+ nl_cb_put(cb);
+
+ return err;
+}
+
+static int pickup_cb(struct nl_object *c, struct nl_parser_param *p)
+{
+ return nl_cache_add((struct nl_cache *) p->pp_arg, c);
+}
+
+/**
+ * Pickup a netlink dump response and put it into a cache.
+ * @arg handle Netlink handle.
+ * @arg cache Cache to put items into.
+ *
+ * Waits for netlink messages to arrive, parses them and puts them into
+ * the specified cache.
+ *
+ * @return 0 on success or a negative error code.
+ */
+int nl_cache_pickup(struct nl_handle *handle, struct nl_cache *cache)
+{
+ struct nl_parser_param p = {
+ .pp_cb = pickup_cb,
+ .pp_arg = cache,
+ };
+
+ return __cache_pickup(handle, cache, &p);
+}
+
+static int cache_include(struct nl_cache *cache, struct nl_object *obj,
+ struct nl_msgtype *type, change_func_t cb)
+{
+ struct nl_object *old;
+
+ switch (type->mt_act) {
+ case NL_ACT_NEW:
+ case NL_ACT_DEL:
+ old = nl_cache_search(cache, obj);
+ if (old) {
+ nl_cache_remove(old);
+ if (type->mt_act == NL_ACT_DEL && cb)
+ cb(cache, old, NL_ACT_DEL);
+ }
+
+ if (type->mt_act == NL_ACT_NEW) {
+ nl_cache_move(cache, obj);
+ if (old == NULL && cb)
+ cb(cache, obj, NL_ACT_NEW);
+ else if (old) {
+ if (nl_object_diff(old, obj) && cb)
+ cb(cache, obj, NL_ACT_CHANGE);
+
+ nl_object_put(old);
+ }
+ }
+ break;
+ default:
+ NL_DBG(2, "Unknown action associated to object %p\n", obj);
+ return 0;
+ }
+
+ return 0;
+}
+
+int nl_cache_include(struct nl_cache *cache, struct nl_object *obj,
+ change_func_t change_cb)
+{
+ struct nl_cache_ops *ops = cache->c_ops;
+ int i;
+
+ if (ops->co_obj_ops != obj->ce_ops)
+ return nl_error(EINVAL, "Object mismatches cache type");
+
+ for (i = 0; ops->co_msgtypes[i].mt_id >= 0; i++)
+ if (ops->co_msgtypes[i].mt_id == obj->ce_msgtype)
+ return cache_include(cache, obj, &ops->co_msgtypes[i],
+ change_cb);
+
+ return nl_errno(EINVAL);
+}
+
+static int resync_cb(struct nl_object *c, struct nl_parser_param *p)
+{
+ struct nl_cache_assoc *ca = p->pp_arg;
+
+ return nl_cache_include(ca->ca_cache, c, ca->ca_change);
+}
+
+int nl_cache_resync(struct nl_handle *handle, struct nl_cache *cache,
+ change_func_t change_cb)
+{
+ struct nl_object *obj, *next;
+ struct nl_cache_assoc ca = {
+ .ca_cache = cache,
+ .ca_change = change_cb,
+ };
+ struct nl_parser_param p = {
+ .pp_cb = resync_cb,
+ .pp_arg = &ca,
+ };
+ int err;
+
+ NL_DBG(1, "Resyncing cache %p <%s>...\n", cache, nl_cache_name(cache));
+
+ /* Mark all objects so we can see if some of them are obsolete */
+ nl_cache_mark_all(cache);
+
+ err = nl_cache_request_full_dump(handle, cache);
+ if (err < 0)
+ goto errout;
+
+ err = __cache_pickup(handle, cache, &p);
+ if (err < 0)
+ goto errout;
+
+ nl_list_for_each_entry_safe(obj, next, &cache->c_items, ce_list)
+ if (nl_object_is_marked(obj))
+ nl_cache_remove(obj);
+
+ NL_DBG(1, "Finished resyncing %p <%s>\n", cache, nl_cache_name(cache));
+
+ err = 0;
+errout:
+ return err;
+}
+
+/** @} */
+
+/**
+ * @name Parsing
+ * @{
+ */
+
+/** @cond SKIP */
+int nl_cache_parse(struct nl_cache_ops *ops, struct sockaddr_nl *who,
+ struct nlmsghdr *nlh, struct nl_parser_param *params)
+{
+ int i, err;
+
+ if (nlh->nlmsg_len < nlmsg_msg_size(ops->co_hdrsize)) {
+ err = nl_error(EINVAL, "netlink message too short to be "
+ "of kind %s", ops->co_name);
+ goto errout;
+ }
+
+ for (i = 0; ops->co_msgtypes[i].mt_id >= 0; i++) {
+ if (ops->co_msgtypes[i].mt_id == nlh->nlmsg_type) {
+ err = ops->co_msg_parser(ops, who, nlh, params);
+ if (err != -ENOENT)
+ goto errout;
+ }
+ }
+
+
+ err = nl_error(EINVAL, "Unsupported netlink message type %d",
+ nlh->nlmsg_type);
+errout:
+ return err;
+}
+/** @endcond */
+
+/**
+ * Parse a netlink message and add it to the cache.
+ * @arg cache cache to add element to
+ * @arg msg netlink message
+ *
+ * Parses a netlink message by calling the cache specific message parser
+ * and adds the new element to the cache.
+ *
+ * @return 0 or a negative error code.
+ */
+int nl_cache_parse_and_add(struct nl_cache *cache, struct nl_msg *msg)
+{
+ struct nl_parser_param p = {
+ .pp_cb = pickup_cb,
+ .pp_arg = cache,
+ };
+
+ return nl_cache_parse(cache->c_ops, NULL, nlmsg_hdr(msg), &p);
+}
+
+/**
+ * (Re)fill a cache with the contents in the kernel.
+ * @arg handle netlink handle
+ * @arg cache cache to update
+ *
+ * Clears the specified cache and fills it with the current state in
+ * the kernel.
+ *
+ * @return 0 or a negative error code.
+ */
+int nl_cache_refill(struct nl_handle *handle, struct nl_cache *cache)
+{
+ int err;
+
+ err = nl_cache_request_full_dump(handle, cache);
+ if (err < 0)
+ return err;
+
+ NL_DBG(2, "Upading cache %p <%s>, request sent, waiting for dump...\n",
+ cache, nl_cache_name(cache));
+ nl_cache_clear(cache);
+
+ return nl_cache_pickup(handle, cache);
+}
+
+/** @} */
+
+/**
+ * @name Utillities
+ * @{
+ */
+
+/**
+ * Mark all objects in a cache
+ * @arg cache Cache to mark all objects in
+ */
+void nl_cache_mark_all(struct nl_cache *cache)
+{
+ struct nl_object *obj;
+
+ NL_DBG(2, "Marking all objects in cache %p <%s>...\n",
+ cache, nl_cache_name(cache));
+
+ nl_list_for_each_entry(obj, &cache->c_items, ce_list)
+ nl_object_mark(obj);
+}
+
+/** @} */
+
+/**
+ * @name Dumping
+ * @{
+ */
+
+/**
+ * Dump all elements of a cache.
+ * @arg cache cache to dump
+ * @arg params dumping parameters
+ *
+ * Dumps all elements of the \a cache to the file descriptor \a fd.
+ */
+void nl_cache_dump(struct nl_cache *cache, struct nl_dump_params *params)
+{
+ nl_cache_dump_filter(cache, params, NULL);
+}
+
+/**
+ * Dump all elements of a cache (filtered).
+ * @arg cache cache to dump
+ * @arg params dumping parameters (optional)
+ * @arg filter filter object
+ *
+ * Dumps all elements of the \a cache to the file descriptor \a fd
+ * given they match the given filter \a filter.
+ */
+void nl_cache_dump_filter(struct nl_cache *cache,
+ struct nl_dump_params *params,
+ struct nl_object *filter)
+{
+ int type = params ? params->dp_type : NL_DUMP_FULL;
+ struct nl_object_ops *ops;
+ struct nl_object *obj;
+
+ NL_DBG(2, "Dumping cache %p <%s> filter %p\n",
+ cache, nl_cache_name(cache), filter);
+
+ if (type > NL_DUMP_MAX || type < 0)
+ BUG();
+
+ if (cache->c_ops == NULL)
+ BUG();
+
+ ops = cache->c_ops->co_obj_ops;
+ if (!ops->oo_dump[type])
+ return;
+
+ nl_list_for_each_entry(obj, &cache->c_items, ce_list) {
+ if (filter && !nl_object_match_filter(obj, filter))
+ continue;
+
+ NL_DBG(4, "Dumping object %p...\n", obj);
+ dump_from_ops(obj, params);
+ }
+}
+
+/** @} */
+
+/**
+ * @name Iterators
+ * @{
+ */
+
+/**
+ * Call a callback on each element of the cache.
+ * @arg cache cache to iterate on
+ * @arg cb callback function
+ * @arg arg argument passed to callback function
+ *
+ * Calls a callback function \a cb on each element of the \a cache.
+ * The argument \a arg is passed on the callback function.
+ */
+void nl_cache_foreach(struct nl_cache *cache,
+ void (*cb)(struct nl_object *, void *), void *arg)
+{
+ nl_cache_foreach_filter(cache, NULL, cb, arg);
+}
+
+/**
+ * Call a callback on each element of the cache (filtered).
+ * @arg cache cache to iterate on
+ * @arg filter filter object
+ * @arg cb callback function
+ * @arg arg argument passed to callback function
+ *
+ * Calls a callback function \a cb on each element of the \a cache
+ * that matches the \a filter. The argument \a arg is passed on
+ * to the callback function.
+ */
+void nl_cache_foreach_filter(struct nl_cache *cache, struct nl_object *filter,
+ void (*cb)(struct nl_object *, void *), void *arg)
+{
+ struct nl_object *obj, *tmp;
+ struct nl_object_ops *ops;
+
+ if (cache->c_ops == NULL)
+ BUG();
+
+ ops = cache->c_ops->co_obj_ops;
+
+ nl_list_for_each_entry_safe(obj, tmp, &cache->c_items, ce_list) {
+ if (filter && !nl_object_match_filter(obj, filter))
+ continue;
+
+ cb(obj, arg);
+ }
+}
+
+/** @} */
+
+/** @} */
diff --git a/lib/cache_mngr.c b/lib/cache_mngr.c
new file mode 100644
index 0000000..4e6b1a6
--- /dev/null
+++ b/lib/cache_mngr.c
@@ -0,0 +1,392 @@
+/*
+ * lib/cache_mngr.c Cache Manager
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2007 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup cache_mngt
+ * @defgroup cache_mngr Manager
+ * @brief Helps keeping caches up to date.
+ *
+ * The purpose of a cache manager is to keep track of caches and
+ * automatically receive event notifications to keep the caches
+ * up to date with the kernel state. Each manager has exactly one
+ * netlink socket assigned which limits the scope of each manager
+ * to exactly one netlink family. Therefore all caches committed
+ * to a manager must be part of the same netlink family. Due to the
+ * nature of a manager, it is not possible to have a cache maintain
+ * two instances of the same cache type. The socket is subscribed
+ * to the event notification group of each cache and also put into
+ * non-blocking mode. Functions exist to poll() on the socket to
+ * wait for new events to be received.
+ *
+ * @code
+ * App libnl Kernel
+ * | |
+ * +-----------------+ [ notification, link change ]
+ * | | Cache Manager | | [ (IFF_UP | IFF_RUNNING) ]
+ * | | |
+ * | | +------------+| | | [ notification, new addr ]
+ * <-------|---| route/link |<-------(async)--+ [ 10.0.1.1/32 dev eth1 ]
+ * | | +------------+| | |
+ * | +------------+| |
+ * <---|---|---| route/addr |<------|-(async)--------------+
+ * | +------------+|
+ * | | +------------+| |
+ * <-------|---| ... ||
+ * | | +------------+| |
+ * +-----------------+
+ * | |
+ * @endcode
+ *
+ * @par 1) Creating a new cache manager
+ * @code
+ * struct nl_cache_mngr *mngr;
+ *
+ * // Allocate a new cache manager for RTNETLINK and automatically
+ * // provide the caches added to the manager.
+ * mngr = nl_cache_mngr_alloc(NETLINK_ROUTE, NL_AUTO_PROVIDE);
+ * @endcode
+ *
+ * @par 2) Keep track of a cache
+ * @code
+ * struct nl_cache *cache;
+ *
+ * // Create a new cache for links/interfaces and ask the manager to
+ * // keep it up to date for us. This will trigger a full dump request
+ * // to initially fill the cache.
+ * cache = nl_cache_mngr_add(mngr, "route/link");
+ * @endcode
+ *
+ * @par 3) Make the manager receive updates
+ * @code
+ * // Give the manager the ability to receive updates, will call poll()
+ * // with a timeout of 5 seconds.
+ * if (nl_cache_mngr_poll(mngr, 5000) > 0) {
+ * // Manager received at least one update, dump cache?
+ * nl_cache_dump(cache, ...);
+ * }
+ * @endcode
+ *
+ * @par 4) Release cache manager
+ * @code
+ * nl_cache_mngr_free(mngr);
+ * @endcode
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/cache.h>
+#include <netlink/utils.h>
+
+static int include_cb(struct nl_object *obj, struct nl_parser_param *p)
+{
+ struct nl_cache_assoc *ca = p->pp_arg;
+ int err;
+
+ NL_DBG(2, "Including object %p into cache %p\n", obj, ca->ca_cache);
+#ifdef NL_DEBUG
+ if (nl_debug >= 4)
+ nl_object_dump(obj, &nl_debug_dp);
+#endif
+ err = nl_cache_include(ca->ca_cache, obj, ca->ca_change);
+
+ nl_object_put(obj);
+
+ return err;
+}
+
+static int event_input(struct nl_msg *msg, void *arg)
+{
+ struct nl_cache_mngr *mngr = arg;
+ int protocol = nlmsg_get_proto(msg);
+ int type = nlmsg_hdr(msg)->nlmsg_type;
+ struct nl_cache_ops *ops;
+ int i, n;
+ struct nl_parser_param p = {
+ .pp_cb = include_cb,
+ };
+
+ NL_DBG(2, "Cache manager %p, handling new message %p as event\n",
+ mngr, msg);
+#ifdef NL_DEBUG
+ if (nl_debug >= 4)
+ nl_msg_dump(msg, stderr);
+#endif
+
+ if (mngr->cm_protocol != protocol)
+ BUG();
+
+ for (i = 0; i < mngr->cm_nassocs; i++) {
+ if (mngr->cm_assocs[i].ca_cache) {
+ ops = mngr->cm_assocs[i].ca_cache->c_ops;
+ for (n = 0; ops->co_msgtypes[n].mt_id >= 0; n++)
+ if (ops->co_msgtypes[n].mt_id == type)
+ goto found;
+ }
+ }
+
+ return NL_SKIP;
+
+found:
+ NL_DBG(2, "Associated message %p to cache %p\n",
+ msg, mngr->cm_assocs[i].ca_cache);
+ p.pp_arg = &mngr->cm_assocs[i];
+
+ return nl_cache_parse(ops, NULL, nlmsg_hdr(msg), &p);
+}
+
+/**
+ * Allocate new cache manager
+ * @arg protocol Netlink Protocol this manager is used for
+ * @arg flags Flags
+ *
+ * @return Newly allocated cache manager or NULL on failure.
+ */
+struct nl_cache_mngr *nl_cache_mngr_alloc(struct nl_handle *handle,
+ int protocol, int flags)
+{
+ struct nl_cache_mngr *mngr;
+
+ if (handle == NULL)
+ BUG();
+
+ mngr = calloc(1, sizeof(*mngr));
+ if (!mngr)
+ goto enomem;
+
+ mngr->cm_handle = handle;
+ mngr->cm_nassocs = 32;
+ mngr->cm_protocol = protocol;
+ mngr->cm_flags = flags;
+ mngr->cm_assocs = calloc(mngr->cm_nassocs,
+ sizeof(struct nl_cache_assoc));
+ if (!mngr->cm_assocs)
+ goto enomem;
+
+
+ nl_socket_modify_cb(mngr->cm_handle, NL_CB_VALID, NL_CB_CUSTOM,
+ event_input, mngr);
+
+ /* Required to receive async event notifications */
+ nl_disable_sequence_check(mngr->cm_handle);
+
+ if (nl_connect(mngr->cm_handle, protocol) < 0)
+ goto errout;
+
+ if (nl_socket_set_nonblocking(mngr->cm_handle) < 0)
+ goto errout;
+
+ NL_DBG(1, "Allocated cache manager %p, protocol %d, %d caches\n",
+ mngr, protocol, mngr->cm_nassocs);
+
+ return mngr;
+
+enomem:
+ nl_errno(ENOMEM);
+errout:
+ nl_cache_mngr_free(mngr);
+ return NULL;
+}
+
+/**
+ * Add cache responsibility to cache manager
+ * @arg mngr Cache manager.
+ * @arg name Name of cache to keep track of
+ *
+ * Allocates a new cache of the specified type and adds it to the manager.
+ * The operation will trigger a full dump request from the kernel to
+ * initially fill the contents of the cache. The manager will subscribe
+ * to the notification group of the cache to keep track of any further
+ * changes.
+ *
+ * @return The newly allocated cache or NULL on failure.
+ */
+struct nl_cache *nl_cache_mngr_add(struct nl_cache_mngr *mngr, const char *name,
+ change_func_t cb)
+{
+ struct nl_cache_ops *ops;
+ struct nl_cache *cache;
+ struct nl_af_group *grp;
+ int err, i;
+
+ ops = nl_cache_ops_lookup(name);
+ if (!ops) {
+ nl_error(ENOENT, "Unknown cache type");
+ return NULL;
+ }
+
+ if (ops->co_protocol != mngr->cm_protocol) {
+ nl_error(EINVAL, "Netlink protocol mismatch");
+ return NULL;
+ }
+
+ if (ops->co_groups == NULL) {
+ nl_error(EOPNOTSUPP, NULL);
+ return NULL;
+ }
+
+ for (i = 0; i < mngr->cm_nassocs; i++) {
+ if (mngr->cm_assocs[i].ca_cache &&
+ mngr->cm_assocs[i].ca_cache->c_ops == ops) {
+ nl_error(EEXIST, "Cache of this type already managed");
+ return NULL;
+ }
+ }
+
+retry:
+ for (i = 0; i < mngr->cm_nassocs; i++)
+ if (!mngr->cm_assocs[i].ca_cache)
+ break;
+
+ if (i >= mngr->cm_nassocs) {
+ mngr->cm_nassocs += 16;
+ mngr->cm_assocs = realloc(mngr->cm_assocs,
+ mngr->cm_nassocs *
+ sizeof(struct nl_cache_assoc));
+ if (mngr->cm_assocs == NULL) {
+ nl_errno(ENOMEM);
+ return NULL;
+ } else {
+ NL_DBG(1, "Increased capacity of cache manager %p " \
+ "to %d\n", mngr, mngr->cm_nassocs);
+ goto retry;
+ }
+ }
+
+ cache = nl_cache_alloc(ops);
+ if (!cache) {
+ nl_errno(ENOMEM);
+ return NULL;
+ }
+
+ for (grp = ops->co_groups; grp->ag_group; grp++) {
+ err = nl_socket_add_membership(mngr->cm_handle, grp->ag_group);
+ if (err < 0)
+ goto errout_free_cache;
+ }
+
+ err = nl_cache_refill(mngr->cm_handle, cache);
+ if (err < 0)
+ goto errout_drop_membership;
+
+ mngr->cm_assocs[i].ca_cache = cache;
+ mngr->cm_assocs[i].ca_change = cb;
+
+ if (mngr->cm_flags & NL_AUTO_PROVIDE)
+ nl_cache_mngt_provide(cache);
+
+ NL_DBG(1, "Added cache %p <%s> to cache manager %p\n",
+ cache, nl_cache_name(cache), mngr);
+
+ return cache;
+
+errout_drop_membership:
+ for (grp = ops->co_groups; grp->ag_group; grp++)
+ nl_socket_drop_membership(mngr->cm_handle, grp->ag_group);
+errout_free_cache:
+ nl_cache_free(cache);
+
+ return NULL;
+}
+
+/**
+ * Get file descriptor
+ * @arg mngr Cache Manager
+ *
+ * Get the file descriptor of the socket associated to the manager.
+ * This can be used to change socket options or monitor activity
+ * using poll()/select().
+ */
+int nl_cache_mngr_get_fd(struct nl_cache_mngr *mngr)
+{
+ return nl_socket_get_fd(mngr->cm_handle);
+}
+
+/**
+ * Check for event notifications
+ * @arg mngr Cache Manager
+ * @arg timeout Upper limit poll() will block, in milliseconds.
+ *
+ * Causes poll() to be called to check for new event notifications
+ * being available. Automatically receives and handles available
+ * notifications.
+ *
+ * This functionally is ideally called regularly during an idle
+ * period.
+ *
+ * @return A positive value if at least one update was handled, 0
+ * for none, or a negative error code.
+ */
+int nl_cache_mngr_poll(struct nl_cache_mngr *mngr, int timeout)
+{
+ int ret;
+ struct pollfd fds = {
+ .fd = nl_socket_get_fd(mngr->cm_handle),
+ .events = POLLIN,
+ };
+
+ NL_DBG(3, "Cache manager %p, poll() fd %d\n", mngr, fds.fd);
+ ret = poll(&fds, 1, timeout);
+ NL_DBG(3, "Cache manager %p, poll() returned %d\n", mngr, ret);
+ if (ret < 0)
+ return nl_errno(errno);
+
+ if (ret == 0)
+ return 0;
+
+ return nl_cache_mngr_data_ready(mngr);
+}
+
+/**
+ * Receive available event notifications
+ * @arg mngr Cache manager
+ *
+ * This function can be called if the socket associated to the manager
+ * contains updates to be received. This function should not be used
+ * if nl_cache_mngr_poll() is used.
+ *
+ * @return A positive value if at least one update was handled, 0
+ * for none, or a negative error code.
+ */
+int nl_cache_mngr_data_ready(struct nl_cache_mngr *mngr)
+{
+ int err;
+
+ err = nl_recvmsgs_default(mngr->cm_handle);
+ if (err < 0)
+ return err;
+
+ return 1;
+}
+
+/**
+ * Free cache manager
+ * @arg mngr Cache manager
+ *
+ * Release all resources after usage of a cache manager.
+ */
+void nl_cache_mngr_free(struct nl_cache_mngr *mngr)
+{
+ if (!mngr)
+ return;
+
+ if (mngr->cm_handle) {
+ nl_close(mngr->cm_handle);
+ nl_handle_destroy(mngr->cm_handle);
+ }
+
+ free(mngr->cm_assocs);
+ free(mngr);
+
+ NL_DBG(1, "Cache manager %p freed\n", mngr);
+}
+
+/** @} */
diff --git a/lib/cache_mngt.c b/lib/cache_mngt.c
new file mode 100644
index 0000000..7cf1a03
--- /dev/null
+++ b/lib/cache_mngt.c
@@ -0,0 +1,266 @@
+/*
+ * lib/cache_mngt.c Cache Management
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @defgroup cache_mngt Caching
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/cache.h>
+#include <netlink/utils.h>
+
+static struct nl_cache_ops *cache_ops;
+
+/**
+ * Associate a message type to a set of cache operations
+ * @arg protocol netlink protocol
+ * @arg message_type netlink message type
+ *
+ * Associates the specified netlink message type with
+ * a registered set of cache operations.
+ *
+ * @return The cache operations or NULL if no association
+ * could be made.
+ */
+struct nl_cache_ops *nl_cache_mngt_associate(int protocol, int message_type)
+{
+ int i;
+ struct nl_cache_ops *ops;
+
+ for (ops = cache_ops; ops; ops = ops->co_next)
+ for (i = 0; ops->co_msgtypes[i].mt_id >= 0; i++)
+ if (ops->co_msgtypes[i].mt_id == message_type &&
+ ops->co_protocol == protocol)
+ return ops;
+
+ return NULL;
+}
+
+/**
+ * Convert message type to character string.
+ * @arg ops Cache operations.
+ * @arg protocol Netlink Protocol.
+ * @arg msgtype Message type.
+ * @arg buf Destination buffer.
+ * @arg len Size of destination buffer.
+ *
+ * Converts a message type to a character string and stores it in the
+ * provided buffer.
+ *
+ * @return The destination buffer or the message type encoded in
+ * hexidecimal form if no match was found.
+ */
+char *nl_cache_mngt_type2name(struct nl_cache_ops *ops, int protocol,
+ int msgtype, char *buf, size_t len)
+{
+ int i;
+
+ for (i = 0; ops->co_msgtypes[i].mt_id >= 0; i++) {
+ if (ops->co_msgtypes[i].mt_id == msgtype &&
+ ops->co_protocol == protocol) {
+ snprintf(buf, len, "%s::%s",
+ ops->co_name,
+ ops->co_msgtypes[i].mt_name);
+ return buf;
+ }
+ }
+
+ snprintf(buf, len, "%d:%s->0x%x()", protocol, ops->co_name, msgtype);
+ return buf;
+}
+
+/**
+ * @name Cache Type Management
+ * @{
+ */
+
+/**
+ * Lookup the set cache operations of a certain cache type
+ * @arg name name of the cache type
+ *
+ * @return The cache operations or NULL if no operations
+ * have been registered under the specified name.
+ */
+struct nl_cache_ops *nl_cache_ops_lookup(const char *name)
+{
+ struct nl_cache_ops *ops;
+
+ for (ops = cache_ops; ops; ops = ops->co_next)
+ if (!strcmp(ops->co_name, name))
+ return ops;
+
+ return NULL;
+}
+
+/**
+ * Lookupt the set of cache operations responsible for a type of object
+ * @arg obj_ops Object operations
+ *
+ * @return The cache operations or NULL if not found.
+ */
+struct nl_cache_ops *nl_cache_ops_lookup_for_obj(struct nl_object_ops *obj_ops)
+{
+ struct nl_cache_ops *ops;
+
+ for (ops = cache_ops; ops; ops = ops->co_next)
+ if (ops->co_obj_ops == obj_ops)
+ return ops;
+
+ return NULL;
+
+}
+
+/**
+ * Call a function for each registered cache operation
+ * @arg cb Callback function to be called
+ * @arg arg User specific argument.
+ */
+void nl_cache_mngt_foreach(void (*cb)(struct nl_cache_ops *, void *), void *arg)
+{
+ struct nl_cache_ops *ops;
+
+ for (ops = cache_ops; ops; ops = ops->co_next)
+ cb(ops, arg);
+}
+
+/**
+ * Register a set of cache operations
+ * @arg ops cache operations
+ *
+ * Called by users of caches to announce the avaibility of
+ * a certain cache type.
+ *
+ * @return 0 on success or a negative error code.
+ */
+int nl_cache_mngt_register(struct nl_cache_ops *ops)
+{
+ if (!ops->co_name)
+ return nl_error(EINVAL, "No cache name specified");
+
+ if (!ops->co_obj_ops)
+ return nl_error(EINVAL, "No obj cache ops specified");
+
+ if (nl_cache_ops_lookup(ops->co_name))
+ return nl_error(EEXIST, "Cache operations already exist");
+
+ ops->co_next = cache_ops;
+ cache_ops = ops;
+
+ NL_DBG(1, "Registered cache operations %s\n", ops->co_name);
+
+ return 0;
+}
+
+/**
+ * Unregister a set of cache operations
+ * @arg ops cache operations
+ *
+ * Called by users of caches to announce a set of
+ * cache operations is no longer available. The
+ * specified cache operations must have been registered
+ * previously using nl_cache_mngt_register()
+ *
+ * @return 0 on success or a negative error code
+ */
+int nl_cache_mngt_unregister(struct nl_cache_ops *ops)
+{
+ struct nl_cache_ops *t, **tp;
+
+ for (tp = &cache_ops; (t=*tp) != NULL; tp = &t->co_next)
+ if (t == ops)
+ break;
+
+ if (!t)
+ return nl_error(ENOENT, "No such cache operations");
+
+ NL_DBG(1, "Unregistered cache operations %s\n", ops->co_name);
+
+ *tp = t->co_next;
+ return 0;
+}
+
+/** @} */
+
+/**
+ * @name Global Cache Provisioning/Requiring
+ * @{
+ */
+
+/**
+ * Provide a cache for global use
+ * @arg cache cache to provide
+ *
+ * Offers the specified cache to be used by other modules.
+ * Only one cache per type may be shared at a time,
+ * a previsouly provided caches will be overwritten.
+ */
+void nl_cache_mngt_provide(struct nl_cache *cache)
+{
+ struct nl_cache_ops *ops;
+
+ ops = nl_cache_ops_lookup_for_obj(cache->c_ops->co_obj_ops);
+ if (!ops)
+ BUG();
+ else
+ ops->co_major_cache = cache;
+}
+
+/**
+ * Unprovide a cache for global use
+ * @arg cache cache to unprovide
+ *
+ * Cancels the offer to use a cache globally. The
+ * cache will no longer be returned via lookups but
+ * may still be in use.
+ */
+void nl_cache_mngt_unprovide(struct nl_cache *cache)
+{
+ struct nl_cache_ops *ops;
+
+ ops = nl_cache_ops_lookup_for_obj(cache->c_ops->co_obj_ops);
+ if (!ops)
+ BUG();
+ else if (ops->co_major_cache == cache)
+ ops->co_major_cache = NULL;
+}
+
+/**
+ * Demand the use of a global cache
+ * @arg name name of the required object type
+ *
+ * Trys to find a cache of the specified type for global
+ * use.
+ *
+ * @return A cache provided by another subsystem of the
+ * specified type marked to be available.
+ */
+struct nl_cache *nl_cache_mngt_require(const char *name)
+{
+ struct nl_cache_ops *ops;
+
+ ops = nl_cache_ops_lookup(name);
+ if (!ops || !ops->co_major_cache) {
+ fprintf(stderr, "Application BUG: Your application must "
+ "call nl_cache_mngt_provide() and\nprovide a valid "
+ "%s cache to be used for internal lookups.\nSee the "
+ " API documentation for more details.\n", name);
+
+ return NULL;
+ }
+
+ return ops->co_major_cache;
+}
+
+/** @} */
+
+/** @} */
diff --git a/lib/data.c b/lib/data.c
new file mode 100644
index 0000000..9399389
--- /dev/null
+++ b/lib/data.c
@@ -0,0 +1,172 @@
+/*
+ * lib/data.c Abstract Data
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup utils
+ * @defgroup data Abstract Data
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <linux/socket.h>
+
+/**
+ * @name General
+ * @{
+ */
+
+/**
+ * Allocate a new abstract data object.
+ * @arg buf Data buffer containing the actual data.
+ * @arg size Size of data buffer.
+ *
+ * Allocates a new abstract data and copies the specified data
+ * buffer into the new handle.
+ *
+ * @return Newly allocated data handle or NULL
+ */
+struct nl_data *nl_data_alloc(void *buf, size_t size)
+{
+ struct nl_data *data;
+
+ data = calloc(1, sizeof(*data));
+ if (!data)
+ goto errout;
+
+ data->d_data = calloc(1, size);
+ if (!data->d_data) {
+ free(data);
+ goto errout;
+ }
+
+ data->d_size = size;
+
+ if (buf)
+ memcpy(data->d_data, buf, size);
+
+ return data;
+errout:
+ nl_errno(ENOMEM);
+ return NULL;
+}
+
+/**
+ * Clone an abstract data object.
+ * @arg src Abstract data object
+ *
+ * @return Cloned object or NULL
+ */
+struct nl_data *nl_data_clone(struct nl_data *src)
+{
+ return nl_data_alloc(src->d_data, src->d_size);
+}
+
+/**
+ * Append data to an abstract data object.
+ * @arg data Abstract data object.
+ * @arg buf Data buffer containing the data to be appended.
+ * @arg size Size of data to be apppended.
+ *
+ * Reallocates an abstract data and copies the specified data
+ * buffer into the new handle.
+ *
+ * @return 0 on success or a negative error code
+ */
+int nl_data_append(struct nl_data *data, void *buf, size_t size)
+{
+ if (size < 0)
+ BUG();
+
+ if (size > 0) {
+ data->d_data = realloc(data->d_data, data->d_size + size);
+ if (!data->d_data)
+ return nl_errno(ENOMEM);
+
+ if (buf)
+ memcpy(data->d_data + data->d_size, buf, size);
+ else
+ memset(data->d_data + data->d_size, 0, size);
+
+ data->d_size += size;
+ }
+
+ return 0;
+}
+
+/**
+ * Free an abstract data object.
+ * @arg data Abstract data object.
+ */
+void nl_data_free(struct nl_data *data)
+{
+ if (data)
+ free(data->d_data);
+
+ free(data);
+}
+
+/** @} */
+
+/**
+ * @name Attribute Access
+ * @{
+ */
+
+/**
+ * Get data buffer of abstract data object.
+ * @arg data Abstract data object.
+ * @return Data buffer or NULL if empty.
+ */
+void *nl_data_get(struct nl_data *data)
+{
+ return data->d_size > 0 ? data->d_data : NULL;
+}
+
+/**
+ * Get size of data buffer of abstract data object.
+ * @arg data Abstract data object.
+ * @return Size of data buffer.
+ */
+size_t nl_data_get_size(struct nl_data *data)
+{
+ return data->d_size;
+}
+
+/** @} */
+
+/**
+ * @name Misc
+ * @{
+ */
+
+/**
+ * Compare two abstract data objects.
+ * @arg a Abstract data object.
+ * @arg b Another abstract data object.
+ * @return An integer less than, equal to, or greater than zero if
+ * a is found, respectively, to be less than, to match, or
+ * be greater than b.
+ */
+int nl_data_cmp(struct nl_data *a, struct nl_data *b)
+{
+ void *a_ = nl_data_get(a);
+ void *b_ = nl_data_get(b);
+
+ if (a_ && b_)
+ return memcmp(a_, b_, nl_data_get_size(a));
+ else
+ return -1;
+}
+
+/** @} */
+/** @} */
diff --git a/lib/defs.h b/lib/defs.h
new file mode 100644
index 0000000..f079bdf
--- /dev/null
+++ b/lib/defs.h
@@ -0,0 +1,29 @@
+/* lib/defs.h. Generated by configure. */
+/* lib/defs.h.in. Generated from configure.in by autoheader. */
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "tgraf@suug.ch"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "libnl"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "libnl 1.0-pre6"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "libnl"
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "1.0-pre6"
+
+/* verbose errors */
+/* #undef VERBOSE_ERRORS */
+
+/* Define to empty if `const' does not conform to ANSI C. */
+/* #undef const */
+
+/* Define to `__inline__' or `__inline' if that's what the C compiler
+ calls it, or to nothing if 'inline' is not supported under any name. */
+#ifndef __cplusplus
+/* #undef inline */
+#endif
diff --git a/lib/defs.h.in b/lib/defs.h.in
new file mode 100644
index 0000000..ef86caa
--- /dev/null
+++ b/lib/defs.h.in
@@ -0,0 +1,28 @@
+/* lib/defs.h.in. Generated from configure.in by autoheader. */
+
+/* Define to the address where bug reports for this package should be sent. */
+#undef PACKAGE_BUGREPORT
+
+/* Define to the full name of this package. */
+#undef PACKAGE_NAME
+
+/* Define to the full name and version of this package. */
+#undef PACKAGE_STRING
+
+/* Define to the one symbol short name of this package. */
+#undef PACKAGE_TARNAME
+
+/* Define to the version of this package. */
+#undef PACKAGE_VERSION
+
+/* verbose errors */
+#undef VERBOSE_ERRORS
+
+/* Define to empty if `const' does not conform to ANSI C. */
+#undef const
+
+/* Define to `__inline__' or `__inline' if that's what the C compiler
+ calls it, or to nothing if 'inline' is not supported under any name. */
+#ifndef __cplusplus
+#undef inline
+#endif
diff --git a/lib/doc.c b/lib/doc.c
new file mode 100644
index 0000000..8fee8c8
--- /dev/null
+++ b/lib/doc.c
@@ -0,0 +1,106 @@
+/*
+ * lib/doc.c Documentation Purpose
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @mainpage
+ *
+ * @section remarks Remarks
+ *
+ * @subsection cache_alloc Allocation of Caches
+ *
+ * Almost all subsystem provide a function to allocate a new cache
+ * of some form. The function usually looks like this:
+ * @code
+ * struct nl_cache *<object name>_alloc_cache(struct nl_handle *handle)
+ * @endcode
+ *
+ * These functions allocate a new cache for the own object type,
+ * initializes it properly and updates it to represent the current
+ * state of their master, e.g. a link cache would include all
+ * links currently configured in the kernel.
+ *
+ * Some of the allocation functions may take additional arguments
+ * to further specify what will be part of the cache.
+ *
+ * All such functions return a newly allocated cache or NULL
+ * in case of an error.
+ *
+ * @subsection addr Setting of Addresses
+ * @code
+ * int <object name>_set_addr(struct nl_object *, struct nl_addr *)
+ * @endcode
+ *
+ * All attribute functions avaiable for assigning addresses to objects
+ * take a struct nl_addr argument. The provided address object is
+ * validated against the address family of the object if known already.
+ * The assignment fails if the address families mismatch. In case the
+ * address family has not been specified yet, the address family of
+ * the new address is elected to be the new requirement.
+ *
+ * The function will acquire a new reference on the address object
+ * before assignment, the caller is NOT responsible for this.
+ *
+ * All functions return 0 on success or a negative error code.
+ *
+ * @subsection flags Flags to Character StringTranslations
+ * All functions converting a set of flags to a character string follow
+ * the same principles, therefore, the following information applies
+ * to all functions convertings flags to a character string and vice versa.
+ *
+ * @subsubsection flags2str Flags to Character String
+ * @code
+ * char *<object name>_flags2str(int flags, char *buf, size_t len)
+ * @endcode
+ * @arg flags Flags.
+ * @arg buf Destination buffer.
+ * @arg len Buffer length.
+ *
+ * Converts the specified flags to a character string separated by
+ * commas and stores it in the specified destination buffer.
+ *
+ * @return The destination buffer
+ *
+ * @subsubsection str2flags Character String to Flags
+ * @code
+ * int <object name>_str2flags(const char *name)
+ * @endcode
+ * @arg name Name of flag.
+ *
+ * Converts the provided character string specifying a flag
+ * to the corresponding numeric value.
+ *
+ * @return Link flag or a negative value if none was found.
+ *
+ * @subsubsection type2str Type to Character String
+ * @code
+ * char *<object name>_<type>2str(int type, char *buf, size_t len)
+ * @endcode
+ * @arg type Type as numeric value
+ * @arg buf Destination buffer.
+ * @arg len Buffer length.
+ *
+ * Converts an identifier (type) to a character string and stores
+ * it in the specified destination buffer.
+ *
+ * @return The destination buffer or the type encoded in hexidecimal
+ * form if the identifier is unknown.
+ *
+ * @subsubsection str2type Character String to Type
+ * @code
+ * int <object name>_str2<type>(const char *name)
+ * @endcode
+ * @arg name Name of identifier (type).
+ *
+ * Converts the provided character string specifying a identifier
+ * to the corresponding numeric value.
+ *
+ * @return Identifier as numeric value or a negative value if none was found.
+ */
diff --git a/lib/family.c b/lib/family.c
new file mode 100644
index 0000000..ba1d65f
--- /dev/null
+++ b/lib/family.c
@@ -0,0 +1,62 @@
+/*
+ * lib/family.c Netlink Family
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @defgroup nlfam Netlink Families
+ * @brief
+ *
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+
+/**
+ * @name Netlink Family Name Translation
+ * @{
+ */
+
+static struct trans_tbl nlfamilies[] = {
+ __ADD(NETLINK_ROUTE,route)
+ __ADD(NETLINK_USERSOCK,usersock)
+ __ADD(NETLINK_FIREWALL,firewall)
+ __ADD(NETLINK_INET_DIAG,inetdiag)
+ __ADD(NETLINK_NFLOG,nflog)
+ __ADD(NETLINK_XFRM,xfrm)
+ __ADD(NETLINK_SELINUX,selinux)
+ __ADD(NETLINK_ISCSI,iscsi)
+ __ADD(NETLINK_AUDIT,audit)
+ __ADD(NETLINK_FIB_LOOKUP,fib_lookup)
+ __ADD(NETLINK_CONNECTOR,connector)
+ __ADD(NETLINK_NETFILTER,netfilter)
+ __ADD(NETLINK_IP6_FW,ip6_fw)
+ __ADD(NETLINK_DNRTMSG,dnrtmsg)
+ __ADD(NETLINK_KOBJECT_UEVENT,kobject_uevent)
+ __ADD(NETLINK_GENERIC,generic)
+ __ADD(NETLINK_SCSITRANSPORT,scsitransport)
+ __ADD(NETLINK_ECRYPTFS,ecryptfs)
+};
+
+char * nl_nlfamily2str(int family, char *buf, size_t size)
+{
+ return __type2str(family, buf, size, nlfamilies,
+ ARRAY_SIZE(nlfamilies));
+}
+
+int nl_str2nlfamily(const char *name)
+{
+ return __str2type(name, nlfamilies, ARRAY_SIZE(nlfamilies));
+}
+
+/** @} */
+
+/** @} */
diff --git a/lib/fib_lookup/lookup.c b/lib/fib_lookup/lookup.c
new file mode 100644
index 0000000..2b0070d
--- /dev/null
+++ b/lib/fib_lookup/lookup.c
@@ -0,0 +1,353 @@
+/*
+ * lib/fib_lookup/lookup.c FIB Lookup
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup nlfam
+ * @defgroup fib_lookup FIB Lookup
+ * @brief
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/attr.h>
+#include <netlink/utils.h>
+#include <netlink/object.h>
+#include <netlink/route/rtnl.h>
+#include <netlink/route/route.h>
+#include <netlink/fib_lookup/request.h>
+#include <netlink/fib_lookup/lookup.h>
+
+/** @cond SKIP */
+static struct nl_cache_ops fib_lookup_ops;
+static struct nl_object_ops result_obj_ops;
+
+/* not exported so far */
+struct fib_result_nl {
+ uint32_t fl_addr; /* To be looked up*/
+ uint32_t fl_fwmark;
+ unsigned char fl_tos;
+ unsigned char fl_scope;
+ unsigned char tb_id_in;
+
+ unsigned char tb_id; /* Results */
+ unsigned char prefixlen;
+ unsigned char nh_sel;
+ unsigned char type;
+ unsigned char scope;
+ int err;
+};
+/** @endcond */
+
+static void result_free_data(struct nl_object *obj)
+{
+ struct flnl_result *res = nl_object_priv(obj);
+
+ if (res && res->fr_req)
+ nl_object_put(OBJ_CAST(res->fr_req));
+}
+
+static int result_clone(struct nl_object *_dst, struct nl_object *_src)
+{
+ struct flnl_result *dst = nl_object_priv(_dst);
+ struct flnl_result *src = nl_object_priv(_src);
+
+ if (src->fr_req)
+ if (!(dst->fr_req = (struct flnl_request *)
+ nl_object_clone(OBJ_CAST(src->fr_req))))
+ return nl_get_errno();
+
+ return 0;
+}
+
+static int result_msg_parser(struct nl_cache_ops *ops, struct sockaddr_nl *who,
+ struct nlmsghdr *n, void *arg)
+{
+ struct flnl_result *res;
+ struct fib_result_nl *fr;
+ struct nl_parser_param *pp = arg;
+ struct nl_addr *addr;
+ int err = -EINVAL;
+
+ res = flnl_result_alloc();
+ if (!res)
+ goto errout;
+
+ res->ce_msgtype = n->nlmsg_type;
+
+ res->fr_req = flnl_request_alloc();
+ if (!res->fr_req)
+ goto errout;
+
+ fr = nlmsg_data(n);
+ addr = nl_addr_build(AF_INET, &fr->fl_addr, 4);
+ if (!addr)
+ goto errout;
+ err = flnl_request_set_addr(res->fr_req, addr);
+ nl_addr_put(addr);
+ if (err < 0)
+ goto errout;
+
+ flnl_request_set_fwmark(res->fr_req, fr->fl_fwmark);
+ flnl_request_set_tos(res->fr_req, fr->fl_tos);
+ flnl_request_set_scope(res->fr_req, fr->fl_scope);
+ flnl_request_set_table(res->fr_req, fr->tb_id_in);
+
+ res->fr_table_id = fr->tb_id;
+ res->fr_prefixlen = fr->prefixlen;
+ res->fr_nh_sel = fr->nh_sel;
+ res->fr_type = fr->type;
+ res->fr_scope = fr->scope;
+ res->fr_error = fr->err;
+
+ err = pp->pp_cb((struct nl_object *) res, pp);
+ if (err < 0)
+ goto errout;
+
+ /* REAL HACK, fib_lookup doesn't support ACK nor does it
+ * send a DONE message, enforce end of message stream
+ * after just the first message */
+ return NL_STOP;
+
+errout:
+ flnl_result_put(res);
+ return err;
+}
+
+static int result_dump_brief(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct flnl_result *res = (struct flnl_result *) obj;
+ char buf[128];
+ int line = 1;
+
+ dp_dump(p, "table %s prefixlen %u next-hop-selector %u\n",
+ rtnl_route_table2str(res->fr_table_id, buf, sizeof(buf)),
+ res->fr_prefixlen, res->fr_nh_sel);
+ dp_dump_line(p, line++, "type %s ",
+ nl_rtntype2str(res->fr_type, buf, sizeof(buf)));
+ dp_dump(p, "scope %s error %s (%d)\n",
+ rtnl_scope2str(res->fr_scope, buf, sizeof(buf)),
+ strerror(-res->fr_error), res->fr_error);
+
+ return line;
+}
+
+static int result_dump_full(struct nl_object *obj, struct nl_dump_params *p)
+{
+ return result_dump_brief(obj, p);
+}
+
+static int result_compare(struct nl_object *_a, struct nl_object *_b,
+ uint32_t attrs, int flags)
+{
+ return 0;
+}
+
+/**
+ * @name Allocation/Freeing
+ * @{
+ */
+
+struct flnl_result *flnl_result_alloc(void)
+{
+ return (struct flnl_result *) nl_object_alloc(&result_obj_ops);
+}
+
+void flnl_result_put(struct flnl_result *res)
+{
+ nl_object_put((struct nl_object *) res);
+}
+
+/** @} */
+
+/**
+ * @name Cache Management
+ * @{
+ */
+
+/**
+ * Allocate lookup result cache.
+ *
+ * Allocates a new lookup result cache and initializes it properly.
+ *
+ * @note Free the memory after usage using nl_cache_destroy_and_free().
+ * @return Newly allocated cache or NULL if an error occured.
+ */
+struct nl_cache *flnl_result_alloc_cache(void)
+{
+ return nl_cache_alloc(&fib_lookup_ops);
+}
+
+/** @} */
+
+/**
+ * @name Lookup
+ * @{
+ */
+
+/**
+ * Builds a netlink request message to do a lookup
+ * @arg req Requested match.
+ * @arg flags additional netlink message flags
+ *
+ * Builds a new netlink message requesting a change of link attributes.
+ * The netlink message header isn't fully equipped with all relevant
+ * fields and must be sent out via nl_send_auto_complete() or
+ * supplemented as needed.
+ * \a old must point to a link currently configured in the kernel
+ * and \a tmpl must contain the attributes to be changed set via
+ * \c rtnl_link_set_* functions.
+ *
+ * @return New netlink message
+ * @note Not all attributes can be changed, see
+ * \ref link_changeable "Changeable Attributes" for more details.
+ */
+struct nl_msg *flnl_lookup_build_request(struct flnl_request *req, int flags)
+{
+ struct nl_msg *msg;
+ struct nl_addr *addr;
+ uint64_t fwmark;
+ int tos, scope, table;
+ struct fib_result_nl fr = {0};
+
+ fwmark = flnl_request_get_fwmark(req);
+ tos = flnl_request_get_tos(req);
+ scope = flnl_request_get_scope(req);
+ table = flnl_request_get_table(req);
+
+ fr.fl_fwmark = fwmark != UINT_LEAST64_MAX ? fwmark : 0;
+ fr.fl_tos = tos >= 0 ? tos : 0;
+ fr.fl_scope = scope >= 0 ? scope : RT_SCOPE_UNIVERSE;
+ fr.tb_id_in = table >= 0 ? table : RT_TABLE_UNSPEC;
+
+ addr = flnl_request_get_addr(req);
+ if (!addr) {
+ nl_error(EINVAL, "Request must specify the address");
+ return NULL;
+ }
+
+ fr.fl_addr = *(uint32_t *) nl_addr_get_binary_addr(addr);
+
+ msg = nlmsg_alloc_simple(0, flags);
+ if (!msg)
+ goto errout;
+
+ if (nlmsg_append(msg, &fr, sizeof(fr), NLMSG_ALIGNTO) < 0)
+ goto errout;
+
+ return msg;
+
+errout:
+ nlmsg_free(msg);
+ return NULL;
+}
+
+/**
+ * Perform FIB Lookup
+ * @arg handle Netlink handle.
+ * @arg req Lookup request object.
+ * @arg cache Cache for result.
+ *
+ * Builds a netlink message to request a FIB lookup, waits for the
+ * reply and adds the result to the specified cache.
+ *
+ * @return 0 on success or a negative error code.
+ */
+int flnl_lookup(struct nl_handle *handle, struct flnl_request *req,
+ struct nl_cache *cache)
+{
+ struct nl_msg *msg;
+ int err;
+
+ msg = flnl_lookup_build_request(req, 0);
+ if (!msg)
+ return nl_errno(ENOMEM);
+
+ err = nl_send_auto_complete(handle, msg);
+ nlmsg_free(msg);
+ if (err < 0)
+ return err;
+
+ return nl_cache_pickup(handle, cache);
+}
+
+/** @} */
+
+/**
+ * @name Attribute Access
+ * @{
+ */
+
+int flnl_result_get_table_id(struct flnl_result *res)
+{
+ return res->fr_table_id;
+}
+
+int flnl_result_get_prefixlen(struct flnl_result *res)
+{
+ return res->fr_prefixlen;
+}
+
+int flnl_result_get_nexthop_sel(struct flnl_result *res)
+{
+ return res->fr_nh_sel;
+}
+
+int flnl_result_get_type(struct flnl_result *res)
+{
+ return res->fr_type;
+}
+
+int flnl_result_get_scope(struct flnl_result *res)
+{
+ return res->fr_scope;
+}
+
+int flnl_result_get_error(struct flnl_result *res)
+{
+ return res->fr_error;
+}
+
+/** @} */
+
+static struct nl_object_ops result_obj_ops = {
+ .oo_name = "fib_lookup/result",
+ .oo_size = sizeof(struct flnl_result),
+ .oo_free_data = result_free_data,
+ .oo_clone = result_clone,
+ .oo_dump[NL_DUMP_BRIEF] = result_dump_brief,
+ .oo_dump[NL_DUMP_FULL] = result_dump_full,
+ .oo_compare = result_compare,
+};
+
+static struct nl_cache_ops fib_lookup_ops = {
+ .co_name = "fib_lookup/fib_lookup",
+ .co_hdrsize = sizeof(struct fib_result_nl),
+ .co_msgtypes = {
+ { 0, NL_ACT_UNSPEC, "any" },
+ END_OF_MSGTYPES_LIST,
+ },
+ .co_protocol = NETLINK_FIB_LOOKUP,
+ .co_msg_parser = result_msg_parser,
+ .co_obj_ops = &result_obj_ops,
+};
+
+static void __init fib_lookup_init(void)
+{
+ nl_cache_mngt_register(&fib_lookup_ops);
+}
+
+static void __exit fib_lookup_exit(void)
+{
+ nl_cache_mngt_unregister(&fib_lookup_ops);
+}
+
+/** @} */
diff --git a/lib/fib_lookup/request.c b/lib/fib_lookup/request.c
new file mode 100644
index 0000000..8b00224
--- /dev/null
+++ b/lib/fib_lookup/request.c
@@ -0,0 +1,187 @@
+/*
+ * lib/fib_lookup/request.c FIB Lookup Request
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup fib_lookup
+ * @defgroup flreq Request
+ * @brief
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/attr.h>
+#include <netlink/utils.h>
+#include <netlink/object.h>
+#include <netlink/fib_lookup/request.h>
+
+static struct nl_object_ops request_obj_ops;
+
+/** @cond SKIP */
+#define REQUEST_ATTR_ADDR 0x01
+#define REQUEST_ATTR_FWMARK 0x02
+#define REQUEST_ATTR_TOS 0x04
+#define REQUEST_ATTR_SCOPE 0x08
+#define REQUEST_ATTR_TABLE 0x10
+/** @endcond */
+
+static void request_free_data(struct nl_object *obj)
+{
+ struct flnl_request *req = REQUEST_CAST(obj);
+
+ if (req)
+ nl_addr_put(req->lr_addr);
+}
+
+static int request_clone(struct nl_object *_dst, struct nl_object *_src)
+{
+ struct flnl_request *dst = nl_object_priv(_dst);
+ struct flnl_request *src = nl_object_priv(_src);
+
+ if (src->lr_addr)
+ if (!(dst->lr_addr = nl_addr_clone(src->lr_addr)))
+ goto errout;
+
+ return 0;
+errout:
+ return nl_get_errno();
+}
+
+static int request_compare(struct nl_object *_a, struct nl_object *_b,
+ uint32_t attrs, int flags)
+{
+ struct flnl_request *a = (struct flnl_request *) _a;
+ struct flnl_request *b = (struct flnl_request *) _b;
+ int diff = 0;
+
+#define REQ_DIFF(ATTR, EXPR) ATTR_DIFF(attrs, REQUEST_ATTR_##ATTR, a, b, EXPR)
+
+ diff |= REQ_DIFF(FWMARK, a->lr_fwmark != b->lr_fwmark);
+ diff |= REQ_DIFF(TOS, a->lr_tos != b->lr_tos);
+ diff |= REQ_DIFF(SCOPE, a->lr_scope != b->lr_scope);
+ diff |= REQ_DIFF(TABLE, a->lr_table != b->lr_table);
+ diff |= REQ_DIFF(ADDR, nl_addr_cmp(a->lr_addr, b->lr_addr));
+
+#undef REQ_DIFF
+
+ return diff;
+}
+
+
+/**
+ * @name Lookup Request Creation/Deletion
+ * @{
+ */
+
+struct flnl_request *flnl_request_alloc(void)
+{
+ return REQUEST_CAST(nl_object_alloc(&request_obj_ops));
+}
+
+/** @} */
+
+/**
+ * @name Attributes
+ * @{
+ */
+
+void flnl_request_set_fwmark(struct flnl_request *req, uint64_t fwmark)
+{
+ req->lr_fwmark = fwmark;
+ req->ce_mask |= REQUEST_ATTR_FWMARK;
+}
+
+uint64_t flnl_request_get_fwmark(struct flnl_request *req)
+{
+ if (req->ce_mask & REQUEST_ATTR_FWMARK)
+ return req->lr_fwmark;
+ else
+ return UINT_LEAST64_MAX;
+}
+
+void flnl_request_set_tos(struct flnl_request *req, int tos)
+{
+ req->lr_tos = tos;
+ req->ce_mask |= REQUEST_ATTR_TOS;
+}
+
+int flnl_request_get_tos(struct flnl_request *req)
+{
+ if (req->ce_mask & REQUEST_ATTR_TOS)
+ return req->lr_tos;
+ else
+ return -1;
+}
+
+void flnl_request_set_scope(struct flnl_request *req, int scope)
+{
+ req->lr_scope = scope;
+ req->ce_mask |= REQUEST_ATTR_SCOPE;
+}
+
+int flnl_request_get_scope(struct flnl_request *req)
+{
+ if (req->ce_mask & REQUEST_ATTR_SCOPE)
+ return req->lr_scope;
+ else
+ return -1;
+}
+
+void flnl_request_set_table(struct flnl_request *req, int table)
+{
+ req->lr_table = table;
+ req->ce_mask |= REQUEST_ATTR_TABLE;
+}
+
+int flnl_request_get_table(struct flnl_request *req)
+{
+ if (req->ce_mask & REQUEST_ATTR_TABLE)
+ return req->lr_table;
+ else
+ return -1;
+}
+
+int flnl_request_set_addr(struct flnl_request *req, struct nl_addr *addr)
+{
+ if (addr->a_family != AF_INET)
+ return nl_error(EINVAL, "Address must be an IPv4 address");
+
+ if (req->lr_addr)
+ nl_addr_put(req->lr_addr);
+
+ nl_addr_get(addr);
+ req->lr_addr = addr;
+
+ req->ce_mask |= REQUEST_ATTR_ADDR;
+
+ return 0;
+}
+
+struct nl_addr *flnl_request_get_addr(struct flnl_request *req)
+{
+ if (req->ce_mask & REQUEST_ATTR_ADDR)
+ return req->lr_addr;
+ else
+ return NULL;
+}
+
+/** @} */
+
+static struct nl_object_ops request_obj_ops = {
+ .oo_name = "fib_lookup/request",
+ .oo_size = sizeof(struct flnl_request),
+ .oo_free_data = request_free_data,
+ .oo_clone = request_clone,
+ .oo_compare = request_compare,
+ .oo_id_attrs = ~0,
+};
+
+/** @} */
diff --git a/lib/genl/ctrl.c b/lib/genl/ctrl.c
new file mode 100644
index 0000000..b4dc489
--- /dev/null
+++ b/lib/genl/ctrl.c
@@ -0,0 +1,319 @@
+/*
+ * lib/genl/ctrl.c Generic Netlink Controller
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup genl_mngt
+ * @defgroup ctrl Controller
+ * @brief
+ *
+ * @{
+ */
+
+#include <netlink-generic.h>
+#include <netlink/netlink.h>
+#include <netlink/genl/genl.h>
+#include <netlink/genl/family.h>
+#include <netlink/genl/mngt.h>
+#include <netlink/genl/ctrl.h>
+#include <netlink/utils.h>
+
+/** @cond SKIP */
+#define CTRL_VERSION 0x0001
+
+static struct nl_cache_ops genl_ctrl_ops;
+/** @endcond */
+
+static int ctrl_request_update(struct nl_cache *c, struct nl_handle *h)
+{
+ return genl_send_simple(h, GENL_ID_CTRL, CTRL_CMD_GETFAMILY,
+ CTRL_VERSION, NLM_F_DUMP);
+}
+
+static struct nla_policy ctrl_policy[CTRL_ATTR_MAX+1] = {
+ [CTRL_ATTR_FAMILY_ID] = { .type = NLA_U16 },
+ [CTRL_ATTR_FAMILY_NAME] = { .type = NLA_STRING,
+ .maxlen = GENL_NAMSIZ },
+ [CTRL_ATTR_VERSION] = { .type = NLA_U32 },
+ [CTRL_ATTR_HDRSIZE] = { .type = NLA_U32 },
+ [CTRL_ATTR_MAXATTR] = { .type = NLA_U32 },
+ [CTRL_ATTR_OPS] = { .type = NLA_NESTED },
+};
+
+static struct nla_policy family_op_policy[CTRL_ATTR_OP_MAX+1] = {
+ [CTRL_ATTR_OP_ID] = { .type = NLA_U32 },
+ [CTRL_ATTR_OP_FLAGS] = { .type = NLA_U32 },
+};
+
+static int ctrl_msg_parser(struct nl_cache_ops *ops, struct genl_cmd *cmd,
+ struct genl_info *info, void *arg)
+{
+ struct genl_family *family;
+ struct nl_parser_param *pp = arg;
+ int err;
+
+ family = genl_family_alloc();
+ if (family == NULL) {
+ err = nl_errno(ENOMEM);
+ goto errout;
+ }
+
+ if (info->attrs[CTRL_ATTR_FAMILY_NAME] == NULL) {
+ err = nl_error(EINVAL, "Missing family name TLV");
+ goto errout;
+ }
+
+ if (info->attrs[CTRL_ATTR_FAMILY_ID] == NULL) {
+ err = nl_error(EINVAL, "Missing family id TLV");
+ goto errout;
+ }
+
+ family->ce_msgtype = info->nlh->nlmsg_type;
+ genl_family_set_id(family,
+ nla_get_u16(info->attrs[CTRL_ATTR_FAMILY_ID]));
+ genl_family_set_name(family,
+ nla_get_string(info->attrs[CTRL_ATTR_FAMILY_NAME]));
+
+ if (info->attrs[CTRL_ATTR_VERSION]) {
+ uint32_t version = nla_get_u32(info->attrs[CTRL_ATTR_VERSION]);
+ genl_family_set_version(family, version);
+ }
+
+ if (info->attrs[CTRL_ATTR_HDRSIZE]) {
+ uint32_t hdrsize = nla_get_u32(info->attrs[CTRL_ATTR_HDRSIZE]);
+ genl_family_set_hdrsize(family, hdrsize);
+ }
+
+ if (info->attrs[CTRL_ATTR_MAXATTR]) {
+ uint32_t maxattr = nla_get_u32(info->attrs[CTRL_ATTR_MAXATTR]);
+ genl_family_set_maxattr(family, maxattr);
+ }
+
+ if (info->attrs[CTRL_ATTR_OPS]) {
+ struct nlattr *nla, *nla_ops;
+ int remaining;
+
+ nla_ops = info->attrs[CTRL_ATTR_OPS];
+ nla_for_each_nested(nla, nla_ops, remaining) {
+ struct nlattr *tb[CTRL_ATTR_OP_MAX+1];
+ int flags = 0, id;
+
+ err = nla_parse_nested(tb, CTRL_ATTR_OP_MAX, nla,
+ family_op_policy);
+ if (err < 0)
+ goto errout;
+
+ if (tb[CTRL_ATTR_OP_ID] == NULL) {
+ err = nl_errno(EINVAL);
+ goto errout;
+ }
+
+ id = nla_get_u32(tb[CTRL_ATTR_OP_ID]);
+
+ if (tb[CTRL_ATTR_OP_FLAGS])
+ flags = nla_get_u32(tb[CTRL_ATTR_OP_FLAGS]);
+
+ err = genl_family_add_op(family, id, flags);
+ if (err < 0)
+ goto errout;
+
+ }
+ }
+
+ err = pp->pp_cb((struct nl_object *) family, pp);
+ if (err < 0)
+ goto errout;
+
+ return P_ACCEPT;
+
+errout:
+ genl_family_put(family);
+ return err;
+}
+
+/**
+ * @name Cache Management
+ * @{
+ */
+
+struct nl_cache *genl_ctrl_alloc_cache(struct nl_handle *handle)
+{
+ struct nl_cache * cache;
+
+ cache = nl_cache_alloc(&genl_ctrl_ops);
+ if (cache == NULL)
+ return NULL;
+
+ if (handle && nl_cache_refill(handle, cache) < 0) {
+ nl_cache_free(cache);
+ return NULL;
+ }
+
+ return cache;
+}
+
+/**
+ * Look up generic netlink family by id in the provided cache.
+ * @arg cache Generic netlink family cache.
+ * @arg id Family identifier.
+ *
+ * Searches through the cache looking for a registered family
+ * matching the specified identifier. The caller will own a
+ * reference on the returned object which needs to be given
+ * back after usage using genl_family_put().
+ *
+ * @return Generic netlink family object or NULL if no match was found.
+ */
+struct genl_family *genl_ctrl_search(struct nl_cache *cache, int id)
+{
+ struct genl_family *fam;
+
+ if (cache->c_ops != &genl_ctrl_ops)
+ BUG();
+
+ nl_list_for_each_entry(fam, &cache->c_items, ce_list) {
+ if (fam->gf_id == id) {
+ nl_object_get((struct nl_object *) fam);
+ return fam;
+ }
+ }
+
+ return NULL;
+}
+
+/**
+ * @name Resolver
+ * @{
+ */
+
+/**
+ * Look up generic netlink family by family name in the provided cache.
+ * @arg cache Generic netlink family cache.
+ * @arg name Family name.
+ *
+ * Searches through the cache looking for a registered family
+ * matching the specified name. The caller will own a reference
+ * on the returned object which needs to be given back after
+ * usage using genl_family_put().
+ *
+ * @return Generic netlink family object or NULL if no match was found.
+ */
+struct genl_family *genl_ctrl_search_by_name(struct nl_cache *cache,
+ const char *name)
+{
+ struct genl_family *fam;
+
+ if (cache->c_ops != &genl_ctrl_ops)
+ BUG();
+
+ nl_list_for_each_entry(fam, &cache->c_items, ce_list) {
+ if (!strcmp(name, fam->gf_name)) {
+ nl_object_get((struct nl_object *) fam);
+ return fam;
+ }
+ }
+
+ return NULL;
+}
+
+/** @} */
+
+/**
+ * Resolve generic netlink family name to its identifier
+ * @arg handle Netlink Handle
+ * @arg name Name of generic netlink family
+ *
+ * Resolves the generic netlink family name to its identifer and returns
+ * it.
+ *
+ * @return A positive identifier or a negative error code.
+ */
+int genl_ctrl_resolve(struct nl_handle *handle, const char *name)
+{
+ struct nl_cache *cache;
+ struct genl_family *family;
+ int err;
+
+ cache = genl_ctrl_alloc_cache(handle);
+ if (cache == NULL)
+ return nl_get_errno();
+
+ family = genl_ctrl_search_by_name(cache, name);
+ if (family == NULL) {
+ err = nl_error(ENOENT, "Generic Netlink Family not found");
+ goto errout;
+ }
+
+ err = genl_family_get_id(family);
+ genl_family_put(family);
+errout:
+ nl_cache_free(cache);
+
+ return err;
+}
+
+/** @} */
+
+static struct genl_cmd genl_cmds[] = {
+ {
+ .c_id = CTRL_CMD_NEWFAMILY,
+ .c_name = "NEWFAMILY" ,
+ .c_maxattr = CTRL_ATTR_MAX,
+ .c_attr_policy = ctrl_policy,
+ .c_msg_parser = ctrl_msg_parser,
+ },
+ {
+ .c_id = CTRL_CMD_DELFAMILY,
+ .c_name = "DELFAMILY" ,
+ },
+ {
+ .c_id = CTRL_CMD_GETFAMILY,
+ .c_name = "GETFAMILY" ,
+ },
+ {
+ .c_id = CTRL_CMD_NEWOPS,
+ .c_name = "NEWOPS" ,
+ },
+ {
+ .c_id = CTRL_CMD_DELOPS,
+ .c_name = "DELOPS" ,
+ },
+};
+
+static struct genl_ops genl_ops = {
+ .o_cmds = genl_cmds,
+ .o_ncmds = ARRAY_SIZE(genl_cmds),
+};
+
+/** @cond SKIP */
+extern struct nl_object_ops genl_family_ops;
+/** @endcond */
+
+static struct nl_cache_ops genl_ctrl_ops = {
+ .co_name = "genl/family",
+ .co_hdrsize = GENL_HDRSIZE(0),
+ .co_msgtypes = GENL_FAMILY(GENL_ID_CTRL, "nlctrl"),
+ .co_genl = &genl_ops,
+ .co_protocol = NETLINK_GENERIC,
+ .co_request_update = ctrl_request_update,
+ .co_obj_ops = &genl_family_ops,
+};
+
+static void __init ctrl_init(void)
+{
+ genl_register(&genl_ctrl_ops);
+}
+
+static void __exit ctrl_exit(void)
+{
+ genl_unregister(&genl_ctrl_ops);
+}
+
+/** @} */
diff --git a/lib/genl/family.c b/lib/genl/family.c
new file mode 100644
index 0000000..e05b52c
--- /dev/null
+++ b/lib/genl/family.c
@@ -0,0 +1,285 @@
+/*
+ * lib/genl/family.c Generic Netlink Family
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup genl
+ * @defgroup genl_family Generic Netlink Family
+ * @brief
+ *
+ * @{
+ */
+
+#include <netlink-generic.h>
+#include <netlink/netlink.h>
+#include <netlink/genl/genl.h>
+#include <netlink/genl/family.h>
+#include <netlink/utils.h>
+
+/** @cond SKIP */
+#define FAMILY_ATTR_ID 0x01
+#define FAMILY_ATTR_NAME 0x02
+#define FAMILY_ATTR_VERSION 0x04
+#define FAMILY_ATTR_HDRSIZE 0x08
+#define FAMILY_ATTR_MAXATTR 0x10
+#define FAMILY_ATTR_OPS 0x20
+
+struct nl_object_ops genl_family_ops;
+/** @endcond */
+
+static void family_constructor(struct nl_object *c)
+{
+ struct genl_family *family = (struct genl_family *) c;
+
+ nl_init_list_head(&family->gf_ops);
+}
+
+static void family_free_data(struct nl_object *c)
+{
+ struct genl_family *family = (struct genl_family *) c;
+ struct genl_family_op *ops, *tmp;
+
+ if (family == NULL)
+ return;
+
+ nl_list_for_each_entry_safe(ops, tmp, &family->gf_ops, o_list) {
+ nl_list_del(&ops->o_list);
+ free(ops);
+ }
+}
+
+static int family_clone(struct nl_object *_dst, struct nl_object *_src)
+{
+ struct genl_family *dst = nl_object_priv(_dst);
+ struct genl_family *src = nl_object_priv(_src);
+ struct genl_family_op *ops;
+ int err;
+
+ nl_list_for_each_entry(ops, &src->gf_ops, o_list) {
+ err = genl_family_add_op(dst, ops->o_id, ops->o_flags);
+ if (err < 0)
+ return err;
+ }
+
+ return 0;
+}
+
+static int family_dump_brief(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct genl_family *family = (struct genl_family *) obj;
+
+ dp_dump(p, "0x%04x %s version %u\n",
+ family->gf_id, family->gf_name, family->gf_version);
+
+ return 1;
+}
+
+static struct trans_tbl ops_flags[] = {
+ __ADD(GENL_ADMIN_PERM, admin-perm)
+ __ADD(GENL_CMD_CAP_DO, has-doit)
+ __ADD(GENL_CMD_CAP_DUMP, has-dump)
+ __ADD(GENL_CMD_CAP_HASPOL, has-policy)
+};
+
+static char *ops_flags2str(int flags, char *buf, size_t len)
+{
+ return __flags2str(flags, buf, len, ops_flags, ARRAY_SIZE(ops_flags));
+}
+
+static int family_dump_full(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct genl_family *family = (struct genl_family *) obj;
+ int line;
+
+ line = family_dump_brief(obj, p);
+ dp_dump_line(p, line++, " hdrsize %u maxattr %u\n",
+ family->gf_hdrsize, family->gf_maxattr);
+
+ if (family->ce_mask & FAMILY_ATTR_OPS) {
+ struct genl_family_op *op;
+ char buf[64];
+
+ nl_list_for_each_entry(op, &family->gf_ops, o_list) {
+ ops_flags2str(op->o_flags, buf, sizeof(buf));
+
+ genl_op2name(family->gf_id, op->o_id, buf, sizeof(buf));
+
+ dp_dump_line(p, line++, " op %s (0x%02x)",
+ buf, op->o_id);
+
+ if (op->o_flags)
+ dp_dump(p, " <%s>",
+ ops_flags2str(op->o_flags, buf,
+ sizeof(buf)));
+
+ dp_dump(p, "\n");
+ }
+ }
+
+ return line;
+}
+
+static int family_dump_stats(struct nl_object *obj, struct nl_dump_params *p)
+{
+ return family_dump_full(obj, p);
+}
+
+static int family_compare(struct nl_object *_a, struct nl_object *_b,
+ uint32_t attrs, int flags)
+{
+ struct genl_family *a = (struct genl_family *) _a;
+ struct genl_family *b = (struct genl_family *) _b;
+ int diff = 0;
+
+#define FAM_DIFF(ATTR, EXPR) ATTR_DIFF(attrs, FAMILY_ATTR_##ATTR, a, b, EXPR)
+
+ diff |= FAM_DIFF(ID, a->gf_id != b->gf_id);
+ diff |= FAM_DIFF(VERSION, a->gf_version != b->gf_version);
+ diff |= FAM_DIFF(HDRSIZE, a->gf_hdrsize != b->gf_hdrsize);
+ diff |= FAM_DIFF(MAXATTR, a->gf_maxattr != b->gf_maxattr);
+ diff |= FAM_DIFF(NAME, strcmp(a->gf_name, b->gf_name));
+
+#undef FAM_DIFF
+
+ return diff;
+}
+
+
+/**
+ * @name Family Object
+ * @{
+ */
+
+struct genl_family *genl_family_alloc(void)
+{
+ return (struct genl_family *) nl_object_alloc(&genl_family_ops);
+}
+
+void genl_family_put(struct genl_family *family)
+{
+ nl_object_put((struct nl_object *) family);
+}
+
+/** @} */
+
+/**
+ * @name Attributes
+ * @{
+ */
+
+unsigned int genl_family_get_id(struct genl_family *family)
+{
+ if (family->ce_mask & FAMILY_ATTR_ID)
+ return family->gf_id;
+ else
+ return GENL_ID_GENERATE;
+}
+
+void genl_family_set_id(struct genl_family *family, unsigned int id)
+{
+ family->gf_id = id;
+ family->ce_mask |= FAMILY_ATTR_ID;
+}
+
+char *genl_family_get_name(struct genl_family *family)
+{
+ if (family->ce_mask & FAMILY_ATTR_NAME)
+ return family->gf_name;
+ else
+ return NULL;
+}
+
+void genl_family_set_name(struct genl_family *family, const char *name)
+{
+ strncpy(family->gf_name, name, GENL_NAMSIZ-1);
+ family->ce_mask |= FAMILY_ATTR_NAME;
+}
+
+uint8_t genl_family_get_version(struct genl_family *family)
+{
+ if (family->ce_mask & FAMILY_ATTR_VERSION)
+ return family->gf_version;
+ else
+ return 0;
+}
+
+void genl_family_set_version(struct genl_family *family, uint8_t version)
+{
+ family->gf_version = version;
+ family->ce_mask |= FAMILY_ATTR_VERSION;
+}
+
+uint32_t genl_family_get_hdrsize(struct genl_family *family)
+{
+ if (family->ce_mask & FAMILY_ATTR_HDRSIZE)
+ return family->gf_hdrsize;
+ else
+ return 0;
+}
+
+void genl_family_set_hdrsize(struct genl_family *family, uint32_t hdrsize)
+{
+ family->gf_hdrsize = hdrsize;
+ family->ce_mask |= FAMILY_ATTR_HDRSIZE;
+}
+
+uint32_t genl_family_get_maxattr(struct genl_family *family)
+{
+ if (family->ce_mask & FAMILY_ATTR_MAXATTR)
+ return family->gf_maxattr;
+ else
+ return family->gf_maxattr;
+}
+
+void genl_family_set_maxattr(struct genl_family *family, uint32_t maxattr)
+{
+ family->gf_maxattr = maxattr;
+ family->ce_mask |= FAMILY_ATTR_MAXATTR;
+}
+
+int genl_family_add_op(struct genl_family *family, int id, int flags)
+{
+ struct genl_family_op *op;
+
+ op = calloc(1, sizeof(*op));
+ if (op == NULL)
+ return nl_errno(ENOMEM);
+
+ op->o_id = id;
+ op->o_flags = flags;
+
+ nl_list_add_tail(&op->o_list, &family->gf_ops);
+ family->ce_mask |= FAMILY_ATTR_OPS;
+
+ return 0;
+}
+
+/** @} */
+
+/** @cond SKIP */
+struct nl_object_ops genl_family_ops = {
+ .oo_name = "genl/family",
+ .oo_size = sizeof(struct genl_family),
+ .oo_constructor = family_constructor,
+ .oo_free_data = family_free_data,
+ .oo_clone = family_clone,
+ .oo_dump[NL_DUMP_BRIEF] = family_dump_brief,
+ .oo_dump[NL_DUMP_FULL] = family_dump_full,
+ .oo_dump[NL_DUMP_STATS] = family_dump_stats,
+#if 0
+ .oo_dump[NL_DUMP_XML] = addr_dump_xml,
+ .oo_dump[NL_DUMP_ENV] = addr_dump_env,
+#endif
+ .oo_compare = family_compare,
+ .oo_id_attrs = FAMILY_ATTR_ID,
+};
+/** @endcond */
+
+/** @} */
diff --git a/lib/genl/genl.c b/lib/genl/genl.c
new file mode 100644
index 0000000..c600579
--- /dev/null
+++ b/lib/genl/genl.c
@@ -0,0 +1,210 @@
+/*
+ * lib/genl/genl.c Generic Netlink
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup nlfam
+ * @defgroup genl Generic Netlink
+ *
+ * @par Message Format
+ * @code
+ * <------- NLMSG_ALIGN(hlen) ------> <---- NLMSG_ALIGN(len) --->
+ * +----------------------------+- - -+- - - - - - - - - - -+- - -+
+ * | Header | Pad | Payload | Pad |
+ * | struct nlmsghdr | | | |
+ * +----------------------------+- - -+- - - - - - - - - - -+- - -+
+ * @endcode
+ * @code
+ * <-------- GENL_HDRLEN -------> <--- hdrlen -->
+ * <------- genlmsg_len(ghdr) ------>
+ * +------------------------+- - -+---------------+- - -+------------+
+ * | Generic Netlink Header | Pad | Family Header | Pad | Attributes |
+ * | struct genlmsghdr | | | | |
+ * +------------------------+- - -+---------------+- - -+------------+
+ * genlmsg_data(ghdr)--------------^ ^
+ * genlmsg_attrdata(ghdr, hdrlen)-------------------------
+ * @endcode
+ *
+ * @par 1) Creating a new generic netlink message
+ * @code
+ * struct nl_msg *msg;
+ * struct myhdr {
+ * int a;
+ * int b;
+ * } *hdr;
+ *
+ * // Create a new empty netlink message
+ * msg = nlmsg_alloc();
+ *
+ * // Append the netlink and generic netlink message header, this
+ * // operation also reserves room for the family specific header.
+ * hdr = genlmsg_put(msg, NL_AUTO_PID, NL_AUTO_SEQ, family, sizeof(hdr),
+ * NLM_F_ECHO, MYOP, VERSION);
+ *
+ * // Fill out your own family specific header.
+ * hdr->a = 1;
+ * hdr->b = 2;
+ *
+ * // Append the optional attributes.
+ * nla_put_u32(msg, 1, 0x10);
+ *
+ * // Message is ready to be sent.
+ * nl_send_auto_complete(nl_handle, msg);
+ *
+ * // All done? Free the message.
+ * nlmsg_free(msg);
+ * @endcode
+ *
+ * @par 2) Sending of trivial messages
+ * @code
+ * // For trivial messages not requiring any family specific header or
+ * // attributes, genl_send_simple() may be used to send messages directly.
+ * genl_send_simple(nl_handle, family, MY_SIMPLE_CMD, VERSION, 0);
+ * @endcode
+ * @{
+ */
+
+#include <netlink-generic.h>
+#include <netlink/netlink.h>
+#include <netlink/genl/genl.h>
+#include <netlink/utils.h>
+
+/**
+ * @name Socket Creating
+ * @{
+ */
+
+int genl_connect(struct nl_handle *handle)
+{
+ return nl_connect(handle, NETLINK_GENERIC);
+}
+
+/** @} */
+
+/**
+ * @name Sending
+ * @{
+ */
+
+/**
+ * Send trivial generic netlink message
+ * @arg handle Netlink handle.
+ * @arg family Generic netlink family
+ * @arg cmd Command
+ * @arg version Version
+ * @arg flags Additional netlink message flags.
+ *
+ * Fills out a routing netlink request message and sends it out
+ * using nl_send_simple().
+ *
+ * @return 0 on success or a negative error code.
+ */
+int genl_send_simple(struct nl_handle *handle, int family, int cmd,
+ int version, int flags)
+{
+ struct genlmsghdr hdr = {
+ .cmd = cmd,
+ .version = version,
+ };
+
+ return nl_send_simple(handle, family, flags, &hdr, sizeof(hdr));
+}
+
+/** @} */
+
+
+/**
+ * @name Message Parsing
+ * @{
+ */
+
+/**
+ * Get head of message payload
+ * @arg gnlh genetlink messsage header
+ */
+void *genlmsg_data(const struct genlmsghdr *gnlh)
+{
+ return ((unsigned char *) gnlh + GENL_HDRLEN);
+}
+
+/**
+ * Get lenght of message payload
+ * @arg gnlh genetlink message header
+ */
+int genlmsg_len(const struct genlmsghdr *gnlh)
+{
+ struct nlmsghdr *nlh = (struct nlmsghdr *)((unsigned char *)gnlh -
+ NLMSG_HDRLEN);
+ return (nlh->nlmsg_len - GENL_HDRLEN - NLMSG_HDRLEN);
+}
+
+/**
+ * Get head of attribute data
+ * @arg gnlh generic netlink message header
+ * @arg hdrlen length of family specific header
+ */
+struct nlattr *genlmsg_attrdata(const struct genlmsghdr *gnlh, int hdrlen)
+{
+ return genlmsg_data(gnlh) + NLMSG_ALIGN(hdrlen);
+}
+
+/**
+ * Get length of attribute data
+ * @arg gnlh generic netlink message header
+ * @arg hdrlen length of family specific header
+ */
+int genlmsg_attrlen(const struct genlmsghdr *gnlh, int hdrlen)
+{
+ return genlmsg_len(gnlh) - NLMSG_ALIGN(hdrlen);
+}
+
+/** @} */
+
+/**
+ * @name Message Building
+ * @{
+ */
+
+/**
+ * Add generic netlink header to netlink message
+ * @arg msg netlink message
+ * @arg pid netlink process id or NL_AUTO_PID
+ * @arg seq sequence number of message or NL_AUTO_SEQ
+ * @arg family generic netlink family
+ * @arg hdrlen length of user specific header
+ * @arg flags message flags
+ * @arg cmd generic netlink command
+ * @arg version protocol version
+ *
+ * Returns pointer to user specific header.
+ */
+void *genlmsg_put(struct nl_msg *msg, uint32_t pid, uint32_t seq, int family,
+ int hdrlen, int flags, uint8_t cmd, uint8_t version)
+{
+ struct nlmsghdr *nlh;
+ struct genlmsghdr hdr = {
+ .cmd = cmd,
+ .version = version,
+ };
+
+ nlh = nlmsg_put(msg, pid, seq, family, GENL_HDRLEN + hdrlen, flags);
+ if (nlh == NULL)
+ return NULL;
+
+ memcpy(nlmsg_data(nlh), &hdr, sizeof(hdr));
+ NL_DBG(2, "msg %p: Added generic netlink header cmd=%d version=%d\n",
+ msg, cmd, version);
+
+ return nlmsg_data(nlh) + GENL_HDRLEN;
+}
+
+/** @} */
+
+/** @} */
diff --git a/lib/genl/mngt.c b/lib/genl/mngt.c
new file mode 100644
index 0000000..846cd7e
--- /dev/null
+++ b/lib/genl/mngt.c
@@ -0,0 +1,285 @@
+/*
+ * lib/genl/mngt.c Generic Netlink Management
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup genl
+ * @defgroup genl_mngt Management
+ *
+ * @par 1) Registering a generic netlink module
+ * @code
+ * #include <netlink/genl/mngt.h>
+ *
+ * // First step is to define all the commands being used in
+ * // particular generic netlink family. The ID and name are
+ * // mandatory to be filled out. A callback function and
+ * // most the attribute policy that comes with it must be
+ * // defined for commands expected to be issued towards
+ * // userspace.
+ * static struct genl_cmd foo_cmds[] = {
+ * {
+ * .c_id = FOO_CMD_NEW,
+ * .c_name = "NEWFOO" ,
+ * .c_maxattr = FOO_ATTR_MAX,
+ * .c_attr_policy = foo_policy,
+ * .c_msg_parser = foo_msg_parser,
+ * },
+ * {
+ * .c_id = FOO_CMD_DEL,
+ * .c_name = "DELFOO" ,
+ * },
+ * };
+ *
+ * // The list of commands must then be integrated into a
+ * // struct genl_ops serving as handle for this particular
+ * // family.
+ * static struct genl_ops my_genl_ops = {
+ * .o_cmds = foo_cmds,
+ * .o_ncmds = ARRAY_SIZE(foo_cmds),
+ * };
+ *
+ * // Using the above struct genl_ops an arbitary number of
+ * // cache handles can be associated to it.
+ * //
+ * // The macro GENL_HDRSIZE() must be used to specify the
+ * // length of the header to automatically take headers on
+ * // generic layers into account.
+ * //
+ * // The macro GENL_FAMILY() is used to represent the generic
+ * // netlink family id.
+ * static struct nl_cache_ops genl_foo_ops = {
+ * .co_name = "genl/foo",
+ * .co_hdrsize = GENL_HDRSIZE(sizeof(struct my_hdr)),
+ * .co_msgtypes = GENL_FAMILY(GENL_ID_GENERATE, "foo"),
+ * .co_genl = &my_genl_ops,
+ * .co_protocol = NETLINK_GENERIC,
+ * .co_request_update = foo_request_update,
+ * .co_obj_ops = &genl_foo_ops,
+ * };
+ *
+ * // Finally each cache handle for a generic netlink family
+ * // must be registered using genl_register().
+ * static void __init foo_init(void)
+ * {
+ * genl_register(&genl_foo_ops);
+ * }
+ *
+ * // ... respectively unregsted again.
+ * static void __exit foo_exit(void)
+ * {
+ * genl_unregister(&genl_foo_ops);
+ * }
+ * @endcode
+ * @{
+ */
+
+#include <netlink-generic.h>
+#include <netlink/netlink.h>
+#include <netlink/genl/genl.h>
+#include <netlink/genl/mngt.h>
+#include <netlink/genl/family.h>
+#include <netlink/genl/ctrl.h>
+#include <netlink/utils.h>
+
+static NL_LIST_HEAD(genl_ops_list);
+
+static int genl_msg_parser(struct nl_cache_ops *ops, struct sockaddr_nl *who,
+ struct nlmsghdr *nlh, void *arg)
+{
+ int i, err;
+ struct genlmsghdr *ghdr;
+ struct genl_cmd *cmd;
+
+ ghdr = nlmsg_data(nlh);
+
+ if (ops->co_genl == NULL)
+ BUG();
+
+ for (i = 0; i < ops->co_genl->o_ncmds; i++) {
+ cmd = &ops->co_genl->o_cmds[i];
+ if (cmd->c_id == ghdr->cmd)
+ goto found;
+ }
+
+ err = nl_errno(ENOENT);
+ goto errout;
+
+found:
+ if (cmd->c_msg_parser == NULL)
+ err = nl_error(EOPNOTSUPP, "No message parser found.");
+ else {
+ struct nlattr *tb[cmd->c_maxattr + 1];
+ struct genl_info info = {
+ .who = who,
+ .nlh = nlh,
+ .genlhdr = ghdr,
+ .userhdr = genlmsg_data(ghdr),
+ .attrs = tb,
+ };
+
+ err = nlmsg_parse(nlh, ops->co_hdrsize, tb, cmd->c_maxattr,
+ cmd->c_attr_policy);
+ if (err < 0)
+ goto errout;
+
+ err = cmd->c_msg_parser(ops, cmd, &info, arg);
+ }
+errout:
+ return err;
+
+}
+
+char *genl_op2name(int family, int op, char *buf, size_t len)
+{
+ struct genl_ops *ops;
+ int i;
+
+ nl_list_for_each_entry(ops, &genl_ops_list, o_list) {
+ if (ops->o_family == family) {
+ for (i = 0; i < ops->o_ncmds; i++) {
+ struct genl_cmd *cmd;
+ cmd = &ops->o_cmds[i];
+
+ if (cmd->c_id == op) {
+ strncpy(buf, cmd->c_name, len - 1);
+ return buf;
+ }
+ }
+ }
+ }
+
+ strncpy(buf, "unknown", len - 1);
+ return NULL;
+}
+
+
+/**
+ * @name Register/Unregister
+ * @{
+ */
+
+/**
+ * Register generic netlink operations
+ * @arg ops cache operations
+ */
+int genl_register(struct nl_cache_ops *ops)
+{
+ int err;
+
+ if (ops->co_protocol != NETLINK_GENERIC) {
+ err = nl_error(EINVAL, "cache operations not for protocol " \
+ "NETLINK_GENERIC (protocol=%s)",
+ ops->co_protocol);
+ goto errout;
+ }
+
+ if (ops->co_hdrsize < GENL_HDRSIZE(0)) {
+ err = nl_error(EINVAL, "co_hdrsize too short, probably " \
+ "not including genlmsghdr, minsize=%d",
+ GENL_HDRSIZE(0));
+ goto errout;
+ }
+
+ if (ops->co_genl == NULL) {
+ err = nl_error(EINVAL, "co_genl is NULL, must provide " \
+ "valid genl operations");
+ goto errout;
+ }
+
+ ops->co_genl->o_cache_ops = ops;
+ ops->co_genl->o_name = ops->co_msgtypes[0].mt_name;
+ ops->co_genl->o_family = ops->co_msgtypes[0].mt_id;
+ ops->co_msg_parser = genl_msg_parser;
+
+ /* FIXME: check for dup */
+
+ nl_list_add_tail(&ops->co_genl->o_list, &genl_ops_list);
+
+ err = nl_cache_mngt_register(ops);
+errout:
+ return err;
+}
+
+/**
+ * Unregister generic netlink operations
+ * @arg ops cache operations
+ */
+void genl_unregister(struct nl_cache_ops *ops)
+{
+ nl_cache_mngt_unregister(ops);
+ nl_list_del(&ops->co_genl->o_list);
+}
+
+/** @} */
+
+/**
+ * @name Resolving ID/Name
+ * @{
+ */
+
+static int __genl_ops_resolve(struct nl_cache *ctrl, struct genl_ops *ops)
+{
+ struct genl_family *family;
+
+ family = genl_ctrl_search_by_name(ctrl, ops->o_name);
+ if (family != NULL) {
+ ops->o_id = genl_family_get_id(family);
+ genl_family_put(family);
+
+ return 0;
+ }
+
+ return nl_error(ENOENT, "Unable to find generic netlink family \"%s\"",
+ ops->o_name);
+}
+
+int genl_ops_resolve(struct nl_handle *handle, struct genl_ops *ops)
+{
+ struct nl_cache *ctrl;
+ int err;
+
+ ctrl = genl_ctrl_alloc_cache(handle);
+ if (ctrl == NULL) {
+ err = nl_get_errno();
+ goto errout;
+ }
+
+ err = __genl_ops_resolve(ctrl, ops);
+
+ nl_cache_free(ctrl);
+errout:
+ return err;
+}
+
+int genl_mngt_resolve(struct nl_handle *handle)
+{
+ struct nl_cache *ctrl;
+ struct genl_ops *ops;
+ int err = 0;
+
+ ctrl = genl_ctrl_alloc_cache(handle);
+ if (ctrl == NULL) {
+ err = nl_get_errno();
+ goto errout;
+ }
+
+ nl_list_for_each_entry(ops, &genl_ops_list, o_list) {
+ err = __genl_ops_resolve(ctrl, ops);
+ }
+
+ nl_cache_free(ctrl);
+errout:
+ return err;
+}
+
+/** @} */
+
+
+/** @} */
diff --git a/lib/handlers.c b/lib/handlers.c
new file mode 100644
index 0000000..1797e4f
--- /dev/null
+++ b/lib/handlers.c
@@ -0,0 +1,447 @@
+/*
+ * lib/handlers.c default netlink message handlers
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup nl
+ * @defgroup cb Callbacks/Customization
+ * @brief
+ *
+ * Callbacks and overwriting capabilities are provided to take influence
+ * in various control flows inside the library. All callbacks are packed
+ * together in struct nl_cb which is then attached to a netlink socket or
+ * passed on to the respective functions directly.
+ *
+ * Callbacks can control the flow of the underlying layer by returning
+ * the appropriate error codes:
+ * @code
+ * Action ID | Description
+ * -----------------+-------------------------------------------------------
+ * NL_OK | Proceed with whatever comes next.
+ * NL_SKIP | Skip message currently being processed and continue
+ * | with next message.
+ * NL_STOP | Stop parsing and discard all remaining messages in
+ * | this set of messages.
+ * @endcode
+ *
+ * All callbacks are optional and a default action is performed if no
+ * application specific implementation is provided:
+ *
+ * @code
+ * Callback ID | Default Return Value
+ * ------------------+----------------------
+ * NL_CB_VALID | NL_OK
+ * NL_CB_FINISH | NL_STOP
+ * NL_CB_OVERRUN | NL_STOP
+ * NL_CB_SKIPPED | NL_SKIP
+ * NL_CB_ACK | NL_STOP
+ * NL_CB_MSG_IN | NL_OK
+ * NL_CB_MSG_OUT | NL_OK
+ * NL_CB_INVALID | NL_STOP
+ * NL_CB_SEQ_CHECK | NL_OK
+ * NL_CB_SEND_ACK | NL_OK
+ * |
+ * Error Callback | NL_STOP
+ * @endcode
+ *
+ * In order to simplify typical usages of the library, different sets of
+ * default callback implementations exist:
+ * @code
+ * NL_CB_DEFAULT: No additional actions
+ * NL_CB_VERBOSE: Automatically print warning and error messages to a file
+ * descriptor as appropriate. This is useful for CLI based
+ * applications.
+ * NL_CB_DEBUG: Print informal debugging information for each message
+ * received. This will result in every message beint sent or
+ * received to be printed to the screen in a decoded,
+ * human-readable format.
+ * @endcode
+ *
+ * @par 1) Setting up a callback set
+ * @code
+ * // Allocate a callback set and initialize it to the verbose default set
+ * struct nl_cb *cb = nl_cb_alloc(NL_CB_VERBOSE);
+ *
+ * // Modify the set to call my_func() for all valid messages
+ * nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, my_func, NULL);
+ *
+ * // Set the error message handler to the verbose default implementation
+ * // and direct it to print all errors to the given file descriptor.
+ * FILE *file = fopen(...);
+ * nl_cb_err(cb, NL_CB_VERBOSE, NULL, file);
+ * @endcode
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/msg.h>
+#include <netlink/handlers.h>
+
+static void print_header_content(FILE *ofd, struct nlmsghdr *n)
+{
+ char flags[128];
+ char type[32];
+
+ fprintf(ofd, "type=%s length=%u flags=<%s> sequence-nr=%u pid=%u",
+ nl_nlmsgtype2str(n->nlmsg_type, type, sizeof(type)),
+ n->nlmsg_len, nl_nlmsg_flags2str(n->nlmsg_flags, flags,
+ sizeof(flags)), n->nlmsg_seq, n->nlmsg_pid);
+}
+
+static int nl_valid_handler_verbose(struct nl_msg *msg, void *arg)
+{
+ FILE *ofd = arg ? arg : stdout;
+
+ fprintf(ofd, "-- Warning: unhandled valid message: ");
+ print_header_content(ofd, nlmsg_hdr(msg));
+ fprintf(ofd, "\n");
+
+ return NL_OK;
+}
+
+static int nl_invalid_handler_verbose(struct nl_msg *msg, void *arg)
+{
+ FILE *ofd = arg ? arg : stderr;
+
+ fprintf(ofd, "-- Error: Invalid message: ");
+ print_header_content(ofd, nlmsg_hdr(msg));
+ fprintf(ofd, "\n");
+
+ return NL_STOP;
+}
+
+static int nl_overrun_handler_verbose(struct nl_msg *msg, void *arg)
+{
+ FILE *ofd = arg ? arg : stderr;
+
+ fprintf(ofd, "-- Error: Netlink Overrun: ");
+ print_header_content(ofd, nlmsg_hdr(msg));
+ fprintf(ofd, "\n");
+
+ return NL_STOP;
+}
+
+static int nl_error_handler_verbose(struct sockaddr_nl *who,
+ struct nlmsgerr *e, void *arg)
+{
+ FILE *ofd = arg ? arg : stderr;
+
+ fprintf(ofd, "-- Error received: %s\n-- Original message: ",
+ strerror(-e->error));
+ print_header_content(ofd, &e->msg);
+ fprintf(ofd, "\n");
+
+ return e->error;
+}
+
+static int nl_valid_handler_debug(struct nl_msg *msg, void *arg)
+{
+ FILE *ofd = arg ? arg : stderr;
+
+ fprintf(ofd, "-- Debug: Unhandled Valid message: ");
+ print_header_content(ofd, nlmsg_hdr(msg));
+ fprintf(ofd, "\n");
+
+ return NL_OK;
+}
+
+static int nl_finish_handler_debug(struct nl_msg *msg, void *arg)
+{
+ FILE *ofd = arg ? arg : stderr;
+
+ fprintf(ofd, "-- Debug: End of multipart message block: ");
+ print_header_content(ofd, nlmsg_hdr(msg));
+ fprintf(ofd, "\n");
+
+ return NL_STOP;
+}
+
+static int nl_msg_in_handler_debug(struct nl_msg *msg, void *arg)
+{
+ FILE *ofd = arg ? arg : stderr;
+
+ fprintf(ofd, "-- Debug: Received Message:\n");
+ nl_msg_dump(msg, ofd);
+
+ return NL_OK;
+}
+
+static int nl_msg_out_handler_debug(struct nl_msg *msg, void *arg)
+{
+ FILE *ofd = arg ? arg : stderr;
+
+ fprintf(ofd, "-- Debug: Sent Message:\n");
+ nl_msg_dump(msg, ofd);
+
+ return NL_OK;
+}
+
+static int nl_skipped_handler_debug(struct nl_msg *msg, void *arg)
+{
+ FILE *ofd = arg ? arg : stderr;
+
+ fprintf(ofd, "-- Debug: Skipped message: ");
+ print_header_content(ofd, nlmsg_hdr(msg));
+ fprintf(ofd, "\n");
+
+ return NL_SKIP;
+}
+
+static int nl_ack_handler_debug(struct nl_msg *msg, void *arg)
+{
+ FILE *ofd = arg ? arg : stderr;
+
+ fprintf(ofd, "-- Debug: ACK: ");
+ print_header_content(ofd, nlmsg_hdr(msg));
+ fprintf(ofd, "\n");
+
+ return NL_STOP;
+}
+
+static nl_recvmsg_msg_cb_t cb_def[NL_CB_TYPE_MAX+1][NL_CB_KIND_MAX+1] = {
+ [NL_CB_VALID] = {
+ [NL_CB_VERBOSE] = nl_valid_handler_verbose,
+ [NL_CB_DEBUG] = nl_valid_handler_debug,
+ },
+ [NL_CB_FINISH] = {
+ [NL_CB_DEBUG] = nl_finish_handler_debug,
+ },
+ [NL_CB_INVALID] = {
+ [NL_CB_VERBOSE] = nl_invalid_handler_verbose,
+ [NL_CB_DEBUG] = nl_invalid_handler_verbose,
+ },
+ [NL_CB_MSG_IN] = {
+ [NL_CB_DEBUG] = nl_msg_in_handler_debug,
+ },
+ [NL_CB_MSG_OUT] = {
+ [NL_CB_DEBUG] = nl_msg_out_handler_debug,
+ },
+ [NL_CB_OVERRUN] = {
+ [NL_CB_VERBOSE] = nl_overrun_handler_verbose,
+ [NL_CB_DEBUG] = nl_overrun_handler_verbose,
+ },
+ [NL_CB_SKIPPED] = {
+ [NL_CB_DEBUG] = nl_skipped_handler_debug,
+ },
+ [NL_CB_ACK] = {
+ [NL_CB_DEBUG] = nl_ack_handler_debug,
+ },
+};
+
+static nl_recvmsg_err_cb_t cb_err_def[NL_CB_KIND_MAX+1] = {
+ [NL_CB_VERBOSE] = nl_error_handler_verbose,
+ [NL_CB_DEBUG] = nl_error_handler_verbose,
+};
+
+/**
+ * @name Callback Handle Management
+ * @{
+ */
+
+/**
+ * Allocate a new callback handle
+ * @arg kind callback kind to be used for initialization
+ * @return Newly allocated callback handle or NULL
+ */
+struct nl_cb *nl_cb_alloc(enum nl_cb_kind kind)
+{
+ int i;
+ struct nl_cb *cb;
+
+ if (kind < 0 || kind > NL_CB_KIND_MAX)
+ return NULL;
+
+ cb = calloc(1, sizeof(*cb));
+ if (!cb) {
+ nl_errno(ENOMEM);
+ return NULL;
+ }
+
+ cb->cb_refcnt = 1;
+
+ for (i = 0; i <= NL_CB_TYPE_MAX; i++)
+ nl_cb_set(cb, i, kind, NULL, NULL);
+
+ nl_cb_err(cb, kind, NULL, NULL);
+
+ return cb;
+}
+
+/**
+ * Clone an existing callback handle
+ * @arg orig original callback handle
+ * @return Newly allocated callback handle being a duplicate of
+ * orig or NULL
+ */
+struct nl_cb *nl_cb_clone(struct nl_cb *orig)
+{
+ struct nl_cb *cb;
+
+ cb = nl_cb_alloc(NL_CB_DEFAULT);
+ if (!cb)
+ return NULL;
+
+ memcpy(cb, orig, sizeof(*orig));
+ cb->cb_refcnt = 1;
+
+ return cb;
+}
+
+struct nl_cb *nl_cb_get(struct nl_cb *cb)
+{
+ cb->cb_refcnt++;
+
+ return cb;
+}
+
+void nl_cb_put(struct nl_cb *cb)
+{
+ if (!cb)
+ return;
+
+ cb->cb_refcnt--;
+
+ if (cb->cb_refcnt < 0)
+ BUG();
+
+ if (cb->cb_refcnt <= 0)
+ free(cb);
+}
+
+/** @} */
+
+/**
+ * @name Callback Setup
+ * @{
+ */
+
+/**
+ * Set up a callback
+ * @arg cb callback set
+ * @arg type callback to modify
+ * @arg kind kind of implementation
+ * @arg func callback function (NL_CB_CUSTOM)
+ * @arg arg argument passed to callback
+ *
+ * @return 0 on success or a negative error code
+ */
+int nl_cb_set(struct nl_cb *cb, enum nl_cb_type type, enum nl_cb_kind kind,
+ nl_recvmsg_msg_cb_t func, void *arg)
+{
+ if (type < 0 || type > NL_CB_TYPE_MAX)
+ return nl_error(ERANGE, "Callback type out of range");
+
+ if (kind < 0 || kind > NL_CB_KIND_MAX)
+ return nl_error(ERANGE, "Callback kind out of range");
+
+ if (kind == NL_CB_CUSTOM) {
+ cb->cb_set[type] = func;
+ cb->cb_args[type] = arg;
+ } else {
+ cb->cb_set[type] = cb_def[type][kind];
+ cb->cb_args[type] = arg;
+ }
+
+ return 0;
+}
+
+/**
+ * Set up a all callbacks
+ * @arg cb callback set
+ * @arg kind kind of callback
+ * @arg func callback function
+ * @arg arg argument to be passwd to callback function
+ *
+ * @return 0 on success or a negative error code
+ */
+int nl_cb_set_all(struct nl_cb *cb, enum nl_cb_kind kind,
+ nl_recvmsg_msg_cb_t func, void *arg)
+{
+ int i, err;
+
+ for (i = 0; i <= NL_CB_TYPE_MAX; i++) {
+ err = nl_cb_set(cb, i, kind, func, arg);
+ if (err < 0)
+ return err;
+ }
+
+ return 0;
+}
+
+/**
+ * Set up an error callback
+ * @arg cb callback set
+ * @arg kind kind of callback
+ * @arg func callback function
+ * @arg arg argument to be passed to callback function
+ */
+int nl_cb_err(struct nl_cb *cb, enum nl_cb_kind kind,
+ nl_recvmsg_err_cb_t func, void *arg)
+{
+ if (kind < 0 || kind > NL_CB_KIND_MAX)
+ return nl_error(ERANGE, "Callback kind out of range");
+
+ if (kind == NL_CB_CUSTOM) {
+ cb->cb_err = func;
+ cb->cb_err_arg = arg;
+ } else {
+ cb->cb_err = cb_err_def[kind];
+ cb->cb_err_arg = arg;
+ }
+
+ return 0;
+}
+
+/** @} */
+
+/**
+ * @name Overwriting
+ * @{
+ */
+
+/**
+ * Overwrite internal calls to nl_recvmsgs()
+ * @arg cb callback set
+ * @arg func replacement callback for nl_recvmsgs()
+ */
+void nl_cb_overwrite_recvmsgs(struct nl_cb *cb,
+ int (*func)(struct nl_handle *, struct nl_cb *))
+{
+ cb->cb_recvmsgs_ow = func;
+}
+
+/**
+ * Overwrite internal calls to nl_recv()
+ * @arg cb callback set
+ * @arg func replacement callback for nl_recv()
+ */
+void nl_cb_overwrite_recv(struct nl_cb *cb,
+ int (*func)(struct nl_handle *, struct sockaddr_nl *,
+ unsigned char **, struct ucred **))
+{
+ cb->cb_recv_ow = func;
+}
+
+/**
+ * Overwrite internal calls to nl_send()
+ * @arg cb callback set
+ * @arg func replacement callback for nl_send()
+ */
+void nl_cb_overwrite_send(struct nl_cb *cb,
+ int (*func)(struct nl_handle *, struct nl_msg *))
+{
+ cb->cb_send_ow = func;
+}
+
+/** @} */
+
+/** @} */
diff --git a/lib/msg.c b/lib/msg.c
new file mode 100644
index 0000000..caae744
--- /dev/null
+++ b/lib/msg.c
@@ -0,0 +1,931 @@
+/*
+ * lib/msg.c Netlink Messages Interface
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup nl
+ * @defgroup msg Messages
+ * Netlink Message Construction/Parsing Interface
+ *
+ * The following information is partly extracted from RFC3549
+ * (ftp://ftp.rfc-editor.org/in-notes/rfc3549.txt)
+ *
+ * @par Message Format
+ * Netlink messages consist of a byte stream with one or multiple
+ * Netlink headers and an associated payload. If the payload is too big
+ * to fit into a single message it, can be split over multiple Netlink
+ * messages, collectively called a multipart message. For multipart
+ * messages, the first and all following headers have the \c NLM_F_MULTI
+ * Netlink header flag set, except for the last header which has the
+ * Netlink header type \c NLMSG_DONE.
+ *
+ * @par
+ * The Netlink message header (\link nlmsghdr struct nlmsghdr\endlink) is shown below.
+ * @code
+ * 0 1 2 3
+ * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * | Length |
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * | Type | Flags |
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * | Sequence Number |
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * | Process ID (PID) |
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * @endcode
+ *
+ * @par
+ * The netlink message header and payload must be aligned properly:
+ * @code
+ * <------- NLMSG_ALIGN(hlen) ------> <---- NLMSG_ALIGN(len) --->
+ * +----------------------------+- - -+- - - - - - - - - - -+- - -+
+ * | Header | Pad | Payload | Pad |
+ * | struct nlmsghdr | | | |
+ * +----------------------------+- - -+- - - - - - - - - - -+- - -+
+ * @endcode
+ * @par
+ * Message Format:
+ * @code
+ * <--- nlmsg_total_size(payload) --->
+ * <-- nlmsg_msg_size(payload) ->
+ * +----------+- - -+-------------+- - -+-------- - -
+ * | nlmsghdr | Pad | Payload | Pad | nlmsghdr
+ * +----------+- - -+-------------+- - -+-------- - -
+ * nlmsg_data(nlh)---^ ^
+ * nlmsg_next(nlh)-----------------------+
+ * @endcode
+ * @par
+ * The payload may consist of arbitary data but may have strict
+ * alignment and formatting rules depening on the specific netlink
+ * families.
+ * @par
+ * @code
+ * <---------------------- nlmsg_len(nlh) --------------------->
+ * <------ hdrlen ------> <- nlmsg_attrlen(nlh, hdrlen) ->
+ * +----------------------+- - -+--------------------------------+
+ * | Family Header | Pad | Attributes |
+ * +----------------------+- - -+--------------------------------+
+ * nlmsg_attrdata(nlh, hdrlen)---^
+ * @endcode
+ * @par The ACK Netlink Message
+ * This message is actually used to denote both an ACK and a NACK.
+ * Typically, the direction is from FEC to CPC (in response to an ACK
+ * request message). However, the CPC should be able to send ACKs back
+ * to FEC when requested.
+ * @code
+ * 0 1 2 3
+ * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * | Netlink message header |
+ * | type = NLMSG_ERROR |
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * | Error code |
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * | OLD Netlink message header |
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * @endcode
+ *
+ * @par 1) Creating a new netlink message
+ * @code
+ * // Netlink messages can be allocated in various ways, you may
+ * // allocate an empty netlink message by using nlmsg_alloc():
+ * struct nl_msg *msg = nlmsg_alloc();
+ *
+ * // Very often, the message type and message flags are known
+ * // at allocation time while the other fields are auto generated:
+ * struct nl_msg *msg = nlmsg_alloc_simple(MY_TYPE, MY_FLAGS);
+ *
+ * // Alternatively an existing netlink message header can be used
+ * // to inherit header values from:
+ * struct nlmsghdr hdr = {
+ * .nlmsg_type = MY_TYPE,
+ * .nlmsg_flags = MY_FLAGS,
+ * };
+ * struct nl_msg *msg = nlmsg_inherit(&hdr);
+ *
+ * // Last but not least, netlink messages received from netlink sockets
+ * // can be converted into nl_msg objects using nlmsg_convert():
+ * struct nl_msg *msg = nlmsg_convert(nlh_from_nl_sock);
+ *
+ * // The header can later be retrieved with nlmsg_hdr() and changed again:
+ * nlmsg_hdr(msg)->nlmsg_flags |= YET_ANOTHER_FLAG;
+ * @endcode
+ *
+ * @par 2) Appending data to the message
+ * @code
+ * // Payload may be added to the message via nlmsg_append(). The fourth
+ * // parameter specifies the number of alignment bytes the data should
+ * // be padding with at the end. Common values are 0 to disable it or
+ * // NLMSG_ALIGNTO to ensure proper netlink message padding.
+ * nlmsg_append(msg, &mydata, sizeof(mydata), 0);
+ *
+ * // Sometimes it may be necessary to reserve room for data but defer
+ * // the actual copying to a later point, nlmsg_reserve() can be used
+ * // for this purpose:
+ * void *data = nlmsg_reserve(msg, sizeof(mydata), NLMSG_ALIGNTO);
+ * @endcode
+ *
+ * @par 3) Cleaning up message construction
+ * @code
+ * // After successful use of the message, the memory must be freed
+ * // using nlmsg_free()
+ * nlmsg_free(msg);
+ * @endcode
+ *
+ * @par 4) Parsing messages
+ * @code
+ * int n;
+ * unsigned char *buf;
+ * struct nlmsghdr *hdr;
+ *
+ * n = nl_recv(handle, NULL, &buf);
+ *
+ * hdr = (struct nlmsghdr *) buf;
+ * while (nlmsg_ok(hdr, n)) {
+ * // Process message here...
+ * hdr = nlmsg_next(hdr, &n);
+ * }
+ * @endcode
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/cache.h>
+#include <netlink/attr.h>
+#include <linux/socket.h>
+
+/**
+ * @name Size Calculations
+ * @{
+ */
+
+/**
+ * length of netlink message not including padding
+ * @arg payload length of message payload
+ */
+int nlmsg_msg_size(int payload)
+{
+ return NLMSG_HDRLEN + payload;
+}
+
+/**
+ * length of netlink message including padding
+ * @arg payload length of message payload
+ */
+int nlmsg_total_size(int payload)
+{
+ return NLMSG_ALIGN(nlmsg_msg_size(payload));
+}
+
+/**
+ * length of padding at the message's tail
+ * @arg payload length of message payload
+ */
+int nlmsg_padlen(int payload)
+{
+ return nlmsg_total_size(payload) - nlmsg_msg_size(payload);
+}
+
+/** @} */
+
+/**
+ * @name Payload Access
+ * @{
+ */
+
+/**
+ * head of message payload
+ * @arg nlh netlink messsage header
+ */
+void *nlmsg_data(const struct nlmsghdr *nlh)
+{
+ return (unsigned char *) nlh + NLMSG_HDRLEN;
+}
+
+void *nlmsg_tail(const struct nlmsghdr *nlh)
+{
+ return (unsigned char *) nlh + NLMSG_ALIGN(nlh->nlmsg_len);
+}
+
+/**
+ * length of message payload
+ * @arg nlh netlink message header
+ */
+int nlmsg_len(const struct nlmsghdr *nlh)
+{
+ return nlh->nlmsg_len - NLMSG_HDRLEN;
+}
+
+/** @} */
+
+/**
+ * @name Attribute Access
+ * @{
+ */
+
+/**
+ * head of attributes data
+ * @arg nlh netlink message header
+ * @arg hdrlen length of family specific header
+ */
+struct nlattr *nlmsg_attrdata(const struct nlmsghdr *nlh, int hdrlen)
+{
+ unsigned char *data = nlmsg_data(nlh);
+ return (struct nlattr *) (data + NLMSG_ALIGN(hdrlen));
+}
+
+/**
+ * length of attributes data
+ * @arg nlh netlink message header
+ * @arg hdrlen length of family specific header
+ */
+int nlmsg_attrlen(const struct nlmsghdr *nlh, int hdrlen)
+{
+ return nlmsg_len(nlh) - NLMSG_ALIGN(hdrlen);
+}
+
+/** @} */
+
+/**
+ * @name Message Parsing
+ * @{
+ */
+
+/**
+ * check if the netlink message fits into the remaining bytes
+ * @arg nlh netlink message header
+ * @arg remaining number of bytes remaining in message stream
+ */
+int nlmsg_ok(const struct nlmsghdr *nlh, int remaining)
+{
+ return (remaining >= sizeof(struct nlmsghdr) &&
+ nlh->nlmsg_len >= sizeof(struct nlmsghdr) &&
+ nlh->nlmsg_len <= remaining);
+}
+
+/**
+ * next netlink message in message stream
+ * @arg nlh netlink message header
+ * @arg remaining number of bytes remaining in message stream
+ *
+ * @returns the next netlink message in the message stream and
+ * decrements remaining by the size of the current message.
+ */
+struct nlmsghdr *nlmsg_next(struct nlmsghdr *nlh, int *remaining)
+{
+ int totlen = NLMSG_ALIGN(nlh->nlmsg_len);
+
+ *remaining -= totlen;
+
+ return (struct nlmsghdr *) ((unsigned char *) nlh + totlen);
+}
+
+/**
+ * parse attributes of a netlink message
+ * @arg nlh netlink message header
+ * @arg hdrlen length of family specific header
+ * @arg tb destination array with maxtype+1 elements
+ * @arg maxtype maximum attribute type to be expected
+ * @arg policy validation policy
+ *
+ * See nla_parse()
+ */
+int nlmsg_parse(struct nlmsghdr *nlh, int hdrlen, struct nlattr *tb[],
+ int maxtype, struct nla_policy *policy)
+{
+ if (nlh->nlmsg_len < nlmsg_msg_size(hdrlen))
+ return nl_errno(EINVAL);
+
+ return nla_parse(tb, maxtype, nlmsg_attrdata(nlh, hdrlen),
+ nlmsg_attrlen(nlh, hdrlen), policy);
+}
+
+/**
+ * nlmsg_find_attr - find a specific attribute in a netlink message
+ * @arg nlh netlink message header
+ * @arg hdrlen length of familiy specific header
+ * @arg attrtype type of attribute to look for
+ *
+ * Returns the first attribute which matches the specified type.
+ */
+struct nlattr *nlmsg_find_attr(struct nlmsghdr *nlh, int hdrlen, int attrtype)
+{
+ return nla_find(nlmsg_attrdata(nlh, hdrlen),
+ nlmsg_attrlen(nlh, hdrlen), attrtype);
+}
+
+/**
+ * nlmsg_validate - validate a netlink message including attributes
+ * @arg nlh netlinket message header
+ * @arg hdrlen length of familiy specific header
+ * @arg maxtype maximum attribute type to be expected
+ * @arg policy validation policy
+ */
+int nlmsg_validate(struct nlmsghdr *nlh, int hdrlen, int maxtype,
+ struct nla_policy *policy)
+{
+ if (nlh->nlmsg_len < nlmsg_msg_size(hdrlen))
+ return nl_errno(EINVAL);
+
+ return nla_validate(nlmsg_attrdata(nlh, hdrlen),
+ nlmsg_attrlen(nlh, hdrlen), maxtype, policy);
+}
+
+/** @} */
+
+/**
+ * @name Message Building/Access
+ * @{
+ */
+
+static struct nl_msg *__nlmsg_alloc(size_t len)
+{
+ struct nl_msg *nm;
+
+ nm = calloc(1, sizeof(*nm));
+ if (!nm)
+ goto errout;
+
+ nm->nm_nlh = calloc(1, len);
+ if (!nm->nm_nlh)
+ goto errout;
+
+ nm->nm_protocol = -1;
+ nm->nm_nlh->nlmsg_len = len;
+
+ NL_DBG(2, "msg %p: Allocated new message, nlmsg_len=%d\n", nm, len);
+
+ return nm;
+errout:
+ free(nm);
+ nl_errno(ENOMEM);
+ return NULL;
+}
+
+/**
+ * Allocate a new netlink message
+ *
+ * Allocates a new netlink message without any further payload.
+ *
+ * @return Newly allocated netlink message or NULL.
+ */
+struct nl_msg *nlmsg_alloc(void)
+{
+ return __nlmsg_alloc(nlmsg_total_size(0));
+}
+
+/**
+ * Allocate a new netlink message and inherit netlink message header
+ * @arg hdr Netlink message header template
+ *
+ * Allocates a new netlink message with a tailroom for the netlink
+ * message header. If \a hdr is not NULL it will be used as a
+ * template for the netlink message header, otherwise the header
+ * is left blank.
+ *
+ * @return Newly allocated netlink message or NULL
+ */
+struct nl_msg *nlmsg_inherit(struct nlmsghdr *hdr)
+{
+ struct nl_msg *nm;
+
+ nm = nlmsg_alloc();
+ if (nm && hdr) {
+ struct nlmsghdr *new = nm->nm_nlh;
+
+ new->nlmsg_type = hdr->nlmsg_type;
+ new->nlmsg_flags = hdr->nlmsg_flags;
+ new->nlmsg_seq = hdr->nlmsg_seq;
+ new->nlmsg_pid = hdr->nlmsg_pid;
+ }
+
+ return nm;
+}
+
+/**
+ * Allocate a new netlink message
+ * @arg nlmsgtype Netlink message type
+ * @arg flags Message flags.
+ *
+ * @return Newly allocated netlink message or NULL.
+ */
+struct nl_msg *nlmsg_alloc_simple(int nlmsgtype, int flags)
+{
+ struct nl_msg *msg;
+ struct nlmsghdr nlh = {
+ .nlmsg_type = nlmsgtype,
+ .nlmsg_flags = flags,
+ };
+
+ msg = nlmsg_inherit(&nlh);
+ if (msg)
+ NL_DBG(2, "msg %p: Allocated new simple message\n", msg);
+
+ return msg;
+}
+
+/**
+ * Convert a netlink message received from a netlink socket to a nl_msg
+ * @arg hdr Netlink message received from netlink socket.
+ *
+ * Allocates a new netlink message and copies all of the data pointed to
+ * by \a hdr into the new message object.
+ *
+ * @return Newly allocated netlink message or NULL.
+ */
+struct nl_msg *nlmsg_convert(struct nlmsghdr *hdr)
+{
+ struct nl_msg *nm;
+
+ nm = __nlmsg_alloc(NLMSG_ALIGN(hdr->nlmsg_len));
+ if (!nm)
+ goto errout;
+
+ memcpy(nm->nm_nlh, hdr, hdr->nlmsg_len);
+
+ return nm;
+errout:
+ nlmsg_free(nm);
+ return NULL;
+}
+
+/**
+ * Reserve room for additional data in a netlink message
+ * @arg n netlink message
+ * @arg len length of additional data to reserve room for
+ * @arg pad number of bytes to align data to
+ *
+ * Reserves room for additional data at the tail of the an
+ * existing netlink message. Eventual padding required will
+ * be zeroed out.
+ *
+ * @note All existing pointers into the old data section may have
+ * become obsolete and illegal to reference after this call.
+ *
+ * @return Pointer to start of additional data tailroom or NULL.
+ */
+void *nlmsg_reserve(struct nl_msg *n, size_t len, int pad)
+{
+ void *tmp;
+ size_t tlen;
+
+ tlen = pad ? ((len + (pad - 1)) & ~(pad - 1)) : len;
+
+ tmp = realloc(n->nm_nlh, n->nm_nlh->nlmsg_len + tlen);
+ if (!tmp) {
+ nl_errno(ENOMEM);
+ return NULL;
+ }
+
+ n->nm_nlh = tmp;
+ tmp += n->nm_nlh->nlmsg_len;
+ n->nm_nlh->nlmsg_len += tlen;
+
+ if (tlen > len)
+ memset(tmp + len, 0, tlen - len);
+
+ NL_DBG(2, "msg %p: Reserved %d bytes, pad=%d, nlmsg_len=%d\n",
+ n, len, pad, n->nm_nlh->nlmsg_len);
+
+ return tmp;
+}
+
+/**
+ * Append data to tail of a netlink message
+ * @arg n netlink message
+ * @arg data data to add
+ * @arg len length of data
+ * @arg pad Number of bytes to align data to.
+ *
+ * Extends the netlink message as needed and appends the data of given
+ * length to the message.
+ *
+ * @note All existing pointers into the old data section may have
+ * become obsolete and illegal to reference after this call.
+ *
+ * @return 0 on success or a negative error code
+ */
+int nlmsg_append(struct nl_msg *n, void *data, size_t len, int pad)
+{
+ void *tmp;
+
+ tmp = nlmsg_reserve(n, len, pad);
+ if (tmp == NULL)
+ return nl_errno(ENOMEM);
+
+ memcpy(tmp, data, len);
+ NL_DBG(2, "msg %p: Appended %d bytes with padding %d\n", n, len, pad);
+
+ return 0;
+}
+
+/**
+ * Add a netlink message header to a netlink message
+ * @arg n netlink message
+ * @arg pid netlink process id or NL_AUTO_PID
+ * @arg seq sequence number of message or NL_AUTO_SEQ
+ * @arg type message type
+ * @arg payload length of message payload
+ * @arg flags message flags
+ *
+ * Adds or overwrites the netlink message header in an existing message
+ * object. If \a payload is greater-than zero additional room will be
+ * reserved, f.e. for family specific headers. It can be accesed via
+ * nlmsg_data().
+ *
+ * @return A pointer to the netlink message header or NULL.
+ */
+struct nlmsghdr *nlmsg_put(struct nl_msg *n, uint32_t pid, uint32_t seq,
+ int type, int payload, int flags)
+{
+ struct nlmsghdr *nlh;
+
+ if (n->nm_nlh->nlmsg_len < NLMSG_HDRLEN)
+ BUG();
+
+ nlh = (struct nlmsghdr *) n->nm_nlh;
+ nlh->nlmsg_type = type;
+ nlh->nlmsg_flags = flags;
+ nlh->nlmsg_pid = pid;
+ nlh->nlmsg_seq = seq;
+
+ NL_DBG(2, "msg %p: Added netlink header type=%d, flags=%d, pid=%d, "
+ "seq=%d\n", n, type, flags, pid, seq);
+
+ if (payload > 0 &&
+ nlmsg_reserve(n, payload, NLMSG_ALIGNTO) == NULL)
+ return NULL;
+
+ return nlh;
+}
+
+/**
+ * Return actual netlink message
+ * @arg n netlink message
+ *
+ * Returns the actual netlink message casted to the type of the netlink
+ * message header.
+ *
+ * @return A pointer to the netlink message.
+ */
+struct nlmsghdr *nlmsg_hdr(struct nl_msg *n)
+{
+ return n->nm_nlh;
+}
+
+/**
+ * Free a netlink message
+ * @arg n netlink message
+ *
+ * Destroys a netlink message and frees up all used memory.
+ *
+ * @pre The message must be unused.
+ */
+void nlmsg_free(struct nl_msg *n)
+{
+ if (!n)
+ return;
+
+ free(n->nm_nlh);
+ free(n);
+ NL_DBG(2, "msg %p: Freed\n", n);
+}
+
+/** @} */
+
+/**
+ * @name Attributes
+ * @{
+ */
+
+void nlmsg_set_proto(struct nl_msg *msg, int protocol)
+{
+ msg->nm_protocol = protocol;
+}
+
+int nlmsg_get_proto(struct nl_msg *msg)
+{
+ return msg->nm_protocol;
+}
+
+void nlmsg_set_src(struct nl_msg *msg, struct sockaddr_nl *addr)
+{
+ memcpy(&msg->nm_src, addr, sizeof(*addr));
+}
+
+struct sockaddr_nl *nlmsg_get_src(struct nl_msg *msg)
+{
+ return &msg->nm_src;
+}
+
+void nlmsg_set_dst(struct nl_msg *msg, struct sockaddr_nl *addr)
+{
+ memcpy(&msg->nm_dst, addr, sizeof(*addr));
+}
+
+struct sockaddr_nl *nlmsg_get_dst(struct nl_msg *msg)
+{
+ return &msg->nm_dst;
+}
+
+void nlmsg_set_creds(struct nl_msg *msg, struct ucred *creds)
+{
+ memcpy(&msg->nm_creds, creds, sizeof(*creds));
+ msg->nm_flags |= NL_MSG_CRED_PRESENT;
+}
+
+struct ucred *nlmsg_get_creds(struct nl_msg *msg)
+{
+ if (msg->nm_flags & NL_MSG_CRED_PRESENT)
+ return &msg->nm_creds;
+ return NULL;
+}
+
+/** @} */
+
+/**
+ * @name Netlink Message Type Translations
+ * @{
+ */
+
+static struct trans_tbl nl_msgtypes[] = {
+ __ADD(NLMSG_NOOP,NOOP)
+ __ADD(NLMSG_ERROR,ERROR)
+ __ADD(NLMSG_DONE,DONE)
+ __ADD(NLMSG_OVERRUN,OVERRUN)
+};
+
+char *nl_nlmsgtype2str(int type, char *buf, size_t size)
+{
+ return __type2str(type, buf, size, nl_msgtypes,
+ ARRAY_SIZE(nl_msgtypes));
+}
+
+int nl_str2nlmsgtype(const char *name)
+{
+ return __str2type(name, nl_msgtypes, ARRAY_SIZE(nl_msgtypes));
+}
+
+/** @} */
+
+/**
+ * @name Netlink Message Flags Translations
+ * @{
+ */
+
+char *nl_nlmsg_flags2str(int flags, char *buf, size_t len)
+{
+ memset(buf, 0, len);
+
+#define PRINT_FLAG(f) \
+ if (flags & NLM_F_##f) { \
+ flags &= ~NLM_F_##f; \
+ strncat(buf, #f, len - strlen(buf) - 1); \
+ if (flags) \
+ strncat(buf, ",", len - strlen(buf) - 1); \
+ }
+
+ PRINT_FLAG(REQUEST);
+ PRINT_FLAG(MULTI);
+ PRINT_FLAG(ACK);
+ PRINT_FLAG(ECHO);
+ PRINT_FLAG(ROOT);
+ PRINT_FLAG(MATCH);
+ PRINT_FLAG(ATOMIC);
+ PRINT_FLAG(REPLACE);
+ PRINT_FLAG(EXCL);
+ PRINT_FLAG(CREATE);
+ PRINT_FLAG(APPEND);
+
+ if (flags) {
+ char s[32];
+ snprintf(s, sizeof(s), "0x%x", flags);
+ strncat(buf, s, len - strlen(buf) - 1);
+ }
+#undef PRINT_FLAG
+
+ return buf;
+}
+
+/** @} */
+
+/**
+ * @name Direct Parsing
+ * @{
+ */
+
+/** @cond SKIP */
+struct dp_xdata {
+ void (*cb)(struct nl_object *, void *);
+ void *arg;
+};
+/** @endcond */
+
+static int parse_cb(struct nl_object *obj, struct nl_parser_param *p)
+{
+ struct dp_xdata *x = p->pp_arg;
+
+ x->cb(obj, x->arg);
+ nl_object_put(obj);
+ return 0;
+}
+
+int nl_msg_parse(struct nl_msg *msg, void (*cb)(struct nl_object *, void *),
+ void *arg)
+{
+ struct nl_cache_ops *ops;
+ struct nl_parser_param p = {
+ .pp_cb = parse_cb
+ };
+ struct dp_xdata x = {
+ .cb = cb,
+ .arg = arg,
+ };
+
+ ops = nl_cache_mngt_associate(nlmsg_get_proto(msg),
+ nlmsg_hdr(msg)->nlmsg_type);
+ if (ops == NULL)
+ return nl_error(ENOENT, "Unknown message type %d",
+ nlmsg_hdr(msg)->nlmsg_type);
+ p.pp_arg = &x;
+
+ return nl_cache_parse(ops, NULL, nlmsg_hdr(msg), &p);
+}
+
+/** @} */
+
+/**
+ * @name Dumping
+ * @{
+ */
+
+static void prefix_line(FILE *ofd, int prefix)
+{
+ int i;
+
+ for (i = 0; i < prefix; i++)
+ fprintf(ofd, " ");
+}
+
+static inline void dump_hex(FILE *ofd, char *start, int len, int prefix)
+{
+ int i, a, c, limit;
+ char ascii[21] = {0};
+
+ limit = 18 - (prefix * 2);
+ prefix_line(ofd, prefix);
+ fprintf(ofd, " ");
+
+ for (i = 0, a = 0, c = 0; i < len; i++) {
+ int v = *(uint8_t *) (start + i);
+
+ fprintf(ofd, "%02x ", v);
+ ascii[a++] = isprint(v) ? v : '.';
+
+ if (c == limit-1) {
+ fprintf(ofd, "%s\n", ascii);
+ if (i < (len - 1)) {
+ prefix_line(ofd, prefix);
+ fprintf(ofd, " ");
+ }
+ a = c = 0;
+ memset(ascii, 0, sizeof(ascii));
+ } else
+ c++;
+ }
+
+ if (c != 0) {
+ for (i = 0; i < (limit - c); i++)
+ fprintf(ofd, " ");
+ fprintf(ofd, "%s\n", ascii);
+ }
+}
+
+static void print_hdr(FILE *ofd, struct nl_msg *msg)
+{
+ struct nlmsghdr *nlh = nlmsg_hdr(msg);
+ struct nl_cache_ops *ops;
+ char buf[128];
+
+ fprintf(ofd, " .nlmsg_len = %d\n", nlh->nlmsg_len);
+
+ ops = nl_cache_mngt_associate(nlmsg_get_proto(msg), nlh->nlmsg_type);
+
+ fprintf(ofd, " .nlmsg_type = %d <%s>\n", nlh->nlmsg_type,
+ ops ? nl_cache_mngt_type2name(ops, msg->nm_protocol,
+ nlh->nlmsg_type, buf, sizeof(buf))
+ : nl_nlmsgtype2str(nlh->nlmsg_type, buf, sizeof(buf)));
+ fprintf(ofd, " .nlmsg_flags = %d <%s>\n", nlh->nlmsg_flags,
+ nl_nlmsg_flags2str(nlh->nlmsg_flags, buf, sizeof(buf)));
+ fprintf(ofd, " .nlmsg_seq = %d\n", nlh->nlmsg_seq);
+ fprintf(ofd, " .nlmsg_pid = %d\n", nlh->nlmsg_pid);
+
+}
+
+static void dump_attrs(FILE *ofd, struct nlattr *attrs, int attrlen,
+ int prefix)
+{
+ int rem;
+ struct nlattr *nla;
+
+ nla_for_each_attr(nla, attrs, attrlen, rem) {
+ int padlen, alen = nla_len(nla);
+
+ prefix_line(ofd, prefix);
+ fprintf(ofd, " [ATTR %02d%s] %d octets\n", nla_type(nla),
+ nla->nla_type & NLA_F_NESTED ? " NESTED" : "",
+ alen);
+
+ if (nla->nla_type & NLA_F_NESTED)
+ dump_attrs(ofd, nla_data(nla), alen, prefix+1);
+ else
+ dump_hex(ofd, nla_data(nla), alen, prefix);
+
+ padlen = nla_padlen(alen);
+ if (padlen > 0) {
+ prefix_line(ofd, prefix);
+ fprintf(ofd, " [PADDING] %d octets\n",
+ padlen);
+ dump_hex(ofd, nla_data(nla) + alen,
+ padlen, prefix);
+ }
+ }
+
+ if (rem) {
+ prefix_line(ofd, prefix);
+ fprintf(ofd, " [LEFTOVER] %d octets\n", rem);
+ }
+}
+
+/**
+ * Dump message in human readable format to file descriptor
+ * @arg msg Message to print
+ * @arg ofd File descriptor.
+ */
+void nl_msg_dump(struct nl_msg *msg, FILE *ofd)
+{
+ struct nlmsghdr *hdr = nlmsg_hdr(msg);
+
+ fprintf(ofd,
+ "-------------------------- BEGIN NETLINK MESSAGE "
+ "---------------------------\n");
+
+ fprintf(ofd, " [HEADER] %Zu octets\n", sizeof(struct nlmsghdr));
+ print_hdr(ofd, msg);
+
+ if (hdr->nlmsg_type == NLMSG_ERROR &&
+ hdr->nlmsg_len >= nlmsg_msg_size(sizeof(struct nlmsgerr))) {
+ struct nl_msg *errmsg;
+ struct nlmsgerr *err = nlmsg_data(hdr);
+
+ fprintf(ofd, " [ERRORMSG] %Zu octets\n", sizeof(*err));
+ fprintf(ofd, " .error = %d \"%s\"\n", err->error,
+ strerror(-err->error));
+ fprintf(ofd, " [ORIGINAL MESSAGE] %Zu octets\n", sizeof(*hdr));
+
+ errmsg = nlmsg_inherit(&err->msg);
+ print_hdr(ofd, errmsg);
+ nlmsg_free(errmsg);
+ } else if (nlmsg_len(hdr) > 0) {
+ struct nl_cache_ops *ops;
+ int payloadlen = nlmsg_len(hdr);
+ int attrlen = 0;
+
+ ops = nl_cache_mngt_associate(nlmsg_get_proto(msg),
+ hdr->nlmsg_type);
+ if (ops) {
+ attrlen = nlmsg_attrlen(hdr, ops->co_hdrsize);
+ payloadlen -= attrlen;
+ }
+
+ fprintf(ofd, " [PAYLOAD] %d octets\n", payloadlen);
+ dump_hex(ofd, nlmsg_data(hdr), payloadlen, 0);
+
+ if (attrlen) {
+ struct nlattr *attrs;
+ int attrlen;
+
+ attrs = nlmsg_attrdata(hdr, ops->co_hdrsize);
+ attrlen = nlmsg_attrlen(hdr, ops->co_hdrsize);
+ dump_attrs(ofd, attrs, attrlen, 0);
+ }
+ }
+
+ fprintf(ofd,
+ "--------------------------- END NETLINK MESSAGE "
+ "---------------------------\n");
+}
+
+/** @} */
+
+/** @} */
diff --git a/lib/netfilter/ct.c b/lib/netfilter/ct.c
new file mode 100644
index 0000000..24b67fd
--- /dev/null
+++ b/lib/netfilter/ct.c
@@ -0,0 +1,465 @@
+/*
+ * lib/netfilter/ct.c Conntrack
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ * Copyright (c) 2007 Philip Craig <philipc@snapgear.com>
+ * Copyright (c) 2007 Secure Computing Corporation
+ */
+
+/**
+ * @ingroup nfnl
+ * @defgroup ct Conntrack
+ * @brief
+ * @{
+ */
+
+#include <byteswap.h>
+#include <sys/types.h>
+#include <linux/netfilter/nfnetlink_conntrack.h>
+
+#include <netlink-local.h>
+#include <netlink/attr.h>
+#include <netlink/netfilter/nfnl.h>
+#include <netlink/netfilter/ct.h>
+
+static struct nl_cache_ops nfnl_ct_ops;
+
+#if __BYTE_ORDER == __BIG_ENDIAN
+static uint64_t ntohll(uint64_t x)
+{
+ return x;
+}
+#elif __BYTE_ORDER == __LITTLE_ENDIAN
+static uint64_t ntohll(uint64_t x)
+{
+ return __bswap_64(x);
+}
+#endif
+
+static struct nla_policy ct_policy[CTA_MAX+1] = {
+ [CTA_TUPLE_ORIG] = { .type = NLA_NESTED },
+ [CTA_TUPLE_REPLY] = { .type = NLA_NESTED },
+ [CTA_STATUS] = { .type = NLA_U32 },
+ [CTA_PROTOINFO] = { .type = NLA_NESTED },
+ //[CTA_HELP]
+ //[CTA_NAT_SRC]
+ [CTA_TIMEOUT] = { .type = NLA_U32 },
+ [CTA_MARK] = { .type = NLA_U32 },
+ [CTA_COUNTERS_ORIG] = { .type = NLA_NESTED },
+ [CTA_COUNTERS_REPLY] = { .type = NLA_NESTED },
+ [CTA_USE] = { .type = NLA_U32 },
+ [CTA_ID] = { .type = NLA_U32 },
+ //[CTA_NAT_DST]
+};
+
+static struct nla_policy ct_tuple_policy[CTA_TUPLE_MAX+1] = {
+ [CTA_TUPLE_IP] = { .type = NLA_NESTED },
+ [CTA_TUPLE_PROTO] = { .type = NLA_NESTED },
+};
+
+static struct nla_policy ct_ip_policy[CTA_IP_MAX+1] = {
+ [CTA_IP_V4_SRC] = { .type = NLA_U32 },
+ [CTA_IP_V4_DST] = { .type = NLA_U32 },
+ [CTA_IP_V6_SRC] = { .minlen = 16 },
+ [CTA_IP_V6_DST] = { .minlen = 16 },
+};
+
+static struct nla_policy ct_proto_policy[CTA_PROTO_MAX+1] = {
+ [CTA_PROTO_NUM] = { .type = NLA_U8 },
+ [CTA_PROTO_SRC_PORT] = { .type = NLA_U16 },
+ [CTA_PROTO_DST_PORT] = { .type = NLA_U16 },
+ [CTA_PROTO_ICMP_ID] = { .type = NLA_U16 },
+ [CTA_PROTO_ICMP_TYPE] = { .type = NLA_U8 },
+ [CTA_PROTO_ICMP_CODE] = { .type = NLA_U8 },
+ [CTA_PROTO_ICMPV6_ID] = { .type = NLA_U16 },
+ [CTA_PROTO_ICMPV6_TYPE] = { .type = NLA_U8 },
+ [CTA_PROTO_ICMPV6_CODE] = { .type = NLA_U8 },
+};
+
+static struct nla_policy ct_protoinfo_policy[CTA_PROTOINFO_MAX+1] = {
+ [CTA_PROTOINFO_TCP] = { .type = NLA_NESTED },
+};
+
+static struct nla_policy ct_protoinfo_tcp_policy[CTA_PROTOINFO_TCP_MAX+1] = {
+ [CTA_PROTOINFO_TCP_STATE] = { .type = NLA_U8 },
+ [CTA_PROTOINFO_TCP_WSCALE_ORIGINAL] = { .type = NLA_U8 },
+ [CTA_PROTOINFO_TCP_WSCALE_REPLY] = { .type = NLA_U8 },
+ [CTA_PROTOINFO_TCP_FLAGS_ORIGINAL] = { .minlen = 2 },
+ [CTA_PROTOINFO_TCP_FLAGS_REPLY] = { .minlen = 2 },
+
+};
+
+static struct nla_policy ct_counters_policy[CTA_COUNTERS_MAX+1] = {
+ [CTA_COUNTERS_PACKETS] = { .type = NLA_U64 },
+ [CTA_COUNTERS_BYTES] = { .type = NLA_U64 },
+ [CTA_COUNTERS32_PACKETS]= { .type = NLA_U32 },
+ [CTA_COUNTERS32_BYTES] = { .type = NLA_U32 },
+};
+
+static int ct_parse_ip(struct nfnl_ct *ct, int repl, struct nlattr *attr)
+{
+ struct nlattr *tb[CTA_IP_MAX+1];
+ struct nl_addr *addr;
+ int err;
+
+ err = nla_parse_nested(tb, CTA_IP_MAX, attr, ct_ip_policy);
+ if (err < 0)
+ goto errout;
+
+ if (tb[CTA_IP_V4_SRC]) {
+ addr = nla_get_addr(tb[CTA_IP_V4_SRC], AF_INET);
+ if (addr == NULL)
+ goto errout_errno;
+ err = nfnl_ct_set_src(ct, repl, addr);
+ nl_addr_put(addr);
+ if (err < 0)
+ goto errout;
+ }
+ if (tb[CTA_IP_V4_DST]) {
+ addr = nla_get_addr(tb[CTA_IP_V4_DST], AF_INET);
+ if (addr == NULL)
+ goto errout_errno;
+ err = nfnl_ct_set_dst(ct, repl, addr);
+ nl_addr_put(addr);
+ if (err < 0)
+ goto errout;
+ }
+ if (tb[CTA_IP_V6_SRC]) {
+ addr = nla_get_addr(tb[CTA_IP_V6_SRC], AF_INET6);
+ if (addr == NULL)
+ goto errout_errno;
+ err = nfnl_ct_set_src(ct, repl, addr);
+ nl_addr_put(addr);
+ if (err < 0)
+ goto errout;
+ }
+ if (tb[CTA_IP_V6_DST]) {
+ addr = nla_get_addr(tb[CTA_IP_V6_DST], AF_INET6);
+ if (addr == NULL)
+ goto errout_errno;
+ err = nfnl_ct_set_dst(ct, repl, addr);
+ nl_addr_put(addr);
+ if (err < 0)
+ goto errout;
+ }
+
+ return 0;
+
+errout_errno:
+ return nl_get_errno();
+errout:
+ return err;
+}
+
+static int ct_parse_proto(struct nfnl_ct *ct, int repl, struct nlattr *attr)
+{
+ struct nlattr *tb[CTA_PROTO_MAX+1];
+ int err;
+
+ err = nla_parse_nested(tb, CTA_PROTO_MAX, attr, ct_proto_policy);
+ if (err < 0)
+ return err;
+
+ if (!repl && tb[CTA_PROTO_NUM])
+ nfnl_ct_set_proto(ct, nla_get_u8(tb[CTA_PROTO_NUM]));
+ if (tb[CTA_PROTO_SRC_PORT])
+ nfnl_ct_set_src_port(ct, repl,
+ nla_get_u16(tb[CTA_PROTO_SRC_PORT]));
+ if (tb[CTA_PROTO_DST_PORT])
+ nfnl_ct_set_dst_port(ct, repl,
+ nla_get_u16(tb[CTA_PROTO_DST_PORT]));
+ if (tb[CTA_PROTO_ICMP_ID])
+ nfnl_ct_set_icmp_id(ct, repl,
+ nla_get_u16(tb[CTA_PROTO_ICMP_ID]));
+ if (tb[CTA_PROTO_ICMP_TYPE])
+ nfnl_ct_set_icmp_type(ct, repl,
+ nla_get_u8(tb[CTA_PROTO_ICMP_TYPE]));
+ if (tb[CTA_PROTO_ICMP_CODE])
+ nfnl_ct_set_icmp_code(ct, repl,
+ nla_get_u8(tb[CTA_PROTO_ICMP_CODE]));
+
+ return 0;
+}
+
+static int ct_parse_tuple(struct nfnl_ct *ct, int repl, struct nlattr *attr)
+{
+ struct nlattr *tb[CTA_TUPLE_MAX+1];
+ int err;
+
+ err = nla_parse_nested(tb, CTA_TUPLE_MAX, attr, ct_tuple_policy);
+ if (err < 0)
+ return err;
+
+ if (tb[CTA_TUPLE_IP]) {
+ err = ct_parse_ip(ct, repl, tb[CTA_TUPLE_IP]);
+ if (err < 0)
+ return err;
+ }
+
+ if (tb[CTA_TUPLE_PROTO]) {
+ err = ct_parse_proto(ct, repl, tb[CTA_TUPLE_PROTO]);
+ if (err < 0)
+ return err;
+ }
+
+ return 0;
+}
+
+static int ct_parse_protoinfo_tcp(struct nfnl_ct *ct, struct nlattr *attr)
+{
+ struct nlattr *tb[CTA_PROTOINFO_TCP_MAX+1];
+ int err;
+
+ err = nla_parse_nested(tb, CTA_PROTOINFO_TCP_MAX, attr,
+ ct_protoinfo_tcp_policy);
+ if (err < 0)
+ return err;
+
+ if (tb[CTA_PROTOINFO_TCP_STATE])
+ nfnl_ct_set_tcp_state(ct,
+ nla_get_u8(tb[CTA_PROTOINFO_TCP_STATE]));
+
+ return 0;
+}
+
+static int ct_parse_protoinfo(struct nfnl_ct *ct, struct nlattr *attr)
+{
+ struct nlattr *tb[CTA_PROTOINFO_MAX+1];
+ int err;
+
+ err = nla_parse_nested(tb, CTA_PROTOINFO_MAX, attr,
+ ct_protoinfo_policy);
+ if (err < 0)
+ return err;
+
+ if (tb[CTA_PROTOINFO_TCP]) {
+ err = ct_parse_protoinfo_tcp(ct, tb[CTA_PROTOINFO_TCP]);
+ if (err < 0)
+ return err;
+ }
+
+ return 0;
+}
+
+static int ct_parse_counters(struct nfnl_ct *ct, int repl, struct nlattr *attr)
+{
+ struct nlattr *tb[CTA_COUNTERS_MAX+1];
+ int err;
+
+ err = nla_parse_nested(tb, CTA_COUNTERS_MAX, attr, ct_counters_policy);
+ if (err < 0)
+ return err;
+
+ if (tb[CTA_COUNTERS_PACKETS])
+ nfnl_ct_set_packets(ct, repl,
+ ntohll(nla_get_u64(tb[CTA_COUNTERS_PACKETS])));
+ if (tb[CTA_COUNTERS32_PACKETS])
+ nfnl_ct_set_packets(ct, repl,
+ ntohl(nla_get_u32(tb[CTA_COUNTERS32_PACKETS])));
+ if (tb[CTA_COUNTERS_BYTES])
+ nfnl_ct_set_bytes(ct, repl,
+ ntohll(nla_get_u64(tb[CTA_COUNTERS_BYTES])));
+ if (tb[CTA_COUNTERS32_BYTES])
+ nfnl_ct_set_bytes(ct, repl,
+ ntohl(nla_get_u32(tb[CTA_COUNTERS32_BYTES])));
+
+ return 0;
+}
+
+int nfnlmsg_ct_group(struct nlmsghdr *nlh)
+{
+ switch (nfnlmsg_subtype(nlh)) {
+ case IPCTNL_MSG_CT_NEW:
+ if (nlh->nlmsg_flags & (NLM_F_CREATE|NLM_F_EXCL))
+ return NFNLGRP_CONNTRACK_NEW;
+ else
+ return NFNLGRP_CONNTRACK_UPDATE;
+ case IPCTNL_MSG_CT_DELETE:
+ return NFNLGRP_CONNTRACK_DESTROY;
+ default:
+ return NFNLGRP_NONE;
+ }
+}
+
+struct nfnl_ct *nfnlmsg_ct_parse(struct nlmsghdr *nlh)
+{
+ struct nfnl_ct *ct;
+ struct nlattr *tb[CTA_MAX+1];
+ int err;
+
+ ct = nfnl_ct_alloc();
+ if (!ct)
+ return NULL;
+
+ ct->ce_msgtype = nlh->nlmsg_type;
+
+ err = nlmsg_parse(nlh, sizeof(struct nfgenmsg), tb, CTA_MAX,
+ ct_policy);
+ if (err < 0)
+ goto errout;
+
+ nfnl_ct_set_family(ct, nfnlmsg_family(nlh));
+
+ if (tb[CTA_TUPLE_ORIG]) {
+ err = ct_parse_tuple(ct, 0, tb[CTA_TUPLE_ORIG]);
+ if (err < 0)
+ goto errout;
+ }
+ if (tb[CTA_TUPLE_REPLY]) {
+ err = ct_parse_tuple(ct, 1, tb[CTA_TUPLE_REPLY]);
+ if (err < 0)
+ goto errout;
+ }
+
+ if (tb[CTA_PROTOINFO]) {
+ err = ct_parse_protoinfo(ct, tb[CTA_PROTOINFO]);
+ if (err < 0)
+ goto errout;
+ }
+
+ if (tb[CTA_STATUS])
+ nfnl_ct_set_status(ct, ntohl(nla_get_u32(tb[CTA_STATUS])));
+ if (tb[CTA_TIMEOUT])
+ nfnl_ct_set_timeout(ct, ntohl(nla_get_u32(tb[CTA_TIMEOUT])));
+ if (tb[CTA_MARK])
+ nfnl_ct_set_mark(ct, ntohl(nla_get_u32(tb[CTA_MARK])));
+ if (tb[CTA_USE])
+ nfnl_ct_set_use(ct, ntohl(nla_get_u32(tb[CTA_USE])));
+ if (tb[CTA_ID])
+ nfnl_ct_set_id(ct, ntohl(nla_get_u32(tb[CTA_ID])));
+
+ if (tb[CTA_COUNTERS_ORIG]) {
+ err = ct_parse_counters(ct, 0, tb[CTA_COUNTERS_ORIG]);
+ if (err < 0)
+ goto errout;
+ }
+
+ if (tb[CTA_COUNTERS_REPLY]) {
+ err = ct_parse_counters(ct, 1, tb[CTA_COUNTERS_REPLY]);
+ if (err < 0)
+ goto errout;
+ }
+
+ return ct;
+
+errout:
+ nfnl_ct_put(ct);
+ return NULL;
+}
+
+static int ct_msg_parser(struct nl_cache_ops *ops, struct sockaddr_nl *who,
+ struct nlmsghdr *nlh, void *arg)
+{
+ struct nl_parser_param *pp = arg;
+ struct nfnl_ct *ct;
+ int err;
+
+ ct = nfnlmsg_ct_parse(nlh);
+ if (ct == NULL)
+ goto errout_errno;
+
+ err = pp->pp_cb((struct nl_object *) ct, pp);
+ if (err < 0)
+ goto errout;
+
+ return P_ACCEPT;
+
+errout_errno:
+ err = nl_get_errno();
+errout:
+ nfnl_ct_put(ct);
+ return err;
+}
+
+int nfnl_ct_dump_request(struct nl_handle *h)
+{
+ return nfnl_send_simple(h, NFNL_SUBSYS_CTNETLINK, IPCTNL_MSG_CT_GET,
+ NLM_F_DUMP, AF_UNSPEC, 0);
+}
+
+static int ct_request_update(struct nl_cache *c, struct nl_handle *h)
+{
+ return nfnl_ct_dump_request(h);
+}
+
+/**
+ * @name Cache Management
+ * @{
+ */
+
+/**
+ * Build a conntrack cache holding all conntrack currently in the kernel
+ * @arg handle netlink handle
+ *
+ * Allocates a new cache, initializes it properly and updates it to
+ * contain all conntracks currently in the kernel.
+ *
+ * @note The caller is responsible for destroying and freeing the
+ * cache after using it.
+ * @return The cache or NULL if an error has occured.
+ */
+struct nl_cache *nfnl_ct_alloc_cache(struct nl_handle *handle)
+{
+ struct nl_cache *cache;
+
+ cache = nl_cache_alloc(&nfnl_ct_ops);
+ if (!cache)
+ return NULL;
+
+ if (handle && nl_cache_refill(handle, cache) < 0) {
+ free(cache);
+ return NULL;
+ }
+
+ return cache;
+}
+
+/** @} */
+
+/**
+ * @name Conntrack Addition
+ * @{
+ */
+
+/** @} */
+
+static struct nl_af_group ct_groups[] = {
+ { AF_UNSPEC, NFNLGRP_CONNTRACK_NEW },
+ { AF_UNSPEC, NFNLGRP_CONNTRACK_UPDATE },
+ { AF_UNSPEC, NFNLGRP_CONNTRACK_DESTROY },
+ { END_OF_GROUP_LIST },
+};
+
+#define NFNLMSG_CT_TYPE(type) NFNLMSG_TYPE(NFNL_SUBSYS_CTNETLINK, (type))
+static struct nl_cache_ops nfnl_ct_ops = {
+ .co_name = "netfilter/ct",
+ .co_hdrsize = NFNL_HDRLEN,
+ .co_msgtypes = {
+ { NFNLMSG_CT_TYPE(IPCTNL_MSG_CT_NEW), NL_ACT_NEW, "new" },
+ { NFNLMSG_CT_TYPE(IPCTNL_MSG_CT_GET), NL_ACT_GET, "get" },
+ { NFNLMSG_CT_TYPE(IPCTNL_MSG_CT_DELETE), NL_ACT_DEL, "del" },
+ END_OF_MSGTYPES_LIST,
+ },
+ .co_protocol = NETLINK_NETFILTER,
+ .co_groups = ct_groups,
+ .co_request_update = ct_request_update,
+ .co_msg_parser = ct_msg_parser,
+ .co_obj_ops = &ct_obj_ops,
+};
+
+static void __init ct_init(void)
+{
+ nl_cache_mngt_register(&nfnl_ct_ops);
+}
+
+static void __exit ct_exit(void)
+{
+ nl_cache_mngt_unregister(&nfnl_ct_ops);
+}
+
+/** @} */
diff --git a/lib/netfilter/ct_obj.c b/lib/netfilter/ct_obj.c
new file mode 100644
index 0000000..1f4284e
--- /dev/null
+++ b/lib/netfilter/ct_obj.c
@@ -0,0 +1,667 @@
+/*
+ * lib/netfilter/ct_obj.c Conntrack Object
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ * Copyright (c) 2007 Philip Craig <philipc@snapgear.com>
+ * Copyright (c) 2007 Secure Computing Corporation
+ */
+
+#include <sys/types.h>
+#include <linux/netfilter/nfnetlink_conntrack.h>
+#include <linux/netfilter/nf_conntrack_common.h>
+#include <linux/netfilter/nf_conntrack_tcp.h>
+
+#include <netlink-local.h>
+#include <netlink/netfilter/nfnl.h>
+#include <netlink/netfilter/ct.h>
+
+/** @cond SKIP */
+#define CT_ATTR_FAMILY (1UL << 0)
+#define CT_ATTR_PROTO (1UL << 1)
+
+#define CT_ATTR_TCP_STATE (1UL << 2)
+
+#define CT_ATTR_STATUS (1UL << 3)
+#define CT_ATTR_TIMEOUT (1UL << 4)
+#define CT_ATTR_MARK (1UL << 5)
+#define CT_ATTR_USE (1UL << 6)
+#define CT_ATTR_ID (1UL << 7)
+
+#define CT_ATTR_ORIG_SRC (1UL << 8)
+#define CT_ATTR_ORIG_DST (1UL << 9)
+#define CT_ATTR_ORIG_SRC_PORT (1UL << 10)
+#define CT_ATTR_ORIG_DST_PORT (1UL << 11)
+#define CT_ATTR_ORIG_ICMP_ID (1UL << 12)
+#define CT_ATTR_ORIG_ICMP_TYPE (1UL << 13)
+#define CT_ATTR_ORIG_ICMP_CODE (1UL << 14)
+#define CT_ATTR_ORIG_PACKETS (1UL << 15)
+#define CT_ATTR_ORIG_BYTES (1UL << 16)
+
+#define CT_ATTR_REPL_SRC (1UL << 17)
+#define CT_ATTR_REPL_DST (1UL << 18)
+#define CT_ATTR_REPL_SRC_PORT (1UL << 19)
+#define CT_ATTR_REPL_DST_PORT (1UL << 20)
+#define CT_ATTR_REPL_ICMP_ID (1UL << 21)
+#define CT_ATTR_REPL_ICMP_TYPE (1UL << 22)
+#define CT_ATTR_REPL_ICMP_CODE (1UL << 23)
+#define CT_ATTR_REPL_PACKETS (1UL << 24)
+#define CT_ATTR_REPL_BYTES (1UL << 25)
+/** @endcond */
+
+static void ct_free_data(struct nl_object *c)
+{
+ struct nfnl_ct *ct = (struct nfnl_ct *) c;
+
+ if (ct == NULL)
+ return;
+
+ nl_addr_put(ct->ct_orig.src);
+ nl_addr_put(ct->ct_orig.dst);
+ nl_addr_put(ct->ct_repl.src);
+ nl_addr_put(ct->ct_repl.dst);
+}
+
+static int ct_clone(struct nl_object *_dst, struct nl_object *_src)
+{
+ struct nfnl_ct *dst = (struct nfnl_ct *) _dst;
+ struct nfnl_ct *src = (struct nfnl_ct *) _src;
+ struct nl_addr *addr;
+
+ if (src->ct_orig.src) {
+ addr = nl_addr_clone(src->ct_orig.src);
+ if (!addr)
+ goto errout;
+ dst->ct_orig.src = addr;
+ }
+
+ if (src->ct_orig.dst) {
+ addr = nl_addr_clone(src->ct_orig.dst);
+ if (!addr)
+ goto errout;
+ dst->ct_orig.dst = addr;
+ }
+
+ if (src->ct_repl.src) {
+ addr = nl_addr_clone(src->ct_repl.src);
+ if (!addr)
+ goto errout;
+ dst->ct_repl.src = addr;
+ }
+
+ if (src->ct_repl.dst) {
+ addr = nl_addr_clone(src->ct_repl.dst);
+ if (!addr)
+ goto errout;
+ dst->ct_repl.dst = addr;
+ }
+
+ return 0;
+errout:
+ return nl_get_errno();
+}
+
+static void ct_dump_dir(struct nfnl_ct *ct, int repl,
+ struct nl_dump_params *p)
+{
+ struct nl_addr *addr;
+ char addrbuf[64];
+
+ addr = nfnl_ct_get_src(ct, repl);
+ if (addr)
+ dp_dump(p, "src=%s ",
+ nl_addr2str(addr, addrbuf, sizeof(addrbuf)));
+
+ addr = nfnl_ct_get_dst(ct, repl);
+ if (addr)
+ dp_dump(p, "dst=%s ",
+ nl_addr2str(addr, addrbuf, sizeof(addrbuf)));
+
+ if (nfnl_ct_test_src_port(ct, repl))
+ dp_dump(p, "sport=%u ", ntohs(nfnl_ct_get_src_port(ct, repl)));
+ if (nfnl_ct_test_dst_port(ct, repl))
+ dp_dump(p, "dport=%u ", ntohs(nfnl_ct_get_dst_port(ct, repl)));
+
+ if (nfnl_ct_test_icmp_type(ct, repl))
+ dp_dump(p, "type=%d ", nfnl_ct_get_icmp_type(ct, repl));
+ if (nfnl_ct_test_icmp_type(ct, repl))
+ dp_dump(p, "code=%d ", nfnl_ct_get_icmp_code(ct, repl));
+ if (nfnl_ct_test_icmp_type(ct, repl))
+ dp_dump(p, "id=%d ", ntohs(nfnl_ct_get_icmp_id(ct, repl)));
+
+ if (nfnl_ct_test_packets(ct, repl))
+ dp_dump(p, "packets=%llu ", nfnl_ct_get_packets(ct, repl));
+ if (nfnl_ct_test_bytes(ct, repl))
+ dp_dump(p, "bytes=%llu ", nfnl_ct_get_bytes(ct, repl));
+}
+
+/* Compatible with /proc/net/nf_conntrack */
+static int ct_dump(struct nl_object *a, struct nl_dump_params *p)
+{
+ struct nfnl_ct *ct = (struct nfnl_ct *) a;
+ char buf[64];
+ uint32_t status;
+ uint8_t family;
+ uint8_t proto;
+
+ family = nfnl_ct_get_family(ct);
+ dp_dump(p, "%-8s %u ", nl_af2str(family, buf, sizeof(buf)), family);
+
+ if (nfnl_ct_test_proto(ct)) {
+ proto = nfnl_ct_get_proto(ct);
+ dp_dump(p, "%-8s %u ",
+ nl_ip_proto2str(proto, buf, sizeof(buf)), proto);
+ }
+
+ if (nfnl_ct_test_timeout(ct))
+ dp_dump(p, "%ld ", nfnl_ct_get_timeout(ct));
+
+ if (nfnl_ct_test_tcp_state(ct))
+ dp_dump(p, "%s ",
+ nfnl_ct_tcp_state2str(nfnl_ct_get_tcp_state(ct),
+ buf, sizeof(buf)));
+
+ ct_dump_dir(ct, 0, p);
+
+ status = nfnl_ct_get_status(ct);
+ if (!(status & IPS_SEEN_REPLY))
+ dp_dump(p, "[UNREPLIED] ");
+
+ ct_dump_dir(ct, 1, p);
+
+ if (status & IPS_ASSURED)
+ dp_dump(p, "[ASSURED] ");
+
+ if (nfnl_ct_test_mark(ct))
+ dp_dump(p, "mark=%u ", nfnl_ct_get_mark(ct));
+
+ if (nfnl_ct_test_use(ct))
+ dp_dump(p, "use=%u ", nfnl_ct_get_use(ct));
+
+ dp_dump(p, "\n");
+
+ return 1;
+}
+
+static int ct_compare(struct nl_object *_a, struct nl_object *_b,
+ uint32_t attrs, int flags)
+{
+ struct nfnl_ct *a = (struct nfnl_ct *) _a;
+ struct nfnl_ct *b = (struct nfnl_ct *) _b;
+ int diff = 0;
+
+#define CT_DIFF(ATTR, EXPR) ATTR_DIFF(attrs, CT_ATTR_##ATTR, a, b, EXPR)
+#define CT_DIFF_VAL(ATTR, FIELD) CT_DIFF(ATTR, a->FIELD != b->FIELD)
+#define CT_DIFF_ADDR(ATTR, FIELD) \
+ ((flags & LOOSE_FLAG_COMPARISON) \
+ ? CT_DIFF(ATTR, nl_addr_cmp_prefix(a->FIELD, b->FIELD)) \
+ : CT_DIFF(ATTR, nl_addr_cmp(a->FIELD, b->FIELD)))
+
+ diff |= CT_DIFF_VAL(FAMILY, ct_family);
+ diff |= CT_DIFF_VAL(PROTO, ct_proto);
+ diff |= CT_DIFF_VAL(TCP_STATE, ct_protoinfo.tcp.state);
+ diff |= CT_DIFF_VAL(STATUS, ct_status);
+ diff |= CT_DIFF_VAL(TIMEOUT, ct_timeout);
+ diff |= CT_DIFF_VAL(MARK, ct_mark);
+ diff |= CT_DIFF_VAL(USE, ct_use);
+ diff |= CT_DIFF_VAL(ID, ct_id);
+ diff |= CT_DIFF_ADDR(ORIG_SRC, ct_orig.src);
+ diff |= CT_DIFF_ADDR(ORIG_DST, ct_orig.dst);
+ diff |= CT_DIFF_VAL(ORIG_SRC_PORT, ct_orig.proto.port.src);
+ diff |= CT_DIFF_VAL(ORIG_DST_PORT, ct_orig.proto.port.dst);
+ diff |= CT_DIFF_VAL(ORIG_ICMP_ID, ct_orig.proto.icmp.id);
+ diff |= CT_DIFF_VAL(ORIG_ICMP_TYPE, ct_orig.proto.icmp.type);
+ diff |= CT_DIFF_VAL(ORIG_ICMP_CODE, ct_orig.proto.icmp.code);
+ diff |= CT_DIFF_VAL(ORIG_PACKETS, ct_orig.packets);
+ diff |= CT_DIFF_VAL(ORIG_BYTES, ct_orig.bytes);
+ diff |= CT_DIFF_ADDR(REPL_SRC, ct_repl.src);
+ diff |= CT_DIFF_ADDR(ORIG_DST, ct_repl.dst);
+ diff |= CT_DIFF_VAL(REPL_SRC_PORT, ct_repl.proto.port.src);
+ diff |= CT_DIFF_VAL(REPL_DST_PORT, ct_repl.proto.port.dst);
+ diff |= CT_DIFF_VAL(REPL_ICMP_ID, ct_repl.proto.icmp.id);
+ diff |= CT_DIFF_VAL(REPL_ICMP_TYPE, ct_repl.proto.icmp.type);
+ diff |= CT_DIFF_VAL(REPL_ICMP_CODE, ct_repl.proto.icmp.code);
+ diff |= CT_DIFF_VAL(REPL_PACKETS, ct_repl.packets);
+ diff |= CT_DIFF_VAL(REPL_BYTES, ct_repl.bytes);
+
+#undef CT_DIFF
+#undef CT_DIFF_VAL
+#undef CT_DIFF_ADDR
+
+ return diff;
+}
+
+static struct trans_tbl ct_attrs[] = {
+ __ADD(CT_ATTR_FAMILY, family)
+ __ADD(CT_ATTR_PROTO, proto)
+ __ADD(CT_ATTR_TCP_STATE, tcpstate)
+ __ADD(CT_ATTR_STATUS, status)
+ __ADD(CT_ATTR_TIMEOUT, timeout)
+ __ADD(CT_ATTR_MARK, mark)
+ __ADD(CT_ATTR_USE, use)
+ __ADD(CT_ATTR_ID, id)
+ __ADD(CT_ATTR_ORIG_SRC, origsrc)
+ __ADD(CT_ATTR_ORIG_DST, origdst)
+ __ADD(CT_ATTR_ORIG_SRC_PORT, origsrcport)
+ __ADD(CT_ATTR_ORIG_DST_PORT, origdstport)
+ __ADD(CT_ATTR_ORIG_ICMP_ID, origicmpid)
+ __ADD(CT_ATTR_ORIG_ICMP_TYPE, origicmptype)
+ __ADD(CT_ATTR_ORIG_ICMP_CODE, origicmpcode)
+ __ADD(CT_ATTR_ORIG_PACKETS, origpackets)
+ __ADD(CT_ATTR_ORIG_BYTES, origbytes)
+ __ADD(CT_ATTR_REPL_SRC, replysrc)
+ __ADD(CT_ATTR_REPL_DST, replydst)
+ __ADD(CT_ATTR_REPL_SRC_PORT, replysrcport)
+ __ADD(CT_ATTR_REPL_DST_PORT, replydstport)
+ __ADD(CT_ATTR_REPL_ICMP_ID, replyicmpid)
+ __ADD(CT_ATTR_REPL_ICMP_TYPE, replyicmptype)
+ __ADD(CT_ATTR_REPL_ICMP_CODE, replyicmpcode)
+ __ADD(CT_ATTR_REPL_PACKETS, replypackets)
+ __ADD(CT_ATTR_REPL_BYTES, replybytes)
+};
+
+static char *ct_attrs2str(int attrs, char *buf, size_t len)
+{
+ return __flags2str(attrs, buf, len, ct_attrs, ARRAY_SIZE(ct_attrs));
+}
+
+/**
+ * @name Allocation/Freeing
+ * @{
+ */
+
+struct nfnl_ct *nfnl_ct_alloc(void)
+{
+ return (struct nfnl_ct *) nl_object_alloc(&ct_obj_ops);
+}
+
+void nfnl_ct_get(struct nfnl_ct *ct)
+{
+ nl_object_get((struct nl_object *) ct);
+}
+
+void nfnl_ct_put(struct nfnl_ct *ct)
+{
+ nl_object_put((struct nl_object *) ct);
+}
+
+/** @} */
+
+/**
+ * @name Attributes
+ * @{
+ */
+
+void nfnl_ct_set_family(struct nfnl_ct *ct, uint8_t family)
+{
+ ct->ct_family = family;
+ ct->ce_mask |= CT_ATTR_FAMILY;
+}
+
+uint8_t nfnl_ct_get_family(const struct nfnl_ct *ct)
+{
+ if (ct->ce_mask & CT_ATTR_FAMILY)
+ return ct->ct_family;
+ else
+ return AF_UNSPEC;
+}
+
+void nfnl_ct_set_proto(struct nfnl_ct *ct, uint8_t proto)
+{
+ ct->ct_proto = proto;
+ ct->ce_mask |= CT_ATTR_PROTO;
+}
+
+int nfnl_ct_test_proto(const struct nfnl_ct *ct)
+{
+ return !!(ct->ce_mask & CT_ATTR_PROTO);
+}
+
+uint8_t nfnl_ct_get_proto(const struct nfnl_ct *ct)
+{
+ return ct->ct_proto;
+}
+
+void nfnl_ct_set_tcp_state(struct nfnl_ct *ct, uint8_t state)
+{
+ ct->ct_protoinfo.tcp.state = state;
+ ct->ce_mask |= CT_ATTR_TCP_STATE;
+}
+
+int nfnl_ct_test_tcp_state(const struct nfnl_ct *ct)
+{
+ return !!(ct->ce_mask & CT_ATTR_TCP_STATE);
+}
+
+uint8_t nfnl_ct_get_tcp_state(const struct nfnl_ct *ct)
+{
+ return ct->ct_protoinfo.tcp.state;
+}
+
+static struct trans_tbl tcp_states[] = {
+ __ADD(TCP_CONNTRACK_NONE,NONE)
+ __ADD(TCP_CONNTRACK_SYN_SENT,SYN_SENT)
+ __ADD(TCP_CONNTRACK_SYN_RECV,SYN_RECV)
+ __ADD(TCP_CONNTRACK_ESTABLISHED,ESTABLISHED)
+ __ADD(TCP_CONNTRACK_FIN_WAIT,FIN_WAIT)
+ __ADD(TCP_CONNTRACK_CLOSE_WAIT,CLOSE_WAIT)
+ __ADD(TCP_CONNTRACK_LAST_ACK,LAST_ACK)
+ __ADD(TCP_CONNTRACK_TIME_WAIT,TIME_WAIT)
+ __ADD(TCP_CONNTRACK_CLOSE,CLOSE)
+ __ADD(TCP_CONNTRACK_LISTEN,LISTEN)
+};
+
+char *nfnl_ct_tcp_state2str(uint8_t state, char *buf, size_t len)
+{
+ return __type2str(state, buf, len, tcp_states, ARRAY_SIZE(tcp_states));
+}
+
+int nfnl_ct_str2tcp_state(const char *name)
+{
+ return __str2type(name, tcp_states, ARRAY_SIZE(tcp_states));
+}
+
+void nfnl_ct_set_status(struct nfnl_ct *ct, uint32_t status)
+{
+ ct->ct_status = status;
+ ct->ce_mask |= CT_ATTR_STATUS;
+}
+
+int nfnl_ct_test_status(const struct nfnl_ct *ct)
+{
+ return !!(ct->ce_mask & CT_ATTR_STATUS);
+}
+
+uint32_t nfnl_ct_get_status(const struct nfnl_ct *ct)
+{
+ return ct->ct_status;
+}
+
+void nfnl_ct_set_timeout(struct nfnl_ct *ct, uint32_t timeout)
+{
+ ct->ct_timeout = timeout;
+ ct->ce_mask |= CT_ATTR_TIMEOUT;
+}
+
+int nfnl_ct_test_timeout(const struct nfnl_ct *ct)
+{
+ return !!(ct->ce_mask & CT_ATTR_TIMEOUT);
+}
+
+uint32_t nfnl_ct_get_timeout(const struct nfnl_ct *ct)
+{
+ return ct->ct_timeout;
+}
+
+void nfnl_ct_set_mark(struct nfnl_ct *ct, uint32_t mark)
+{
+ ct->ct_mark = mark;
+ ct->ce_mask |= CT_ATTR_MARK;
+}
+
+int nfnl_ct_test_mark(const struct nfnl_ct *ct)
+{
+ return !!(ct->ce_mask & CT_ATTR_MARK);
+}
+
+uint32_t nfnl_ct_get_mark(const struct nfnl_ct *ct)
+{
+ return ct->ct_mark;
+}
+
+void nfnl_ct_set_use(struct nfnl_ct *ct, uint32_t use)
+{
+ ct->ct_use = use;
+ ct->ce_mask |= CT_ATTR_USE;
+}
+
+int nfnl_ct_test_use(const struct nfnl_ct *ct)
+{
+ return !!(ct->ce_mask & CT_ATTR_USE);
+}
+
+uint32_t nfnl_ct_get_use(const struct nfnl_ct *ct)
+{
+ return ct->ct_use;
+}
+
+void nfnl_ct_set_id(struct nfnl_ct *ct, uint32_t id)
+{
+ ct->ct_id = id;
+ ct->ce_mask |= CT_ATTR_ID;
+}
+
+int nfnl_ct_test_id(const struct nfnl_ct *ct)
+{
+ return !!(ct->ce_mask & CT_ATTR_ID);
+}
+
+uint32_t nfnl_ct_get_id(const struct nfnl_ct *ct)
+{
+ return ct->ct_id;
+}
+
+static int ct_set_addr(struct nfnl_ct *ct, struct nl_addr *addr,
+ int attr, struct nl_addr ** ct_addr)
+{
+ if (ct->ce_mask & CT_ATTR_FAMILY) {
+ if (addr->a_family != ct->ct_family)
+ return nl_error(EINVAL, "Address family mismatch");
+ } else
+ nfnl_ct_set_family(ct, addr->a_family);
+
+ if (*ct_addr)
+ nl_addr_put(*ct_addr);
+
+ nl_addr_get(addr);
+ *ct_addr = addr;
+ ct->ce_mask |= attr;
+
+ return 0;
+}
+
+int nfnl_ct_set_src(struct nfnl_ct *ct, int repl, struct nl_addr *addr)
+{
+ struct nfnl_ct_dir *dir = repl ? &ct->ct_repl : &ct->ct_orig;
+ int attr = repl ? CT_ATTR_REPL_SRC : CT_ATTR_ORIG_SRC;
+ return ct_set_addr(ct, addr, attr, &dir->src);
+}
+
+int nfnl_ct_set_dst(struct nfnl_ct *ct, int repl, struct nl_addr *addr)
+{
+ struct nfnl_ct_dir *dir = repl ? &ct->ct_repl : &ct->ct_orig;
+ int attr = repl ? CT_ATTR_REPL_DST : CT_ATTR_ORIG_DST;
+ return ct_set_addr(ct, addr, attr, &dir->dst);
+}
+
+struct nl_addr *nfnl_ct_get_src(const struct nfnl_ct *ct, int repl)
+{
+ const struct nfnl_ct_dir *dir = repl ? &ct->ct_repl : &ct->ct_orig;
+ int attr = repl ? CT_ATTR_REPL_SRC : CT_ATTR_ORIG_SRC;
+ if (!(ct->ce_mask & attr))
+ return NULL;
+ return dir->src;
+}
+
+struct nl_addr *nfnl_ct_get_dst(const struct nfnl_ct *ct, int repl)
+{
+ const struct nfnl_ct_dir *dir = repl ? &ct->ct_repl : &ct->ct_orig;
+ int attr = repl ? CT_ATTR_REPL_DST : CT_ATTR_ORIG_DST;
+ if (!(ct->ce_mask & attr))
+ return NULL;
+ return dir->dst;
+}
+
+void nfnl_ct_set_src_port(struct nfnl_ct *ct, int repl, uint16_t port)
+{
+ struct nfnl_ct_dir *dir = repl ? &ct->ct_repl : &ct->ct_orig;
+ int attr = repl ? CT_ATTR_REPL_SRC_PORT : CT_ATTR_ORIG_SRC_PORT;
+
+ dir->proto.port.src = port;
+ ct->ce_mask |= attr;
+}
+
+int nfnl_ct_test_src_port(const struct nfnl_ct *ct, int repl)
+{
+ int attr = repl ? CT_ATTR_REPL_SRC_PORT : CT_ATTR_ORIG_SRC_PORT;
+ return !!(ct->ce_mask & attr);
+}
+
+uint16_t nfnl_ct_get_src_port(const struct nfnl_ct *ct, int repl)
+{
+ const struct nfnl_ct_dir *dir = repl ? &ct->ct_repl : &ct->ct_orig;
+
+ return dir->proto.port.src;
+}
+
+void nfnl_ct_set_dst_port(struct nfnl_ct *ct, int repl, uint16_t port)
+{
+ struct nfnl_ct_dir *dir = repl ? &ct->ct_repl : &ct->ct_orig;
+ int attr = repl ? CT_ATTR_REPL_DST_PORT : CT_ATTR_ORIG_DST_PORT;
+
+ dir->proto.port.dst = port;
+ ct->ce_mask |= attr;
+}
+
+int nfnl_ct_test_dst_port(const struct nfnl_ct *ct, int repl)
+{
+ int attr = repl ? CT_ATTR_REPL_DST_PORT : CT_ATTR_ORIG_DST_PORT;
+ return !!(ct->ce_mask & attr);
+}
+
+uint16_t nfnl_ct_get_dst_port(const struct nfnl_ct *ct, int repl)
+{
+ const struct nfnl_ct_dir *dir = repl ? &ct->ct_repl : &ct->ct_orig;
+
+ return dir->proto.port.dst;
+}
+
+void nfnl_ct_set_icmp_id(struct nfnl_ct *ct, int repl, uint16_t id)
+{
+ struct nfnl_ct_dir *dir = repl ? &ct->ct_repl : &ct->ct_orig;
+ int attr = repl ? CT_ATTR_REPL_ICMP_ID : CT_ATTR_ORIG_ICMP_ID;
+
+ dir->proto.icmp.id = id;
+ ct->ce_mask |= attr;
+}
+
+int nfnl_ct_test_icmp_id(const struct nfnl_ct *ct, int repl)
+{
+ int attr = repl ? CT_ATTR_REPL_ICMP_ID : CT_ATTR_ORIG_ICMP_ID;
+ return !!(ct->ce_mask & attr);
+}
+
+uint16_t nfnl_ct_get_icmp_id(const struct nfnl_ct *ct, int repl)
+{
+ const struct nfnl_ct_dir *dir = repl ? &ct->ct_repl : &ct->ct_orig;
+
+ return dir->proto.icmp.id;
+}
+
+void nfnl_ct_set_icmp_type(struct nfnl_ct *ct, int repl, uint8_t type)
+{
+ struct nfnl_ct_dir *dir = repl ? &ct->ct_repl : &ct->ct_orig;
+ int attr = repl ? CT_ATTR_REPL_ICMP_TYPE : CT_ATTR_ORIG_ICMP_TYPE;
+
+ dir->proto.icmp.type = type;
+ ct->ce_mask |= attr;
+}
+
+int nfnl_ct_test_icmp_type(const struct nfnl_ct *ct, int repl)
+{
+ int attr = repl ? CT_ATTR_REPL_ICMP_TYPE : CT_ATTR_ORIG_ICMP_TYPE;
+ return !!(ct->ce_mask & attr);
+}
+
+uint8_t nfnl_ct_get_icmp_type(const struct nfnl_ct *ct, int repl)
+{
+ const struct nfnl_ct_dir *dir = repl ? &ct->ct_repl : &ct->ct_orig;
+
+ return dir->proto.icmp.type;
+}
+
+void nfnl_ct_set_icmp_code(struct nfnl_ct *ct, int repl, uint8_t code)
+{
+ struct nfnl_ct_dir *dir = repl ? &ct->ct_repl : &ct->ct_orig;
+ int attr = repl ? CT_ATTR_REPL_ICMP_CODE : CT_ATTR_ORIG_ICMP_CODE;
+
+ dir->proto.icmp.code = code;
+ ct->ce_mask |= attr;
+}
+
+int nfnl_ct_test_icmp_code(const struct nfnl_ct *ct, int repl)
+{
+ int attr = repl ? CT_ATTR_REPL_ICMP_CODE : CT_ATTR_ORIG_ICMP_CODE;
+ return !!(ct->ce_mask & attr);
+}
+
+uint8_t nfnl_ct_get_icmp_code(const struct nfnl_ct *ct, int repl)
+{
+ const struct nfnl_ct_dir *dir = repl ? &ct->ct_repl : &ct->ct_orig;
+
+ return dir->proto.icmp.code;
+}
+
+void nfnl_ct_set_packets(struct nfnl_ct *ct, int repl, uint64_t packets)
+{
+ struct nfnl_ct_dir *dir = repl ? &ct->ct_repl : &ct->ct_orig;
+ int attr = repl ? CT_ATTR_REPL_PACKETS : CT_ATTR_ORIG_PACKETS;
+
+ dir->packets = packets;
+ ct->ce_mask |= attr;
+}
+
+int nfnl_ct_test_packets(const struct nfnl_ct *ct, int repl)
+{
+ int attr = repl ? CT_ATTR_REPL_PACKETS : CT_ATTR_ORIG_PACKETS;
+ return !!(ct->ce_mask & attr);
+}
+
+uint64_t nfnl_ct_get_packets(const struct nfnl_ct *ct, int repl)
+{
+ const struct nfnl_ct_dir *dir = repl ? &ct->ct_repl : &ct->ct_orig;
+
+ return dir->packets;
+}
+
+void nfnl_ct_set_bytes(struct nfnl_ct *ct, int repl, uint64_t bytes)
+{
+ struct nfnl_ct_dir *dir = repl ? &ct->ct_repl : &ct->ct_orig;
+ int attr = repl ? CT_ATTR_REPL_BYTES : CT_ATTR_ORIG_BYTES;
+
+ dir->bytes = bytes;
+ ct->ce_mask |= attr;
+}
+
+int nfnl_ct_test_bytes(const struct nfnl_ct *ct, int repl)
+{
+ int attr = repl ? CT_ATTR_REPL_BYTES : CT_ATTR_ORIG_BYTES;
+ return !!(ct->ce_mask & attr);
+}
+
+uint64_t nfnl_ct_get_bytes(const struct nfnl_ct *ct, int repl)
+{
+ const struct nfnl_ct_dir *dir = repl ? &ct->ct_repl : &ct->ct_orig;
+
+ return dir->bytes;
+}
+
+/** @} */
+
+struct nl_object_ops ct_obj_ops = {
+ .oo_name = "netfilter/ct",
+ .oo_size = sizeof(struct nfnl_ct),
+ .oo_free_data = ct_free_data,
+ .oo_clone = ct_clone,
+ .oo_dump[NL_DUMP_BRIEF] = ct_dump,
+ .oo_dump[NL_DUMP_FULL] = ct_dump,
+ .oo_dump[NL_DUMP_STATS] = ct_dump,
+ .oo_compare = ct_compare,
+ .oo_attrs2str = ct_attrs2str,
+};
+
+/** @} */
diff --git a/lib/netfilter/log.c b/lib/netfilter/log.c
new file mode 100644
index 0000000..ccc90a8
--- /dev/null
+++ b/lib/netfilter/log.c
@@ -0,0 +1,349 @@
+/*
+ * lib/netfilter/log.c Netfilter Log
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ * Copyright (c) 2007 Philip Craig <philipc@snapgear.com>
+ * Copyright (c) 2007 Secure Computing Corporation
+ */
+
+/**
+ * @ingroup nfnl
+ * @defgroup log Log
+ * @brief
+ * @{
+ */
+
+#include <sys/types.h>
+#include <linux/netfilter/nfnetlink_log.h>
+
+#include <netlink-local.h>
+#include <netlink/attr.h>
+#include <netlink/netfilter/nfnl.h>
+#include <netlink/netfilter/log.h>
+
+static struct nl_cache_ops nfnl_log_ops;
+
+#if __BYTE_ORDER == __BIG_ENDIAN
+static uint64_t ntohll(uint64_t x)
+{
+ return x;
+}
+#elif __BYTE_ORDER == __LITTLE_ENDIAN
+static uint64_t ntohll(uint64_t x)
+{
+ return __bswap_64(x);
+}
+#endif
+
+static struct nla_policy log_policy[NFULA_MAX+1] = {
+ [NFULA_PACKET_HDR] = {
+ .minlen = sizeof(struct nfulnl_msg_packet_hdr)
+ },
+ [NFULA_MARK] = { .type = NLA_U32 },
+ [NFULA_TIMESTAMP] = {
+ .minlen = sizeof(struct nfulnl_msg_packet_timestamp)
+ },
+ [NFULA_IFINDEX_INDEV] = { .type = NLA_U32 },
+ [NFULA_IFINDEX_OUTDEV] = { .type = NLA_U32 },
+ [NFULA_IFINDEX_PHYSINDEV] = { .type = NLA_U32 },
+ [NFULA_IFINDEX_PHYSOUTDEV] = { .type = NLA_U32 },
+ [NFULA_HWADDR] = {
+ .minlen = sizeof(struct nfulnl_msg_packet_hw)
+ },
+ //[NFULA_PAYLOAD]
+ [NFULA_PREFIX] = { .type = NLA_STRING, },
+ [NFULA_UID] = { .type = NLA_U32 },
+ [NFULA_SEQ] = { .type = NLA_U32 },
+ [NFULA_SEQ_GLOBAL] = { .type = NLA_U32 },
+};
+
+struct nfnl_log *nfnlmsg_log_parse(struct nlmsghdr *nlh)
+{
+ struct nfnl_log *log;
+ struct nlattr *tb[NFULA_MAX+1];
+ struct nlattr *attr;
+ int err;
+
+ log = nfnl_log_alloc();
+ if (!log)
+ return NULL;
+
+ log->ce_msgtype = nlh->nlmsg_type;
+
+ err = nlmsg_parse(nlh, sizeof(struct nfgenmsg), tb, NFULA_MAX,
+ log_policy);
+ if (err < 0)
+ goto errout;
+
+ nfnl_log_set_family(log, nfnlmsg_family(nlh));
+
+ attr = tb[NFULA_PACKET_HDR];
+ if (attr) {
+ struct nfulnl_msg_packet_hdr *hdr = nla_data(attr);
+
+ nfnl_log_set_hwproto(log, hdr->hw_protocol);
+ nfnl_log_set_hook(log, hdr->hook);
+ }
+
+ attr = tb[NFULA_MARK];
+ if (attr)
+ nfnl_log_set_mark(log, ntohl(nla_get_u32(attr)));
+
+ attr = tb[NFULA_TIMESTAMP];
+ if (attr) {
+ struct nfulnl_msg_packet_timestamp *timestamp = nla_data(attr);
+ struct timeval tv;
+
+ tv.tv_sec = ntohll(timestamp->sec);
+ tv.tv_usec = ntohll(timestamp->usec);
+ nfnl_log_set_timestamp(log, &tv);
+ }
+
+ attr = tb[NFULA_IFINDEX_INDEV];
+ if (attr)
+ nfnl_log_set_indev(log, ntohl(nla_get_u32(attr)));
+
+ attr = tb[NFULA_IFINDEX_OUTDEV];
+ if (attr)
+ nfnl_log_set_outdev(log, ntohl(nla_get_u32(attr)));
+
+ attr = tb[NFULA_IFINDEX_PHYSINDEV];
+ if (attr)
+ nfnl_log_set_physindev(log, ntohl(nla_get_u32(attr)));
+
+ attr = tb[NFULA_IFINDEX_PHYSOUTDEV];
+ if (attr)
+ nfnl_log_set_physoutdev(log, ntohl(nla_get_u32(attr)));
+
+ attr = tb[NFULA_HWADDR];
+ if (attr) {
+ struct nfulnl_msg_packet_hw *hw = nla_data(attr);
+
+ nfnl_log_set_hwaddr(log, hw->hw_addr, ntohs(hw->hw_addrlen));
+ }
+
+ attr = tb[NFULA_PAYLOAD];
+ if (attr) {
+ err = nfnl_log_set_payload(log, nla_data(attr), nla_len(attr));
+ if (err < 0)
+ goto errout;
+ }
+
+ attr = tb[NFULA_PREFIX];
+ if (attr) {
+ err = nfnl_log_set_prefix(log, nla_data(attr));
+ if (err < 0)
+ goto errout;
+ }
+
+ attr = tb[NFULA_UID];
+ if (attr)
+ nfnl_log_set_uid(log, ntohl(nla_get_u32(attr)));
+
+ attr = tb[NFULA_SEQ];
+ if (attr)
+ nfnl_log_set_seq(log, ntohl(nla_get_u32(attr)));
+
+ attr = tb[NFULA_SEQ_GLOBAL];
+ if (attr)
+ nfnl_log_set_seq_global(log, ntohl(nla_get_u32(attr)));
+
+ return log;
+
+errout:
+ nfnl_log_put(log);
+ return NULL;
+}
+
+static int log_msg_parser(struct nl_cache_ops *ops, struct sockaddr_nl *who,
+ struct nlmsghdr *nlh, void *arg)
+{
+ struct nl_parser_param *pp = arg;
+ struct nfnl_log *log;
+ int err;
+
+ log = nfnlmsg_log_parse(nlh);
+ if (log == NULL)
+ goto errout_errno;
+
+ err = pp->pp_cb((struct nl_object *) log, pp);
+ if (err < 0)
+ goto errout;
+
+ return P_ACCEPT;
+
+errout_errno:
+ err = nl_get_errno();
+errout:
+ nfnl_log_put(log);
+ return err;
+}
+
+/**
+ * @name Log Commands
+ * @{
+ */
+
+static struct nl_msg *build_log_cmd_msg(uint8_t family, uint16_t queuenum,
+ uint8_t command)
+{
+ struct nl_msg *msg;
+ struct nfulnl_msg_config_cmd cmd;
+
+ msg = nfnlmsg_alloc_simple(NFNL_SUBSYS_ULOG, NFULNL_MSG_CONFIG, 0,
+ family, queuenum);
+ if (msg == NULL)
+ return NULL;
+
+ cmd.command = command;
+ if (nla_put(msg, NFULA_CFG_CMD, sizeof(cmd), &cmd) < 0)
+ goto nla_put_failure;
+
+ return msg;
+
+nla_put_failure:
+ nlmsg_free(msg);
+ return NULL;
+}
+
+static int send_log_msg(struct nl_handle *handle, struct nl_msg *msg)
+{
+ int err;
+
+ err = nl_send_auto_complete(handle, msg);
+ nlmsg_free(msg);
+ if (err < 0)
+ return err;
+
+ return nl_wait_for_ack(handle);
+}
+
+struct nl_msg *nfnl_log_build_bind(uint16_t queuenum)
+{
+ return build_log_cmd_msg(0, queuenum, NFULNL_CFG_CMD_BIND);
+}
+
+int nfnl_log_bind(struct nl_handle *nlh, uint16_t queuenum)
+{
+ struct nl_msg *msg;
+
+ msg = nfnl_log_build_bind(queuenum);
+ if (!msg)
+ return nl_get_errno();
+
+ return send_log_msg(nlh, msg);
+}
+
+struct nl_msg *nfnl_log_build_unbind(uint16_t queuenum)
+{
+ return build_log_cmd_msg(0, queuenum, NFULNL_CFG_CMD_UNBIND);
+}
+
+int nfnl_log_unbind(struct nl_handle *nlh, uint16_t queuenum)
+{
+ struct nl_msg *msg;
+
+ msg = nfnl_log_build_bind(queuenum);
+ if (!msg)
+ return nl_get_errno();
+
+ return send_log_msg(nlh, msg);
+}
+
+struct nl_msg *nfnl_log_build_pf_bind(uint8_t pf)
+{
+ return build_log_cmd_msg(pf, 0, NFULNL_CFG_CMD_PF_BIND);
+}
+
+int nfnl_log_pf_bind(struct nl_handle *nlh, uint8_t pf)
+{
+ struct nl_msg *msg;
+
+ msg = nfnl_log_build_pf_bind(pf);
+ if (!msg)
+ return nl_get_errno();
+
+ return send_log_msg(nlh, msg);
+}
+
+struct nl_msg *nfnl_log_build_pf_unbind(uint8_t pf)
+{
+ return build_log_cmd_msg(pf, 0, NFULNL_CFG_CMD_PF_UNBIND);
+}
+
+int nfnl_log_pf_unbind(struct nl_handle *nlh, uint8_t pf)
+{
+ struct nl_msg *msg;
+
+ msg = nfnl_log_build_pf_unbind(pf);
+ if (!msg)
+ return nl_get_errno();
+
+ return send_log_msg(nlh, msg);
+}
+
+struct nl_msg *nfnl_log_build_mode(uint16_t queuenum, uint8_t copy_mode,
+ uint32_t copy_range)
+{
+ struct nl_msg *msg;
+ struct nfulnl_msg_config_mode mode;
+
+ msg = nfnlmsg_alloc_simple(NFNL_SUBSYS_ULOG, NFULNL_MSG_CONFIG, 0,
+ 0, queuenum);
+ if (msg == NULL)
+ return NULL;
+
+ mode.copy_mode = copy_mode;
+ mode.copy_range = htonl(copy_range);
+ if (nla_put(msg, NFULA_CFG_MODE, sizeof(mode), &mode) < 0)
+ goto nla_put_failure;
+
+ return msg;
+
+nla_put_failure:
+ nlmsg_free(msg);
+ return NULL;
+}
+
+int nfnl_log_set_mode(struct nl_handle *nlh, uint16_t queuenum,
+ uint8_t copy_mode, uint32_t copy_range)
+{
+ struct nl_msg *msg;
+
+ msg = nfnl_log_build_mode(queuenum, copy_mode, copy_range);
+ if (!msg)
+ return nl_get_errno();
+ return send_log_msg(nlh, msg);
+}
+
+/** @} */
+
+#define NFNLMSG_LOG_TYPE(type) NFNLMSG_TYPE(NFNL_SUBSYS_ULOG, (type))
+static struct nl_cache_ops nfnl_log_ops = {
+ .co_name = "netfilter/log",
+ .co_hdrsize = NFNL_HDRLEN,
+ .co_msgtypes = {
+ { NFNLMSG_LOG_TYPE(NFULNL_MSG_PACKET), NL_ACT_NEW, "new" },
+ END_OF_MSGTYPES_LIST,
+ },
+ .co_protocol = NETLINK_NETFILTER,
+ .co_msg_parser = log_msg_parser,
+ .co_obj_ops = &log_obj_ops,
+};
+
+static void __init log_init(void)
+{
+ nl_cache_mngt_register(&nfnl_log_ops);
+}
+
+static void __exit log_exit(void)
+{
+ nl_cache_mngt_unregister(&nfnl_log_ops);
+}
+
+/** @} */
diff --git a/lib/netfilter/log_obj.c b/lib/netfilter/log_obj.c
new file mode 100644
index 0000000..c3adc51
--- /dev/null
+++ b/lib/netfilter/log_obj.c
@@ -0,0 +1,425 @@
+/*
+ * lib/netfilter/log_obj.c Netfilter Log Object
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ * Copyright (c) 2007 Philip Craig <philipc@snapgear.com>
+ * Copyright (c) 2007 Secure Computing Corporation
+ */
+
+#include <netlink-local.h>
+#include <netlink/netfilter/nfnl.h>
+#include <netlink/netfilter/log.h>
+
+/** @cond SKIP */
+#define LOG_ATTR_FAMILY (1UL << 0)
+#define LOG_ATTR_HWPROTO (1UL << 1)
+#define LOG_ATTR_HOOK (1UL << 2)
+#define LOG_ATTR_MARK (1UL << 3)
+#define LOG_ATTR_TIMESTAMP (1UL << 4)
+#define LOG_ATTR_INDEV (1UL << 5)
+#define LOG_ATTR_OUTDEV (1UL << 6)
+#define LOG_ATTR_PHYSINDEV (1UL << 7)
+#define LOG_ATTR_PHYSOUTDEV (1UL << 8)
+#define LOG_ATTR_HWADDR (1UL << 9)
+#define LOG_ATTR_PAYLOAD (1UL << 10)
+#define LOG_ATTR_PREFIX (1UL << 11)
+#define LOG_ATTR_UID (1UL << 12)
+#define LOG_ATTR_SEQ (1UL << 13)
+#define LOG_ATTR_SEQ_GLOBAL (1UL << 14)
+/** @endcond */
+
+static void log_free_data(struct nl_object *c)
+{
+ struct nfnl_log *log = (struct nfnl_log *) c;
+
+ if (log == NULL)
+ return;
+
+ free(log->log_payload);
+ free(log->log_prefix);
+}
+
+static int log_clone(struct nl_object *_dst, struct nl_object *_src)
+{
+ struct nfnl_log *dst = (struct nfnl_log *) _dst;
+ struct nfnl_log *src = (struct nfnl_log *) _src;
+ int err;
+
+ if (src->log_payload) {
+ err = nfnl_log_set_payload(dst, src->log_payload,
+ src->log_payload_len);
+ if (err < 0)
+ goto errout;
+ }
+
+ if (src->log_prefix) {
+ err = nfnl_log_set_prefix(dst, src->log_prefix);
+ if (err < 0)
+ goto errout;
+ }
+
+ return 0;
+errout:
+ return err;
+}
+
+static int log_dump(struct nl_object *a, struct nl_dump_params *p)
+{
+ struct nfnl_log *log = (struct nfnl_log *) a;
+ struct nl_cache *link_cache;
+ char buf[64];
+
+ link_cache = nl_cache_mngt_require("route/link");
+
+ if (log->ce_mask & LOG_ATTR_PREFIX)
+ dp_dump(p, "%s", log->log_prefix);
+
+ if (log->ce_mask & LOG_ATTR_INDEV) {
+ if (link_cache)
+ dp_dump(p, "IN=%s ",
+ rtnl_link_i2name(link_cache, log->log_indev,
+ buf, sizeof(buf)));
+ else
+ dp_dump(p, "IN=%d ", log->log_indev);
+ }
+
+ if (log->ce_mask & LOG_ATTR_PHYSINDEV) {
+ if (link_cache)
+ dp_dump(p, "PHYSIN=%s ",
+ rtnl_link_i2name(link_cache, log->log_physindev,
+ buf, sizeof(buf)));
+ else
+ dp_dump(p, "IN=%d ", log->log_physindev);
+ }
+
+ if (log->ce_mask & LOG_ATTR_OUTDEV) {
+ if (link_cache)
+ dp_dump(p, "OUT=%s ",
+ rtnl_link_i2name(link_cache, log->log_outdev,
+ buf, sizeof(buf)));
+ else
+ dp_dump(p, "OUT=%d ", log->log_outdev);
+ }
+
+ if (log->ce_mask & LOG_ATTR_PHYSOUTDEV) {
+ if (link_cache)
+ dp_dump(p, "PHYSOUT=%s ",
+ rtnl_link_i2name(link_cache,log->log_physoutdev,
+ buf, sizeof(buf)));
+ else
+ dp_dump(p, "PHYSOUT=%d ", log->log_physoutdev);
+ }
+
+ if (log->ce_mask & LOG_ATTR_HWADDR) {
+ int i;
+
+ dp_dump(p, "MAC");
+ for (i = 0; i < log->log_hwaddr_len; i++)
+ dp_dump(p, "%c%02x", i?':':'=', log->log_hwaddr[i]);
+ dp_dump(p, " ");
+ }
+
+ /* FIXME: parse the payload to get iptables LOG compatible format */
+
+ if (log->ce_mask & LOG_ATTR_FAMILY)
+ dp_dump(p, "FAMILY=%s ",
+ nl_af2str(log->log_family, buf, sizeof(buf)));
+
+ if (log->ce_mask & LOG_ATTR_HWPROTO)
+ dp_dump(p, "HWPROTO=%s ",
+ nl_ether_proto2str(ntohs(log->log_hwproto),
+ buf, sizeof(buf)));
+
+ if (log->ce_mask & LOG_ATTR_HOOK)
+ dp_dump(p, "HOOK=%d ", log->log_hook);
+
+ if (log->ce_mask & LOG_ATTR_MARK)
+ dp_dump(p, "MARK=%d ", log->log_mark);
+
+ if (log->ce_mask & LOG_ATTR_PAYLOAD)
+ dp_dump(p, "PAYLOADLEN=%d ", log->log_payload_len);
+
+ if (log->ce_mask & LOG_ATTR_SEQ)
+ dp_dump(p, "SEQ=%d ", log->log_seq);
+
+ if (log->ce_mask & LOG_ATTR_SEQ_GLOBAL)
+ dp_dump(p, "SEQGLOBAL=%d ", log->log_seq_global);
+
+ dp_dump(p, "\n");
+
+ return 1;
+}
+
+/**
+ * @name Allocation/Freeing
+ * @{
+ */
+
+struct nfnl_log *nfnl_log_alloc(void)
+{
+ return (struct nfnl_log *) nl_object_alloc(&log_obj_ops);
+}
+
+void nfnl_log_get(struct nfnl_log *log)
+{
+ nl_object_get((struct nl_object *) log);
+}
+
+void nfnl_log_put(struct nfnl_log *log)
+{
+ nl_object_put((struct nl_object *) log);
+}
+
+/** @} */
+
+/**
+ * @name Attributes
+ * @{
+ */
+
+void nfnl_log_set_family(struct nfnl_log *log, uint8_t family)
+{
+ log->log_family = family;
+ log->ce_mask |= LOG_ATTR_FAMILY;
+}
+
+uint8_t nfnl_log_get_family(const struct nfnl_log *log)
+{
+ if (log->ce_mask & LOG_ATTR_FAMILY)
+ return log->log_family;
+ else
+ return AF_UNSPEC;
+}
+
+void nfnl_log_set_hwproto(struct nfnl_log *log, uint16_t hwproto)
+{
+ log->log_hwproto = hwproto;
+ log->ce_mask |= LOG_ATTR_HWPROTO;
+}
+
+int nfnl_log_test_hwproto(const struct nfnl_log *log)
+{
+ return !!(log->ce_mask & LOG_ATTR_HWPROTO);
+}
+
+uint16_t nfnl_log_get_hwproto(const struct nfnl_log *log)
+{
+ return log->log_hwproto;
+}
+
+void nfnl_log_set_hook(struct nfnl_log *log, uint8_t hook)
+{
+ log->log_hook = hook;
+ log->ce_mask |= LOG_ATTR_HOOK;
+}
+
+int nfnl_log_test_hook(const struct nfnl_log *log)
+{
+ return !!(log->ce_mask & LOG_ATTR_HOOK);
+}
+
+uint8_t nfnl_log_get_hook(const struct nfnl_log *log)
+{
+ return log->log_hook;
+}
+
+void nfnl_log_set_mark(struct nfnl_log *log, uint32_t mark)
+{
+ log->log_mark = mark;
+ log->ce_mask |= LOG_ATTR_MARK;
+}
+
+int nfnl_log_test_mark(const struct nfnl_log *log)
+{
+ return !!(log->ce_mask & LOG_ATTR_MARK);
+}
+
+uint32_t nfnl_log_get_mark(const struct nfnl_log *log)
+{
+ return log->log_mark;
+}
+
+void nfnl_log_set_timestamp(struct nfnl_log *log, struct timeval *tv)
+{
+ log->log_timestamp.tv_sec = tv->tv_sec;
+ log->log_timestamp.tv_usec = tv->tv_usec;
+ log->ce_mask |= LOG_ATTR_TIMESTAMP;
+}
+
+const struct timeval *nfnl_log_get_timestamp(const struct nfnl_log *log)
+{
+ if (!(log->ce_mask & LOG_ATTR_TIMESTAMP))
+ return NULL;
+ return &log->log_timestamp;
+}
+
+void nfnl_log_set_indev(struct nfnl_log *log, uint32_t indev)
+{
+ log->log_indev = indev;
+ log->ce_mask |= LOG_ATTR_INDEV;
+}
+
+uint32_t nfnl_log_get_indev(const struct nfnl_log *log)
+{
+ return log->log_indev;
+}
+
+void nfnl_log_set_outdev(struct nfnl_log *log, uint32_t outdev)
+{
+ log->log_outdev = outdev;
+ log->ce_mask |= LOG_ATTR_OUTDEV;
+}
+
+uint32_t nfnl_log_get_outdev(const struct nfnl_log *log)
+{
+ return log->log_outdev;
+}
+
+void nfnl_log_set_physindev(struct nfnl_log *log, uint32_t physindev)
+{
+ log->log_physindev = physindev;
+ log->ce_mask |= LOG_ATTR_PHYSINDEV;
+}
+
+uint32_t nfnl_log_get_physindev(const struct nfnl_log *log)
+{
+ return log->log_physindev;
+}
+
+void nfnl_log_set_physoutdev(struct nfnl_log *log, uint32_t physoutdev)
+{
+ log->log_physoutdev = physoutdev;
+ log->ce_mask |= LOG_ATTR_PHYSOUTDEV;
+}
+
+uint32_t nfnl_log_get_physoutdev(const struct nfnl_log *log)
+{
+ return log->log_physoutdev;
+}
+
+void nfnl_log_set_hwaddr(struct nfnl_log *log, uint8_t *hwaddr, int len)
+{
+ if (len > sizeof(log->log_hwaddr))
+ len = sizeof(log->log_hwaddr);
+ log->log_hwaddr_len = len;
+ memcpy(log->log_hwaddr, hwaddr, len);
+ log->ce_mask |= LOG_ATTR_HWADDR;
+}
+
+const uint8_t *nfnl_log_get_hwaddr(const struct nfnl_log *log, int *len)
+{
+ if (!(log->ce_mask & LOG_ATTR_HWADDR)) {
+ *len = 0;
+ return NULL;
+ }
+
+ *len = log->log_hwaddr_len;
+ return log->log_hwaddr;
+}
+
+int nfnl_log_set_payload(struct nfnl_log *log, uint8_t *payload, int len)
+{
+ free(log->log_payload);
+ log->log_payload = malloc(len);
+ if (!log->log_payload)
+ return nl_errno(ENOMEM);
+
+ memcpy(log->log_payload, payload, len);
+ log->log_payload_len = len;
+ log->ce_mask |= LOG_ATTR_PAYLOAD;
+ return 0;
+}
+
+const void *nfnl_log_get_payload(const struct nfnl_log *log, int *len)
+{
+ if (!(log->ce_mask & LOG_ATTR_PAYLOAD)) {
+ *len = 0;
+ return NULL;
+ }
+
+ *len = log->log_payload_len;
+ return log->log_payload;
+}
+
+int nfnl_log_set_prefix(struct nfnl_log *log, void *prefix)
+{
+ free(log->log_prefix);
+ log->log_prefix = strdup(prefix);
+ if (!log->log_prefix)
+ return nl_errno(ENOMEM);
+
+ log->ce_mask |= LOG_ATTR_PREFIX;
+ return 0;
+}
+
+const char *nfnl_log_get_prefix(const struct nfnl_log *log)
+{
+ return log->log_prefix;
+}
+
+void nfnl_log_set_uid(struct nfnl_log *log, uint32_t uid)
+{
+ log->log_uid = uid;
+ log->ce_mask |= LOG_ATTR_UID;
+}
+
+int nfnl_log_test_uid(const struct nfnl_log *log)
+{
+ return !!(log->ce_mask & LOG_ATTR_UID);
+}
+
+uint32_t nfnl_log_get_uid(const struct nfnl_log *log)
+{
+ return log->log_uid;
+}
+
+void nfnl_log_set_seq(struct nfnl_log *log, uint32_t seq)
+{
+ log->log_seq = seq;
+ log->ce_mask |= LOG_ATTR_SEQ;
+}
+
+int nfnl_log_test_seq(const struct nfnl_log *log)
+{
+ return !!(log->ce_mask & LOG_ATTR_SEQ);
+}
+
+uint32_t nfnl_log_get_seq(const struct nfnl_log *log)
+{
+ return log->log_seq;
+}
+
+void nfnl_log_set_seq_global(struct nfnl_log *log, uint32_t seq_global)
+{
+ log->log_seq_global = seq_global;
+ log->ce_mask |= LOG_ATTR_SEQ_GLOBAL;
+}
+
+int nfnl_log_test_seq_global(const struct nfnl_log *log)
+{
+ return !!(log->ce_mask & LOG_ATTR_SEQ_GLOBAL);
+}
+
+uint32_t nfnl_log_get_seq_global(const struct nfnl_log *log)
+{
+ return log->log_seq_global;
+}
+
+/** @} */
+
+struct nl_object_ops log_obj_ops = {
+ .oo_name = "netfilter/log",
+ .oo_size = sizeof(struct nfnl_log),
+ .oo_free_data = log_free_data,
+ .oo_clone = log_clone,
+ .oo_dump[NL_DUMP_BRIEF] = log_dump,
+ .oo_dump[NL_DUMP_FULL] = log_dump,
+ .oo_dump[NL_DUMP_STATS] = log_dump,
+};
+
+/** @} */
diff --git a/lib/netfilter/nfnl.c b/lib/netfilter/nfnl.c
new file mode 100644
index 0000000..554e234
--- /dev/null
+++ b/lib/netfilter/nfnl.c
@@ -0,0 +1,246 @@
+/*
+ * lib/netfilter/nfnl.c Netfilter Netlink
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ * Copyright (c) 2007 Philip Craig <philipc@snapgear.com>
+ * Copyright (c) 2007 Secure Computing Corporation
+ */
+
+/**
+ * @ingroup nlfam
+ * @defgroup nfnl Netfilter Netlink
+ *
+ * @par Message Format
+ * @code
+ * <------- NLMSG_ALIGN(hlen) ------> <---- NLMSG_ALIGN(len) --->
+ * +----------------------------+- - -+- - - - - - - - - - -+- - -+
+ * | Header | Pad | Payload | Pad |
+ * | struct nlmsghdr | | | |
+ * +----------------------------+- - -+- - - - - - - - - - -+- - -+
+ * @endcode
+ * @code
+ * <-------- NFNL_HDRLEN --------->
+ * +--------------------------+- - -+------------+
+ * | Netfilter Netlink Header | Pad | Attributes |
+ * | struct nfgenmsg | | |
+ * +--------------------------+- - -+------------+
+ * nfnlmsg_attrdata(nfg, hdrlen)-----^
+ * @endcode
+ *
+ * @par 1) Creating a new netfilter netlink message
+ * @code
+ * struct nl_msg *msg;
+ *
+ * // Create a new empty netlink message
+ * msg = nlmsg_alloc();
+ *
+ * // Append the netlink and netfilter netlink message header
+ * hdr = nfnlmsg_put(msg, PID, SEQ, SUBSYS, TYPE, NLM_F_ECHO,
+ * FAMILY, RES_ID);
+ *
+ * // Append the attributes.
+ * nla_put_u32(msg, 1, 0x10);
+ *
+ * // Message is ready to be sent.
+ * nl_send_auto_complete(nl_handle, msg);
+ *
+ * // All done? Free the message.
+ * nlmsg_free(msg);
+ * @endcode
+ *
+ * @par 2) Sending of trivial messages
+ * @code
+ * // For trivial messages not requiring any subsys specific header or
+ * // attributes, nfnl_send_simple() may be used to send messages directly.
+ * nfnl_send_simple(nl_handle, SUBSYS, TYPE, 0, FAMILY, RES_ID);
+ * @endcode
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/netfilter/nfnl.h>
+
+/**
+ * @name Socket Creating
+ * @{
+ */
+
+/**
+ * Create and connect netfilter netlink socket.
+ * @arg handle Netlink handle.
+ *
+ * Creates a NETLINK_NETFILTER netlink socket, binds the socket and
+ * issues a connection attempt.
+ *
+ * @see nl_connect()
+ *
+ * @return 0 on success or a negative error code.
+ */
+int nfnl_connect(struct nl_handle *handle)
+{
+ return nl_connect(handle, NETLINK_NETFILTER);
+}
+
+/** @} */
+
+/**
+ * @name Sending
+ * @{
+ */
+
+/**
+ * Send trivial netfilter netlink message
+ * @arg handle Netlink handle.
+ * @arg subsys_id nfnetlink subsystem
+ * @arg type nfnetlink message type
+ * @arg flags message flags
+ * @arg family nfnetlink address family
+ * @arg res_id nfnetlink resource id
+ *
+ * @return Newly allocated netlink message or NULL.
+ */
+int nfnl_send_simple(struct nl_handle *handle, uint8_t subsys_id, uint8_t type,
+ int flags, uint8_t family, uint16_t res_id)
+{
+ struct nfgenmsg hdr = {
+ .nfgen_family = family,
+ .version = NFNETLINK_V0,
+ .res_id = htons(res_id),
+ };
+
+ return nl_send_simple(handle, NFNLMSG_TYPE(subsys_id, type), flags,
+ &hdr, sizeof(hdr));
+}
+
+/** @} */
+
+/**
+ * @name Message Parsing
+ * @{
+ */
+
+/**
+ * Get netfilter subsystem id from message
+ * @arg nlh netlink messsage header
+ */
+uint8_t nfnlmsg_subsys(struct nlmsghdr *nlh)
+{
+ return NFNL_SUBSYS_ID(nlh->nlmsg_type);
+}
+
+/**
+ * Get netfilter message type from message
+ * @arg nlh netlink messsage header
+ */
+uint8_t nfnlmsg_subtype(struct nlmsghdr *nlh)
+{
+ return NFNL_MSG_TYPE(nlh->nlmsg_type);
+}
+
+/**
+ * Get netfilter family from message
+ * @arg nlh netlink messsage header
+ */
+uint8_t nfnlmsg_family(struct nlmsghdr *nlh)
+{
+ struct nfgenmsg *nfg = nlmsg_data(nlh);
+
+ return nfg->nfgen_family;
+}
+
+/**
+ * Get netfilter resource id from message
+ * @arg nlh netlink messsage header
+ */
+uint16_t nfnlmsg_res_id(struct nlmsghdr *nlh)
+{
+ struct nfgenmsg *nfg = nlmsg_data(nlh);
+
+ return ntohs(nfg->res_id);
+}
+
+/** @} */
+
+/**
+ * @name Message Building
+ * @{
+ */
+
+static int nfnlmsg_append(struct nl_msg *msg, uint8_t family, uint16_t res_id)
+{
+ struct nfgenmsg *nfg;
+
+ nfg = nlmsg_reserve(msg, sizeof(*nfg), NLMSG_ALIGNTO);
+ if (nfg == NULL)
+ return nl_errno(ENOMEM);
+
+ nfg->nfgen_family = family;
+ nfg->version = NFNETLINK_V0;
+ nfg->res_id = htons(res_id);
+ NL_DBG(2, "msg %p: Added nfnetlink header family=%d res_id=%d\n",
+ msg, family, res_id);
+ return 0;
+}
+
+/**
+ * Allocate a new netfilter netlink message
+ * @arg subsys_id nfnetlink subsystem
+ * @arg type nfnetlink message type
+ * @arg flags message flags
+ * @arg family nfnetlink address family
+ * @arg res_id nfnetlink resource id
+ *
+ * @return Newly allocated netlink message or NULL.
+ */
+struct nl_msg *nfnlmsg_alloc_simple(uint8_t subsys_id, uint8_t type, int flags,
+ uint8_t family, uint16_t res_id)
+{
+ struct nl_msg *msg;
+
+ msg = nlmsg_alloc_simple(NFNLMSG_TYPE(subsys_id, type), flags);
+ if (msg == NULL)
+ return NULL;
+
+ if (nfnlmsg_append(msg, family, res_id) < 0)
+ goto nla_put_failure;
+
+ return msg;
+
+nla_put_failure:
+ nlmsg_free(msg);
+ return NULL;
+}
+
+/**
+ * Add netlink and netfilter netlink headers to netlink message
+ * @arg msg netlink message
+ * @arg pid netlink process id
+ * @arg seq sequence number of message
+ * @arg subsys_id nfnetlink subsystem
+ * @arg type nfnetlink message type
+ * @arg flags message flags
+ * @arg family nfnetlink address family
+ * @arg res_id nfnetlink resource id
+ */
+int nfnlmsg_put(struct nl_msg *msg, uint32_t pid, uint32_t seq,
+ uint8_t subsys_id, uint8_t type, int flags, uint8_t family,
+ uint16_t res_id)
+{
+ struct nlmsghdr *nlh;
+
+ nlh = nlmsg_put(msg, pid, seq, NFNLMSG_TYPE(subsys_id, type), 0, flags);
+ if (nlh == NULL)
+ return nl_get_errno();
+
+ return nfnlmsg_append(msg, family, res_id);
+}
+
+/** @} */
+
+/** @} */
diff --git a/lib/nl.c b/lib/nl.c
new file mode 100644
index 0000000..3866846
--- /dev/null
+++ b/lib/nl.c
@@ -0,0 +1,798 @@
+/*
+ * lib/nl.c Core Netlink Interface
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @defgroup nl Core Netlink API
+ * @brief
+ *
+ * @par Receiving Semantics
+ * @code
+ * nl_recvmsgs_default(socket)
+ * |
+ * | cb = nl_socket_get_cb(socket)
+ * v
+ * nl_recvmsgs(socket, cb)
+ * | [Application provides nl_recvmsgs() replacement]
+ * |- - - - - - - - - - - - - - - v
+ * | cb->cb_recvmsgs_ow()
+ * |
+ * | [Application provides nl_recv() replacement]
+ * +-------------->|- - - - - - - - - - - - - - - v
+ * | nl_recv() cb->cb_recv_ow()
+ * | +----------->|<- - - - - - - - - - - - - - -+
+ * | | v
+ * | | Parse Message
+ * | | |- - - - - - - - - - - - - - - v
+ * | | | NL_CB_MSG_IN()
+ * | | |<- - - - - - - - - - - - - - -+
+ * | | |
+ * | | |- - - - - - - - - - - - - - - v
+ * | | Sequence Check NL_CB_SEQ_CHECK()
+ * | | |<- - - - - - - - - - - - - - -+
+ * | | |
+ * | | |- - - - - - - - - - - - - - - v [ NLM_F_ACK is set ]
+ * | | | NL_CB_SEND_ACK()
+ * | | |<- - - - - - - - - - - - - - -+
+ * | | |
+ * | | +-----+------+--------------+----------------+--------------+
+ * | | v v v v v
+ * | | Valid Message ACK NOOP Message End of Multipart Error Message
+ * | | | | | | |
+ * | | v v v v v
+ * | |NL_CB_VALID() NL_CB_ACK() NL_CB_SKIPPED() NL_CB_FINISH() cb->cb_err()
+ * | | | | | | |
+ * | | +------------+--------------+----------------+ v
+ * | | | (FAILURE)
+ * | | | [Callback returned NL_SKIP]
+ * | | [More messages to be parsed] |<-----------
+ * | +----------------------------------|
+ * | |
+ * | [Multipart message] |
+ * +-------------------------------------| [Callback returned NL_STOP]
+ * |<-----------
+ * v
+ * (SUCCESS)
+ *
+ * At any time:
+ * Message Format Error
+ * |- - - - - - - - - - - - v
+ * v NL_CB_INVALID()
+ * (FAILURE)
+ *
+ * Message Overrun (Kernel Lost Data)
+ * |- - - - - - - - - - - - v
+ * v NL_CB_OVERRUN()
+ * (FAILURE)
+ *
+ * Callback returned negative error code
+ * (FAILURE)
+ * @endcode
+ *
+ * @par Sending Semantics
+ * @code
+ * nl_send_auto_complete()
+ * |
+ * | Automatically fill in PID and/or sequence number
+ * |
+ * | [Application provides nl_send() replacement]
+ * |- - - - - - - - - - - - - - - - - - - - v
+ * v cb->cb_send_ow()
+ * nl_send()
+ * | Add destination address and credentials
+ * v
+ * nl_sendmsg()
+ * | Set source address
+ * |
+ * |- - - - - - - - - - - - - - - - - - - - v
+ * | NL_CB_MSG_OUT()
+ * |<- - - - - - - - - - - - - - - - - - - -+
+ * v
+ * sendmsg()
+ * @endcode
+ *
+ * @par 1) Connecting the socket
+ * @code
+ * // Bind and connect the socket to a protocol, NETLINK_ROUTE in this example.
+ * nl_connect(handle, NETLINK_ROUTE);
+ * @endcode
+ *
+ * @par 2) Sending data
+ * @code
+ * // The most rudimentary method is to use nl_sendto() simply pushing
+ * // a piece of data to the other netlink peer. This method is not
+ * // recommended.
+ * const char buf[] = { 0x01, 0x02, 0x03, 0x04 };
+ * nl_sendto(handle, buf, sizeof(buf));
+ *
+ * // A more comfortable interface is nl_send() taking a pointer to
+ * // a netlink message.
+ * struct nl_msg *msg = my_msg_builder();
+ * nl_send(handle, nlmsg_hdr(msg));
+ *
+ * // nl_sendmsg() provides additional control over the sendmsg() message
+ * // header in order to allow more specific addressing of multiple peers etc.
+ * struct msghdr hdr = { ... };
+ * nl_sendmsg(handle, nlmsg_hdr(msg), &hdr);
+ *
+ * // You're probably too lazy to fill out the netlink pid, sequence number
+ * // and message flags all the time. nl_send_auto_complete() automatically
+ * // extends your message header as needed with an appropriate sequence
+ * // number, the netlink pid stored in the netlink handle and the message
+ * // flags NLM_F_REQUEST and NLM_F_ACK
+ * nl_send_auto_complete(handle, nlmsg_hdr(msg));
+ *
+ * // Simple protocols don't require the complex message construction interface
+ * // and may favour nl_send_simple() to easly send a bunch of payload
+ * // encapsulated in a netlink message header.
+ * nl_send_simple(handle, MY_MSG_TYPE, 0, buf, sizeof(buf));
+ * @endcode
+ *
+ * @par 3) Receiving data
+ * @code
+ * // nl_recv() receives a single message allocating a buffer for the message
+ * // content and gives back the pointer to you.
+ * struct sockaddr_nl peer;
+ * unsigned char *msg;
+ * nl_recv(handle, &peer, &msg);
+ *
+ * // nl_recvmsgs() receives a bunch of messages until the callback system
+ * // orders it to state, usually after receving a compolete multi part
+ * // message series.
+ * nl_recvmsgs(handle, my_callback_configuration);
+ *
+ * // nl_recvmsgs_default() acts just like nl_recvmsg() but uses the callback
+ * // configuration stored in the handle.
+ * nl_recvmsgs_default(handle);
+ *
+ * // In case you want to wait for the ACK to be recieved that you requested
+ * // with your latest message, you can call nl_wait_for_ack()
+ * nl_wait_for_ack(handle);
+ * @endcode
+ *
+ * @par 4) Closing
+ * @code
+ * // Close the socket first to release kernel memory
+ * nl_close(handle);
+ * @endcode
+ *
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/handlers.h>
+#include <netlink/msg.h>
+#include <netlink/attr.h>
+
+/**
+ * @name Connection Management
+ * @{
+ */
+
+/**
+ * Create and connect netlink socket.
+ * @arg handle Netlink handle.
+ * @arg protocol Netlink protocol to use.
+ *
+ * Creates a netlink socket using the specified protocol, binds the socket
+ * and issues a connection attempt.
+ *
+ * @return 0 on success or a negative error code.
+ */
+int nl_connect(struct nl_handle *handle, int protocol)
+{
+ int err;
+ socklen_t addrlen;
+
+ handle->h_fd = socket(AF_NETLINK, SOCK_RAW, protocol);
+ if (handle->h_fd < 0)
+ return nl_error(1, "socket(AF_NETLINK, ...) failed");
+
+ if (!(handle->h_flags & NL_SOCK_BUFSIZE_SET)) {
+ err = nl_set_buffer_size(handle, 0, 0);
+ if (err < 0)
+ return err;
+ }
+
+ err = bind(handle->h_fd, (struct sockaddr*) &handle->h_local,
+ sizeof(handle->h_local));
+ if (err < 0)
+ return nl_error(1, "bind() failed");
+
+ addrlen = sizeof(handle->h_local);
+ err = getsockname(handle->h_fd, (struct sockaddr *) &handle->h_local,
+ &addrlen);
+ if (err < 0)
+ return nl_error(1, "getsockname failed");
+
+ if (addrlen != sizeof(handle->h_local))
+ return nl_error(EADDRNOTAVAIL, "Invalid address length");
+
+ if (handle->h_local.nl_family != AF_NETLINK)
+ return nl_error(EPFNOSUPPORT, "Address format not supported");
+
+ handle->h_proto = protocol;
+
+ return 0;
+}
+
+/**
+ * Close/Disconnect netlink socket.
+ * @arg handle Netlink handle
+ */
+void nl_close(struct nl_handle *handle)
+{
+ if (handle->h_fd >= 0) {
+ close(handle->h_fd);
+ handle->h_fd = -1;
+ }
+
+ handle->h_proto = 0;
+}
+
+/** @} */
+
+/**
+ * @name Send
+ * @{
+ */
+
+/**
+ * Send raw data over netlink socket.
+ * @arg handle Netlink handle.
+ * @arg buf Data buffer.
+ * @arg size Size of data buffer.
+ * @return Number of characters written on success or a negative error code.
+ */
+int nl_sendto(struct nl_handle *handle, void *buf, size_t size)
+{
+ int ret;
+
+ ret = sendto(handle->h_fd, buf, size, 0, (struct sockaddr *)
+ &handle->h_peer, sizeof(handle->h_peer));
+ if (ret < 0)
+ return nl_errno(errno);
+
+ return ret;
+}
+
+/**
+ * Send netlink message with control over sendmsg() message header.
+ * @arg handle Netlink handle.
+ * @arg msg Netlink message to be sent.
+ * @arg hdr Sendmsg() message header.
+ * @return Number of characters sent on sucess or a negative error code.
+ */
+int nl_sendmsg(struct nl_handle *handle, struct nl_msg *msg, struct msghdr *hdr)
+{
+ struct nl_cb *cb;
+ int ret;
+
+ struct iovec iov = {
+ .iov_base = (void *) nlmsg_hdr(msg),
+ .iov_len = nlmsg_hdr(msg)->nlmsg_len,
+ };
+
+ hdr->msg_iov = &iov;
+ hdr->msg_iovlen = 1;
+
+ nlmsg_set_src(msg, &handle->h_local);
+
+ cb = handle->h_cb;
+ if (cb->cb_set[NL_CB_MSG_OUT])
+ if (nl_cb_call(cb, NL_CB_MSG_OUT, msg) != NL_OK)
+ return 0;
+
+ ret = sendmsg(handle->h_fd, hdr, 0);
+ if (ret < 0)
+ return nl_errno(errno);
+
+ return ret;
+}
+
+
+/**
+ * Send netlink message.
+ * @arg handle Netlink handle
+ * @arg msg Netlink message to be sent.
+ * @see nl_sendmsg()
+ * @return Number of characters sent on success or a negative error code.
+ */
+int nl_send(struct nl_handle *handle, struct nl_msg *msg)
+{
+ struct sockaddr_nl *dst;
+ struct ucred *creds;
+
+ struct msghdr hdr = {
+ .msg_name = (void *) &handle->h_peer,
+ .msg_namelen = sizeof(struct sockaddr_nl),
+ };
+
+ /* Overwrite destination if specified in the message itself, defaults
+ * to the peer address of the handle.
+ */
+ dst = nlmsg_get_dst(msg);
+ if (dst->nl_family == AF_NETLINK)
+ hdr.msg_name = dst;
+
+ /* Add credentials if present. */
+ creds = nlmsg_get_creds(msg);
+ if (creds != NULL) {
+ char buf[CMSG_SPACE(sizeof(struct ucred))];
+ struct cmsghdr *cmsg;
+
+ hdr.msg_control = buf;
+ hdr.msg_controllen = sizeof(buf);
+
+ cmsg = CMSG_FIRSTHDR(&hdr);
+ cmsg->cmsg_level = SOL_SOCKET;
+ cmsg->cmsg_type = SCM_CREDENTIALS;
+ cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
+ memcpy(CMSG_DATA(cmsg), creds, sizeof(struct ucred));
+ }
+
+ return nl_sendmsg(handle, msg, &hdr);
+}
+
+/**
+ * Send netlink message and check & extend header values as needed.
+ * @arg handle Netlink handle.
+ * @arg msg Netlink message to be sent.
+ *
+ * Checks the netlink message \c nlh for completness and extends it
+ * as required before sending it out. Checked fields include pid,
+ * sequence nr, and flags.
+ *
+ * @see nl_send()
+ * @return Number of characters sent or a negative error code.
+ */
+int nl_send_auto_complete(struct nl_handle *handle, struct nl_msg *msg)
+{
+ struct nlmsghdr *nlh;
+ struct nl_cb *cb = handle->h_cb;
+
+ nlh = nlmsg_hdr(msg);
+ if (nlh->nlmsg_pid == 0)
+ nlh->nlmsg_pid = handle->h_local.nl_pid;
+
+ if (nlh->nlmsg_seq == 0)
+ nlh->nlmsg_seq = handle->h_seq_next++;
+
+ if (msg->nm_protocol == -1)
+ msg->nm_protocol = handle->h_proto;
+
+ nlh->nlmsg_flags |= (NLM_F_REQUEST | NLM_F_ACK);
+
+ if (cb->cb_send_ow)
+ return cb->cb_send_ow(handle, msg);
+ else
+ return nl_send(handle, msg);
+}
+
+/**
+ * Send simple netlink message using nl_send_auto_complete()
+ * @arg handle Netlink handle.
+ * @arg type Netlink message type.
+ * @arg flags Netlink message flags.
+ * @arg buf Data buffer.
+ * @arg size Size of data buffer.
+ *
+ * Builds a netlink message with the specified type and flags and
+ * appends the specified data as payload to the message.
+ *
+ * @see nl_send_auto_complete()
+ * @return Number of characters sent on success or a negative error code.
+ */
+int nl_send_simple(struct nl_handle *handle, int type, int flags, void *buf,
+ size_t size)
+{
+ int err;
+ struct nl_msg *msg;
+
+ msg = nlmsg_alloc_simple(type, flags);
+ if (!msg)
+ return nl_errno(ENOMEM);
+
+ if (buf && size)
+ nlmsg_append(msg, buf, size, NLMSG_ALIGNTO);
+
+ err = nl_send_auto_complete(handle, msg);
+ nlmsg_free(msg);
+
+ return err;
+}
+
+/** @} */
+
+/**
+ * @name Receive
+ * @{
+ */
+
+/**
+ * Receive data from netlink socket
+ * @arg handle Netlink handle.
+ * @arg nla Destination pointer for peer's netlink address.
+ * @arg buf Destination pointer for message content.
+ * @arg creds Destination pointer for credentials.
+ *
+ * Receives a netlink message, allocates a buffer in \c *buf and
+ * stores the message content. The peer's netlink address is stored
+ * in \c *nla. The caller is responsible for freeing the buffer allocated
+ * in \c *buf if a positive value is returned. Interruped system calls
+ * are handled by repeating the read. The input buffer size is determined
+ * by peeking before the actual read is done.
+ *
+ * A non-blocking sockets causes the function to return immediately with
+ * a return value of 0 if no data is available.
+ *
+ * @return Number of octets read, 0 on EOF or a negative error code.
+ */
+int nl_recv(struct nl_handle *handle, struct sockaddr_nl *nla,
+ unsigned char **buf, struct ucred **creds)
+{
+ int n;
+ int flags = 0;
+ static int page_size = 0;
+ struct iovec iov;
+ struct msghdr msg = {
+ .msg_name = (void *) nla,
+ .msg_namelen = sizeof(struct sockaddr_nl),
+ .msg_iov = &iov,
+ .msg_iovlen = 1,
+ .msg_control = NULL,
+ .msg_controllen = 0,
+ .msg_flags = 0,
+ };
+ struct cmsghdr *cmsg;
+
+ if (handle->h_flags & NL_MSG_PEEK)
+ flags |= MSG_PEEK;
+
+ if (page_size == 0)
+ page_size = getpagesize();
+
+ iov.iov_len = page_size;
+ iov.iov_base = *buf = calloc(1, iov.iov_len);
+
+ if (handle->h_flags & NL_SOCK_PASSCRED) {
+ msg.msg_controllen = CMSG_SPACE(sizeof(struct ucred));
+ msg.msg_control = calloc(1, msg.msg_controllen);
+ }
+retry:
+
+ n = recvmsg(handle->h_fd, &msg, flags);
+ if (!n)
+ goto abort;
+ else if (n < 0) {
+ if (errno == EINTR) {
+ NL_DBG(3, "recvmsg() returned EINTR, retrying\n");
+ goto retry;
+ } else if (errno == EAGAIN) {
+ NL_DBG(3, "recvmsg() returned EAGAIN, aborting\n");
+ goto abort;
+ } else {
+ free(msg.msg_control);
+ free(*buf);
+ return nl_error(errno, "recvmsg failed");
+ }
+ }
+
+ if (iov.iov_len < n ||
+ msg.msg_flags & MSG_TRUNC) {
+ /* Provided buffer is not long enough, enlarge it
+ * and try again. */
+ iov.iov_len *= 2;
+ iov.iov_base = *buf = realloc(*buf, iov.iov_len);
+ goto retry;
+ } else if (msg.msg_flags & MSG_CTRUNC) {
+ msg.msg_controllen *= 2;
+ msg.msg_control = realloc(msg.msg_control, msg.msg_controllen);
+ goto retry;
+ } else if (flags != 0) {
+ /* Buffer is big enough, do the actual reading */
+ flags = 0;
+ goto retry;
+ }
+
+ if (msg.msg_namelen != sizeof(struct sockaddr_nl)) {
+ free(msg.msg_control);
+ free(*buf);
+ return nl_error(EADDRNOTAVAIL, "socket address size mismatch");
+ }
+
+ for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
+ if (cmsg->cmsg_level == SOL_SOCKET &&
+ cmsg->cmsg_type == SCM_CREDENTIALS) {
+ *creds = calloc(1, sizeof(struct ucred));
+ memcpy(*creds, CMSG_DATA(cmsg), sizeof(struct ucred));
+ break;
+ }
+ }
+
+ free(msg.msg_control);
+ return n;
+
+abort:
+ free(msg.msg_control);
+ free(*buf);
+ return 0;
+}
+
+#define NL_CB_CALL(cb, type, msg) \
+do { \
+ err = nl_cb_call(cb, type, msg); \
+ switch (err) { \
+ case NL_OK: \
+ err = 0; \
+ break; \
+ case NL_SKIP: \
+ goto skip; \
+ case NL_STOP: \
+ goto stop; \
+ default: \
+ goto out; \
+ } \
+} while (0)
+
+static int recvmsgs(struct nl_handle *handle, struct nl_cb *cb)
+{
+ int n, err = 0, multipart = 0;
+ unsigned char *buf = NULL;
+ struct nlmsghdr *hdr;
+ struct sockaddr_nl nla = {0};
+ struct nl_msg *msg = NULL;
+ struct ucred *creds = NULL;
+
+continue_reading:
+ NL_DBG(3, "Attempting to read from %p\n", handle);
+ if (cb->cb_recv_ow)
+ n = cb->cb_recv_ow(handle, &nla, &buf, &creds);
+ else
+ n = nl_recv(handle, &nla, &buf, &creds);
+
+ if (n <= 0)
+ return n;
+
+ NL_DBG(3, "recvmsgs(%p): Read %d bytes\n", handle, n);
+
+ hdr = (struct nlmsghdr *) buf;
+ while (nlmsg_ok(hdr, n)) {
+ NL_DBG(3, "recgmsgs(%p): Processing valid message...\n",
+ handle);
+
+ nlmsg_free(msg);
+ msg = nlmsg_convert(hdr);
+ if (!msg) {
+ err = nl_errno(ENOMEM);
+ goto out;
+ }
+
+ nlmsg_set_proto(msg, handle->h_proto);
+ nlmsg_set_src(msg, &nla);
+ if (creds)
+ nlmsg_set_creds(msg, creds);
+
+ /* Raw callback is the first, it gives the most control
+ * to the user and he can do his very own parsing. */
+ if (cb->cb_set[NL_CB_MSG_IN])
+ NL_CB_CALL(cb, NL_CB_MSG_IN, msg);
+
+ /* Sequence number checking. The check may be done by
+ * the user, otherwise a very simple check is applied
+ * enforcing strict ordering */
+ if (cb->cb_set[NL_CB_SEQ_CHECK])
+ NL_CB_CALL(cb, NL_CB_SEQ_CHECK, msg);
+ else if (hdr->nlmsg_seq != handle->h_seq_expect) {
+ if (cb->cb_set[NL_CB_INVALID])
+ NL_CB_CALL(cb, NL_CB_INVALID, msg);
+ else {
+ err = nl_error(EINVAL,
+ "Sequence number mismatch");
+ goto out;
+ }
+ }
+
+ if (hdr->nlmsg_type == NLMSG_DONE ||
+ hdr->nlmsg_type == NLMSG_ERROR ||
+ hdr->nlmsg_type == NLMSG_NOOP ||
+ hdr->nlmsg_type == NLMSG_OVERRUN) {
+ /* We can't check for !NLM_F_MULTI since some netlink
+ * users in the kernel are broken. */
+ handle->h_seq_expect++;
+ NL_DBG(3, "recvmsgs(%p): Increased expected " \
+ "sequence number to %d\n",
+ handle, handle->h_seq_expect);
+ }
+
+ if (hdr->nlmsg_flags & NLM_F_MULTI)
+ multipart = 1;
+
+ /* Other side wishes to see an ack for this message */
+ if (hdr->nlmsg_flags & NLM_F_ACK) {
+ if (cb->cb_set[NL_CB_SEND_ACK])
+ NL_CB_CALL(cb, NL_CB_SEND_ACK, msg);
+ else {
+ /* FIXME: implement */
+ }
+ }
+
+ /* messages terminates a multpart message, this is
+ * usually the end of a message and therefore we slip
+ * out of the loop by default. the user may overrule
+ * this action by skipping this packet. */
+ if (hdr->nlmsg_type == NLMSG_DONE) {
+ multipart = 0;
+ if (cb->cb_set[NL_CB_FINISH])
+ NL_CB_CALL(cb, NL_CB_FINISH, msg);
+ }
+
+ /* Message to be ignored, the default action is to
+ * skip this message if no callback is specified. The
+ * user may overrule this action by returning
+ * NL_PROCEED. */
+ else if (hdr->nlmsg_type == NLMSG_NOOP) {
+ if (cb->cb_set[NL_CB_SKIPPED])
+ NL_CB_CALL(cb, NL_CB_SKIPPED, msg);
+ else
+ goto skip;
+ }
+
+ /* Data got lost, report back to user. The default action is to
+ * quit parsing. The user may overrule this action by retuning
+ * NL_SKIP or NL_PROCEED (dangerous) */
+ else if (hdr->nlmsg_type == NLMSG_OVERRUN) {
+ if (cb->cb_set[NL_CB_OVERRUN])
+ NL_CB_CALL(cb, NL_CB_OVERRUN, msg);
+ else {
+ err = nl_error(EOVERFLOW, "Overrun");
+ goto out;
+ }
+ }
+
+ /* Message carries a nlmsgerr */
+ else if (hdr->nlmsg_type == NLMSG_ERROR) {
+ struct nlmsgerr *e = nlmsg_data(hdr);
+
+ if (hdr->nlmsg_len < nlmsg_msg_size(sizeof(*e))) {
+ /* Truncated error message, the default action
+ * is to stop parsing. The user may overrule
+ * this action by returning NL_SKIP or
+ * NL_PROCEED (dangerous) */
+ if (cb->cb_set[NL_CB_INVALID])
+ NL_CB_CALL(cb, NL_CB_INVALID, msg);
+ else {
+ err = nl_error(EINVAL,
+ "Truncated error message");
+ goto out;
+ }
+ } else if (e->error) {
+ /* Error message reported back from kernel. */
+ if (cb->cb_err) {
+ err = cb->cb_err(&nla, e,
+ cb->cb_err_arg);
+ if (err < 0)
+ goto out;
+ else if (err == NL_SKIP)
+ goto skip;
+ else if (err == NL_STOP) {
+ err = nl_error(-e->error,
+ "Netlink Error");
+ goto out;
+ }
+ } else {
+ err = nl_error(-e->error,
+ "Netlink Error");
+ goto out;
+ }
+ } else if (cb->cb_set[NL_CB_ACK])
+ NL_CB_CALL(cb, NL_CB_ACK, msg);
+ } else {
+ /* Valid message (not checking for MULTIPART bit to
+ * get along with broken kernels. NL_SKIP has no
+ * effect on this. */
+ if (cb->cb_set[NL_CB_VALID])
+ NL_CB_CALL(cb, NL_CB_VALID, msg);
+ }
+skip:
+ err = 0;
+ hdr = nlmsg_next(hdr, &n);
+ }
+
+ nlmsg_free(msg);
+ free(buf);
+ free(creds);
+ buf = NULL;
+ msg = NULL;
+ creds = NULL;
+
+ if (multipart) {
+ /* Multipart message not yet complete, continue reading */
+ goto continue_reading;
+ }
+stop:
+ err = 0;
+out:
+ nlmsg_free(msg);
+ free(buf);
+ free(creds);
+
+ return err;
+}
+
+/**
+ * Receive a set of messages from a netlink socket.
+ * @arg handle netlink handle
+ * @arg cb set of callbacks to control behaviour.
+ *
+ * Repeatedly calls nl_recv() or the respective replacement if provided
+ * by the application (see nl_cb_overwrite_recv()) and parses the
+ * received data as netlink messages. Stops reading if one of the
+ * callbacks returns NL_STOP or nl_recv returns either 0 or a negative error code.
+ *
+ * A non-blocking sockets causes the function to return immediately if
+ * no data is available.
+ *
+ * @return 0 on success or a negative error code from nl_recv().
+ */
+int nl_recvmsgs(struct nl_handle *handle, struct nl_cb *cb)
+{
+ if (cb->cb_recvmsgs_ow)
+ return cb->cb_recvmsgs_ow(handle, cb);
+ else
+ return recvmsgs(handle, cb);
+}
+
+/**
+ * Receive a set of message from a netlink socket using handlers in nl_handle.
+ * @arg handle netlink handle
+ *
+ * Calls nl_recvmsgs() with the handlers configured in the netlink handle.
+ */
+int nl_recvmsgs_default(struct nl_handle *handle)
+{
+ return nl_recvmsgs(handle, handle->h_cb);
+
+}
+
+static int ack_wait_handler(struct nl_msg *msg, void *arg)
+{
+ return NL_STOP;
+}
+
+/**
+ * Wait for ACK.
+ * @arg handle netlink handle
+ * @pre The netlink socket must be in blocking state.
+ *
+ * Waits until an ACK is received for the latest not yet acknowledged
+ * netlink message.
+ */
+int nl_wait_for_ack(struct nl_handle *handle)
+{
+ int err;
+ struct nl_cb *cb;
+
+ cb = nl_cb_clone(handle->h_cb);
+ if (cb == NULL)
+ return nl_get_errno();
+
+ nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ack_wait_handler, NULL);
+ err = nl_recvmsgs(handle, cb);
+ nl_cb_put(cb);
+
+ return err;
+}
+
+/** @} */
+
+/** @} */
diff --git a/lib/object.c b/lib/object.c
new file mode 100644
index 0000000..74f6e2d
--- /dev/null
+++ b/lib/object.c
@@ -0,0 +1,386 @@
+/*
+ * lib/object.c Generic Cacheable Object
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup cache
+ * @defgroup object Object
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/cache.h>
+#include <netlink/object.h>
+#include <netlink/utils.h>
+
+static inline struct nl_object_ops *obj_ops(struct nl_object *obj)
+{
+ if (!obj->ce_ops)
+ BUG();
+
+ return obj->ce_ops;
+}
+
+/**
+ * @name Object Creation/Deletion
+ * @{
+ */
+
+/**
+ * Allocate a new object of kind specified by the operations handle
+ * @arg ops cache operations handle
+ * @return The new object or NULL
+ */
+struct nl_object *nl_object_alloc(struct nl_object_ops *ops)
+{
+ struct nl_object *new;
+
+ if (ops->oo_size < sizeof(*new))
+ BUG();
+
+ new = calloc(1, ops->oo_size);
+ if (!new) {
+ nl_errno(ENOMEM);
+ return NULL;
+ }
+
+ new->ce_refcnt = 1;
+ nl_init_list_head(&new->ce_list);
+
+ new->ce_ops = ops;
+ if (ops->oo_constructor)
+ ops->oo_constructor(new);
+
+ NL_DBG(4, "Allocated new object %p\n", new);
+
+ return new;
+}
+
+/**
+ * Allocate a new object of kind specified by the name
+ * @arg kind name of object type
+ * @return The new object or nULL
+ */
+struct nl_object *nl_object_alloc_name(const char *kind)
+{
+ struct nl_cache_ops *ops;
+
+ ops = nl_cache_ops_lookup(kind);
+ if (!ops) {
+ nl_error(ENOENT, "Unable to lookup cache kind \"%s\"", kind);
+ return NULL;
+ }
+
+ return nl_object_alloc(ops->co_obj_ops);
+}
+
+struct nl_derived_object {
+ NLHDR_COMMON
+ char data;
+};
+
+/**
+ * Allocate a new object and copy all data from an existing object
+ * @arg obj object to inherite data from
+ * @return The new object or NULL.
+ */
+struct nl_object *nl_object_clone(struct nl_object *obj)
+{
+ struct nl_object *new;
+ struct nl_object_ops *ops = obj_ops(obj);
+ int doff = offsetof(struct nl_derived_object, data);
+ int size;
+
+ new = nl_object_alloc(ops);
+ if (!new)
+ return NULL;
+
+ size = ops->oo_size - doff;
+ if (size < 0)
+ BUG();
+
+ new->ce_ops = obj->ce_ops;
+ new->ce_msgtype = obj->ce_msgtype;
+
+ if (size)
+ memcpy((void *)new + doff, (void *)obj + doff, size);
+
+ if (ops->oo_clone) {
+ if (ops->oo_clone(new, obj) < 0) {
+ nl_object_free(new);
+ return NULL;
+ }
+ } else if (size && ops->oo_free_data)
+ BUG();
+
+ return new;
+}
+
+/**
+ * Free a cacheable object
+ * @arg obj object to free
+ *
+ * @return 0 or a negative error code.
+ */
+void nl_object_free(struct nl_object *obj)
+{
+ struct nl_object_ops *ops = obj_ops(obj);
+
+ if (obj->ce_refcnt > 0)
+ NL_DBG(1, "Warning: Freeing object in use...\n");
+
+ if (obj->ce_cache)
+ nl_cache_remove(obj);
+
+ if (ops->oo_free_data)
+ ops->oo_free_data(obj);
+
+ free(obj);
+
+ NL_DBG(4, "Freed object %p\n", obj);
+}
+
+/** @} */
+
+/**
+ * @name Reference Management
+ * @{
+ */
+
+/**
+ * Acquire a reference on a object
+ * @arg obj object to acquire reference from
+ */
+void nl_object_get(struct nl_object *obj)
+{
+ obj->ce_refcnt++;
+ NL_DBG(4, "New reference to object %p, total %d\n",
+ obj, obj->ce_refcnt);
+}
+
+/**
+ * Release a reference from an object
+ * @arg obj object to release reference from
+ */
+void nl_object_put(struct nl_object *obj)
+{
+ if (!obj)
+ return;
+
+ obj->ce_refcnt--;
+ NL_DBG(4, "Returned object reference %p, %d remaining\n",
+ obj, obj->ce_refcnt);
+
+ if (obj->ce_refcnt < 0)
+ BUG();
+
+ if (obj->ce_refcnt <= 0)
+ nl_object_free(obj);
+}
+
+/**
+ * Check whether this object is used by multiple users
+ * @arg obj object to check
+ * @return true or false
+ */
+int nl_object_shared(struct nl_object *obj)
+{
+ return obj->ce_refcnt > 1;
+}
+
+/** @} */
+
+/**
+ * @name Marks
+ * @{
+ */
+
+/**
+ * Add mark to object
+ * @arg obj Object to mark
+ */
+void nl_object_mark(struct nl_object *obj)
+{
+ obj->ce_flags |= NL_OBJ_MARK;
+}
+
+/**
+ * Remove mark from object
+ * @arg obj Object to unmark
+ */
+void nl_object_unmark(struct nl_object *obj)
+{
+ obj->ce_flags &= ~NL_OBJ_MARK;
+}
+
+/**
+ * Return true if object is marked
+ * @arg obj Object to check
+ * @return true if object is marked, otherwise false
+ */
+int nl_object_is_marked(struct nl_object *obj)
+{
+ return (obj->ce_flags & NL_OBJ_MARK);
+}
+
+/** @} */
+
+/**
+ * @name Utillities
+ * @{
+ */
+
+/**
+ * Dump this object according to the specified parameters
+ * @arg obj object to dump
+ * @arg params dumping parameters
+ */
+void nl_object_dump(struct nl_object *obj, struct nl_dump_params *params)
+{
+ dump_from_ops(obj, params);
+}
+
+/**
+ * Check if the identifiers of two objects are identical
+ * @arg a an object
+ * @arg b another object of same type
+ *
+ * @return true if both objects have equal identifiers, otherwise false.
+ */
+int nl_object_identical(struct nl_object *a, struct nl_object *b)
+{
+ struct nl_object_ops *ops = obj_ops(a);
+ int req_attrs;
+
+ /* Both objects must be of same type */
+ if (ops != obj_ops(b))
+ return 0;
+
+ req_attrs = ops->oo_id_attrs;
+
+ /* Both objects must provide all required attributes to uniquely
+ * identify an object */
+ if ((a->ce_mask & req_attrs) != req_attrs ||
+ (b->ce_mask & req_attrs) != req_attrs)
+ return 0;
+
+ /* Can't judge unless we can compare */
+ if (ops->oo_compare == NULL)
+ return 0;
+
+ return !(ops->oo_compare(a, b, req_attrs, 0));
+}
+
+/**
+ * Compute bitmask representing difference in attribute values
+ * @arg a an object
+ * @arg b another object of same type
+ *
+ * The bitmask returned is specific to an object type, each bit set represents
+ * an attribute which mismatches in either of the two objects. Unavailability
+ * of an attribute in one object and presence in the other is regarded a
+ * mismatch as well.
+ *
+ * @return Bitmask describing differences or 0 if they are completely identical.
+ */
+uint32_t nl_object_diff(struct nl_object *a, struct nl_object *b)
+{
+ struct nl_object_ops *ops = obj_ops(a);
+
+ if (ops != obj_ops(b) || ops->oo_compare == NULL)
+ return UINT_MAX;
+
+ return ops->oo_compare(a, b, ~0, 0);
+}
+
+/**
+ * Match a filter against an object
+ * @arg obj object to check
+ * @arg filter object of same type acting as filter
+ *
+ * @return 1 if the object matches the filter or 0
+ * if no filter procedure is available or if the
+ * filter does not match.
+ */
+int nl_object_match_filter(struct nl_object *obj, struct nl_object *filter)
+{
+ struct nl_object_ops *ops = obj_ops(obj);
+
+ if (ops != obj_ops(filter) || ops->oo_compare == NULL)
+ return 0;
+
+ return !(ops->oo_compare(obj, filter, filter->ce_mask,
+ LOOSE_FLAG_COMPARISON));
+}
+
+/**
+ * Convert bitmask of attributes to a character string
+ * @arg obj object of same type as attribute bitmask
+ * @arg attrs bitmask of attribute types
+ * @arg buf destination buffer
+ * @arg len length of destination buffer
+ *
+ * Converts the bitmask of attribute types into a list of attribute
+ * names separated by comas.
+ *
+ * @return destination buffer.
+ */
+char *nl_object_attrs2str(struct nl_object *obj, uint32_t attrs,
+ char *buf, size_t len)
+{
+ struct nl_object_ops *ops = obj_ops(obj);
+
+ if (ops->oo_attrs2str != NULL)
+ return ops->oo_attrs2str(attrs, buf, len);
+ else {
+ memset(buf, 0, len);
+ return buf;
+ }
+}
+
+/**
+ * Return list of attributes present in an object
+ * @arg obj an object
+ * @arg buf destination buffer
+ * @arg len length of destination buffer
+ *
+ * @return destination buffer.
+ */
+char *nl_object_attr_list(struct nl_object *obj, char *buf, size_t len)
+{
+ return nl_object_attrs2str(obj, obj->ce_mask, buf, len);
+}
+
+/** @} */
+
+/**
+ * @name Attributes
+ * @{
+ */
+
+int nl_object_get_refcnt(struct nl_object *obj)
+{
+ return obj->ce_refcnt;
+}
+
+struct nl_cache *nl_object_get_cache(struct nl_object *obj)
+{
+ return obj->ce_cache;
+}
+
+inline void *nl_object_priv(struct nl_object *obj)
+{
+ return obj;
+}
+
+/** @} */
+
+/** @} */
diff --git a/lib/route/addr.c b/lib/route/addr.c
new file mode 100644
index 0000000..1947b5a
--- /dev/null
+++ b/lib/route/addr.c
@@ -0,0 +1,1130 @@
+/*
+ * lib/route/addr.c Addresses
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ * Baruch Even <baruch@ev-en.org>,
+ * Mediatrix Telecom, inc. <ericb@mediatrix.com>
+ */
+
+/**
+ * @ingroup rtnl
+ * @defgroup rtaddr Addresses
+ * @brief
+ *
+ * @note The maximum size of an address label is IFNAMSIZ.
+ *
+ * @note The address may not contain a prefix length if the peer address
+ * has been specified already.
+ *
+ * @par 1) Address Addition
+ * @code
+ * // Allocate an empty address object to be filled out with the attributes
+ * // of the new address.
+ * struct rtnl_addr *addr = rtnl_addr_alloc();
+ *
+ * // Fill out the mandatory attributes of the new address. Setting the
+ * // local address will automatically set the address family and the
+ * // prefix length to the correct values.
+ * rtnl_addr_set_ifindex(addr, ifindex);
+ * rtnl_addr_set_local(addr, local_addr);
+ *
+ * // The label of the address can be specified, currently only supported
+ * // by IPv4 and DECnet.
+ * rtnl_addr_set_label(addr, "mylabel");
+ *
+ * // The peer address can be specified if necessary, in either case a peer
+ * // address will be sent to the kernel in order to fullfil the interface
+ * // requirements. If none is set, it will equal the local address.
+ * // Note: Real peer addresses are only supported by IPv4 for now.
+ * rtnl_addr_set_peer(addr, peer_addr);
+ *
+ * // In case you want to have the address have a scope other than global
+ * // it may be overwritten using rtnl_addr_set_scope(). The scope currently
+ * // cannot be set for IPv6 addresses.
+ * rtnl_addr_set_scope(addr, rtnl_str2scope("site"));
+ *
+ * // Broadcast and anycast address may be specified using the relevant
+ * // functions, the address family will be verified if one of the other
+ * // addresses has been set already. Currently only works for IPv4.
+ * rtnl_addr_set_broadcast(addr, broadcast_addr);
+ * rtnl_addr_set_anycast(addr, anycast_addr);
+ *
+ * // Build the netlink message and send it to the kernel, the operation will
+ * // block until the operation has been completed. Alternatively the required
+ * // netlink message can be built using rtnl_addr_build_add_request() to be
+ * // sent out using nl_send_auto_complete().
+ * rtnl_addr_add(handle, addr, 0);
+ *
+ * // Free the memory
+ * rtnl_addr_put(addr);
+ * @endcode
+ *
+ * @par 2) Address Deletion
+ * @code
+ * // Allocate an empty address object to be filled out with the attributes
+ * // matching the address to be deleted. Alternatively a fully equipped
+ * // address object out of a cache can be used instead.
+ * struct rtnl_addr *addr = rtnl_addr_alloc();
+ *
+ * // The only mandatory parameter besides the address family is the interface
+ * // index the address is on, i.e. leaving out all other parameters will
+ * // result in all addresses of the specified address family interface tuple
+ * // to be deleted.
+ * rtnl_addr_set_ifindex(addr, ifindex);
+ *
+ * // Specyfing the address family manually is only required if neither the
+ * // local nor peer address have been specified.
+ * rtnl_addr_set_family(addr, AF_INET);
+ *
+ * // Specyfing the local address is optional but the best choice to delete
+ * // specific addresses.
+ * rtnl_addr_set_local(addr, local_addr);
+ *
+ * // The label of the address can be specified, currently only supported
+ * // by IPv4 and DECnet.
+ * rtnl_addr_set_label(addr, "mylabel");
+ *
+ * // The peer address can be specified if necessary, in either case a peer
+ * // address will be sent to the kernel in order to fullfil the interface
+ * // requirements. If none is set, it will equal the local address.
+ * // Note: Real peer addresses are only supported by IPv4 for now.
+ * rtnl_addr_set_peer(addr, peer_addr);
+ *
+ * // Build the netlink message and send it to the kernel, the operation will
+ * // block until the operation has been completed. Alternatively the required
+ * // netlink message can be built using rtnl_addr_build_delete_request()
+ * // to be sent out using nl_send_auto_complete().
+ * rtnl_addr_delete(handle, addr, 0);
+ *
+ * // Free the memory
+ * rtnl_addr_put(addr);
+ * @endcode
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/route/rtnl.h>
+#include <netlink/route/addr.h>
+#include <netlink/route/route.h>
+#include <netlink/route/link.h>
+#include <netlink/utils.h>
+
+/** @cond SKIP */
+#define ADDR_ATTR_FAMILY 0x0001
+#define ADDR_ATTR_PREFIXLEN 0x0002
+#define ADDR_ATTR_FLAGS 0x0004
+#define ADDR_ATTR_SCOPE 0x0008
+#define ADDR_ATTR_IFINDEX 0x0010
+#define ADDR_ATTR_LABEL 0x0020
+#define ADDR_ATTR_CACHEINFO 0x0040
+#define ADDR_ATTR_PEER 0x0080
+#define ADDR_ATTR_LOCAL 0x0100
+#define ADDR_ATTR_BROADCAST 0x0200
+#define ADDR_ATTR_ANYCAST 0x0400
+#define ADDR_ATTR_MULTICAST 0x0800
+
+static struct nl_cache_ops rtnl_addr_ops;
+static struct nl_object_ops addr_obj_ops;
+/** @endcond */
+
+static void addr_free_data(struct nl_object *obj)
+{
+ struct rtnl_addr *addr = nl_object_priv(obj);
+
+ if (!addr)
+ return;
+
+ nl_addr_put(addr->a_peer);
+ nl_addr_put(addr->a_local);
+ nl_addr_put(addr->a_bcast);
+ nl_addr_put(addr->a_anycast);
+ nl_addr_put(addr->a_multicast);
+}
+
+static int addr_clone(struct nl_object *_dst, struct nl_object *_src)
+{
+ struct rtnl_addr *dst = nl_object_priv(_dst);
+ struct rtnl_addr *src = nl_object_priv(_src);
+
+ if (src->a_peer)
+ if (!(dst->a_peer = nl_addr_clone(src->a_peer)))
+ goto errout;
+
+ if (src->a_local)
+ if (!(dst->a_local = nl_addr_clone(src->a_local)))
+ goto errout;
+
+ if (src->a_bcast)
+ if (!(dst->a_bcast = nl_addr_clone(src->a_bcast)))
+ goto errout;
+
+ if (src->a_anycast)
+ if (!(dst->a_anycast = nl_addr_clone(src->a_anycast)))
+ goto errout;
+
+ if (src->a_multicast)
+ if (!(dst->a_multicast = nl_addr_clone(src->a_multicast)))
+ goto errout;
+
+ return 0;
+errout:
+ return nl_get_errno();
+}
+
+static struct nla_policy addr_policy[IFA_MAX+1] = {
+ [IFA_LABEL] = { .type = NLA_STRING,
+ .maxlen = IFNAMSIZ },
+ [IFA_CACHEINFO] = { .minlen = sizeof(struct ifa_cacheinfo) },
+};
+
+static int addr_msg_parser(struct nl_cache_ops *ops, struct sockaddr_nl *who,
+ struct nlmsghdr *nlh, void *arg)
+{
+ struct rtnl_addr *addr;
+ struct nl_parser_param *pp = arg;
+ struct ifaddrmsg *ifa;
+ struct nlattr *tb[IFA_MAX+1];
+ int err = -ENOMEM, peer_prefix = 0;
+
+ addr = rtnl_addr_alloc();
+ if (!addr) {
+ err = nl_errno(ENOMEM);
+ goto errout;
+ }
+ addr->ce_msgtype = nlh->nlmsg_type;
+
+ err = nlmsg_parse(nlh, sizeof(*ifa), tb, IFA_MAX, addr_policy);
+ if (err < 0)
+ goto errout_free;
+
+ ifa = nlmsg_data(nlh);
+ addr->a_family = ifa->ifa_family;
+ addr->a_prefixlen = ifa->ifa_prefixlen;
+ addr->a_flags = ifa->ifa_flags;
+ addr->a_scope = ifa->ifa_scope;
+ addr->a_ifindex = ifa->ifa_index;
+
+ addr->ce_mask = (ADDR_ATTR_FAMILY | ADDR_ATTR_PREFIXLEN |
+ ADDR_ATTR_FLAGS | ADDR_ATTR_SCOPE | ADDR_ATTR_IFINDEX);
+
+ if (tb[IFA_LABEL]) {
+ nla_strlcpy(addr->a_label, tb[IFA_LABEL], IFNAMSIZ);
+ addr->ce_mask |= ADDR_ATTR_LABEL;
+ }
+
+ if (tb[IFA_CACHEINFO]) {
+ struct ifa_cacheinfo *ca;
+
+ ca = nla_data(tb[IFA_CACHEINFO]);
+ addr->a_cacheinfo.aci_prefered = ca->ifa_prefered;
+ addr->a_cacheinfo.aci_valid = ca->ifa_valid;
+ addr->a_cacheinfo.aci_cstamp = ca->cstamp;
+ addr->a_cacheinfo.aci_tstamp = ca->tstamp;
+ addr->ce_mask |= ADDR_ATTR_CACHEINFO;
+ }
+
+ if (tb[IFA_LOCAL]) {
+ addr->a_local = nla_get_addr(tb[IFA_LOCAL], addr->a_family);
+ if (!addr->a_local)
+ goto errout_free;
+ addr->ce_mask |= ADDR_ATTR_LOCAL;
+ }
+
+ if (tb[IFA_ADDRESS]) {
+ struct nl_addr *a;
+
+ a = nla_get_addr(tb[IFA_ADDRESS], addr->a_family);
+ if (!a)
+ goto errout_free;
+
+ /* IPv6 sends the local address as IFA_ADDRESS with
+ * no IFA_LOCAL, IPv4 sends both IFA_LOCAL and IFA_ADDRESS
+ * with IFA_ADDRESS being the peer address if they differ */
+ if (!tb[IFA_LOCAL] || !nl_addr_cmp(a, addr->a_local)) {
+ nl_addr_put(addr->a_local);
+ addr->a_local = a;
+ addr->ce_mask |= ADDR_ATTR_LOCAL;
+ } else {
+ addr->a_peer = a;
+ addr->ce_mask |= ADDR_ATTR_PEER;
+ peer_prefix = 1;
+ }
+ }
+
+ nl_addr_set_prefixlen(peer_prefix ? addr->a_peer : addr->a_local,
+ addr->a_prefixlen);
+
+ if (tb[IFA_BROADCAST]) {
+ addr->a_bcast = nla_get_addr(tb[IFA_BROADCAST], addr->a_family);
+ if (!addr->a_bcast)
+ goto errout_free;
+
+ addr->ce_mask |= ADDR_ATTR_BROADCAST;
+ }
+
+ if (tb[IFA_ANYCAST]) {
+ addr->a_anycast = nla_get_addr(tb[IFA_ANYCAST], addr->a_family);
+ if (!addr->a_anycast)
+ goto errout_free;
+
+ addr->ce_mask |= ADDR_ATTR_ANYCAST;
+ }
+
+ if (tb[IFA_MULTICAST]) {
+ addr->a_multicast = nla_get_addr(tb[IFA_MULTICAST],
+ addr->a_family);
+ if (!addr->a_multicast)
+ goto errout_free;
+
+ addr->ce_mask |= ADDR_ATTR_MULTICAST;
+ }
+
+ err = pp->pp_cb((struct nl_object *) addr, pp);
+ if (err < 0)
+ goto errout_free;
+
+ return P_ACCEPT;
+
+errout_free:
+ rtnl_addr_put(addr);
+errout:
+ return err;
+}
+
+static int addr_request_update(struct nl_cache *cache, struct nl_handle *handle)
+{
+ return nl_rtgen_request(handle, RTM_GETADDR, AF_UNSPEC, NLM_F_DUMP);
+}
+
+static int addr_dump_brief(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_addr *addr = (struct rtnl_addr *) obj;
+ struct nl_cache *link_cache;
+ char buf[128];
+
+ link_cache = nl_cache_mngt_require("route/link");
+
+ if (addr->ce_mask & ADDR_ATTR_LOCAL)
+ dp_dump(p, "%s",
+ nl_addr2str(addr->a_local, buf, sizeof(buf)));
+ else
+ dp_dump(p, "none");
+
+ if (addr->ce_mask & ADDR_ATTR_PEER)
+ dp_dump(p, " peer %s",
+ nl_addr2str(addr->a_peer, buf, sizeof(buf)));
+
+ dp_dump(p, " %s ", nl_af2str(addr->a_family, buf, sizeof(buf)));
+
+ if (link_cache)
+ dp_dump(p, "dev %s ",
+ rtnl_link_i2name(link_cache, addr->a_ifindex,
+ buf, sizeof(buf)));
+ else
+ dp_dump(p, "dev %d ", addr->a_ifindex);
+
+ dp_dump(p, "scope %s",
+ rtnl_scope2str(addr->a_scope, buf, sizeof(buf)));
+
+ rtnl_addr_flags2str(addr->a_flags, buf, sizeof(buf));
+ if (buf[0])
+ dp_dump(p, " <%s>", buf);
+
+ dp_dump(p, "\n");
+
+ return 1;
+}
+
+static int addr_dump_full(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_addr *addr = (struct rtnl_addr *) obj;
+ int line = addr_dump_brief(obj, p);
+ char buf[128];
+
+ if (addr->ce_mask & (ADDR_ATTR_LABEL | ADDR_ATTR_BROADCAST |
+ ADDR_ATTR_ANYCAST | ADDR_ATTR_MULTICAST)) {
+ dp_dump_line(p, line++, " ");
+
+ if (addr->ce_mask & ADDR_ATTR_LABEL)
+ dp_dump(p, " label %s", addr->a_label);
+
+ if (addr->ce_mask & ADDR_ATTR_BROADCAST)
+ dp_dump(p, " broadcast %s",
+ nl_addr2str(addr->a_bcast, buf, sizeof(buf)));
+
+ if (addr->ce_mask & ADDR_ATTR_ANYCAST)
+ dp_dump(p, " anycast %s",
+ nl_addr2str(addr->a_anycast, buf,
+ sizeof(buf)));
+
+ if (addr->ce_mask & ADDR_ATTR_MULTICAST)
+ dp_dump(p, " multicast %s",
+ nl_addr2str(addr->a_multicast, buf,
+ sizeof(buf)));
+
+ dp_dump(p, "\n");
+ }
+
+ if (addr->ce_mask & ADDR_ATTR_CACHEINFO) {
+ struct rtnl_addr_cacheinfo *ci = &addr->a_cacheinfo;
+
+ dp_dump_line(p, line++, " valid-lifetime %s",
+ ci->aci_valid == 0xFFFFFFFFU ? "forever" :
+ nl_msec2str(ci->aci_valid * 1000,
+ buf, sizeof(buf)));
+
+ dp_dump(p, " preferred-lifetime %s\n",
+ ci->aci_prefered == 0xFFFFFFFFU ? "forever" :
+ nl_msec2str(ci->aci_prefered * 1000,
+ buf, sizeof(buf)));
+
+ dp_dump_line(p, line++, " created boot-time+%s ",
+ nl_msec2str(addr->a_cacheinfo.aci_cstamp * 10,
+ buf, sizeof(buf)));
+
+ dp_dump(p, "last-updated boot-time+%s\n",
+ nl_msec2str(addr->a_cacheinfo.aci_tstamp * 10,
+ buf, sizeof(buf)));
+ }
+
+ return line;
+}
+
+static int addr_dump_stats(struct nl_object *obj, struct nl_dump_params *p)
+{
+ return addr_dump_full(obj, p);
+}
+
+static int addr_dump_xml(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_addr *addr = (struct rtnl_addr *) obj;
+ struct nl_cache *link_cache;
+ char buf[128];
+ int line = 0;
+
+ dp_dump_line(p, line++, "<address>\n");
+ dp_dump_line(p, line++, " <family>%s</family>\n",
+ nl_af2str(addr->a_family, buf, sizeof(buf)));
+
+ if (addr->ce_mask & ADDR_ATTR_LOCAL)
+ dp_dump_line(p, line++, " <local>%s</local>\n",
+ nl_addr2str(addr->a_local, buf, sizeof(buf)));
+
+ if (addr->ce_mask & ADDR_ATTR_PEER)
+ dp_dump_line(p, line++, " <peer>%s</peer>\n",
+ nl_addr2str(addr->a_peer, buf, sizeof(buf)));
+
+ if (addr->ce_mask & ADDR_ATTR_BROADCAST)
+ dp_dump_line(p, line++, " <broadcast>%s</broadcast>\n",
+ nl_addr2str(addr->a_bcast, buf, sizeof(buf)));
+
+ if (addr->ce_mask & ADDR_ATTR_ANYCAST)
+ dp_dump_line(p, line++, " <anycast>%s</anycast>\n",
+ nl_addr2str(addr->a_anycast, buf, sizeof(buf)));
+
+ if (addr->ce_mask & ADDR_ATTR_MULTICAST)
+ dp_dump_line(p, line++, " <multicast>%s</multicast>\n",
+ nl_addr2str(addr->a_multicast, buf,
+ sizeof(buf)));
+
+ if (addr->ce_mask & ADDR_ATTR_PREFIXLEN)
+ dp_dump_line(p, line++, " <prefixlen>%u</prefixlen>\n",
+ addr->a_prefixlen);
+ link_cache = nl_cache_mngt_require("route/link");
+
+ if (link_cache)
+ dp_dump_line(p, line++, " <device>%s</device>\n",
+ rtnl_link_i2name(link_cache, addr->a_ifindex,
+ buf, sizeof(buf)));
+ else
+ dp_dump_line(p, line++, " <device>%u</device>\n",
+ addr->a_ifindex);
+
+ if (addr->ce_mask & ADDR_ATTR_SCOPE)
+ dp_dump_line(p, line++, " <scope>%s</scope>\n",
+ rtnl_scope2str(addr->a_scope, buf, sizeof(buf)));
+
+ if (addr->ce_mask & ADDR_ATTR_LABEL)
+ dp_dump_line(p, line++, " <label>%s</label>\n", addr->a_label);
+
+ rtnl_addr_flags2str(addr->a_flags, buf, sizeof(buf));
+ if (buf[0])
+ dp_dump_line(p, line++, " <flags>%s</flags>\n", buf);
+
+ if (addr->ce_mask & ADDR_ATTR_CACHEINFO) {
+ struct rtnl_addr_cacheinfo *ci = &addr->a_cacheinfo;
+
+ dp_dump_line(p, line++, " <cacheinfo>\n");
+
+ dp_dump_line(p, line++, " <valid>%s</valid>\n",
+ ci->aci_valid == 0xFFFFFFFFU ? "forever" :
+ nl_msec2str(ci->aci_valid * 1000,
+ buf, sizeof(buf)));
+
+ dp_dump_line(p, line++, " <prefered>%s</prefered>\n",
+ ci->aci_prefered == 0xFFFFFFFFU ? "forever" :
+ nl_msec2str(ci->aci_prefered * 1000,
+ buf, sizeof(buf)));
+
+ dp_dump_line(p, line++, " <created>%s</created>\n",
+ nl_msec2str(addr->a_cacheinfo.aci_cstamp * 10,
+ buf, sizeof(buf)));
+
+ dp_dump_line(p, line++, " <last-update>%s</last-update>\n",
+ nl_msec2str(addr->a_cacheinfo.aci_tstamp * 10,
+ buf, sizeof(buf)));
+
+ dp_dump_line(p, line++, " </cacheinfo>\n");
+ }
+
+ dp_dump_line(p, line++, "</address>\n");
+
+ return line;
+}
+
+static int addr_dump_env(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_addr *addr = (struct rtnl_addr *) obj;
+ struct nl_cache *link_cache;
+ char buf[128];
+ int line = 0;
+
+ dp_dump_line(p, line++, "ADDR_FAMILY=%s\n",
+ nl_af2str(addr->a_family, buf, sizeof(buf)));
+
+ if (addr->ce_mask & ADDR_ATTR_LOCAL)
+ dp_dump_line(p, line++, "ADDR_LOCAL=%s\n",
+ nl_addr2str(addr->a_local, buf, sizeof(buf)));
+
+ if (addr->ce_mask & ADDR_ATTR_PEER)
+ dp_dump_line(p, line++, "ADDR_PEER=%s\n",
+ nl_addr2str(addr->a_peer, buf, sizeof(buf)));
+
+ if (addr->ce_mask & ADDR_ATTR_BROADCAST)
+ dp_dump_line(p, line++, "ADDR_BROADCAST=%s\n",
+ nl_addr2str(addr->a_bcast, buf, sizeof(buf)));
+
+ if (addr->ce_mask & ADDR_ATTR_ANYCAST)
+ dp_dump_line(p, line++, "ADDR_ANYCAST=%s\n",
+ nl_addr2str(addr->a_anycast, buf, sizeof(buf)));
+
+ if (addr->ce_mask & ADDR_ATTR_MULTICAST)
+ dp_dump_line(p, line++, "ADDR_MULTICAST=%s\n",
+ nl_addr2str(addr->a_multicast, buf,
+ sizeof(buf)));
+
+ if (addr->ce_mask & ADDR_ATTR_PREFIXLEN)
+ dp_dump_line(p, line++, "ADDR_PREFIXLEN=%u\n",
+ addr->a_prefixlen);
+ link_cache = nl_cache_mngt_require("route/link");
+
+ dp_dump_line(p, line++, "ADDR_IFINDEX=%u\n", addr->a_ifindex);
+ if (link_cache)
+ dp_dump_line(p, line++, "ADDR_IFNAME=%s\n",
+ rtnl_link_i2name(link_cache, addr->a_ifindex,
+ buf, sizeof(buf)));
+
+ if (addr->ce_mask & ADDR_ATTR_SCOPE)
+ dp_dump_line(p, line++, "ADDR_SCOPE=%s\n",
+ rtnl_scope2str(addr->a_scope, buf, sizeof(buf)));
+
+ if (addr->ce_mask & ADDR_ATTR_LABEL)
+ dp_dump_line(p, line++, "ADDR_LABEL=%s\n", addr->a_label);
+
+ rtnl_addr_flags2str(addr->a_flags, buf, sizeof(buf));
+ if (buf[0])
+ dp_dump_line(p, line++, "ADDR_FLAGS=%s\n", buf);
+
+ if (addr->ce_mask & ADDR_ATTR_CACHEINFO) {
+ struct rtnl_addr_cacheinfo *ci = &addr->a_cacheinfo;
+
+ dp_dump_line(p, line++, "ADDR_CACHEINFO_VALID=%s\n",
+ ci->aci_valid == 0xFFFFFFFFU ? "forever" :
+ nl_msec2str(ci->aci_valid * 1000,
+ buf, sizeof(buf)));
+
+ dp_dump_line(p, line++, "ADDR_CACHEINFO_PREFERED=%s\n",
+ ci->aci_prefered == 0xFFFFFFFFU ? "forever" :
+ nl_msec2str(ci->aci_prefered * 1000,
+ buf, sizeof(buf)));
+
+ dp_dump_line(p, line++, "ADDR_CACHEINFO_CREATED=%s\n",
+ nl_msec2str(addr->a_cacheinfo.aci_cstamp * 10,
+ buf, sizeof(buf)));
+
+ dp_dump_line(p, line++, "ADDR_CACHEINFO_LASTUPDATE=%s\n",
+ nl_msec2str(addr->a_cacheinfo.aci_tstamp * 10,
+ buf, sizeof(buf)));
+ }
+
+ return line;
+}
+
+static int addr_compare(struct nl_object *_a, struct nl_object *_b,
+ uint32_t attrs, int flags)
+{
+ struct rtnl_addr *a = (struct rtnl_addr *) _a;
+ struct rtnl_addr *b = (struct rtnl_addr *) _b;
+ int diff = 0;
+
+#define ADDR_DIFF(ATTR, EXPR) ATTR_DIFF(attrs, ADDR_ATTR_##ATTR, a, b, EXPR)
+
+ diff |= ADDR_DIFF(IFINDEX, a->a_ifindex != b->a_ifindex);
+ diff |= ADDR_DIFF(FAMILY, a->a_family != b->a_family);
+ diff |= ADDR_DIFF(SCOPE, a->a_scope != b->a_scope);
+ diff |= ADDR_DIFF(LABEL, strcmp(a->a_label, b->a_label));
+ diff |= ADDR_DIFF(PEER, nl_addr_cmp(a->a_peer, b->a_peer));
+ diff |= ADDR_DIFF(LOCAL, nl_addr_cmp(a->a_local, b->a_local));
+ diff |= ADDR_DIFF(ANYCAST, nl_addr_cmp(a->a_anycast,b->a_anycast));
+ diff |= ADDR_DIFF(MULTICAST, nl_addr_cmp(a->a_multicast,
+ b->a_multicast));
+ diff |= ADDR_DIFF(BROADCAST, nl_addr_cmp(a->a_bcast, b->a_bcast));
+
+ if (flags & LOOSE_FLAG_COMPARISON)
+ diff |= ADDR_DIFF(FLAGS,
+ (a->a_flags ^ b->a_flags) & b->a_flag_mask);
+ else
+ diff |= ADDR_DIFF(FLAGS, a->a_flags != b->a_flags);
+
+#undef ADDR_DIFF
+
+ return diff;
+}
+
+static struct trans_tbl addr_attrs[] = {
+ __ADD(ADDR_ATTR_FAMILY, family)
+ __ADD(ADDR_ATTR_PREFIXLEN, prefixlen)
+ __ADD(ADDR_ATTR_FLAGS, flags)
+ __ADD(ADDR_ATTR_SCOPE, scope)
+ __ADD(ADDR_ATTR_IFINDEX, ifindex)
+ __ADD(ADDR_ATTR_LABEL, label)
+ __ADD(ADDR_ATTR_CACHEINFO, cacheinfo)
+ __ADD(ADDR_ATTR_PEER, peer)
+ __ADD(ADDR_ATTR_LOCAL, local)
+ __ADD(ADDR_ATTR_BROADCAST, broadcast)
+ __ADD(ADDR_ATTR_ANYCAST, anycast)
+ __ADD(ADDR_ATTR_MULTICAST, multicast)
+};
+
+static char *addr_attrs2str(int attrs, char *buf, size_t len)
+{
+ return __flags2str(attrs, buf, len, addr_attrs,
+ ARRAY_SIZE(addr_attrs));
+}
+
+/**
+ * @name Allocation/Freeing
+ * @{
+ */
+
+struct rtnl_addr *rtnl_addr_alloc(void)
+{
+ return (struct rtnl_addr *) nl_object_alloc(&addr_obj_ops);
+}
+
+void rtnl_addr_put(struct rtnl_addr *addr)
+{
+ nl_object_put((struct nl_object *) addr);
+}
+
+/** @} */
+
+/**
+ * @name Cache Management
+ * @{
+ */
+
+struct nl_cache *rtnl_addr_alloc_cache(struct nl_handle *handle)
+{
+ struct nl_cache *cache;
+
+ cache = nl_cache_alloc(&rtnl_addr_ops);
+ if (!cache)
+ return NULL;
+
+ if (handle && nl_cache_refill(handle, cache) < 0) {
+ nl_cache_free(cache);
+ return NULL;
+ }
+
+ return cache;
+}
+
+/** @} */
+
+static struct nl_msg *build_addr_msg(struct rtnl_addr *tmpl, int cmd, int flags)
+{
+ struct nl_msg *msg;
+ struct ifaddrmsg am = {
+ .ifa_family = tmpl->a_family,
+ .ifa_index = tmpl->a_ifindex,
+ .ifa_prefixlen = tmpl->a_prefixlen,
+ };
+
+ if (tmpl->ce_mask & ADDR_ATTR_SCOPE)
+ am.ifa_scope = tmpl->a_scope;
+ else {
+ /* compatibility hack */
+ if (tmpl->a_family == AF_INET &&
+ tmpl->ce_mask & ADDR_ATTR_LOCAL &&
+ *((char *) nl_addr_get_binary_addr(tmpl->a_local)) == 127)
+ am.ifa_scope = RT_SCOPE_HOST;
+ else
+ am.ifa_scope = RT_SCOPE_UNIVERSE;
+ }
+
+ msg = nlmsg_alloc_simple(cmd, flags);
+ if (!msg)
+ goto nla_put_failure;
+
+ if (nlmsg_append(msg, &am, sizeof(am), NLMSG_ALIGNTO) < 0)
+ goto nla_put_failure;
+
+ if (tmpl->ce_mask & ADDR_ATTR_LOCAL)
+ NLA_PUT_ADDR(msg, IFA_LOCAL, tmpl->a_local);
+
+ if (tmpl->ce_mask & ADDR_ATTR_PEER)
+ NLA_PUT_ADDR(msg, IFA_ADDRESS, tmpl->a_peer);
+ else
+ NLA_PUT_ADDR(msg, IFA_ADDRESS, tmpl->a_local);
+
+ if (tmpl->ce_mask & ADDR_ATTR_LABEL)
+ NLA_PUT_STRING(msg, IFA_LABEL, tmpl->a_label);
+
+ if (tmpl->ce_mask & ADDR_ATTR_BROADCAST)
+ NLA_PUT_ADDR(msg, IFA_BROADCAST, tmpl->a_bcast);
+
+ if (tmpl->ce_mask & ADDR_ATTR_ANYCAST)
+ NLA_PUT_ADDR(msg, IFA_ANYCAST, tmpl->a_anycast);
+
+ return msg;
+
+nla_put_failure:
+ nlmsg_free(msg);
+ return NULL;
+}
+
+/**
+ * @name Addition
+ * @{
+ */
+
+/**
+ * Build netlink request message to request addition of new address
+ * @arg addr Address object representing the new address.
+ * @arg flags Additional netlink message flags.
+ *
+ * Builds a new netlink message requesting the addition of a new
+ * address. The netlink message header isn't fully equipped with
+ * all relevant fields and must thus be sent out via nl_send_auto_complete()
+ * or supplemented as needed.
+ *
+ * Minimal required attributes:
+ * - interface index (rtnl_addr_set_ifindex())
+ * - local address (rtnl_addr_set_local())
+ *
+ * The scope will default to universe except for loopback addresses in
+ * which case a host scope is used if not specified otherwise.
+ *
+ * @note Free the memory after usage using nlmsg_free().
+ * @return Newly allocated netlink message or NULL if an error occured.
+ */
+struct nl_msg *rtnl_addr_build_add_request(struct rtnl_addr *addr, int flags)
+{
+ int required = ADDR_ATTR_IFINDEX | ADDR_ATTR_FAMILY |
+ ADDR_ATTR_PREFIXLEN | ADDR_ATTR_LOCAL;
+
+ if ((addr->ce_mask & required) != required) {
+ nl_error(EINVAL, "Missing mandatory attributes, required are: "
+ "ifindex, family, prefixlen, local address.");
+ return NULL;
+ }
+
+ return build_addr_msg(addr, RTM_NEWADDR, NLM_F_CREATE | flags);
+}
+
+/**
+ * Request addition of new address
+ * @arg handle Netlink handle.
+ * @arg addr Address object representing the new address.
+ * @arg flags Additional netlink message flags.
+ *
+ * Builds a netlink message by calling rtnl_addr_build_add_request(),
+ * sends the request to the kernel and waits for the next ACK to be
+ * received and thus blocks until the request has been fullfilled.
+ *
+ * @see rtnl_addr_build_add_request()
+ *
+ * @return 0 on sucess or a negative error if an error occured.
+ */
+int rtnl_addr_add(struct nl_handle *handle, struct rtnl_addr *addr, int flags)
+{
+ struct nl_msg *msg;
+ int err;
+
+ msg = rtnl_addr_build_add_request(addr, flags);
+ if (!msg)
+ return nl_get_errno();
+
+ err = nl_send_auto_complete(handle, msg);
+ nlmsg_free(msg);
+ if (err < 0)
+ return err;
+
+ return nl_wait_for_ack(handle);
+}
+
+/** @} */
+
+/**
+ * @name Deletion
+ * @{
+ */
+
+/**
+ * Build a netlink request message to request deletion of an address
+ * @arg addr Address object to be deleteted.
+ * @arg flags Additional netlink message flags.
+ *
+ * Builds a new netlink message requesting a deletion of an address.
+ * The netlink message header isn't fully equipped with all relevant
+ * fields and must thus be sent out via nl_send_auto_complete()
+ * or supplemented as needed.
+ *
+ * Minimal required attributes:
+ * - interface index (rtnl_addr_set_ifindex())
+ * - address family (rtnl_addr_set_family())
+ *
+ * Optional attributes:
+ * - local address (rtnl_addr_set_local())
+ * - label (rtnl_addr_set_label(), IPv4/DECnet only)
+ * - peer address (rtnl_addr_set_peer(), IPv4 only)
+ *
+ * @note Free the memory after usage using nlmsg_free().
+ * @return Newly allocated netlink message or NULL if an error occured.
+ */
+struct nl_msg *rtnl_addr_build_delete_request(struct rtnl_addr *addr, int flags)
+{
+ int required = ADDR_ATTR_IFINDEX | ADDR_ATTR_FAMILY;
+
+ if ((addr->ce_mask & required) != required) {
+ nl_error(EINVAL, "Missing mandatory attributes, required are: "
+ "ifindex, family");
+ return NULL;
+ }
+
+ return build_addr_msg(addr, RTM_DELADDR, flags);
+}
+
+/**
+ * Request deletion of an address
+ * @arg handle Netlink handle.
+ * @arg addr Address object to be deleted.
+ * @arg flags Additional netlink message flags.
+ *
+ * Builds a netlink message by calling rtnl_addr_build_delete_request(),
+ * sends the request to the kernel and waits for the next ACK to be
+ * received and thus blocks until the request has been fullfilled.
+ *
+ * @see rtnl_addr_build_delete_request();
+ *
+ * @return 0 on sucess or a negative error if an error occured.
+ */
+int rtnl_addr_delete(struct nl_handle *handle, struct rtnl_addr *addr,
+ int flags)
+{
+ struct nl_msg *msg;
+ int err;
+
+ msg = rtnl_addr_build_delete_request(addr, flags);
+ if (!msg)
+ return nl_get_errno();
+
+ err = nl_send_auto_complete(handle, msg);
+ nlmsg_free(msg);
+ if (err < 0)
+ return err;
+
+ return nl_wait_for_ack(handle);
+}
+
+/** @} */
+
+/**
+ * @name Attributes
+ * @{
+ */
+
+void rtnl_addr_set_label(struct rtnl_addr *addr, const char *label)
+{
+ strncpy(addr->a_label, label, sizeof(addr->a_label) - 1);
+ addr->ce_mask |= ADDR_ATTR_LABEL;
+}
+
+char *rtnl_addr_get_label(struct rtnl_addr *addr)
+{
+ if (addr->ce_mask & ADDR_ATTR_LABEL)
+ return addr->a_label;
+ else
+ return NULL;
+}
+
+void rtnl_addr_set_ifindex(struct rtnl_addr *addr, int ifindex)
+{
+ addr->a_ifindex = ifindex;
+ addr->ce_mask |= ADDR_ATTR_IFINDEX;
+}
+
+int rtnl_addr_get_ifindex(struct rtnl_addr *addr)
+{
+ if (addr->ce_mask & ADDR_ATTR_IFINDEX)
+ return addr->a_ifindex;
+ else
+ return RTNL_LINK_NOT_FOUND;
+}
+
+void rtnl_addr_set_family(struct rtnl_addr *addr, int family)
+{
+ addr->a_family = family;
+ addr->ce_mask |= ADDR_ATTR_FAMILY;
+}
+
+int rtnl_addr_get_family(struct rtnl_addr *addr)
+{
+ if (addr->ce_mask & ADDR_ATTR_FAMILY)
+ return addr->a_family;
+ else
+ return AF_UNSPEC;
+}
+
+void rtnl_addr_set_prefixlen(struct rtnl_addr *addr, int prefix)
+{
+ addr->a_prefixlen = prefix;
+ addr->ce_mask |= ADDR_ATTR_PREFIXLEN;
+}
+
+int rtnl_addr_get_prefixlen(struct rtnl_addr *addr)
+{
+ if (addr->ce_mask & ADDR_ATTR_PREFIXLEN)
+ return addr->a_prefixlen;
+ else
+ return -1;
+}
+
+void rtnl_addr_set_scope(struct rtnl_addr *addr, int scope)
+{
+ addr->a_scope = scope;
+ addr->ce_mask |= ADDR_ATTR_SCOPE;
+}
+
+int rtnl_addr_get_scope(struct rtnl_addr *addr)
+{
+ if (addr->ce_mask & ADDR_ATTR_SCOPE)
+ return addr->a_scope;
+ else
+ return -1;
+}
+
+void rtnl_addr_set_flags(struct rtnl_addr *addr, unsigned int flags)
+{
+ addr->a_flag_mask |= flags;
+ addr->a_flags |= flags;
+ addr->ce_mask |= ADDR_ATTR_FLAGS;
+}
+
+void rtnl_addr_unset_flags(struct rtnl_addr *addr, unsigned int flags)
+{
+ addr->a_flag_mask |= flags;
+ addr->a_flags &= ~flags;
+ addr->ce_mask |= ADDR_ATTR_FLAGS;
+}
+
+unsigned int rtnl_addr_get_flags(struct rtnl_addr *addr)
+{
+ return addr->a_flags;
+}
+
+static inline int __assign_addr(struct rtnl_addr *addr, struct nl_addr **pos,
+ struct nl_addr *new, int flag)
+{
+ if (addr->ce_mask & ADDR_ATTR_FAMILY) {
+ if (new->a_family != addr->a_family)
+ return nl_error(EINVAL, "Address family mismatch");
+ } else
+ addr->a_family = new->a_family;
+
+ if (*pos)
+ nl_addr_put(*pos);
+
+ *pos = nl_addr_get(new);
+ addr->ce_mask |= (flag | ADDR_ATTR_FAMILY);
+
+ return 0;
+}
+
+int rtnl_addr_set_local(struct rtnl_addr *addr, struct nl_addr *local)
+{
+ int err;
+
+ err = __assign_addr(addr, &addr->a_local, local, ADDR_ATTR_LOCAL);
+ if (err < 0)
+ return err;
+
+ if (!(addr->ce_mask & ADDR_ATTR_PEER)) {
+ addr->a_prefixlen = nl_addr_get_prefixlen(addr->a_local);
+ addr->ce_mask |= ADDR_ATTR_PREFIXLEN;
+ }
+
+ return 0;
+}
+
+struct nl_addr *rtnl_addr_get_local(struct rtnl_addr *addr)
+{
+ if (addr->ce_mask & ADDR_ATTR_LOCAL)
+ return addr->a_local;
+ else
+ return NULL;
+}
+
+int rtnl_addr_set_peer(struct rtnl_addr *addr, struct nl_addr *peer)
+{
+ return __assign_addr(addr, &addr->a_peer, peer, ADDR_ATTR_PEER);
+
+ addr->a_prefixlen = nl_addr_get_prefixlen(addr->a_peer);
+ addr->ce_mask |= ADDR_ATTR_PREFIXLEN;
+
+ return 0;
+}
+
+struct nl_addr *rtnl_addr_get_peer(struct rtnl_addr *addr)
+{
+ if (addr->ce_mask & ADDR_ATTR_PEER)
+ return addr->a_peer;
+ else
+ return NULL;
+}
+
+int rtnl_addr_set_broadcast(struct rtnl_addr *addr, struct nl_addr *bcast)
+{
+ return __assign_addr(addr, &addr->a_bcast, bcast, ADDR_ATTR_BROADCAST);
+}
+
+struct nl_addr *rtnl_addr_get_broadcast(struct rtnl_addr *addr)
+{
+ if (addr->ce_mask & ADDR_ATTR_BROADCAST)
+ return addr->a_bcast;
+ else
+ return NULL;
+}
+
+int rtnl_addr_set_anycast(struct rtnl_addr *addr, struct nl_addr *anycast)
+{
+ return __assign_addr(addr, &addr->a_anycast, anycast,
+ ADDR_ATTR_ANYCAST);
+}
+
+struct nl_addr *rtnl_addr_get_anycast(struct rtnl_addr *addr)
+{
+ if (addr->ce_mask & ADDR_ATTR_ANYCAST)
+ return addr->a_anycast;
+ else
+ return NULL;
+}
+
+int rtnl_addr_set_multicast(struct rtnl_addr *addr, struct nl_addr *multicast)
+{
+ return __assign_addr(addr, &addr->a_multicast, multicast,
+ ADDR_ATTR_MULTICAST);
+}
+
+struct nl_addr *rtnl_addr_get_multicast(struct rtnl_addr *addr)
+{
+ if (addr->ce_mask & ADDR_ATTR_MULTICAST)
+ return addr->a_multicast;
+ else
+ return NULL;
+}
+
+/** @} */
+
+/**
+ * @name Flags Translations
+ * @{
+ */
+
+static struct trans_tbl addr_flags[] = {
+ __ADD(IFA_F_SECONDARY, secondary)
+ __ADD(IFA_F_DEPRECATED, deprecated)
+ __ADD(IFA_F_TENTATIVE, tentative)
+ __ADD(IFA_F_PERMANENT, permanent)
+};
+
+char *rtnl_addr_flags2str(int flags, char *buf, size_t size)
+{
+ return __flags2str(flags, buf, size, addr_flags,
+ ARRAY_SIZE(addr_flags));
+}
+
+int rtnl_addr_str2flags(const char *name)
+{
+ return __str2flags(name, addr_flags, ARRAY_SIZE(addr_flags));
+}
+
+/** @} */
+
+static struct nl_object_ops addr_obj_ops = {
+ .oo_name = "route/addr",
+ .oo_size = sizeof(struct rtnl_addr),
+ .oo_free_data = addr_free_data,
+ .oo_clone = addr_clone,
+ .oo_dump[NL_DUMP_BRIEF] = addr_dump_brief,
+ .oo_dump[NL_DUMP_FULL] = addr_dump_full,
+ .oo_dump[NL_DUMP_STATS] = addr_dump_stats,
+ .oo_dump[NL_DUMP_XML] = addr_dump_xml,
+ .oo_dump[NL_DUMP_ENV] = addr_dump_env,
+ .oo_compare = addr_compare,
+ .oo_attrs2str = addr_attrs2str,
+ .oo_id_attrs = (ADDR_ATTR_FAMILY | ADDR_ATTR_IFINDEX |
+ ADDR_ATTR_LOCAL | ADDR_ATTR_PREFIXLEN |
+ ADDR_ATTR_PEER),
+};
+
+static struct nl_af_group addr_groups[] = {
+ { AF_INET, RTNLGRP_IPV4_IFADDR },
+ { AF_INET6, RTNLGRP_IPV6_IFADDR },
+ { END_OF_GROUP_LIST },
+};
+
+static struct nl_cache_ops rtnl_addr_ops = {
+ .co_name = "route/addr",
+ .co_hdrsize = sizeof(struct ifaddrmsg),
+ .co_msgtypes = {
+ { RTM_NEWADDR, NL_ACT_NEW, "new" },
+ { RTM_DELADDR, NL_ACT_DEL, "del" },
+ { RTM_GETADDR, NL_ACT_GET, "get" },
+ END_OF_MSGTYPES_LIST,
+ },
+ .co_protocol = NETLINK_ROUTE,
+ .co_groups = addr_groups,
+ .co_request_update = addr_request_update,
+ .co_msg_parser = addr_msg_parser,
+ .co_obj_ops = &addr_obj_ops,
+};
+
+static void __init addr_init(void)
+{
+ nl_cache_mngt_register(&rtnl_addr_ops);
+}
+
+static void __exit addr_exit(void)
+{
+ nl_cache_mngt_unregister(&rtnl_addr_ops);
+}
+
+/** @} */
diff --git a/lib/route/class.c b/lib/route/class.c
new file mode 100644
index 0000000..7f2289e
--- /dev/null
+++ b/lib/route/class.c
@@ -0,0 +1,230 @@
+/*
+ * lib/route/class.c Queueing Classes
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup tc
+ * @defgroup class Queueing Classes
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/route/tc.h>
+#include <netlink/route/class.h>
+#include <netlink/route/class-modules.h>
+#include <netlink/route/qdisc.h>
+#include <netlink/route/classifier.h>
+#include <netlink/utils.h>
+
+static struct nl_cache_ops rtnl_class_ops;
+
+static int class_msg_parser(struct nl_cache_ops *ops, struct sockaddr_nl *who,
+ struct nlmsghdr *n, void *arg)
+{
+ int err;
+ struct nl_parser_param *pp = arg;
+ struct rtnl_class *class;
+ struct rtnl_class_ops *cops;
+
+ class = rtnl_class_alloc();
+ if (!class) {
+ err = nl_errno(ENOMEM);
+ goto errout;
+ }
+ class->ce_msgtype = n->nlmsg_type;
+
+ err = tca_msg_parser(n, (struct rtnl_tca *) class);
+ if (err < 0)
+ goto errout_free;
+
+ cops = rtnl_class_lookup_ops(class);
+ if (cops && cops->co_msg_parser) {
+ err = cops->co_msg_parser(class);
+ if (err < 0)
+ goto errout_free;
+ }
+
+ err = pp->pp_cb((struct nl_object *) class, pp);
+ if (err < 0)
+ goto errout_free;
+
+ return P_ACCEPT;
+
+errout_free:
+ rtnl_class_put(class);
+errout:
+ return err;
+}
+
+static int class_request_update(struct nl_cache *cache,
+ struct nl_handle *handle)
+{
+ struct tcmsg tchdr = {
+ .tcm_family = AF_UNSPEC,
+ .tcm_ifindex = cache->c_iarg1,
+ };
+
+ return nl_send_simple(handle, RTM_GETTCLASS, NLM_F_DUMP, &tchdr,
+ sizeof(tchdr));
+}
+
+/**
+ * @name Addition/Modification
+ * @{
+ */
+
+static struct nl_msg *class_build(struct rtnl_class *class, int type, int flags)
+{
+ struct rtnl_class_ops *cops;
+ struct nl_msg *msg;
+ int err;
+
+ msg = tca_build_msg((struct rtnl_tca *) class, type, flags);
+ if (!msg)
+ goto errout;
+
+ cops = rtnl_class_lookup_ops(class);
+ if (cops && cops->co_get_opts) {
+ struct nl_msg *opts;
+
+ opts = cops->co_get_opts(class);
+ if (opts) {
+ err = nla_put_nested(msg, TCA_OPTIONS, opts);
+ nlmsg_free(opts);
+ if (err < 0)
+ goto errout;
+ }
+ }
+
+ return msg;
+errout:
+ nlmsg_free(msg);
+ return NULL;
+}
+
+/**
+ * Build a netlink message to add a new class
+ * @arg class class to add
+ * @arg flags additional netlink message flags
+ *
+ * Builds a new netlink message requesting an addition of a class.
+ * The netlink message header isn't fully equipped with all relevant
+ * fields and must be sent out via nl_send_auto_complete() or
+ * supplemented as needed.
+ *
+ * Common message flags
+ * - NLM_F_REPLACE - replace possibly existing classes
+ *
+ * @return New netlink message
+ */
+struct nl_msg *rtnl_class_build_add_request(struct rtnl_class *class, int flags)
+{
+ return class_build(class, RTM_NEWTCLASS, NLM_F_CREATE | flags);
+}
+
+/**
+ * Add a new class
+ * @arg handle netlink handle
+ * @arg class class to delete
+ * @arg flags additional netlink message flags
+ *
+ * Builds a netlink message by calling rtnl_qdisc_build_add_request(),
+ * sends the request to the kernel and waits for the next ACK to be
+ * received and thus blocks until the request has been processed.
+ *
+ * Common message flags
+ * - NLM_F_REPLACE - replace possibly existing classes
+ *
+ * @return 0 on success or a negative error code
+ */
+int rtnl_class_add(struct nl_handle *handle, struct rtnl_class *class,
+ int flags)
+{
+ struct nl_msg *msg;
+ int err;
+
+ msg = rtnl_class_build_add_request(class, flags);
+ if (!msg)
+ return nl_errno(ENOMEM);
+
+ err = nl_send_auto_complete(handle, msg);
+ if (err < 0)
+ return err;
+
+ nlmsg_free(msg);
+ return nl_wait_for_ack(handle);
+}
+
+/** @} */
+
+/**
+ * @name Cache Management
+ * @{
+ */
+
+/**
+ * Build a class cache including all classes attached to the specified interface
+ * @arg handle netlink handle
+ * @arg ifindex interface index of the link the classes are
+ * attached to.
+ *
+ * Allocates a new cache, initializes it properly and updates it to
+ * include all classes attached to the specified interface.
+ *
+ * @return The cache or NULL if an error has occured.
+ */
+struct nl_cache * rtnl_class_alloc_cache(struct nl_handle *handle, int ifindex)
+{
+ struct nl_cache * cache;
+
+ cache = nl_cache_alloc(&rtnl_class_ops);
+ if (!cache)
+ return NULL;
+
+ cache->c_iarg1 = ifindex;
+
+ if (handle && nl_cache_refill(handle, cache) < 0) {
+ nl_cache_free(cache);
+ return NULL;
+ }
+
+ return cache;
+}
+
+/** @} */
+
+static struct nl_cache_ops rtnl_class_ops = {
+ .co_name = "route/class",
+ .co_hdrsize = sizeof(struct tcmsg),
+ .co_msgtypes = {
+ { RTM_NEWTCLASS, NL_ACT_NEW, "new" },
+ { RTM_DELTCLASS, NL_ACT_DEL, "del" },
+ { RTM_GETTCLASS, NL_ACT_GET, "get" },
+ END_OF_MSGTYPES_LIST,
+ },
+ .co_protocol = NETLINK_ROUTE,
+ .co_request_update = &class_request_update,
+ .co_msg_parser = &class_msg_parser,
+ .co_obj_ops = &class_obj_ops,
+};
+
+static void __init class_init(void)
+{
+ nl_cache_mngt_register(&rtnl_class_ops);
+}
+
+static void __exit class_exit(void)
+{
+ nl_cache_mngt_unregister(&rtnl_class_ops);
+}
+
+/** @} */
diff --git a/lib/route/class_api.c b/lib/route/class_api.c
new file mode 100644
index 0000000..c814486
--- /dev/null
+++ b/lib/route/class_api.c
@@ -0,0 +1,102 @@
+/*
+ * lib/route/class_api.c Queueing Classes Module API
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup class
+ * @defgroup class_api Class Modules
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/route/tc.h>
+#include <netlink/route/class.h>
+#include <netlink/route/class-modules.h>
+#include <netlink/utils.h>
+
+static struct rtnl_class_ops *class_ops_list;
+
+/**
+ * @name Module API
+ * @{
+ */
+
+/**
+ * Register a class module
+ * @arg cops class module operations
+ */
+int rtnl_class_register(struct rtnl_class_ops *cops)
+{
+ struct rtnl_class_ops *o, **op;
+
+ if (!cops->co_kind[0])
+ BUG();
+
+ for (op = &class_ops_list; (o = *op) != NULL; op = &o->co_next)
+ if (!strcasecmp(cops->co_kind, o->co_kind))
+ return nl_errno(EEXIST);
+
+ cops->co_next = NULL;
+ *op = cops;
+
+ return 0;
+}
+
+/**
+ * Unregister a class module
+ * @arg cops class module operations
+ */
+int rtnl_class_unregister(struct rtnl_class_ops *cops)
+{
+ struct rtnl_class_ops *o, **op;
+
+ for (op = &class_ops_list; (o = *op) != NULL; op = &o->co_next)
+ if (!strcasecmp(cops->co_kind, o->co_kind))
+ break;
+
+ if (!o)
+ return nl_errno(ENOENT);
+
+ *op = cops->co_next;
+
+ return 0;
+}
+
+struct rtnl_class_ops *__rtnl_class_lookup_ops(const char *kind)
+{
+ struct rtnl_class_ops *cops;
+
+ for (cops = class_ops_list; cops; cops = cops->co_next)
+ if (!strcmp(kind, cops->co_kind))
+ return cops;
+
+ return NULL;
+}
+
+/**
+ * Lookup class operations for a class object
+ * @arg class Class object.
+ *
+ * @return Class operations or NULL if not found.
+ */
+struct rtnl_class_ops *rtnl_class_lookup_ops(struct rtnl_class *class)
+{
+ if (!class->c_ops)
+ class->c_ops = __rtnl_class_lookup_ops(class->c_kind);
+
+ return class->c_ops;
+}
+
+
+/** @} */
+
+/** @} */
diff --git a/lib/route/class_obj.c b/lib/route/class_obj.c
new file mode 100644
index 0000000..0601bdf
--- /dev/null
+++ b/lib/route/class_obj.c
@@ -0,0 +1,287 @@
+/*
+ * lib/route/class.c Queueing Classes
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup class
+ * @defgroup class_obj Class Object
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/route/tc.h>
+#include <netlink/route/class.h>
+#include <netlink/route/class-modules.h>
+#include <netlink/route/qdisc.h>
+#include <netlink/route/classifier.h>
+#include <netlink/utils.h>
+
+static void class_free_data(struct nl_object *obj)
+{
+ struct rtnl_class *class = (struct rtnl_class *) obj;
+ struct rtnl_class_ops *cops;
+
+ tca_free_data((struct rtnl_tca *) class);
+
+ cops = rtnl_class_lookup_ops(class);
+ if (cops && cops->co_free_data)
+ cops->co_free_data(class);
+}
+
+static int class_clone(struct nl_object *_dst, struct nl_object *_src)
+{
+ struct rtnl_class *dst = nl_object_priv(_dst);
+ struct rtnl_class *src = nl_object_priv(_src);
+ struct rtnl_class_ops *cops;
+ int err;
+
+ err = tca_clone((struct rtnl_tca *) dst, (struct rtnl_tca *) src);
+ if (err < 0)
+ goto errout;
+
+ cops = rtnl_class_lookup_ops(src);
+ if (cops && cops->co_clone)
+ err = cops->co_clone(dst, src);
+errout:
+ return err;
+}
+
+static int class_dump_brief(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_class *class = (struct rtnl_class *) obj;
+ struct rtnl_class_ops *cops;
+
+ int line = tca_dump_brief((struct rtnl_tca *) class, "class", p, 0);
+
+ cops = rtnl_class_lookup_ops(class);
+ if (cops && cops->co_dump[NL_DUMP_BRIEF])
+ line = cops->co_dump[NL_DUMP_BRIEF](class, p, line);
+ dp_dump(p, "\n");
+
+ return line;
+}
+
+static int class_dump_full(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_class *class = (struct rtnl_class *) obj;
+ struct rtnl_class_ops *cops;
+ int line;
+
+ line = class_dump_brief(obj, p);
+ line = tca_dump_full((struct rtnl_tca *) class, p, line);
+
+ if (class->c_info) {
+ char buf[32];
+ dp_dump(p, "child-qdisc %s ",
+ rtnl_tc_handle2str(class->c_info, buf, sizeof(buf)));
+ }
+
+ cops = rtnl_class_lookup_ops(class);
+ if (cops && cops->co_dump[NL_DUMP_FULL])
+ line = cops->co_dump[NL_DUMP_FULL](class, p, line);
+ else if (!class->c_info)
+ dp_dump(p, "noop (no leaf qdisc)");
+
+ dp_dump(p, "\n");
+
+ return line;
+}
+
+static int class_dump_stats(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_class *class = (struct rtnl_class *) obj;
+ struct rtnl_class_ops *cops;
+ int line;
+
+ line = class_dump_full(obj, p);
+ line = tca_dump_stats((struct rtnl_tca *) class, p, line);
+ dp_dump(p, "\n");
+
+ cops = rtnl_class_lookup_ops(class);
+ if (cops && cops->co_dump[NL_DUMP_STATS])
+ line = cops->co_dump[NL_DUMP_STATS](class, p, line);
+
+ return line;
+}
+
+/**
+ * @name Allocation/Freeing
+ * @{
+ */
+
+struct rtnl_class *rtnl_class_alloc(void)
+{
+ return (struct rtnl_class *) nl_object_alloc(&class_obj_ops);
+}
+
+void rtnl_class_put(struct rtnl_class *class)
+{
+ nl_object_put((struct nl_object *) class);
+}
+
+/** @} */
+
+/**
+ * @name Leaf Qdisc
+ * @{
+ */
+
+/**
+ * Lookup the leaf qdisc of a class
+ * @arg class the parent class
+ * @arg cache a qdisc cache including at laest all qdiscs of the
+ * interface the specified class is attached to
+ * @return The qdisc from the cache or NULL if the class has no leaf qdisc
+ */
+struct rtnl_qdisc *rtnl_class_leaf_qdisc(struct rtnl_class *class,
+ struct nl_cache *cache)
+{
+ struct rtnl_qdisc *leaf;
+
+ if (!class->c_info)
+ return NULL;
+
+ leaf = rtnl_qdisc_get_by_parent(cache, class->c_ifindex,
+ class->c_handle);
+ if (!leaf || leaf->q_handle != class->c_info)
+ return NULL;
+
+ return leaf;
+}
+
+/** @} */
+
+
+/**
+ * @name Iterators
+ * @{
+ */
+
+/**
+ * Call a callback for each child of a class
+ * @arg class the parent class
+ * @arg cache a class cache including all classes of the interface
+ * the specified class is attached to
+ * @arg cb callback function
+ * @arg arg argument to be passed to callback function
+ */
+void rtnl_class_foreach_child(struct rtnl_class *class, struct nl_cache *cache,
+ void (*cb)(struct nl_object *, void *), void *arg)
+{
+ struct rtnl_class *filter;
+
+ filter = rtnl_class_alloc();
+ if (!filter)
+ return;
+
+ rtnl_class_set_parent(filter, class->c_handle);
+ rtnl_class_set_ifindex(filter, class->c_ifindex);
+ rtnl_class_set_kind(filter, class->c_kind);
+
+ nl_cache_foreach_filter(cache, (struct nl_object *) filter, cb, arg);
+ rtnl_class_put(filter);
+}
+
+/**
+ * Call a callback for each classifier attached to the class
+ * @arg class the parent class
+ * @arg cache a filter cache including at least all the filters
+ * attached to the specified class
+ * @arg cb callback function
+ * @arg arg argument to be passed to callback function
+ */
+void rtnl_class_foreach_cls(struct rtnl_class *class, struct nl_cache *cache,
+ void (*cb)(struct nl_object *, void *), void *arg)
+{
+ struct rtnl_cls *filter;
+
+ filter = rtnl_cls_alloc();
+ if (!filter)
+ return;
+
+ rtnl_cls_set_ifindex(filter, class->c_ifindex);
+ rtnl_cls_set_parent(filter, class->c_parent);
+
+ nl_cache_foreach_filter(cache, (struct nl_object *) filter, cb, arg);
+ rtnl_cls_put(filter);
+}
+
+/** @} */
+
+
+/**
+ * @name Attributes
+ * @{
+ */
+
+void rtnl_class_set_ifindex(struct rtnl_class *class, int ifindex)
+{
+ tca_set_ifindex((struct rtnl_tca *) class, ifindex);
+}
+
+int rtnl_class_get_ifindex(struct rtnl_class *class)
+{
+ return tca_get_ifindex((struct rtnl_tca *) class);
+}
+
+void rtnl_class_set_handle(struct rtnl_class *class, uint32_t handle)
+{
+ tca_set_handle((struct rtnl_tca *) class, handle);
+}
+
+uint32_t rtnl_class_get_handle(struct rtnl_class *class)
+{
+ return tca_get_handle((struct rtnl_tca *) class);
+}
+
+void rtnl_class_set_parent(struct rtnl_class *class, uint32_t parent)
+{
+ tca_set_parent((struct rtnl_tca *) class, parent);
+}
+
+uint32_t rtnl_class_get_parent(struct rtnl_class *class)
+{
+ return tca_get_parent((struct rtnl_tca *) class);
+}
+
+void rtnl_class_set_kind(struct rtnl_class *class, const char *name)
+{
+ tca_set_kind((struct rtnl_tca *) class, name);
+ class->c_ops = __rtnl_class_lookup_ops(name);
+}
+
+char *rtnl_class_get_kind(struct rtnl_class *class)
+{
+ return tca_get_kind((struct rtnl_tca *) class);
+}
+
+uint64_t rtnl_class_get_stat(struct rtnl_class *class,
+ enum rtnl_tc_stats_id id)
+{
+ return tca_get_stat((struct rtnl_tca *) class, id);
+}
+
+/** @} */
+
+struct nl_object_ops class_obj_ops = {
+ .oo_name = "route/class",
+ .oo_size = sizeof(struct rtnl_class),
+ .oo_free_data = class_free_data,
+ .oo_clone = class_clone,
+ .oo_dump[NL_DUMP_BRIEF] = class_dump_brief,
+ .oo_dump[NL_DUMP_FULL] = class_dump_full,
+ .oo_dump[NL_DUMP_STATS] = class_dump_stats,
+ .oo_compare = tca_compare,
+ .oo_id_attrs = (TCA_ATTR_IFINDEX | TCA_ATTR_HANDLE),
+};
+
+/** @} */
diff --git a/lib/route/classifier.c b/lib/route/classifier.c
new file mode 100644
index 0000000..7ad4722
--- /dev/null
+++ b/lib/route/classifier.c
@@ -0,0 +1,343 @@
+/*
+ * lib/route/classifier.c Classifier
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup tc
+ * @defgroup cls Classifiers
+ *
+ * @par Classifier Identification
+ * - protocol
+ * - priority
+ * - parent
+ * - interface
+ * - kind
+ * - handle
+ *
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/route/tc.h>
+#include <netlink/route/classifier.h>
+#include <netlink/route/classifier-modules.h>
+#include <netlink/route/link.h>
+
+static struct nl_cache_ops rtnl_cls_ops;
+
+static int cls_msg_parser(struct nl_cache_ops *ops, struct sockaddr_nl *who,
+ struct nlmsghdr *nlh, void *arg)
+{
+ int err;
+ struct nl_parser_param *pp = arg;
+ struct rtnl_cls *cls;
+ struct rtnl_cls_ops *cops;
+
+ cls = rtnl_cls_alloc();
+ if (!cls) {
+ err = nl_errno(ENOMEM);
+ goto errout;
+ }
+ cls->ce_msgtype = nlh->nlmsg_type;
+
+ err = tca_msg_parser(nlh, (struct rtnl_tca *) cls);
+ if (err < 0)
+ goto errout_free;
+
+ cls->c_prio = TC_H_MAJ(cls->c_info) >> 16;
+ cls->c_protocol = ntohs(TC_H_MIN(cls->c_info));
+
+ cops = rtnl_cls_lookup_ops(cls);
+ if (cops && cops->co_msg_parser) {
+ err = cops->co_msg_parser(cls);
+ if (err < 0)
+ goto errout_free;
+ }
+
+ err = pp->pp_cb((struct nl_object *) cls, pp);
+ if (err < 0)
+ goto errout_free;
+
+ return P_ACCEPT;
+
+errout_free:
+ rtnl_cls_put(cls);
+errout:
+ return err;
+}
+
+static int cls_request_update(struct nl_cache *cache, struct nl_handle *handle)
+{
+ struct tcmsg tchdr = {
+ .tcm_family = AF_UNSPEC,
+ .tcm_ifindex = cache->c_iarg1,
+ .tcm_parent = cache->c_iarg2,
+ };
+
+ return nl_send_simple(handle, RTM_GETTFILTER, NLM_F_DUMP, &tchdr,
+ sizeof(tchdr));
+}
+
+
+static struct nl_msg *cls_build(struct rtnl_cls *cls, int type, int flags)
+{
+ struct nl_msg *msg;
+ struct rtnl_cls_ops *cops;
+ int err, prio, proto;
+ struct tcmsg *tchdr;
+
+ msg = tca_build_msg((struct rtnl_tca *) cls, type, flags);
+ if (!msg)
+ goto errout;
+
+ tchdr = nlmsg_data(nlmsg_hdr(msg));
+ prio = rtnl_cls_get_prio(cls);
+ proto = rtnl_cls_get_protocol(cls);
+ tchdr->tcm_info = TC_H_MAKE(prio << 16, htons(proto)),
+
+ cops = rtnl_cls_lookup_ops(cls);
+ if (cops && cops->co_get_opts) {
+ struct nl_msg *opts;
+
+ opts = cops->co_get_opts(cls);
+ if (opts) {
+ err = nla_put_nested(msg, TCA_OPTIONS, opts);
+ nlmsg_free(opts);
+ if (err < 0)
+ goto errout;
+ }
+ }
+
+ return msg;
+errout:
+ nlmsg_free(msg);
+ return NULL;
+}
+
+/**
+ * @name Classifier Addition/Modification/Deletion
+ * @{
+ */
+
+/**
+ * Build a netlink message to add a new classifier
+ * @arg cls classifier to add
+ * @arg flags additional netlink message flags
+ *
+ * Builds a new netlink message requesting an addition of a classifier
+ * The netlink message header isn't fully equipped with all relevant
+ * fields and must be sent out via nl_send_auto_complete() or
+ * supplemented as needed. \a classifier must contain the attributes of
+ * the new classifier set via \c rtnl_cls_set_* functions. \a opts
+ * may point to the clsasifier specific options.
+ *
+ * @return New netlink message
+ */
+struct nl_msg * rtnl_cls_build_add_request(struct rtnl_cls *cls, int flags)
+{
+ return cls_build(cls, RTM_NEWTFILTER, NLM_F_CREATE | flags);
+}
+
+/**
+ * Add a new classifier
+ * @arg handle netlink handle
+ * @arg cls classifier to add
+ * @arg flags additional netlink message flags
+ *
+ * Builds a netlink message by calling rtnl_cls_build_add_request(),
+ * sends the request to the kernel and waits for the next ACK to be
+ * received and thus blocks until the request has been processed.
+ *
+ * @return 0 on sucess or a negative error if an error occured.
+ */
+int rtnl_cls_add(struct nl_handle *handle, struct rtnl_cls *cls, int flags)
+{
+ int err;
+ struct nl_msg *msg;
+
+ msg = rtnl_cls_build_add_request(cls, flags);
+ if (!msg)
+ return nl_errno(ENOMEM);
+
+ err = nl_send_auto_complete(handle, msg);
+ if (err < 0)
+ return err;
+
+ nlmsg_free(msg);
+ return nl_wait_for_ack(handle);
+}
+
+/**
+ * Build a netlink message to change classifier attributes
+ * @arg cls classifier to change
+ * @arg flags additional netlink message flags
+ *
+ * Builds a new netlink message requesting a change of a neigh
+ * attributes. The netlink message header isn't fully equipped with
+ * all relevant fields and must thus be sent out via nl_send_auto_complete()
+ * or supplemented as needed.
+ *
+ * @return The netlink message
+ */
+struct nl_msg *rtnl_cls_build_change_request(struct rtnl_cls *cls, int flags)
+{
+ return cls_build(cls, RTM_NEWTFILTER, NLM_F_REPLACE | flags);
+}
+
+/**
+ * Change a classifier
+ * @arg handle netlink handle
+ * @arg cls classifier to change
+ * @arg flags additional netlink message flags
+ *
+ * Builds a netlink message by calling rtnl_cls_build_change_request(),
+ * sends the request to the kernel and waits for the next ACK to be
+ * received and thus blocks until the request has been processed.
+ *
+ * @return 0 on sucess or a negative error if an error occured.
+ */
+int rtnl_cls_change(struct nl_handle *handle, struct rtnl_cls *cls,
+ int flags)
+{
+ int err;
+ struct nl_msg *msg;
+
+ msg = rtnl_cls_build_change_request(cls, flags);
+ if (!msg)
+ return nl_errno(ENOMEM);
+
+ err = nl_send_auto_complete(handle, msg);
+ if (err < 0)
+ return err;
+
+ nlmsg_free(msg);
+ return nl_wait_for_ack(handle);
+}
+
+/**
+ * Build a netlink request message to delete a classifier
+ * @arg cls classifier to delete
+ * @arg flags additional netlink message flags
+ *
+ * Builds a new netlink message requesting a deletion of a classifier.
+ * The netlink message header isn't fully equipped with all relevant
+ * fields and must thus be sent out via nl_send_auto_complete()
+ * or supplemented as needed.
+ *
+ * @return New netlink message
+ */
+struct nl_msg *rtnl_cls_build_delete_request(struct rtnl_cls *cls, int flags)
+{
+ return cls_build(cls, RTM_DELTFILTER, flags);
+}
+
+
+/**
+ * Delete a classifier
+ * @arg handle netlink handle
+ * @arg cls classifier to delete
+ * @arg flags additional netlink message flags
+ *
+ * Builds a netlink message by calling rtnl_cls_build_delete_request(),
+ * sends the request to the kernel and waits for the next ACK to be
+ * received and thus blocks until the request has been processed.
+ *
+ * @return 0 on sucess or a negative error if an error occured.
+ */
+int rtnl_cls_delete(struct nl_handle *handle, struct rtnl_cls *cls, int flags)
+{
+ int err;
+ struct nl_msg *msg;
+
+ msg = rtnl_cls_build_delete_request(cls, flags);
+ if (!msg)
+ return nl_errno(ENOMEM);
+
+ err = nl_send_auto_complete(handle, msg);
+ if (err < 0)
+ return err;
+
+ nlmsg_free(msg);
+ return nl_wait_for_ack(handle);
+}
+
+/** @} */
+
+/**
+ * @name Cache Management
+ * @{
+ */
+
+/**
+ * Build a classifier cache including all classifiers attached to the
+ * specified class/qdisc on eht specified interface.
+ * @arg handle netlink handle
+ * @arg ifindex interface index of the link the classes are
+ * attached to.
+ * @arg parent parent qdisc/class
+ *
+ * Allocates a new cache, initializes it properly and updates it to
+ * include all classes attached to the specified interface.
+ *
+ * @note The caller is responsible for destroying and freeing the
+ * cache after using it.
+ * @return The cache or NULL if an error has occured.
+ */
+struct nl_cache *rtnl_cls_alloc_cache(struct nl_handle *handle,
+ int ifindex, uint32_t parent)
+{
+ struct nl_cache * cache;
+
+ cache = nl_cache_alloc(&rtnl_cls_ops);
+ if (cache == NULL)
+ return NULL;
+
+ cache->c_iarg1 = ifindex;
+ cache->c_iarg2 = parent;
+
+ if (handle && nl_cache_refill(handle, cache) < 0) {
+ nl_cache_free(cache);
+ return NULL;
+ }
+
+ return cache;
+}
+
+/** @} */
+
+static struct nl_cache_ops rtnl_cls_ops = {
+ .co_name = "route/cls",
+ .co_hdrsize = sizeof(struct tcmsg),
+ .co_msgtypes = {
+ { RTM_NEWTFILTER, NL_ACT_NEW, "new" },
+ { RTM_DELTFILTER, NL_ACT_DEL, "del" },
+ { RTM_GETTFILTER, NL_ACT_GET, "get" },
+ END_OF_MSGTYPES_LIST,
+ },
+ .co_protocol = NETLINK_ROUTE,
+ .co_request_update = cls_request_update,
+ .co_msg_parser = cls_msg_parser,
+ .co_obj_ops = &cls_obj_ops,
+};
+
+static void __init cls_init(void)
+{
+ nl_cache_mngt_register(&rtnl_cls_ops);
+}
+
+static void __exit cls_exit(void)
+{
+ nl_cache_mngt_unregister(&rtnl_cls_ops);
+}
+
+/** @} */
diff --git a/lib/route/cls/fw.c b/lib/route/cls/fw.c
new file mode 100644
index 0000000..7ca7619
--- /dev/null
+++ b/lib/route/cls/fw.c
@@ -0,0 +1,251 @@
+/*
+ * lib/route/cls/fw.c fw classifier
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ * Copyright (c) 2006 Petr Gotthard <petr.gotthard@siemens.com>
+ * Copyright (c) 2006 Siemens AG Oesterreich
+ */
+
+/**
+ * @ingroup cls_api
+ * @defgroup fw Firewall Classifier
+ *
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/route/classifier.h>
+#include <netlink/route/classifier-modules.h>
+#include <netlink/route/cls/fw.h>
+
+/** @cond SKIP */
+#define FW_ATTR_CLASSID 0x001
+#define FW_ATTR_ACTION 0x002
+#define FW_ATTR_POLICE 0x004
+#define FW_ATTR_INDEV 0x008
+/** @endcond */
+
+static inline struct rtnl_fw *fw_cls(struct rtnl_cls *cls)
+{
+ return (struct rtnl_fw *) cls->c_subdata;
+}
+
+static inline struct rtnl_fw *fw_alloc(struct rtnl_cls *cls)
+{
+ if (!cls->c_subdata)
+ cls->c_subdata = calloc(1, sizeof(struct rtnl_fw));
+
+ return fw_cls(cls);
+}
+
+static struct nla_policy fw_policy[TCA_FW_MAX+1] = {
+ [TCA_FW_CLASSID] = { .type = NLA_U32 },
+ [TCA_FW_INDEV] = { .type = NLA_STRING,
+ .maxlen = IFNAMSIZ },
+};
+
+static int fw_msg_parser(struct rtnl_cls *cls)
+{
+ int err;
+ struct nlattr *tb[TCA_FW_MAX + 1];
+ struct rtnl_fw *f;
+
+ err = tca_parse(tb, TCA_FW_MAX, (struct rtnl_tca *) cls, fw_policy);
+ if (err < 0)
+ return err;
+
+ f = fw_alloc(cls);
+ if (!f)
+ goto errout_nomem;
+
+ if (tb[TCA_FW_CLASSID]) {
+ f->cf_classid = nla_get_u32(tb[TCA_FW_CLASSID]);
+ f->cf_mask |= FW_ATTR_CLASSID;
+ }
+
+ if (tb[TCA_FW_ACT]) {
+ f->cf_act = nla_get_data(tb[TCA_FW_ACT]);
+ if (!f->cf_act)
+ goto errout_nomem;
+ f->cf_mask |= FW_ATTR_ACTION;
+ }
+
+ if (tb[TCA_FW_POLICE]) {
+ f->cf_police = nla_get_data(tb[TCA_FW_POLICE]);
+ if (!f->cf_police)
+ goto errout_nomem;
+ f->cf_mask |= FW_ATTR_POLICE;
+ }
+
+ if (tb[TCA_FW_INDEV]) {
+ nla_strlcpy(f->cf_indev, tb[TCA_FW_INDEV], IFNAMSIZ);
+ f->cf_mask |= FW_ATTR_INDEV;
+ }
+
+ return 0;
+
+errout_nomem:
+ err = nl_errno(ENOMEM);
+
+ return err;
+}
+
+static void fw_free_data(struct rtnl_cls *cls)
+{
+ struct rtnl_fw *f = fw_cls(cls);
+
+ if (!f)
+ return;
+
+ nl_data_free(f->cf_act);
+ nl_data_free(f->cf_police);
+
+ free(cls->c_subdata);
+}
+
+static int fw_clone(struct rtnl_cls *_dst, struct rtnl_cls *_src)
+{
+ struct rtnl_fw *dst, *src = fw_cls(_src);
+
+ if (!src)
+ return 0;
+
+ dst = fw_alloc(_dst);
+ if (!dst)
+ return nl_errno(ENOMEM);
+
+ if (src->cf_act)
+ if (!(dst->cf_act = nl_data_clone(src->cf_act)))
+ goto errout;
+
+ if (src->cf_police)
+ if (!(dst->cf_police = nl_data_clone(src->cf_police)))
+ goto errout;
+
+ return 0;
+errout:
+ return nl_get_errno();
+}
+
+static int fw_dump_brief(struct rtnl_cls *cls, struct nl_dump_params *p,
+ int line)
+{
+ struct rtnl_fw *f = fw_cls(cls);
+ char buf[32];
+
+ if (!f)
+ goto ignore;
+
+ if (f->cf_mask & FW_ATTR_CLASSID)
+ dp_dump(p, " target %s",
+ rtnl_tc_handle2str(f->cf_classid, buf, sizeof(buf)));
+
+ignore:
+ return line;
+}
+
+static int fw_dump_full(struct rtnl_cls *cls, struct nl_dump_params *p,
+ int line)
+{
+ struct rtnl_fw *f = fw_cls(cls);
+
+ if (!f)
+ goto ignore;
+
+ if (f->cf_mask & FW_ATTR_INDEV)
+ dp_dump(p, "indev %s ", f->cf_indev);
+
+ignore:
+ return line;
+}
+
+static int fw_dump_stats(struct rtnl_cls *cls, struct nl_dump_params *p,
+ int line)
+{
+ struct rtnl_fw *f = fw_cls(cls);
+
+ if (!f)
+ goto ignore;
+
+ignore:
+ return line;
+}
+
+static struct nl_msg *fw_get_opts(struct rtnl_cls *cls)
+{
+ struct rtnl_fw *f;
+ struct nl_msg *msg;
+
+ f = fw_cls(cls);
+ if (!f)
+ return NULL;
+
+ msg = nlmsg_alloc();
+ if (!msg)
+ return NULL;
+
+ if (f->cf_mask & FW_ATTR_CLASSID)
+ nla_put_u32(msg, TCA_FW_CLASSID, f->cf_classid);
+
+ if (f->cf_mask & FW_ATTR_ACTION)
+ nla_put_data(msg, TCA_FW_ACT, f->cf_act);
+
+ if (f->cf_mask & FW_ATTR_POLICE)
+ nla_put_data(msg, TCA_FW_POLICE, f->cf_police);
+
+ if (f->cf_mask & FW_ATTR_INDEV)
+ nla_put_string(msg, TCA_FW_INDEV, f->cf_indev);
+
+ return msg;
+}
+
+/**
+ * @name Attribute Modifications
+ * @{
+ */
+
+int rtnl_fw_set_classid(struct rtnl_cls *cls, uint32_t classid)
+{
+ struct rtnl_fw *f;
+
+ f = fw_alloc(cls);
+ if (!f)
+ return nl_errno(ENOMEM);
+
+ f->cf_classid = classid;
+ f->cf_mask |= FW_ATTR_CLASSID;
+
+ return 0;
+}
+
+/** @} */
+
+static struct rtnl_cls_ops fw_ops = {
+ .co_kind = "fw",
+ .co_msg_parser = fw_msg_parser,
+ .co_free_data = fw_free_data,
+ .co_clone = fw_clone,
+ .co_get_opts = fw_get_opts,
+ .co_dump[NL_DUMP_BRIEF] = fw_dump_brief,
+ .co_dump[NL_DUMP_FULL] = fw_dump_full,
+ .co_dump[NL_DUMP_STATS] = fw_dump_stats,
+};
+
+static void __init fw_init(void)
+{
+ rtnl_cls_register(&fw_ops);
+}
+
+static void __exit fw_exit(void)
+{
+ rtnl_cls_unregister(&fw_ops);
+}
+
+/** @} */
diff --git a/lib/route/cls/police.c b/lib/route/cls/police.c
new file mode 100644
index 0000000..051c6b2
--- /dev/null
+++ b/lib/route/cls/police.c
@@ -0,0 +1,67 @@
+/*
+ * lib/route/cls/police.c Policer
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/route/tc.h>
+#include <netlink/route/classifier.h>
+#include <netlink/route/classifier-modules.h>
+#include <netlink/route/cls/police.h>
+
+/**
+ * @name Policer Type
+ * @{
+ */
+
+static struct trans_tbl police_types[] = {
+ __ADD(TC_POLICE_UNSPEC,unspec)
+ __ADD(TC_POLICE_OK,ok)
+ __ADD(TC_POLICE_RECLASSIFY,reclassify)
+ __ADD(TC_POLICE_SHOT,shot)
+#ifdef TC_POLICE_PIPE
+ __ADD(TC_POLICE_PIPE,pipe)
+#endif
+};
+
+/**
+ * Transform a policer type number into a character string (Reentrant).
+ * @arg type policer type
+ * @arg buf destination buffer
+ * @arg len buffer length
+ *
+ * Transforms a policer type number into a character string and stores
+ * it in the provided buffer.
+ *
+ * @return The destination buffer or the type encoded in hex if no match was found.
+ */
+char * nl_police2str(int type, char *buf, size_t len)
+{
+ return __type2str(type, buf, len, police_types,
+ ARRAY_SIZE(police_types));
+}
+
+/**
+ * Transform a character string into a policer type number
+ * @arg name policer type name
+ *
+ * Transform the provided character string specifying a policer
+ * type into the corresponding numeric value
+ *
+ * @return Policer type number or a negative value.
+ */
+int nl_str2police(const char *name)
+{
+ return __str2type(name, police_types, ARRAY_SIZE(police_types));
+}
+
+/** @} */
diff --git a/lib/route/cls/u32.c b/lib/route/cls/u32.c
new file mode 100644
index 0000000..596e63f
--- /dev/null
+++ b/lib/route/cls/u32.c
@@ -0,0 +1,602 @@
+/*
+ * lib/route/cls/u32.c u32 classifier
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ * Copyright (c) 2005-2006 Petr Gotthard <petr.gotthard@siemens.com>
+ * Copyright (c) 2005-2006 Siemens AG Oesterreich
+ */
+
+/**
+ * @ingroup cls_api
+ * @defgroup u32 Universal 32-bit Classifier
+ *
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/attr.h>
+#include <netlink/utils.h>
+#include <netlink/route/tc.h>
+#include <netlink/route/classifier.h>
+#include <netlink/route/classifier-modules.h>
+#include <netlink/route/cls/u32.h>
+
+/** @cond SKIP */
+#define U32_ATTR_DIVISOR 0x001
+#define U32_ATTR_HASH 0x002
+#define U32_ATTR_CLASSID 0x004
+#define U32_ATTR_LINK 0x008
+#define U32_ATTR_PCNT 0x010
+#define U32_ATTR_SELECTOR 0x020
+#define U32_ATTR_ACTION 0x040
+#define U32_ATTR_POLICE 0x080
+#define U32_ATTR_INDEV 0x100
+/** @endcond */
+
+static inline struct rtnl_u32 *u32_cls(struct rtnl_cls *cls)
+{
+ return (struct rtnl_u32 *) cls->c_subdata;
+}
+
+static inline struct rtnl_u32 *u32_alloc(struct rtnl_cls *cls)
+{
+ if (!cls->c_subdata)
+ cls->c_subdata = calloc(1, sizeof(struct rtnl_u32));
+
+ return u32_cls(cls);
+}
+
+static inline struct tc_u32_sel *u32_selector(struct rtnl_u32 *u)
+{
+ return (struct tc_u32_sel *) u->cu_selector->d_data;
+}
+
+static inline struct tc_u32_sel *u32_selector_alloc(struct rtnl_u32 *u)
+{
+ if (!u->cu_selector)
+ u->cu_selector = nl_data_alloc(NULL, sizeof(struct tc_u32_sel));
+
+ return u32_selector(u);
+}
+
+static struct nla_policy u32_policy[TCA_U32_MAX+1] = {
+ [TCA_U32_DIVISOR] = { .type = NLA_U32 },
+ [TCA_U32_HASH] = { .type = NLA_U32 },
+ [TCA_U32_CLASSID] = { .type = NLA_U32 },
+ [TCA_U32_LINK] = { .type = NLA_U32 },
+ [TCA_U32_INDEV] = { .type = NLA_STRING,
+ .maxlen = IFNAMSIZ },
+ [TCA_U32_SEL] = { .minlen = sizeof(struct tc_u32_sel) },
+ [TCA_U32_PCNT] = { .minlen = sizeof(struct tc_u32_pcnt) },
+};
+
+static int u32_msg_parser(struct rtnl_cls *cls)
+{
+ int err;
+ struct nlattr *tb[TCA_U32_MAX + 1];
+ struct rtnl_u32 *u;
+
+ err = tca_parse(tb, TCA_U32_MAX, (struct rtnl_tca *) cls, u32_policy);
+ if (err < 0)
+ return err;
+
+ u = u32_alloc(cls);
+ if (!u)
+ goto errout_nomem;
+
+ if (tb[TCA_U32_DIVISOR]) {
+ u->cu_divisor = nla_get_u32(tb[TCA_U32_DIVISOR]);
+ u->cu_mask |= U32_ATTR_DIVISOR;
+ }
+
+ if (tb[TCA_U32_SEL]) {
+ u->cu_selector = nla_get_data(tb[TCA_U32_SEL]);
+ if (!u->cu_selector)
+ goto errout_nomem;
+ u->cu_mask |= U32_ATTR_SELECTOR;
+ }
+
+ if (tb[TCA_U32_HASH]) {
+ u->cu_hash = nla_get_u32(tb[TCA_U32_HASH]);
+ u->cu_mask |= U32_ATTR_HASH;
+ }
+
+ if (tb[TCA_U32_CLASSID]) {
+ u->cu_classid = nla_get_u32(tb[TCA_U32_CLASSID]);
+ u->cu_mask |= U32_ATTR_CLASSID;
+ }
+
+ if (tb[TCA_U32_LINK]) {
+ u->cu_link = nla_get_u32(tb[TCA_U32_LINK]);
+ u->cu_mask |= U32_ATTR_LINK;
+ }
+
+ if (tb[TCA_U32_ACT]) {
+ u->cu_act = nla_get_data(tb[TCA_U32_ACT]);
+ if (!u->cu_act)
+ goto errout_nomem;
+ u->cu_mask |= U32_ATTR_ACTION;
+ }
+
+ if (tb[TCA_U32_POLICE]) {
+ u->cu_police = nla_get_data(tb[TCA_U32_POLICE]);
+ if (!u->cu_police)
+ goto errout_nomem;
+ u->cu_mask |= U32_ATTR_POLICE;
+ }
+
+ if (tb[TCA_U32_PCNT]) {
+ struct tc_u32_sel *sel;
+ int pcnt_size;
+
+ if (!tb[TCA_U32_SEL]) {
+ err = nl_error(EINVAL, "Missing TCA_U32_SEL required "
+ "for TCA_U32_PCNT");
+ goto errout;
+ }
+
+ sel = u->cu_selector->d_data;
+ pcnt_size = sizeof(struct tc_u32_pcnt) +
+ (sel->nkeys * sizeof(uint64_t));
+ if (nla_len(tb[TCA_U32_PCNT]) < pcnt_size) {
+ err = nl_error(EINVAL, "Invalid size for TCA_U32_PCNT");
+ goto errout;
+ }
+
+ u->cu_pcnt = nla_get_data(tb[TCA_U32_PCNT]);
+ if (!u->cu_pcnt)
+ goto errout_nomem;
+ u->cu_mask |= U32_ATTR_PCNT;
+ }
+
+ if (tb[TCA_U32_INDEV]) {
+ nla_strlcpy(u->cu_indev, tb[TCA_U32_INDEV], IFNAMSIZ);
+ u->cu_mask |= U32_ATTR_INDEV;
+ }
+
+ return 0;
+
+errout_nomem:
+ err = nl_errno(ENOMEM);
+errout:
+ return err;
+}
+
+static void u32_free_data(struct rtnl_cls *cls)
+{
+ struct rtnl_u32 *u = u32_cls(cls);
+
+ if (!u)
+ return;
+
+ nl_data_free(u->cu_selector);
+ nl_data_free(u->cu_act);
+ nl_data_free(u->cu_police);
+ nl_data_free(u->cu_pcnt);
+
+ free(cls->c_subdata);
+}
+
+static int u32_clone(struct rtnl_cls *_dst, struct rtnl_cls *_src)
+{
+ struct rtnl_u32 *dst, *src = u32_cls(_src);
+
+ if (!src)
+ return 0;
+
+ dst = u32_alloc(_dst);
+ if (!dst)
+ return nl_errno(ENOMEM);
+
+ if (src->cu_selector)
+ if (!(dst->cu_selector = nl_data_clone(src->cu_selector)))
+ goto errout;
+
+ if (src->cu_act)
+ if (!(dst->cu_act = nl_data_clone(src->cu_act)))
+ goto errout;
+
+ if (src->cu_police)
+ if (!(dst->cu_police = nl_data_clone(src->cu_police)))
+ goto errout;
+
+ if (src->cu_pcnt)
+ if (!(dst->cu_pcnt = nl_data_clone(src->cu_pcnt)))
+ goto errout;
+
+ return 0;
+errout:
+ return nl_get_errno();
+}
+
+static int u32_dump_brief(struct rtnl_cls *cls, struct nl_dump_params *p,
+ int line)
+{
+ struct rtnl_u32 *u = u32_cls(cls);
+ char buf[32];
+
+ if (!u)
+ goto ignore;
+
+ if (u->cu_mask & U32_ATTR_DIVISOR)
+ dp_dump(p, " divisor %u", u->cu_divisor);
+ else if (u->cu_mask & U32_ATTR_CLASSID)
+ dp_dump(p, " target %s",
+ rtnl_tc_handle2str(u->cu_classid, buf, sizeof(buf)));
+
+ignore:
+ return line;
+}
+
+static int print_selector(struct nl_dump_params *p, struct tc_u32_sel *sel,
+ struct rtnl_cls *cls, struct rtnl_u32 *u, int line)
+{
+ int i;
+ struct tc_u32_key *key;
+
+ if (sel->hmask || sel->hoff) {
+ /* I guess this will never be used since the kernel only
+ * exports the selector if no divisor is set but hash offset
+ * and hash mask make only sense in hash filters with divisor
+ * set */
+ dp_dump(p, " hash at %u & 0x%x", sel->hoff, sel->hmask);
+ }
+
+ if (sel->flags & (TC_U32_OFFSET | TC_U32_VAROFFSET)) {
+ dp_dump(p, " offset at %u", sel->off);
+
+ if (sel->flags & TC_U32_VAROFFSET)
+ dp_dump(p, " variable (at %u & 0x%x) >> %u",
+ sel->offoff, ntohs(sel->offmask), sel->offshift);
+ }
+
+ if (sel->flags) {
+ int flags = sel->flags;
+ dp_dump(p, " <");
+
+#define PRINT_FLAG(f) if (flags & TC_U32_##f) { \
+ flags &= ~TC_U32_##f; dp_dump(p, #f "%s", flags ? "," : ""); }
+
+ PRINT_FLAG(TERMINAL);
+ PRINT_FLAG(OFFSET);
+ PRINT_FLAG(VAROFFSET);
+ PRINT_FLAG(EAT);
+#undef PRINT_FLAG
+
+ dp_dump(p, ">");
+ }
+
+
+ for (i = 0; i < sel->nkeys; i++) {
+ key = (struct tc_u32_key *) ((char *) sel + sizeof(*sel)) + i;
+
+ dp_dump(p, "\n");
+ dp_dump_line(p, line++, " match key at %s%u ",
+ key->offmask ? "nexthdr+" : "", key->off);
+
+ if (key->offmask)
+ dp_dump(p, "[0x%u] ", key->offmask);
+
+ dp_dump(p, "& 0x%08x == 0x%08x", ntohl(key->mask), ntohl(key->val));
+
+ if (p->dp_type == NL_DUMP_STATS &&
+ (u->cu_mask & U32_ATTR_PCNT)) {
+ struct tc_u32_pcnt *pcnt = u->cu_pcnt->d_data;
+ dp_dump(p, " successful %" PRIu64, pcnt->kcnts[i]);
+ }
+ }
+
+ return line;
+}
+
+
+static int u32_dump_full(struct rtnl_cls *cls, struct nl_dump_params *p,
+ int line)
+{
+ struct rtnl_u32 *u = u32_cls(cls);
+ struct tc_u32_sel *s;
+
+ if (!u)
+ goto ignore;
+
+ if (!(u->cu_mask & U32_ATTR_SELECTOR)) {
+ dp_dump(p, "no-selector\n");
+ return line;
+ }
+
+ s = u->cu_selector->d_data;
+
+ dp_dump(p, "nkeys %u ", s->nkeys);
+
+ if (u->cu_mask & U32_ATTR_HASH)
+ dp_dump(p, "ht key 0x%x hash 0x%u",
+ TC_U32_USERHTID(u->cu_hash), TC_U32_HASH(u->cu_hash));
+
+ if (u->cu_mask & U32_ATTR_LINK)
+ dp_dump(p, "link %u ", u->cu_link);
+
+ if (u->cu_mask & U32_ATTR_INDEV)
+ dp_dump(p, "indev %s ", u->cu_indev);
+
+ line = print_selector(p, s, cls, u, line);
+ dp_dump(p, "\n");
+
+ignore:
+ return line;
+
+#if 0
+#define U32_ATTR_ACTION 0x040
+#define U32_ATTR_POLICE 0x080
+
+ struct nl_data act;
+ struct nl_data police;
+#endif
+}
+
+static int u32_dump_stats(struct rtnl_cls *cls, struct nl_dump_params *p,
+ int line)
+{
+ struct rtnl_u32 *u = u32_cls(cls);
+
+ if (!u)
+ goto ignore;
+
+ if (u->cu_mask & U32_ATTR_PCNT) {
+ struct tc_u32_pcnt *pc = u->cu_pcnt->d_data;
+ dp_dump(p, "\n");
+ dp_dump_line(p, line++, "%s successful hits\n");
+ dp_dump_line(p, line++, "%s %8llu %8llu\n",
+ pc->rhit, pc->rcnt);
+ }
+
+ignore:
+ return line;
+}
+
+static struct nl_msg *u32_get_opts(struct rtnl_cls *cls)
+{
+ struct rtnl_u32 *u;
+ struct nl_msg *msg;
+
+ u = u32_cls(cls);
+ if (!u)
+ return NULL;
+
+ msg = nlmsg_alloc();
+ if (!msg)
+ return NULL;
+
+ if (u->cu_mask & U32_ATTR_DIVISOR)
+ nla_put_u32(msg, TCA_U32_DIVISOR, u->cu_divisor);
+
+ if (u->cu_mask & U32_ATTR_HASH)
+ nla_put_u32(msg, TCA_U32_HASH, u->cu_hash);
+
+ if (u->cu_mask & U32_ATTR_CLASSID)
+ nla_put_u32(msg, TCA_U32_CLASSID, u->cu_classid);
+
+ if (u->cu_mask & U32_ATTR_LINK)
+ nla_put_u32(msg, TCA_U32_LINK, u->cu_link);
+
+ if (u->cu_mask & U32_ATTR_SELECTOR)
+ nla_put_data(msg, TCA_U32_SEL, u->cu_selector);
+
+ if (u->cu_mask & U32_ATTR_ACTION)
+ nla_put_data(msg, TCA_U32_ACT, u->cu_act);
+
+ if (u->cu_mask & U32_ATTR_POLICE)
+ nla_put_data(msg, TCA_U32_POLICE, u->cu_police);
+
+ if (u->cu_mask & U32_ATTR_INDEV)
+ nla_put_string(msg, TCA_U32_INDEV, u->cu_indev);
+
+ return msg;
+}
+
+/**
+ * @name Attribute Modifications
+ * @{
+ */
+
+void rtnl_u32_set_handle(struct rtnl_cls *cls, int htid, int hash,
+ int nodeid)
+{
+ uint32_t handle = (htid << 20) | (hash << 12) | nodeid;
+
+ tca_set_handle((struct rtnl_tca *) cls, handle );
+}
+
+int rtnl_u32_set_classid(struct rtnl_cls *cls, uint32_t classid)
+{
+ struct rtnl_u32 *u;
+
+ u = u32_alloc(cls);
+ if (!u)
+ return nl_errno(ENOMEM);
+
+ u->cu_classid = classid;
+ u->cu_mask |= U32_ATTR_CLASSID;
+
+ return 0;
+}
+
+/** @} */
+
+/**
+ * @name Selector Modifications
+ * @{
+ */
+
+int rtnl_u32_set_flags(struct rtnl_cls *cls, int flags)
+{
+ struct tc_u32_sel *sel;
+ struct rtnl_u32 *u;
+
+ u = u32_alloc(cls);
+ if (!u)
+ return nl_errno(ENOMEM);
+
+ sel = u32_selector_alloc(u);
+ if (!sel)
+ return nl_errno(ENOMEM);
+
+ sel->flags |= flags;
+ u->cu_mask |= U32_ATTR_SELECTOR;
+
+ return 0;
+}
+
+/**
+ * Append new 32-bit key to the selector
+ *
+ * @arg cls classifier to be modifier
+ * @arg val value to be matched (network byte-order)
+ * @arg mask mask to be applied before matching (network byte-order)
+ * @arg off offset, in bytes, to start matching
+ * @arg offmask offset mask
+ *
+ * General selectors define the pattern, mask and offset the pattern will be
+ * matched to the packet contents. Using the general selectors you can match
+ * virtually any single bit in the IP (or upper layer) header.
+ *
+*/
+int rtnl_u32_add_key(struct rtnl_cls *cls, uint32_t val, uint32_t mask,
+ int off, int offmask)
+{
+ struct tc_u32_sel *sel;
+ struct rtnl_u32 *u;
+ int err;
+
+ u = u32_alloc(cls);
+ if (!u)
+ return nl_errno(ENOMEM);
+
+ sel = u32_selector_alloc(u);
+ if (!sel)
+ return nl_errno(ENOMEM);
+
+ err = nl_data_append(u->cu_selector, NULL, sizeof(struct tc_u32_key));
+ if (err < 0)
+ return err;
+
+ /* the selector might have been moved by realloc */
+ sel = u32_selector(u);
+
+ sel->keys[sel->nkeys].mask = mask;
+ sel->keys[sel->nkeys].val = val & mask;
+ sel->keys[sel->nkeys].off = off;
+ sel->keys[sel->nkeys].offmask = offmask;
+ sel->nkeys++;
+ u->cu_mask |= U32_ATTR_SELECTOR;
+
+ return 0;
+}
+
+int rtnl_u32_add_key_uint8(struct rtnl_cls *cls, uint8_t val, uint8_t mask,
+ int off, int offmask)
+{
+ int shift = 24 - 8 * (off & 3);
+
+ return rtnl_u32_add_key(cls, htonl((uint32_t)val << shift),
+ htonl((uint32_t)mask << shift),
+ off & ~3, offmask);
+}
+
+/**
+ * Append new selector key to match a 16-bit number
+ *
+ * @arg cls classifier to be modified
+ * @arg val value to be matched (host byte-order)
+ * @arg mask mask to be applied before matching (host byte-order)
+ * @arg off offset, in bytes, to start matching
+ * @arg offmask offset mask
+*/
+int rtnl_u32_add_key_uint16(struct rtnl_cls *cls, uint16_t val, uint16_t mask,
+ int off, int offmask)
+{
+ int shift = ((off & 3) == 0 ? 16 : 0);
+ if (off % 2)
+ return nl_error(EINVAL, "Invalid offset alignment");
+
+ return rtnl_u32_add_key(cls, htonl((uint32_t)val << shift),
+ htonl((uint32_t)mask << shift),
+ off & ~3, offmask);
+}
+
+/**
+ * Append new selector key to match a 32-bit number
+ *
+ * @arg cls classifier to be modified
+ * @arg val value to be matched (host byte-order)
+ * @arg mask mask to be applied before matching (host byte-order)
+ * @arg off offset, in bytes, to start matching
+ * @arg offmask offset mask
+*/
+int rtnl_u32_add_key_uint32(struct rtnl_cls *cls, uint32_t val, uint32_t mask,
+ int off, int offmask)
+{
+ return rtnl_u32_add_key(cls, htonl(val), htonl(mask),
+ off & ~3, offmask);
+}
+
+int rtnl_u32_add_key_in_addr(struct rtnl_cls *cls, struct in_addr *addr,
+ uint8_t bitmask, int off, int offmask)
+{
+ uint32_t mask = 0xFFFFFFFF << (32 - bitmask);
+ return rtnl_u32_add_key(cls, addr->s_addr, htonl(mask), off, offmask);
+}
+
+int rtnl_u32_add_key_in6_addr(struct rtnl_cls *cls, struct in6_addr *addr,
+ uint8_t bitmask, int off, int offmask)
+{
+ int i, err;
+
+ for (i = 1; i <= 4; i++) {
+ if (32 * i - bitmask <= 0) {
+ if ((err = rtnl_u32_add_key(cls, addr->s6_addr32[i-1],
+ 0xFFFFFFFF, off+4*(i-1), offmask)) < 0)
+ return err;
+ }
+ else if (32 * i - bitmask < 32) {
+ uint32_t mask = 0xFFFFFFFF << (32 * i - bitmask);
+ if ((err = rtnl_u32_add_key(cls, addr->s6_addr32[i-1],
+ htonl(mask), off+4*(i-1), offmask)) < 0)
+ return err;
+ }
+ /* otherwise, if (32*i - bitmask >= 32) no key is generated */
+ }
+
+ return 0;
+}
+
+/** @} */
+
+static struct rtnl_cls_ops u32_ops = {
+ .co_kind = "u32",
+ .co_msg_parser = u32_msg_parser,
+ .co_free_data = u32_free_data,
+ .co_clone = u32_clone,
+ .co_get_opts = u32_get_opts,
+ .co_dump[NL_DUMP_BRIEF] = u32_dump_brief,
+ .co_dump[NL_DUMP_FULL] = u32_dump_full,
+ .co_dump[NL_DUMP_STATS] = u32_dump_stats,
+};
+
+static void __init u32_init(void)
+{
+ rtnl_cls_register(&u32_ops);
+}
+
+static void __exit u32_exit(void)
+{
+ rtnl_cls_unregister(&u32_ops);
+}
+
+/** @} */
diff --git a/lib/route/cls_api.c b/lib/route/cls_api.c
new file mode 100644
index 0000000..f5a083a
--- /dev/null
+++ b/lib/route/cls_api.c
@@ -0,0 +1,103 @@
+/*
+ * lib/route/cls_api.c Classifier Module API
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup cls
+ * @defgroup cls_api Classifier Modules
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/route/tc.h>
+#include <netlink/route/classifier.h>
+#include <netlink/route/classifier-modules.h>
+#include <netlink/route/link.h>
+
+static struct rtnl_cls_ops *cls_ops_list;
+
+/**
+ * @name Classifier Module API
+ * @{
+ */
+
+/**
+ * Register a classifier module
+ * @arg cops classifier module operations
+ */
+int rtnl_cls_register(struct rtnl_cls_ops *cops)
+{
+ struct rtnl_cls_ops *o, **op;
+
+ if (!cops->co_kind)
+ BUG();
+
+ for (op = &cls_ops_list; (o = *op) != NULL; op = &o->co_next)
+ if (!strcasecmp(cops->co_kind, o->co_kind))
+ return nl_errno(EEXIST);
+
+ cops->co_next = NULL;
+ *op = cops;
+
+ return 0;
+}
+
+/**
+ * Unregister a classifier module
+ * @arg cops classifier module operations
+ */
+int rtnl_cls_unregister(struct rtnl_cls_ops *cops)
+{
+ struct rtnl_cls_ops *o, **op;
+
+ for (op = &cls_ops_list; (o = *op) != NULL; op = &o->co_next)
+ if (!strcasecmp(cops->co_kind, o->co_kind))
+ break;
+
+ if (!o)
+ return nl_errno(ENOENT);
+
+ *op = cops->co_next;
+
+ return 0;
+}
+
+struct rtnl_cls_ops *__rtnl_cls_lookup_ops(const char *kind)
+{
+ struct rtnl_cls_ops *cops;
+
+ for (cops = cls_ops_list; cops; cops = cops->co_next)
+ if (!strcmp(kind, cops->co_kind))
+ return cops;
+
+ return NULL;
+}
+
+/**
+ * Lookup classifier operations for a classifier object
+ * @arg cls Classifier object.
+ *
+ * @return Classifier operations or NULL if not found.
+ */
+struct rtnl_cls_ops *rtnl_cls_lookup_ops(struct rtnl_cls *cls)
+{
+ if (!cls->c_ops)
+ cls->c_ops = __rtnl_cls_lookup_ops(cls->c_kind);
+
+ return cls->c_ops;
+}
+
+
+/** @} */
+
+/** @} */
diff --git a/lib/route/cls_obj.c b/lib/route/cls_obj.c
new file mode 100644
index 0000000..e12bc95
--- /dev/null
+++ b/lib/route/cls_obj.c
@@ -0,0 +1,203 @@
+/*
+ * lib/route/cls_api.c Classifier Object
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup cls
+ * @defgroup cls_obj Classifier Object
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/route/tc.h>
+#include <netlink/route/classifier.h>
+#include <netlink/route/classifier-modules.h>
+#include <netlink/route/link.h>
+
+/** @cond SKIP */
+#define CLS_ATTR_PRIO (TCA_ATTR_MAX << 1)
+#define CLS_ATTR_PROTOCOL (TCA_ATTR_MAX << 2)
+/** @endcond */
+
+static void cls_free_data(struct nl_object *obj)
+{
+ struct rtnl_cls *cls = (struct rtnl_cls *) obj;
+ struct rtnl_cls_ops *cops;
+
+ tca_free_data((struct rtnl_tca *) cls);
+
+ cops = rtnl_cls_lookup_ops(cls);
+ if (cops && cops->co_free_data)
+ cops->co_free_data(cls);
+}
+
+static int cls_clone(struct nl_object *_dst, struct nl_object *_src)
+{
+ struct rtnl_cls *dst = nl_object_priv(_dst);
+ struct rtnl_cls *src = nl_object_priv(_src);
+ struct rtnl_cls_ops *cops;
+ int err;
+
+ err = tca_clone((struct rtnl_tca *) dst, (struct rtnl_tca *) src);
+ if (err < 0)
+ goto errout;
+
+ cops = rtnl_cls_lookup_ops(src);
+ if (cops && cops->co_clone)
+ err = cops->co_clone(dst, src);
+errout:
+ return err;
+}
+
+static int cls_dump_brief(struct nl_object *obj, struct nl_dump_params *p)
+{
+ char buf[32];
+ struct rtnl_cls *cls = (struct rtnl_cls *) obj;
+ struct rtnl_cls_ops *cops;
+ int line;
+
+ line = tca_dump_brief((struct rtnl_tca *) cls, "cls", p, 0);
+
+ dp_dump(p, " prio %u protocol %s", cls->c_prio,
+ nl_ether_proto2str(cls->c_protocol, buf, sizeof(buf)));
+
+ cops = rtnl_cls_lookup_ops(cls);
+ if (cops && cops->co_dump[NL_DUMP_BRIEF])
+ line = cops->co_dump[NL_DUMP_BRIEF](cls, p, line);
+ dp_dump(p, "\n");
+
+ return line;
+}
+
+static int cls_dump_full(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_cls *cls = (struct rtnl_cls *) obj;
+ struct rtnl_cls_ops *cops;
+ int line;
+
+ line = cls_dump_brief(obj, p);
+ line = tca_dump_full((struct rtnl_tca *) cls, p, line);
+
+ cops = rtnl_cls_lookup_ops(cls);
+ if (cops && cops->co_dump[NL_DUMP_FULL])
+ line = cops->co_dump[NL_DUMP_FULL](cls, p, line);
+ else
+ dp_dump(p, "no options\n");
+
+ return line;
+}
+
+static int cls_dump_stats(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_cls *cls = (struct rtnl_cls *) obj;
+ struct rtnl_cls_ops *cops;
+ int line;
+
+ line = cls_dump_full(obj, p);
+ line = tca_dump_stats((struct rtnl_tca *) cls, p, line);
+ dp_dump(p, "\n");
+
+ cops = rtnl_cls_lookup_ops(cls);
+ if (cops && cops->co_dump[NL_DUMP_STATS])
+ line = cops->co_dump[NL_DUMP_STATS](cls, p, line);
+
+ return line;
+}
+
+/**
+ * @name Allocation/Freeing
+ * @{
+ */
+
+struct rtnl_cls *rtnl_cls_alloc(void)
+{
+ return (struct rtnl_cls *) nl_object_alloc(&cls_obj_ops);
+}
+
+void rtnl_cls_put(struct rtnl_cls *cls)
+{
+ nl_object_put((struct nl_object *) cls);
+}
+
+/** @} */
+
+
+/**
+ * @name Attributes
+ * @{
+ */
+
+void rtnl_cls_set_ifindex(struct rtnl_cls *f, int ifindex)
+{
+ tca_set_ifindex((struct rtnl_tca *) f, ifindex);
+}
+
+void rtnl_cls_set_handle(struct rtnl_cls *f, uint32_t handle)
+{
+ tca_set_handle((struct rtnl_tca *) f, handle);
+}
+
+void rtnl_cls_set_parent(struct rtnl_cls *f, uint32_t parent)
+{
+ tca_set_parent((struct rtnl_tca *) f, parent);
+}
+
+void rtnl_cls_set_kind(struct rtnl_cls *f, const char *kind)
+{
+ tca_set_kind((struct rtnl_tca *) f, kind);
+ f->c_ops = __rtnl_cls_lookup_ops(kind);
+}
+
+void rtnl_cls_set_prio(struct rtnl_cls *cls, int prio)
+{
+ cls->c_prio = prio;
+ cls->ce_mask |= CLS_ATTR_PRIO;
+}
+
+int rtnl_cls_get_prio(struct rtnl_cls *cls)
+{
+ if (cls->ce_mask & CLS_ATTR_PRIO)
+ return cls->c_prio;
+ else
+ return 0;
+}
+
+void rtnl_cls_set_protocol(struct rtnl_cls *cls, int protocol)
+{
+ cls->c_protocol = protocol;
+ cls->ce_mask |= CLS_ATTR_PROTOCOL;
+}
+
+int rtnl_cls_get_protocol(struct rtnl_cls *cls)
+{
+ if (cls->ce_mask & CLS_ATTR_PROTOCOL)
+ return cls->c_protocol;
+ else
+ return ETH_P_ALL;
+}
+
+/** @} */
+
+struct nl_object_ops cls_obj_ops = {
+ .oo_name = "route/cls",
+ .oo_size = sizeof(struct rtnl_cls),
+ .oo_free_data = cls_free_data,
+ .oo_clone = cls_clone,
+ .oo_dump[NL_DUMP_BRIEF] = cls_dump_brief,
+ .oo_dump[NL_DUMP_FULL] = cls_dump_full,
+ .oo_dump[NL_DUMP_STATS] = cls_dump_stats,
+ .oo_compare = tca_compare,
+ .oo_id_attrs = (TCA_ATTR_IFINDEX | TCA_ATTR_HANDLE),
+};
+
+/** @} */
diff --git a/lib/route/link.c b/lib/route/link.c
new file mode 100644
index 0000000..7ecae12
--- /dev/null
+++ b/lib/route/link.c
@@ -0,0 +1,1313 @@
+/*
+ * lib/route/link.c Links (Interfaces)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup rtnl
+ * @defgroup link Links (Interfaces)
+ * @brief
+ *
+ * @par Link Identification
+ * A link can be identified by either its interface index or by its
+ * name. The kernel favours the interface index but falls back to the
+ * interface name if the interface index is lesser-than 0 for kernels
+ * >= 2.6.11. Therefore you can request changes without mapping a
+ * interface name to the corresponding index first.
+ *
+ * @par Changeable Attributes
+ * @anchor link_changeable
+ * - Link layer address
+ * - Link layer broadcast address
+ * - device mapping (ifmap) (>= 2.6.9)
+ * - MTU (>= 2.6.9)
+ * - Transmission queue length (>= 2.6.9)
+ * - Weight (>= 2.6.9)
+ * - Link name (only via access through interface index) (>= 2.6.9)
+ * - Flags (>= 2.6.9)
+ * - IFF_DEBUG
+ * - IFF_NOTRAILERS
+ * - IFF_NOARP
+ * - IFF_DYNAMIC
+ * - IFF_MULTICAST
+ * - IFF_PORTSEL
+ * - IFF_AUTOMEDIA
+ * - IFF_UP
+ * - IFF_PROMISC
+ * - IFF_ALLMULTI
+ *
+ * @par Link Flags (linux/if.h)
+ * @anchor link_flags
+ * @code
+ * IFF_UP Status of link (up|down)
+ * IFF_BROADCAST Indicates this link allows broadcasting
+ * IFF_MULTICAST Indicates this link allows multicasting
+ * IFF_ALLMULTI Indicates this link is doing multicast routing
+ * IFF_DEBUG Tell the driver to do debugging (currently unused)
+ * IFF_LOOPBACK This is the loopback link
+ * IFF_POINTOPOINT Point-to-point link
+ * IFF_NOARP Link is unable to perform ARP
+ * IFF_PROMISC Status of promiscious mode flag
+ * IFF_MASTER Used by teql
+ * IFF_SLAVE Used by teql
+ * IFF_PORTSEL Indicates this link allows port selection
+ * IFF_AUTOMEDIA Indicates this link selects port automatically
+ * IFF_DYNAMIC Indicates the address of this link is dynamic
+ * IFF_RUNNING Link is running and carrier is ok.
+ * IFF_NOTRAILERS Unused, BSD compat.
+ * @endcode
+ *
+ * @par Notes on IFF_PROMISC and IFF_ALLMULTI flags
+ * Although you can query the status of IFF_PROMISC and IFF_ALLMULTI
+ * they do not represent the actual state in the kernel but rather
+ * whether the flag has been enabled/disabled by userspace. The link
+ * may be in promiscious mode even if IFF_PROMISC is not set in a link
+ * dump request response because promiscity might be needed by the driver
+ * for a period of time.
+ *
+ * @note The unit of the transmission queue length depends on the
+ * link type, a common unit is \a packets.
+ *
+ * @par 1) Retrieving information about available links
+ * @code
+ * // The first step is to retrieve a list of all available interfaces within
+ * // the kernel and put them into a cache.
+ * struct nl_cache *cache = rtnl_link_alloc_cache(nl_handle);
+ *
+ * // In a second step, a specific link may be looked up by either interface
+ * // index or interface name.
+ * struct rtnl_link *link = rtnl_link_get_by_name(cache, "lo");
+ *
+ * // rtnl_link_get_by_name() is the short version for translating the
+ * // interface name to an interface index first like this:
+ * int ifindex = rtnl_link_name2i(cache, "lo");
+ * struct rtnl_link *link = rtnl_link_get(cache, ifindex);
+ *
+ * // After successful usage, the object must be given back to the cache
+ * rtnl_link_put(link);
+ * @endcode
+ *
+ * @par 2) Changing link attributes
+ * @code
+ * // In order to change any attributes of an existing link, we must allocate
+ * // a new link to hold the change requests:
+ * struct rtnl_link *request = rtnl_link_alloc();
+ *
+ * // Now we can go on and specify the attributes we want to change:
+ * rtnl_link_set_weight(request, 300);
+ * rtnl_link_set_mtu(request, 1360);
+ *
+ * // We can also shut an interface down administratively
+ * rtnl_link_unset_flags(request, rtnl_link_str2flags("up"));
+ *
+ * // Actually, we should know which link to change, so let's look it up
+ * struct rtnl_link *old = rtnl_link_get(cache, "eth0");
+ *
+ * // Two ways exist to commit this change request, the first one is to
+ * // build the required netlink message and send it out in one single
+ * // step:
+ * rtnl_link_change(nl_handle, old, request);
+ *
+ * // An alternative way is to build the netlink message and send it
+ * // out yourself using nl_send_auto_complete()
+ * struct nl_msg *msg = rtnl_link_build_change_request(old, request);
+ * nl_send_auto_complete(nl_handle, nlmsg_hdr(msg));
+ * nlmsg_free(msg);
+ *
+ * // Don't forget to give back the link object ;->
+ * rtnl_link_put(old);
+ * @endcode
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/attr.h>
+#include <netlink/utils.h>
+#include <netlink/object.h>
+#include <netlink/route/rtnl.h>
+#include <netlink/route/link.h>
+
+/** @cond SKIP */
+#define LINK_ATTR_MTU 0x0001
+#define LINK_ATTR_LINK 0x0002
+#define LINK_ATTR_TXQLEN 0x0004
+#define LINK_ATTR_WEIGHT 0x0008
+#define LINK_ATTR_MASTER 0x0010
+#define LINK_ATTR_QDISC 0x0020
+#define LINK_ATTR_MAP 0x0040
+#define LINK_ATTR_ADDR 0x0080
+#define LINK_ATTR_BRD 0x0100
+#define LINK_ATTR_FLAGS 0x0200
+#define LINK_ATTR_IFNAME 0x0400
+#define LINK_ATTR_IFINDEX 0x0800
+#define LINK_ATTR_FAMILY 0x1000
+#define LINK_ATTR_ARPTYPE 0x2000
+#define LINK_ATTR_STATS 0x4000
+#define LINK_ATTR_CHANGE 0x8000
+
+static struct nl_cache_ops rtnl_link_ops;
+static struct nl_object_ops link_obj_ops;
+/** @endcond */
+
+static void link_free_data(struct nl_object *c)
+{
+ struct rtnl_link *link = nl_object_priv(c);
+
+ if (link) {
+ nl_addr_put(link->l_addr);
+ nl_addr_put(link->l_bcast);
+ }
+}
+
+static int link_clone(struct nl_object *_dst, struct nl_object *_src)
+{
+ struct rtnl_link *dst = nl_object_priv(_dst);
+ struct rtnl_link *src = nl_object_priv(_src);
+
+ if (src->l_addr)
+ if (!(dst->l_addr = nl_addr_clone(src->l_addr)))
+ goto errout;
+
+ if (src->l_bcast)
+ if (!(dst->l_bcast = nl_addr_clone(src->l_bcast)))
+ goto errout;
+
+ return 0;
+errout:
+ return nl_get_errno();
+}
+
+static struct nla_policy link_policy[IFLA_MAX+1] = {
+ [IFLA_IFNAME] = { .type = NLA_STRING,
+ .maxlen = IFNAMSIZ },
+ [IFLA_MTU] = { .type = NLA_U32 },
+ [IFLA_TXQLEN] = { .type = NLA_U32 },
+ [IFLA_LINK] = { .type = NLA_U32 },
+ [IFLA_WEIGHT] = { .type = NLA_U32 },
+ [IFLA_MASTER] = { .type = NLA_U32 },
+ [IFLA_QDISC] = { .type = NLA_STRING,
+ .maxlen = IFQDISCSIZ },
+ [IFLA_STATS] = { .minlen = sizeof(struct rtnl_link_stats) },
+ [IFLA_MAP] = { .minlen = sizeof(struct rtnl_link_ifmap) },
+};
+
+static int link_msg_parser(struct nl_cache_ops *ops, struct sockaddr_nl *who,
+ struct nlmsghdr *n, void *arg)
+{
+ struct rtnl_link *link;
+ struct ifinfomsg *ifi;
+ struct nlattr *tb[IFLA_MAX+1];
+ struct nl_parser_param *pp = arg;
+ int err;
+
+ link = rtnl_link_alloc();
+ if (link == NULL) {
+ err = nl_errno(ENOMEM);
+ goto errout;
+ }
+
+ link->ce_msgtype = n->nlmsg_type;
+
+ err = nlmsg_parse(n, sizeof(*ifi), tb, IFLA_MAX, link_policy);
+ if (err < 0)
+ goto errout;
+
+ if (tb[IFLA_IFNAME] == NULL) {
+ err = nl_error(EINVAL, "Missing link name TLV");
+ goto errout;
+ }
+
+ nla_strlcpy(link->l_name, tb[IFLA_IFNAME], IFNAMSIZ);
+
+ ifi = nlmsg_data(n);
+ link->l_family = ifi->ifi_family;
+ link->l_arptype = ifi->ifi_type;
+ link->l_index = ifi->ifi_index;
+ link->l_flags = ifi->ifi_flags;
+ link->l_change = ifi->ifi_change;
+ link->ce_mask = (LINK_ATTR_IFNAME | LINK_ATTR_FAMILY |
+ LINK_ATTR_ARPTYPE| LINK_ATTR_IFINDEX |
+ LINK_ATTR_FLAGS | LINK_ATTR_CHANGE);
+
+ if (tb[IFLA_STATS]) {
+ struct rtnl_link_stats *st = nla_data(tb[IFLA_STATS]);
+
+ link->l_stats[RTNL_LINK_RX_PACKETS] = st->rx_packets;
+ link->l_stats[RTNL_LINK_RX_BYTES] = st->rx_bytes;
+ link->l_stats[RTNL_LINK_RX_ERRORS] = st->rx_errors;
+ link->l_stats[RTNL_LINK_RX_DROPPED] = st->rx_dropped;
+ link->l_stats[RTNL_LINK_RX_COMPRESSED] = st->rx_compressed;
+ link->l_stats[RTNL_LINK_RX_FIFO_ERR] = st->rx_fifo_errors;
+ link->l_stats[RTNL_LINK_TX_PACKETS] = st->tx_packets;
+ link->l_stats[RTNL_LINK_TX_BYTES] = st->tx_bytes;
+ link->l_stats[RTNL_LINK_TX_ERRORS] = st->tx_errors;
+ link->l_stats[RTNL_LINK_TX_DROPPED] = st->tx_dropped;
+ link->l_stats[RTNL_LINK_TX_COMPRESSED] = st->tx_compressed;
+ link->l_stats[RTNL_LINK_TX_FIFO_ERR] = st->tx_fifo_errors;
+ link->l_stats[RTNL_LINK_RX_LEN_ERR] = st->rx_length_errors;
+ link->l_stats[RTNL_LINK_RX_OVER_ERR] = st->rx_over_errors;
+ link->l_stats[RTNL_LINK_RX_CRC_ERR] = st->rx_crc_errors;
+ link->l_stats[RTNL_LINK_RX_FRAME_ERR] = st->rx_frame_errors;
+ link->l_stats[RTNL_LINK_RX_MISSED_ERR] = st->rx_missed_errors;
+ link->l_stats[RTNL_LINK_TX_ABORT_ERR] = st->tx_aborted_errors;
+ link->l_stats[RTNL_LINK_TX_CARRIER_ERR] = st->tx_carrier_errors;
+ link->l_stats[RTNL_LINK_TX_HBEAT_ERR] = st->tx_heartbeat_errors;
+ link->l_stats[RTNL_LINK_TX_WIN_ERR] = st->tx_window_errors;
+ link->l_stats[RTNL_LINK_MULTICAST] = st->multicast;
+
+ link->ce_mask |= LINK_ATTR_STATS;
+ }
+
+ if (tb[IFLA_TXQLEN]) {
+ link->l_txqlen = nla_get_u32(tb[IFLA_TXQLEN]);
+ link->ce_mask |= LINK_ATTR_TXQLEN;
+ }
+
+ if (tb[IFLA_MTU]) {
+ link->l_mtu = nla_get_u32(tb[IFLA_MTU]);
+ link->ce_mask |= LINK_ATTR_MTU;
+ }
+
+ if (tb[IFLA_ADDRESS]) {
+ link->l_addr = nla_get_addr(tb[IFLA_ADDRESS], AF_UNSPEC);
+ if (link->l_addr == NULL)
+ goto errout;
+ nl_addr_set_family(link->l_addr,
+ nl_addr_guess_family(link->l_addr));
+ link->ce_mask |= LINK_ATTR_ADDR;
+ }
+
+ if (tb[IFLA_BROADCAST]) {
+ link->l_bcast = nla_get_addr(tb[IFLA_BROADCAST], AF_UNSPEC);
+ if (link->l_bcast == NULL)
+ goto errout;
+ nl_addr_set_family(link->l_bcast,
+ nl_addr_guess_family(link->l_bcast));
+ link->ce_mask |= LINK_ATTR_BRD;
+ }
+
+ if (tb[IFLA_LINK]) {
+ link->l_link = nla_get_u32(tb[IFLA_LINK]);
+ link->ce_mask |= LINK_ATTR_LINK;
+ }
+
+ if (tb[IFLA_WEIGHT]) {
+ link->l_weight = nla_get_u32(tb[IFLA_WEIGHT]);
+ link->ce_mask |= LINK_ATTR_WEIGHT;
+ }
+
+ if (tb[IFLA_QDISC]) {
+ nla_strlcpy(link->l_qdisc, tb[IFLA_QDISC], IFQDISCSIZ);
+ link->ce_mask |= LINK_ATTR_QDISC;
+ }
+
+ if (tb[IFLA_MAP]) {
+ struct rtnl_link_ifmap *map = nla_data(tb[IFLA_MAP]);
+ link->l_map.lm_mem_start = map->mem_start;
+ link->l_map.lm_mem_end = map->mem_end;
+ link->l_map.lm_base_addr = map->base_addr;
+ link->l_map.lm_irq = map->irq;
+ link->l_map.lm_dma = map->dma;
+ link->l_map.lm_port = map->port;
+ link->ce_mask |= LINK_ATTR_MAP;
+ }
+
+ if (tb[IFLA_MASTER]) {
+ link->l_master = nla_get_u32(tb[IFLA_MASTER]);
+ link->ce_mask |= LINK_ATTR_MASTER;
+ }
+
+ err = pp->pp_cb((struct nl_object *) link, pp);
+ if (err < 0)
+ goto errout;
+
+ return P_ACCEPT;
+
+errout:
+ rtnl_link_put(link);
+ return err;
+}
+
+static int link_request_update(struct nl_cache *c, struct nl_handle *h)
+{
+ return nl_rtgen_request(h, RTM_GETLINK, AF_UNSPEC, NLM_F_DUMP);
+}
+
+static int link_dump_brief(struct nl_object *obj, struct nl_dump_params *p)
+{
+ char buf[128];
+ struct nl_cache *cache = dp_cache(obj);
+ struct rtnl_link *link = (struct rtnl_link *) obj;
+ int line = 1;
+
+ dp_dump(p, "%s ", link->l_name);
+
+ if (link->ce_mask & LINK_ATTR_LINK) {
+ struct rtnl_link *ll = rtnl_link_get(cache, link->l_link);
+ dp_dump(p, "@%s", ll ? ll->l_name : "NONE");
+ if (ll)
+ rtnl_link_put(ll);
+ }
+
+ dp_dump(p, "%s ", nl_llproto2str(link->l_arptype, buf, sizeof(buf)));
+ dp_dump(p, "%s ", link->l_addr ? nl_addr2str(link->l_addr, buf,
+ sizeof(buf)) : "none");
+ dp_dump(p, "mtu %u ", link->l_mtu);
+
+ if (link->ce_mask & LINK_ATTR_MASTER) {
+ struct rtnl_link *master = rtnl_link_get(cache, link->l_master);
+ dp_dump(p, "master %s ", master ? master->l_name : "inv");
+ if (master)
+ rtnl_link_put(master);
+ }
+
+ rtnl_link_flags2str(link->l_flags, buf, sizeof(buf));
+ if (buf[0])
+ dp_dump(p, "<%s>", buf);
+
+ dp_dump(p, "\n");
+
+ return line;
+}
+
+static int link_dump_full(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_link *link = (struct rtnl_link *) obj;
+ char buf[64];
+ int line;
+
+ line = link_dump_brief(obj, p);
+ dp_new_line(p, line++);
+
+ dp_dump(p, " txqlen %u weight %u ", link->l_txqlen, link->l_weight);
+
+ if (link->ce_mask & LINK_ATTR_QDISC)
+ dp_dump(p, "qdisc %s ", link->l_qdisc);
+
+ if (link->ce_mask & LINK_ATTR_MAP && link->l_map.lm_irq)
+ dp_dump(p, "irq %u ", link->l_map.lm_irq);
+
+ if (link->ce_mask & LINK_ATTR_IFINDEX)
+ dp_dump(p, "index %u ", link->l_index);
+
+ if (link->ce_mask & LINK_ATTR_BRD)
+ dp_dump(p, "brd %s", nl_addr2str(link->l_bcast, buf,
+ sizeof(buf)));
+
+ dp_dump(p, "\n");
+
+ return line;
+}
+
+static int link_dump_stats(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_link *link = (struct rtnl_link *) obj;
+ char *unit, fmt[64];
+ float res;
+ int line;
+
+ line = link_dump_full(obj, p);
+
+ dp_dump_line(p, line++, " Stats: bytes packets errors "
+ " dropped fifo-err compressed\n");
+
+ res = nl_cancel_down_bytes(link->l_stats[RTNL_LINK_RX_BYTES], &unit);
+
+ strcpy(fmt, " RX %X.2f %s %10llu %10llu %10llu %10llu %10llu\n");
+ fmt[9] = *unit == 'B' ? '9' : '7';
+
+ dp_dump_line(p, line++, fmt,
+ res, unit,
+ link->l_stats[RTNL_LINK_RX_PACKETS],
+ link->l_stats[RTNL_LINK_RX_ERRORS],
+ link->l_stats[RTNL_LINK_RX_DROPPED],
+ link->l_stats[RTNL_LINK_RX_FIFO_ERR],
+ link->l_stats[RTNL_LINK_RX_COMPRESSED]);
+
+ res = nl_cancel_down_bytes(link->l_stats[RTNL_LINK_TX_BYTES], &unit);
+
+ strcpy(fmt, " TX %X.2f %s %10llu %10llu %10llu %10llu %10llu\n");
+ fmt[9] = *unit == 'B' ? '9' : '7';
+
+ dp_dump_line(p, line++, fmt,
+ res, unit,
+ link->l_stats[RTNL_LINK_TX_PACKETS],
+ link->l_stats[RTNL_LINK_TX_ERRORS],
+ link->l_stats[RTNL_LINK_TX_DROPPED],
+ link->l_stats[RTNL_LINK_TX_FIFO_ERR],
+ link->l_stats[RTNL_LINK_TX_COMPRESSED]);
+
+ dp_dump_line(p, line++, " Errors: length over crc "
+ " frame missed multicast\n");
+
+ dp_dump_line(p, line++, " RX %10" PRIu64 " %10" PRIu64 " %10"
+ PRIu64 " %10" PRIu64 " %10" PRIu64 " %10"
+ PRIu64 "\n",
+ link->l_stats[RTNL_LINK_RX_LEN_ERR],
+ link->l_stats[RTNL_LINK_RX_OVER_ERR],
+ link->l_stats[RTNL_LINK_RX_CRC_ERR],
+ link->l_stats[RTNL_LINK_RX_FRAME_ERR],
+ link->l_stats[RTNL_LINK_RX_MISSED_ERR],
+ link->l_stats[RTNL_LINK_MULTICAST]);
+
+ dp_dump_line(p, line++, " Errors: aborted carrier heartbeat "
+ " window collision\n");
+
+ dp_dump_line(p, line++, " TX %10" PRIu64 " %10" PRIu64 " %10"
+ PRIu64 " %10" PRIu64 " %10" PRIu64 "\n",
+ link->l_stats[RTNL_LINK_TX_ABORT_ERR],
+ link->l_stats[RTNL_LINK_TX_CARRIER_ERR],
+ link->l_stats[RTNL_LINK_TX_HBEAT_ERR],
+ link->l_stats[RTNL_LINK_TX_WIN_ERR],
+ link->l_stats[RTNL_LINK_TX_COLLISIONS]);
+
+ return line;
+}
+
+static int link_dump_xml(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_link *link = (struct rtnl_link *) obj;
+ struct nl_cache *cache = dp_cache(obj);
+ char buf[128];
+ int i, line = 0;
+
+ dp_dump_line(p, line++, "<link name=\"%s\" index=\"%u\">\n",
+ link->l_name, link->l_index);
+ dp_dump_line(p, line++, " <family>%s</family>\n",
+ nl_af2str(link->l_family, buf, sizeof(buf)));
+ dp_dump_line(p, line++, " <arptype>%s</arptype>\n",
+ nl_llproto2str(link->l_arptype, buf, sizeof(buf)));
+ dp_dump_line(p, line++, " <address>%s</address>\n",
+ nl_addr2str(link->l_addr, buf, sizeof(buf)));
+ dp_dump_line(p, line++, " <mtu>%u</mtu>\n", link->l_mtu);
+ dp_dump_line(p, line++, " <txqlen>%u</txqlen>\n", link->l_txqlen);
+ dp_dump_line(p, line++, " <weight>%u</weight>\n", link->l_weight);
+
+ rtnl_link_flags2str(link->l_flags, buf, sizeof(buf));
+ if (buf[0])
+ dp_dump_line(p, line++, " <flags>%s</flags>\n", buf);
+
+ if (link->ce_mask & LINK_ATTR_QDISC)
+ dp_dump_line(p, line++, " <qdisc>%s</qdisc>\n", link->l_qdisc);
+
+ if (link->ce_mask & LINK_ATTR_LINK) {
+ struct rtnl_link *ll = rtnl_link_get(cache, link->l_link);
+ dp_dump_line(p, line++, " <link>%s</link>\n",
+ ll ? ll->l_name : "none");
+ if (ll)
+ rtnl_link_put(ll);
+ }
+
+ if (link->ce_mask & LINK_ATTR_MASTER) {
+ struct rtnl_link *master = rtnl_link_get(cache, link->l_master);
+ dp_dump_line(p, line++, " <master>%s</master>\n",
+ master ? master->l_name : "none");
+ if (master)
+ rtnl_link_put(master);
+ }
+
+ if (link->ce_mask & LINK_ATTR_BRD)
+ dp_dump_line(p, line++, " <broadcast>%s</broadcast>\n",
+ nl_addr2str(link->l_bcast, buf, sizeof(buf)));
+
+ if (link->ce_mask & LINK_ATTR_STATS) {
+ dp_dump_line(p, line++, " <stats>\n");
+ for (i = 0; i <= RTNL_LINK_STATS_MAX; i++) {
+ rtnl_link_stat2str(i, buf, sizeof(buf));
+ dp_dump_line(p, line++,
+ " <%s>%" PRIu64 "</%s>\n",
+ buf, link->l_stats[i], buf);
+ }
+ dp_dump_line(p, line++, " </stats>\n");
+ }
+
+ dp_dump_line(p, line++, "</link>\n");
+
+#if 0
+ uint32_t l_change; /**< Change mask */
+ struct rtnl_lifmap l_map; /**< Interface device mapping */
+#endif
+
+ return line;
+}
+
+static int link_dump_env(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_link *link = (struct rtnl_link *) obj;
+ struct nl_cache *cache = dp_cache(obj);
+ char buf[128];
+ int i, line = 0;
+
+ dp_dump_line(p, line++, "LINK_NAME=%s\n", link->l_name);
+ dp_dump_line(p, line++, "LINK_IFINDEX=%u\n", link->l_index);
+ dp_dump_line(p, line++, "LINK_FAMILY=%s\n",
+ nl_af2str(link->l_family, buf, sizeof(buf)));
+ dp_dump_line(p, line++, "LINK_TYPE=%s\n",
+ nl_llproto2str(link->l_arptype, buf, sizeof(buf)));
+ if (link->ce_mask & LINK_ATTR_ADDR)
+ dp_dump_line(p, line++, "LINK_ADDRESS=%s\n",
+ nl_addr2str(link->l_addr, buf, sizeof(buf)));
+ dp_dump_line(p, line++, "LINK_MTU=%u\n", link->l_mtu);
+ dp_dump_line(p, line++, "LINK_TXQUEUELEN=%u\n", link->l_txqlen);
+ dp_dump_line(p, line++, "LINK_WEIGHT=%u\n", link->l_weight);
+
+ rtnl_link_flags2str(link->l_flags & ~IFF_RUNNING, buf, sizeof(buf));
+ if (buf[0])
+ dp_dump_line(p, line++, "LINK_FLAGS=%s\n", buf);
+
+ if (link->ce_mask & LINK_ATTR_QDISC)
+ dp_dump_line(p, line++, "LINK_QDISC=%s\n", link->l_qdisc);
+
+ if (link->ce_mask & LINK_ATTR_LINK) {
+ struct rtnl_link *ll = rtnl_link_get(cache, link->l_link);
+
+ dp_dump_line(p, line++, "LINK_LINK_IFINDEX=%d\n", link->l_link);
+ if (ll) {
+ dp_dump_line(p, line++, "LINK_LINK_IFNAME=%s\n",
+ ll->l_name);
+ rtnl_link_put(ll);
+ }
+ }
+
+ if (link->ce_mask & LINK_ATTR_MASTER) {
+ struct rtnl_link *master = rtnl_link_get(cache, link->l_master);
+ dp_dump_line(p, line++, "LINK_MASTER=%s\n",
+ master ? master->l_name : "none");
+ if (master)
+ rtnl_link_put(master);
+ }
+
+ if (link->ce_mask & LINK_ATTR_BRD)
+ dp_dump_line(p, line++, "LINK_BROADCAST=%s\n",
+ nl_addr2str(link->l_bcast, buf, sizeof(buf)));
+
+ if (link->ce_mask & LINK_ATTR_STATS) {
+ for (i = 0; i <= RTNL_LINK_STATS_MAX; i++) {
+ char *c = buf;
+
+ sprintf(buf, "LINK_");
+ rtnl_link_stat2str(i, buf + 5, sizeof(buf) - 5);
+ while (*c) {
+ *c = toupper(*c);
+ c++;
+ }
+ dp_dump_line(p, line++,
+ "%s=%" PRIu64 "\n", buf, link->l_stats[i]);
+ }
+ }
+
+ return line;
+}
+
+#if 0
+static int link_handle_event(struct nl_object *a, struct rtnl_link_event_cb *cb)
+{
+ struct rtnl_link *l = (struct rtnl_link *) a;
+ struct nl_cache *c = dp_cache(a);
+ int nevents = 0;
+
+ if (l->l_change == ~0U) {
+ if (l->ce_msgtype == RTM_NEWLINK)
+ cb->le_register(l);
+ else
+ cb->le_unregister(l);
+
+ return 1;
+ }
+
+ if (l->l_change & IFF_SLAVE) {
+ if (l->l_flags & IFF_SLAVE) {
+ struct rtnl_link *m = rtnl_link_get(c, l->l_master);
+ cb->le_new_bonding(l, m);
+ if (m)
+ rtnl_link_put(m);
+ } else
+ cb->le_cancel_bonding(l);
+ }
+
+#if 0
+ if (l->l_change & IFF_UP && l->l_change & IFF_RUNNING)
+ dp_dump_line(p, line++, "link %s changed state to %s.\n",
+ l->l_name, l->l_flags & IFF_UP ? "up" : "down");
+
+ if (l->l_change & IFF_PROMISC) {
+ dp_new_line(p, line++);
+ dp_dump(p, "link %s %s promiscuous mode.\n",
+ l->l_name, l->l_flags & IFF_PROMISC ? "entered" : "left");
+ }
+
+ if (line == 0)
+ dp_dump_line(p, line++, "link %s sent unknown event.\n",
+ l->l_name);
+#endif
+
+ return nevents;
+}
+#endif
+
+static int link_compare(struct nl_object *_a, struct nl_object *_b,
+ uint32_t attrs, int flags)
+{
+ struct rtnl_link *a = (struct rtnl_link *) _a;
+ struct rtnl_link *b = (struct rtnl_link *) _b;
+ int diff = 0;
+
+#define LINK_DIFF(ATTR, EXPR) ATTR_DIFF(attrs, LINK_ATTR_##ATTR, a, b, EXPR)
+
+ diff |= LINK_DIFF(IFINDEX, a->l_index != b->l_index);
+ diff |= LINK_DIFF(MTU, a->l_mtu != b->l_mtu);
+ diff |= LINK_DIFF(LINK, a->l_link != b->l_link);
+ diff |= LINK_DIFF(TXQLEN, a->l_txqlen != b->l_txqlen);
+ diff |= LINK_DIFF(WEIGHT, a->l_weight != b->l_weight);
+ diff |= LINK_DIFF(MASTER, a->l_master != b->l_master);
+ diff |= LINK_DIFF(FAMILY, a->l_family != b->l_family);
+ diff |= LINK_DIFF(QDISC, strcmp(a->l_qdisc, b->l_qdisc));
+ diff |= LINK_DIFF(IFNAME, strcmp(a->l_name, b->l_name));
+ diff |= LINK_DIFF(ADDR, nl_addr_cmp(a->l_addr, b->l_addr));
+ diff |= LINK_DIFF(BRD, nl_addr_cmp(a->l_bcast, b->l_bcast));
+
+ if (flags & LOOSE_FLAG_COMPARISON)
+ diff |= LINK_DIFF(FLAGS,
+ (a->l_flags ^ b->l_flags) & b->l_flag_mask);
+ else
+ diff |= LINK_DIFF(FLAGS, a->l_flags != b->l_flags);
+
+#undef LINK_DIFF
+
+ return diff;
+}
+
+static struct trans_tbl link_attrs[] = {
+ __ADD(LINK_ATTR_MTU, mtu)
+ __ADD(LINK_ATTR_LINK, link)
+ __ADD(LINK_ATTR_TXQLEN, txqlen)
+ __ADD(LINK_ATTR_WEIGHT, weight)
+ __ADD(LINK_ATTR_MASTER, master)
+ __ADD(LINK_ATTR_QDISC, qdisc)
+ __ADD(LINK_ATTR_MAP, map)
+ __ADD(LINK_ATTR_ADDR, address)
+ __ADD(LINK_ATTR_BRD, broadcast)
+ __ADD(LINK_ATTR_FLAGS, flags)
+ __ADD(LINK_ATTR_IFNAME, name)
+ __ADD(LINK_ATTR_IFINDEX, ifindex)
+ __ADD(LINK_ATTR_FAMILY, family)
+ __ADD(LINK_ATTR_ARPTYPE, arptype)
+ __ADD(LINK_ATTR_STATS, stats)
+ __ADD(LINK_ATTR_CHANGE, change)
+};
+
+static char *link_attrs2str(int attrs, char *buf, size_t len)
+{
+ return __flags2str(attrs, buf, len, link_attrs,
+ ARRAY_SIZE(link_attrs));
+}
+
+/**
+ * @name Allocation/Freeing
+ * @{
+ */
+
+struct rtnl_link *rtnl_link_alloc(void)
+{
+ return (struct rtnl_link *) nl_object_alloc(&link_obj_ops);
+}
+
+void rtnl_link_put(struct rtnl_link *link)
+{
+ nl_object_put((struct nl_object *) link);
+}
+
+/** @} */
+
+/**
+ * @name Cache Management
+ * @{
+ */
+
+
+/**
+ * Allocate link cache and fill in all configured links.
+ * @arg handle Netlink handle.
+ *
+ * Allocates a new link cache, initializes it properly and updates it
+ * to include all links currently configured in the kernel.
+ *
+ * @note Free the memory after usage.
+ * @return Newly allocated cache or NULL if an error occured.
+ */
+struct nl_cache *rtnl_link_alloc_cache(struct nl_handle *handle)
+{
+ struct nl_cache * cache;
+
+ cache = nl_cache_alloc(&rtnl_link_ops);
+ if (cache == NULL)
+ return NULL;
+
+ if (handle && nl_cache_refill(handle, cache) < 0) {
+ nl_cache_free(cache);
+ return NULL;
+ }
+
+ return cache;
+}
+
+/**
+ * Look up link by interface index in the provided cache
+ * @arg cache link cache
+ * @arg ifindex link interface index
+ *
+ * The caller owns a reference on the returned object and
+ * must give the object back via rtnl_link_put().
+ *
+ * @return pointer to link inside the cache or NULL if no match was found.
+ */
+struct rtnl_link *rtnl_link_get(struct nl_cache *cache, int ifindex)
+{
+ struct rtnl_link *link;
+
+ if (cache->c_ops != &rtnl_link_ops)
+ return NULL;
+
+ nl_list_for_each_entry(link, &cache->c_items, ce_list) {
+ if (link->l_index == ifindex) {
+ nl_object_get((struct nl_object *) link);
+ return link;
+ }
+ }
+
+ return NULL;
+}
+
+/**
+ * Look up link by link name in the provided cache
+ * @arg cache link cache
+ * @arg name link name
+ *
+ * The caller owns a reference on the returned object and
+ * must give the object back via rtnl_link_put().
+ *
+ * @return pointer to link inside the cache or NULL if no match was found.
+ */
+struct rtnl_link *rtnl_link_get_by_name(struct nl_cache *cache,
+ const char *name)
+{
+ struct rtnl_link *link;
+
+ if (cache->c_ops != &rtnl_link_ops)
+ return NULL;
+
+ nl_list_for_each_entry(link, &cache->c_items, ce_list) {
+ if (!strcmp(name, link->l_name)) {
+ nl_object_get((struct nl_object *) link);
+ return link;
+ }
+ }
+
+ return NULL;
+}
+
+/** @} */
+
+/**
+ * @name Link Modifications
+ * @{
+ */
+
+/**
+ * Builds a netlink change request message to change link attributes
+ * @arg old link to be changed
+ * @arg tmpl template with requested changes
+ * @arg flags additional netlink message flags
+ *
+ * Builds a new netlink message requesting a change of link attributes.
+ * The netlink message header isn't fully equipped with all relevant
+ * fields and must be sent out via nl_send_auto_complete() or
+ * supplemented as needed.
+ * \a old must point to a link currently configured in the kernel
+ * and \a tmpl must contain the attributes to be changed set via
+ * \c rtnl_link_set_* functions.
+ *
+ * @return New netlink message
+ * @note Not all attributes can be changed, see
+ * \ref link_changeable "Changeable Attributes" for more details.
+ */
+struct nl_msg * rtnl_link_build_change_request(struct rtnl_link *old,
+ struct rtnl_link *tmpl,
+ int flags)
+{
+ struct nl_msg *msg;
+ struct ifinfomsg ifi = {
+ .ifi_family = old->l_family,
+ .ifi_index = old->l_index,
+ };
+
+ if (tmpl->ce_mask & LINK_ATTR_FLAGS) {
+ ifi.ifi_flags = old->l_flags & ~tmpl->l_flag_mask;
+ ifi.ifi_flags |= tmpl->l_flags;
+ }
+
+ msg = nlmsg_alloc_simple(RTM_SETLINK, flags);
+ if (!msg)
+ goto nla_put_failure;
+
+ if (nlmsg_append(msg, &ifi, sizeof(ifi), NLMSG_ALIGNTO) < 0)
+ goto nla_put_failure;
+
+ if (tmpl->ce_mask & LINK_ATTR_ADDR)
+ NLA_PUT_ADDR(msg, IFLA_ADDRESS, tmpl->l_addr);
+
+ if (tmpl->ce_mask & LINK_ATTR_BRD)
+ NLA_PUT_ADDR(msg, IFLA_BROADCAST, tmpl->l_bcast);
+
+ if (tmpl->ce_mask & LINK_ATTR_MTU)
+ NLA_PUT_U32(msg, IFLA_MTU, tmpl->l_mtu);
+
+ if (tmpl->ce_mask & LINK_ATTR_TXQLEN)
+ NLA_PUT_U32(msg, IFLA_TXQLEN, tmpl->l_txqlen);
+
+ if (tmpl->ce_mask & LINK_ATTR_WEIGHT)
+ NLA_PUT_U32(msg, IFLA_WEIGHT, tmpl->l_weight);
+
+ if (tmpl->ce_mask & LINK_ATTR_IFNAME)
+ NLA_PUT_STRING(msg, IFLA_IFNAME, tmpl->l_name);
+
+ return msg;
+
+nla_put_failure:
+ nlmsg_free(msg);
+ return NULL;
+}
+
+/**
+ * Change link attributes
+ * @arg handle netlink handle
+ * @arg old link to be changed
+ * @arg tmpl template with requested changes
+ * @arg flags additional netlink message flags
+ *
+ * Builds a new netlink message by calling rtnl_link_build_change_request(),
+ * sends the request to the kernel and waits for the next ACK to be
+ * received, i.e. blocks until the request has been processed.
+ *
+ * @return 0 on success or a negative error code
+ * @note Not all attributes can be changed, see
+ * \ref link_changeable "Changeable Attributes" for more details.
+ */
+int rtnl_link_change(struct nl_handle *handle, struct rtnl_link *old,
+ struct rtnl_link *tmpl, int flags)
+{
+ int err;
+ struct nl_msg *msg;
+
+ msg = rtnl_link_build_change_request(old, tmpl, flags);
+ if (!msg)
+ return nl_errno(ENOMEM);
+
+ err = nl_send_auto_complete(handle, msg);
+ if (err < 0)
+ return err;
+
+ nlmsg_free(msg);
+ return nl_wait_for_ack(handle);
+}
+
+/** @} */
+
+/**
+ * @name Name <-> Index Translations
+ * @{
+ */
+
+/**
+ * Translate an interface index to the corresponding link name
+ * @arg cache link cache
+ * @arg ifindex link interface index
+ * @arg dst destination buffer
+ * @arg len length of destination buffer
+ *
+ * Translates the specified interface index to the corresponding
+ * link name and stores the name in the destination buffer.
+ *
+ * @return link name or NULL if no match was found.
+ */
+char * rtnl_link_i2name(struct nl_cache *cache, int ifindex, char *dst,
+ size_t len)
+{
+ struct rtnl_link *link = rtnl_link_get(cache, ifindex);
+
+ if (link) {
+ strncpy(dst, link->l_name, len - 1);
+ rtnl_link_put(link);
+ return dst;
+ }
+
+ return NULL;
+}
+
+/**
+ * Translate a link name to the corresponding interface index
+ * @arg cache link cache
+ * @arg name link name
+ *
+ * @return interface index or RTNL_LINK_NOT_FOUND if no match was found.
+ */
+int rtnl_link_name2i(struct nl_cache *cache, const char *name)
+{
+ int ifindex = RTNL_LINK_NOT_FOUND;
+ struct rtnl_link *link;
+
+ link = rtnl_link_get_by_name(cache, name);
+ if (link) {
+ ifindex = link->l_index;
+ rtnl_link_put(link);
+ }
+
+ return ifindex;
+}
+
+/** @} */
+
+/**
+ * @name Link Flags Translations
+ * @{
+ */
+
+static struct trans_tbl link_flags[] = {
+ __ADD(IFF_LOOPBACK, loopback)
+ __ADD(IFF_BROADCAST, broadcast)
+ __ADD(IFF_POINTOPOINT, pointopoint)
+ __ADD(IFF_MULTICAST, multicast)
+ __ADD(IFF_NOARP, noarp)
+ __ADD(IFF_ALLMULTI, allmulti)
+ __ADD(IFF_PROMISC, promisc)
+ __ADD(IFF_MASTER, master)
+ __ADD(IFF_SLAVE, slave)
+ __ADD(IFF_DEBUG, debug)
+ __ADD(IFF_DYNAMIC, dynamic)
+ __ADD(IFF_AUTOMEDIA, automedia)
+ __ADD(IFF_PORTSEL, portsel)
+ __ADD(IFF_NOTRAILERS, notrailers)
+ __ADD(IFF_UP, up)
+ __ADD(IFF_RUNNING, running)
+ __ADD(IFF_LOWER_UP, lowerup)
+ __ADD(IFF_DORMANT, dormant)
+};
+
+char * rtnl_link_flags2str(int flags, char *buf, size_t len)
+{
+ return __flags2str(flags, buf, len, link_flags,
+ ARRAY_SIZE(link_flags));
+}
+
+int rtnl_link_str2flags(const char *name)
+{
+ return __str2flags(name, link_flags, ARRAY_SIZE(link_flags));
+}
+
+/** @} */
+
+/**
+ * @name Link Statistics Translations
+ * @{
+ */
+
+static struct trans_tbl link_stats[] = {
+ __ADD(RTNL_LINK_RX_PACKETS, rx_packets)
+ __ADD(RTNL_LINK_TX_PACKETS, tx_packets)
+ __ADD(RTNL_LINK_RX_BYTES, rx_bytes)
+ __ADD(RTNL_LINK_TX_BYTES, tx_bytes)
+ __ADD(RTNL_LINK_RX_ERRORS, rx_errors)
+ __ADD(RTNL_LINK_TX_ERRORS, tx_errors)
+ __ADD(RTNL_LINK_RX_DROPPED, rx_dropped)
+ __ADD(RTNL_LINK_TX_DROPPED, tx_dropped)
+ __ADD(RTNL_LINK_RX_COMPRESSED, rx_compressed)
+ __ADD(RTNL_LINK_TX_COMPRESSED, tx_compressed)
+ __ADD(RTNL_LINK_RX_FIFO_ERR, rx_fifo_err)
+ __ADD(RTNL_LINK_TX_FIFO_ERR, tx_fifo_err)
+ __ADD(RTNL_LINK_RX_LEN_ERR, rx_len_err)
+ __ADD(RTNL_LINK_RX_OVER_ERR, rx_over_err)
+ __ADD(RTNL_LINK_RX_CRC_ERR, rx_crc_err)
+ __ADD(RTNL_LINK_RX_FRAME_ERR, rx_frame_err)
+ __ADD(RTNL_LINK_RX_MISSED_ERR, rx_missed_err)
+ __ADD(RTNL_LINK_TX_ABORT_ERR, tx_abort_err)
+ __ADD(RTNL_LINK_TX_CARRIER_ERR, tx_carrier_err)
+ __ADD(RTNL_LINK_TX_HBEAT_ERR, tx_hbeat_err)
+ __ADD(RTNL_LINK_TX_WIN_ERR, tx_win_err)
+ __ADD(RTNL_LINK_TX_COLLISIONS, tx_collision)
+ __ADD(RTNL_LINK_MULTICAST, multicast)
+};
+
+char *rtnl_link_stat2str(int st, char *buf, size_t len)
+{
+ return __type2str(st, buf, len, link_stats, ARRAY_SIZE(link_stats));
+}
+
+int rtnl_link_str2stat(const char *name)
+{
+ return __str2type(name, link_stats, ARRAY_SIZE(link_stats));
+}
+
+/** @} */
+
+/**
+ * @name Attributes
+ * @{
+ */
+
+void rtnl_link_set_qdisc(struct rtnl_link *link, const char *qdisc)
+{
+ strncpy(link->l_qdisc, qdisc, sizeof(link->l_qdisc) - 1);
+ link->ce_mask |= LINK_ATTR_QDISC;
+}
+
+char *rtnl_link_get_qdisc(struct rtnl_link *link)
+{
+ if (link->ce_mask & LINK_ATTR_QDISC)
+ return link->l_qdisc;
+ else
+ return NULL;
+}
+
+void rtnl_link_set_name(struct rtnl_link *link, const char *name)
+{
+ strncpy(link->l_name, name, sizeof(link->l_name) - 1);
+ link->ce_mask |= LINK_ATTR_IFNAME;
+}
+
+char *rtnl_link_get_name(struct rtnl_link *link)
+{
+ if (link->ce_mask & LINK_ATTR_IFNAME)
+ return link->l_name;
+ else
+ return NULL;
+}
+
+static inline void __assign_addr(struct rtnl_link *link, struct nl_addr **pos,
+ struct nl_addr *new, int flag)
+{
+ if (*pos)
+ nl_addr_put(*pos);
+
+ nl_addr_get(new);
+ *pos = new;
+
+ link->ce_mask |= flag;
+}
+
+void rtnl_link_set_addr(struct rtnl_link *link, struct nl_addr *addr)
+{
+ __assign_addr(link, &link->l_addr, addr, LINK_ATTR_ADDR);
+}
+
+struct nl_addr *rtnl_link_get_addr(struct rtnl_link *link)
+{
+ if (link->ce_mask & LINK_ATTR_ADDR)
+ return link->l_addr;
+ else
+ return NULL;
+}
+
+void rtnl_link_set_broadcast(struct rtnl_link *link, struct nl_addr *brd)
+{
+ __assign_addr(link, &link->l_bcast, brd, LINK_ATTR_BRD);
+}
+
+struct nl_addr *rtnl_link_get_broadcast(struct rtnl_link *link)
+{
+ if (link->ce_mask & LINK_ATTR_BRD)
+ return link->l_bcast;
+ else
+ return NULL;
+}
+
+void rtnl_link_set_flags(struct rtnl_link *link, unsigned int flags)
+{
+ link->l_flag_mask |= flags;
+ link->l_flags |= flags;
+ link->ce_mask |= LINK_ATTR_FLAGS;
+}
+
+void rtnl_link_unset_flags(struct rtnl_link *link, unsigned int flags)
+{
+ link->l_flag_mask |= flags;
+ link->l_flags &= ~flags;
+ link->ce_mask |= LINK_ATTR_FLAGS;
+}
+
+unsigned int rtnl_link_get_flags(struct rtnl_link *link)
+{
+ return link->l_flags;
+}
+
+void rtnl_link_set_family(struct rtnl_link *link, int family)
+{
+ link->l_family = family;
+ link->ce_mask |= LINK_ATTR_FAMILY;
+}
+
+int rtnl_link_get_family(struct rtnl_link *link)
+{
+ if (link->l_family & LINK_ATTR_FAMILY)
+ return link->l_family;
+ else
+ return AF_UNSPEC;
+}
+
+void rtnl_link_set_arptype(struct rtnl_link *link, unsigned int arptype)
+{
+ link->l_arptype = arptype;
+}
+
+unsigned int rtnl_link_get_arptype(struct rtnl_link *link)
+{
+ return link->l_arptype;
+}
+
+void rtnl_link_set_ifindex(struct rtnl_link *link, int ifindex)
+{
+ link->l_index = ifindex;
+ link->ce_mask |= LINK_ATTR_IFINDEX;
+}
+
+int rtnl_link_get_ifindex(struct rtnl_link *link)
+{
+ if (link->ce_mask & LINK_ATTR_IFINDEX)
+ return link->l_index;
+ else
+ return RTNL_LINK_NOT_FOUND;
+}
+
+void rtnl_link_set_mtu(struct rtnl_link *link, unsigned int mtu)
+{
+ link->l_mtu = mtu;
+ link->ce_mask |= LINK_ATTR_MTU;
+}
+
+unsigned int rtnl_link_get_mtu(struct rtnl_link *link)
+{
+ if (link->ce_mask & LINK_ATTR_MTU)
+ return link->l_mtu;
+ else
+ return 0;
+}
+
+void rtnl_link_set_txqlen(struct rtnl_link *link, unsigned int txqlen)
+{
+ link->l_txqlen = txqlen;
+ link->ce_mask |= LINK_ATTR_TXQLEN;
+}
+
+unsigned int rtnl_link_get_txqlen(struct rtnl_link *link)
+{
+ if (link->ce_mask & LINK_ATTR_TXQLEN)
+ return link->l_txqlen;
+ else
+ return UINT_MAX;
+}
+
+void rtnl_link_set_weight(struct rtnl_link *link, unsigned int weight)
+{
+ link->l_weight = weight;
+ link->ce_mask |= LINK_ATTR_WEIGHT;
+}
+
+unsigned int rtnl_link_get_weight(struct rtnl_link *link)
+{
+ if (link->ce_mask & LINK_ATTR_WEIGHT)
+ return link->l_weight;
+ else
+ return UINT_MAX;
+}
+
+void rtnl_link_set_link(struct rtnl_link *link, int ifindex)
+{
+ link->l_link = ifindex;
+ link->ce_mask |= LINK_ATTR_LINK;
+}
+
+int rtnl_link_get_link(struct rtnl_link *link)
+{
+ if (link->ce_mask & LINK_ATTR_LINK)
+ return link->l_link;
+ else
+ return RTNL_LINK_NOT_FOUND;
+}
+
+void rtnl_link_set_master(struct rtnl_link *link, int ifindex)
+{
+ link->l_master = ifindex;
+ link->ce_mask |= LINK_ATTR_MASTER;
+}
+
+int rtnl_link_get_master(struct rtnl_link *link)
+{
+ if (link->ce_mask & LINK_ATTR_MASTER)
+ return link->l_master;
+ else
+ return RTNL_LINK_NOT_FOUND;
+}
+
+uint64_t rtnl_link_get_stat(struct rtnl_link *link, int id)
+{
+ if (id < 0 || id > RTNL_LINK_STATS_MAX)
+ return 0;
+
+ return link->l_stats[id];
+}
+
+/** @} */
+
+static struct nl_object_ops link_obj_ops = {
+ .oo_name = "route/link",
+ .oo_size = sizeof(struct rtnl_link),
+ .oo_free_data = link_free_data,
+ .oo_clone = link_clone,
+ .oo_dump[NL_DUMP_BRIEF] = link_dump_brief,
+ .oo_dump[NL_DUMP_FULL] = link_dump_full,
+ .oo_dump[NL_DUMP_STATS] = link_dump_stats,
+ .oo_dump[NL_DUMP_XML] = link_dump_xml,
+ .oo_dump[NL_DUMP_ENV] = link_dump_env,
+ .oo_compare = link_compare,
+ .oo_attrs2str = link_attrs2str,
+ .oo_id_attrs = LINK_ATTR_IFINDEX,
+};
+
+static struct nl_af_group link_groups[] = {
+ { AF_UNSPEC, RTNLGRP_LINK },
+ { END_OF_GROUP_LIST },
+};
+
+static struct nl_cache_ops rtnl_link_ops = {
+ .co_name = "route/link",
+ .co_hdrsize = sizeof(struct ifinfomsg),
+ .co_msgtypes = {
+ { RTM_NEWLINK, NL_ACT_NEW, "new" },
+ { RTM_DELLINK, NL_ACT_DEL, "del" },
+ { RTM_GETLINK, NL_ACT_GET, "get" },
+ END_OF_MSGTYPES_LIST,
+ },
+ .co_protocol = NETLINK_ROUTE,
+ .co_groups = link_groups,
+ .co_request_update = link_request_update,
+ .co_msg_parser = link_msg_parser,
+ .co_obj_ops = &link_obj_ops,
+};
+
+static void __init link_init(void)
+{
+ nl_cache_mngt_register(&rtnl_link_ops);
+}
+
+static void __exit link_exit(void)
+{
+ nl_cache_mngt_unregister(&rtnl_link_ops);
+}
+
+/** @} */
diff --git a/lib/route/neigh.c b/lib/route/neigh.c
new file mode 100644
index 0000000..aac4718
--- /dev/null
+++ b/lib/route/neigh.c
@@ -0,0 +1,1023 @@
+/*
+ * lib/route/neigh.c Neighbours
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup rtnl
+ * @defgroup neigh Neighbours
+ * @brief
+ *
+ * The neighbour table establishes bindings between protocol addresses and
+ * link layer addresses for hosts sharing the same physical link. This
+ * module allows you to access and manipulate the content of these tables.
+ *
+ * @par Neighbour States
+ * @code
+ * NUD_INCOMPLETE
+ * NUD_REACHABLE
+ * NUD_STALE
+ * NUD_DELAY
+ * NUD_PROBE
+ * NUD_FAILED
+ * NUD_NOARP
+ * NUD_PERMANENT
+ * @endcode
+ *
+ * @par Neighbour Flags
+ * @code
+ * NTF_PROXY
+ * NTF_ROUTER
+ * @endcode
+ *
+ * @par Neighbour Identification
+ * A neighbour is uniquely identified by the attributes listed below, whenever
+ * you refer to an existing neighbour all of the attributes must be set.
+ * Neighbours from caches automatically have all required attributes set.
+ * - interface index (rtnl_neigh_set_ifindex())
+ * - destination address (rtnl_neigh_set_dst())
+ *
+ * @par Changeable Attributes
+ * \anchor neigh_changeable
+ * - state (rtnl_neigh_set_state())
+ * - link layer address (rtnl_neigh_set_lladdr())
+ *
+ * @par Required Caches for Dumping
+ * In order to dump neighbour attributes you must provide the following
+ * caches via nl_cache_provide()
+ * - link cache holding all links
+ *
+ * @par TODO
+ * - Document proxy settings
+ * - Document states and their influence
+ *
+ * @par 1) Retrieving information about configured neighbours
+ * @code
+ * // The first step is to retrieve a list of all available neighbour within
+ * // the kernel and put them into a cache.
+ * struct nl_cache *cache = rtnl_neigh_alloc_cache(handle);
+ *
+ * // Neighbours can then be looked up by the interface and destination
+ * // address:
+ * struct rtnl_neigh *neigh = rtnl_neigh_get(cache, ifindex, dst_addr);
+ *
+ * // After successful usage, the object must be given back to the cache
+ * rtnl_neigh_put(neigh);
+ * @endcode
+ *
+ * @par 2) Adding new neighbours
+ * @code
+ * // Allocate an empty neighbour handle to be filled out with the attributes
+ * // of the new neighbour.
+ * struct rtnl_neigh *neigh = rtnl_neigh_alloc();
+ *
+ * // Fill out the attributes of the new neighbour
+ * rtnl_neigh_set_ifindex(neigh, ifindex);
+ * rtnl_neigh_set_dst(neigh, dst_addr);
+ * rtnl_neigh_set_state(neigh, rtnl_neigh_str2state("permanent"));
+ *
+ * // Build the netlink message and send it to the kernel, the operation will
+ * // block until the operation has been completed. Alternatively the required
+ * // netlink message can be built using rtnl_neigh_build_add_request()
+ * // to be sent out using nl_send_auto_complete().
+ * rtnl_neigh_add(nl_handle, neigh, NLM_F_REPLACE);
+ *
+ * // Free the memory
+ * rtnl_neigh_put(neigh);
+ * @endcode
+ *
+ * @par 3) Deleting an existing neighbour
+ * @code
+ * // Allocate an empty neighbour object to be filled out with the attributes
+ * // matching the neighbour to be deleted. Alternatively a fully equipped
+ * // neighbour object out of a cache can be used instead.
+ * struct rtnl_neigh *neigh = rtnl_neigh_alloc();
+ *
+ * // Neighbours are uniquely identified by their interface index and
+ * // destination address, you may fill out other attributes but they
+ * // will have no influence.
+ * rtnl_neigh_set_ifindex(neigh, ifindex);
+ * rtnl_neigh_set_dst(neigh, dst_addr);
+ *
+ * // Build the netlink message and send it to the kernel, the operation will
+ * // block until the operation has been completed. Alternatively the required
+ * // netlink message can be built using rtnl_neigh_build_delete_request()
+ * // to be sent out using nl_send_auto_complete().
+ * rtnl_neigh_delete(handle, neigh, 0);
+ *
+ * // Free the memory
+ * rtnl_neigh_put(neigh);
+ * @endcode
+ *
+ * @par 4) Changing neighbour attributes
+ * @code
+ * // Allocate an empty neighbour object to be filled out with the attributes
+ * // matching the neighbour to be changed and the new parameters. Alternatively
+ * // a fully equipped modified neighbour object out of a cache can be used.
+ * struct rtnl_neigh *neigh = rtnl_neigh_alloc();
+ *
+ * // Identify the neighbour to be changed by its interface index and
+ * // destination address
+ * rtnl_neigh_set_ifindex(neigh, ifindex);
+ * rtnl_neigh_set_dst(neigh, dst_addr);
+ *
+ * // The link layer address may be modified, if so it is wise to change
+ * // its state to "permanent" in order to avoid having it overwritten.
+ * rtnl_neigh_set_lladdr(neigh, lladdr);
+ *
+ * // Secondly the state can be modified allowing normal neighbours to be
+ * // converted into permanent entries or to manually confirm a neighbour.
+ * rtnl_neigh_set_state(neigh, state);
+ *
+ * // Build the netlink message and send it to the kernel, the operation will
+ * // block until the operation has been completed. Alternatively the required
+ * // netlink message can be built using rtnl_neigh_build_change_request()
+ * // to be sent out using nl_send_auto_complete().
+ * rtnl_neigh_change(handle, neigh, 0);
+ *
+ * // Free the memory
+ * rtnl_neigh_put(neigh);
+ * @endcode
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/route/rtnl.h>
+#include <netlink/route/neighbour.h>
+#include <netlink/route/link.h>
+
+/** @cond SKIP */
+#define NEIGH_ATTR_FLAGS 0x01
+#define NEIGH_ATTR_STATE 0x02
+#define NEIGH_ATTR_LLADDR 0x04
+#define NEIGH_ATTR_DST 0x08
+#define NEIGH_ATTR_CACHEINFO 0x10
+#define NEIGH_ATTR_IFINDEX 0x20
+#define NEIGH_ATTR_FAMILY 0x40
+#define NEIGH_ATTR_TYPE 0x80
+#define NEIGH_ATTR_PROBES 0x100
+
+static struct nl_cache_ops rtnl_neigh_ops;
+static struct nl_object_ops neigh_obj_ops;
+/** @endcond */
+
+static void neigh_free_data(struct nl_object *c)
+{
+ struct rtnl_neigh *neigh = nl_object_priv(c);
+
+ if (!neigh)
+ return;
+
+ nl_addr_put(neigh->n_lladdr);
+ nl_addr_put(neigh->n_dst);
+}
+
+static int neigh_clone(struct nl_object *_dst, struct nl_object *_src)
+{
+ struct rtnl_neigh *dst = nl_object_priv(_dst);
+ struct rtnl_neigh *src = nl_object_priv(_src);
+
+ if (src->n_lladdr)
+ if (!(dst->n_lladdr = nl_addr_clone(src->n_lladdr)))
+ goto errout;
+
+ if (src->n_dst)
+ if (!(dst->n_dst = nl_addr_clone(src->n_dst)))
+ goto errout;
+
+ return 0;
+errout:
+ return nl_get_errno();
+}
+
+static int neigh_compare(struct nl_object *_a, struct nl_object *_b,
+ uint32_t attrs, int flags)
+{
+ struct rtnl_neigh *a = (struct rtnl_neigh *) _a;
+ struct rtnl_neigh *b = (struct rtnl_neigh *) _b;
+ int diff = 0;
+
+#define NEIGH_DIFF(ATTR, EXPR) ATTR_DIFF(attrs, NEIGH_ATTR_##ATTR, a, b, EXPR)
+
+ diff |= NEIGH_DIFF(IFINDEX, a->n_ifindex != b->n_ifindex);
+ diff |= NEIGH_DIFF(FAMILY, a->n_family != b->n_family);
+ diff |= NEIGH_DIFF(TYPE, a->n_type != b->n_type);
+ diff |= NEIGH_DIFF(LLADDR, nl_addr_cmp(a->n_lladdr, b->n_lladdr));
+ diff |= NEIGH_DIFF(DST, nl_addr_cmp(a->n_dst, b->n_dst));
+
+ if (flags & LOOSE_FLAG_COMPARISON) {
+ diff |= NEIGH_DIFF(STATE,
+ (a->n_state ^ b->n_state) & b->n_state_mask);
+ diff |= NEIGH_DIFF(FLAGS,
+ (a->n_flags ^ b->n_flags) & b->n_flag_mask);
+ } else {
+ diff |= NEIGH_DIFF(STATE, a->n_state != b->n_state);
+ diff |= NEIGH_DIFF(FLAGS, a->n_flags != b->n_flags);
+ }
+
+#undef NEIGH_DIFF
+
+ return diff;
+}
+
+static struct trans_tbl neigh_attrs[] = {
+ __ADD(NEIGH_ATTR_FLAGS, flags)
+ __ADD(NEIGH_ATTR_STATE, state)
+ __ADD(NEIGH_ATTR_LLADDR, lladdr)
+ __ADD(NEIGH_ATTR_DST, dst)
+ __ADD(NEIGH_ATTR_CACHEINFO, cacheinfo)
+ __ADD(NEIGH_ATTR_IFINDEX, ifindex)
+ __ADD(NEIGH_ATTR_FAMILY, family)
+ __ADD(NEIGH_ATTR_TYPE, type)
+ __ADD(NEIGH_ATTR_PROBES, probes)
+};
+
+static char *neigh_attrs2str(int attrs, char *buf, size_t len)
+{
+ return __flags2str(attrs, buf, len, neigh_attrs,
+ ARRAY_SIZE(neigh_attrs));
+}
+
+static struct nla_policy neigh_policy[NDA_MAX+1] = {
+ [NDA_CACHEINFO] = { .minlen = sizeof(struct nda_cacheinfo) },
+ [NDA_PROBES] = { .type = NLA_U32 },
+};
+
+static int neigh_msg_parser(struct nl_cache_ops *ops, struct sockaddr_nl *who,
+ struct nlmsghdr *n, void *arg)
+{
+ struct rtnl_neigh *neigh;
+ struct nlattr *tb[NDA_MAX + 1];
+ struct nl_parser_param *pp = arg;
+ struct ndmsg *nm;
+ int err;
+
+ neigh = rtnl_neigh_alloc();
+ if (!neigh) {
+ err = nl_errno(ENOMEM);
+ goto errout;
+ }
+
+ neigh->ce_msgtype = n->nlmsg_type;
+ nm = nlmsg_data(n);
+
+ err = nlmsg_parse(n, sizeof(*nm), tb, NDA_MAX, neigh_policy);
+ if (err < 0)
+ goto errout;
+
+ neigh->n_family = nm->ndm_family;
+ neigh->n_ifindex = nm->ndm_ifindex;
+ neigh->n_state = nm->ndm_state;
+ neigh->n_flags = nm->ndm_flags;
+ neigh->n_type = nm->ndm_type;
+
+ neigh->ce_mask |= (NEIGH_ATTR_FAMILY | NEIGH_ATTR_IFINDEX |
+ NEIGH_ATTR_STATE | NEIGH_ATTR_FLAGS |
+ NEIGH_ATTR_TYPE);
+
+ if (tb[NDA_LLADDR]) {
+ neigh->n_lladdr = nla_get_addr(tb[NDA_LLADDR], AF_UNSPEC);
+ if (!neigh->n_lladdr)
+ goto errout;
+ nl_addr_set_family(neigh->n_lladdr,
+ nl_addr_guess_family(neigh->n_lladdr));
+ neigh->ce_mask |= NEIGH_ATTR_LLADDR;
+ }
+
+ if (tb[NDA_DST]) {
+ neigh->n_dst = nla_get_addr(tb[NDA_DST], neigh->n_family);
+ if (!neigh->n_dst)
+ goto errout;
+ neigh->ce_mask |= NEIGH_ATTR_DST;
+ }
+
+ if (tb[NDA_CACHEINFO]) {
+ struct nda_cacheinfo *ci = nla_data(tb[NDA_CACHEINFO]);
+
+ neigh->n_cacheinfo.nci_confirmed = ci->ndm_confirmed;
+ neigh->n_cacheinfo.nci_used = ci->ndm_used;
+ neigh->n_cacheinfo.nci_updated = ci->ndm_updated;
+ neigh->n_cacheinfo.nci_refcnt = ci->ndm_refcnt;
+
+ neigh->ce_mask |= NEIGH_ATTR_CACHEINFO;
+ }
+
+ if (tb[NDA_PROBES]) {
+ neigh->n_probes = nla_get_u32(tb[NDA_PROBES]);
+ neigh->ce_mask |= NEIGH_ATTR_PROBES;
+ }
+
+ err = pp->pp_cb((struct nl_object *) neigh, pp);
+ if (err < 0)
+ goto errout;
+
+ return P_ACCEPT;
+
+errout:
+ rtnl_neigh_put(neigh);
+ return err;
+}
+
+static int neigh_request_update(struct nl_cache *c, struct nl_handle *h)
+{
+ return nl_rtgen_request(h, RTM_GETNEIGH, AF_UNSPEC, NLM_F_DUMP);
+}
+
+
+static int neigh_dump_brief(struct nl_object *a, struct nl_dump_params *p)
+{
+ char dst[INET6_ADDRSTRLEN+5], lladdr[INET6_ADDRSTRLEN+5];
+ struct rtnl_neigh *n = (struct rtnl_neigh *) a;
+ struct nl_cache *link_cache;
+ char state[128], flags[64];
+
+ link_cache = nl_cache_mngt_require("route/link");
+
+ dp_dump(p, "%s ", nl_addr2str(n->n_dst, dst, sizeof(dst)));
+
+ if (link_cache)
+ dp_dump(p, "dev %s ",
+ rtnl_link_i2name(link_cache, n->n_ifindex,
+ state, sizeof(state)));
+ else
+ dp_dump(p, "dev %d ", n->n_ifindex);
+
+ if (n->ce_mask & NEIGH_ATTR_LLADDR)
+ dp_dump(p, "lladdr %s ",
+ nl_addr2str(n->n_lladdr, lladdr, sizeof(lladdr)));
+
+ rtnl_neigh_state2str(n->n_state, state, sizeof(state));
+ rtnl_neigh_flags2str(n->n_flags, flags, sizeof(flags));
+
+ if (state[0])
+ dp_dump(p, "<%s", state);
+ if (flags[0])
+ dp_dump(p, "%s%s", state[0] ? "," : "<", flags);
+ if (state[0] || flags[0])
+ dp_dump(p, ">");
+ dp_dump(p, "\n");
+
+ return 1;
+}
+
+static int neigh_dump_full(struct nl_object *a, struct nl_dump_params *p)
+{
+ char rtn_type[32];
+ struct rtnl_neigh *n = (struct rtnl_neigh *) a;
+ int hz = nl_get_hz();
+
+ int line = neigh_dump_brief(a, p);
+
+ dp_dump_line(p, line++, " refcnt %u type %s confirmed %u used "
+ "%u updated %u\n",
+ n->n_cacheinfo.nci_refcnt,
+ nl_rtntype2str(n->n_type, rtn_type, sizeof(rtn_type)),
+ n->n_cacheinfo.nci_confirmed/hz,
+ n->n_cacheinfo.nci_used/hz, n->n_cacheinfo.nci_updated/hz);
+
+ return line;
+}
+
+static int neigh_dump_stats(struct nl_object *a, struct nl_dump_params *p)
+{
+ return neigh_dump_full(a, p);
+}
+
+static int neigh_dump_xml(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_neigh *neigh = (struct rtnl_neigh *) obj;
+ char buf[128];
+ int line = 0;
+
+ dp_dump_line(p, line++, "<neighbour>\n");
+ dp_dump_line(p, line++, " <family>%s</family>\n",
+ nl_af2str(neigh->n_family, buf, sizeof(buf)));
+
+ if (neigh->ce_mask & NEIGH_ATTR_LLADDR)
+ dp_dump_line(p, line++, " <lladdr>%s</lladdr>\n",
+ nl_addr2str(neigh->n_lladdr, buf, sizeof(buf)));
+
+ if (neigh->ce_mask & NEIGH_ATTR_DST)
+ dp_dump_line(p, line++, " <dst>%s</dst>\n",
+ nl_addr2str(neigh->n_dst, buf, sizeof(buf)));
+
+ if (neigh->ce_mask & NEIGH_ATTR_IFINDEX) {
+ struct nl_cache *link_cache;
+
+ link_cache = nl_cache_mngt_require("route/link");
+
+ if (link_cache)
+ dp_dump_line(p, line++, " <device>%s</device>\n",
+ rtnl_link_i2name(link_cache,
+ neigh->n_ifindex,
+ buf, sizeof(buf)));
+ else
+ dp_dump_line(p, line++, " <device>%u</device>\n",
+ neigh->n_ifindex);
+ }
+
+ if (neigh->ce_mask & NEIGH_ATTR_PROBES)
+ dp_dump_line(p, line++, " <probes>%u</probes>\n",
+ neigh->n_probes);
+
+ if (neigh->ce_mask & NEIGH_ATTR_TYPE)
+ dp_dump_line(p, line++, " <type>%s</type>\n",
+ nl_rtntype2str(neigh->n_type, buf, sizeof(buf)));
+
+ rtnl_neigh_flags2str(neigh->n_flags, buf, sizeof(buf));
+ if (buf[0])
+ dp_dump_line(p, line++, " <flags>%s</flags>\n", buf);
+
+ rtnl_neigh_state2str(neigh->n_state, buf, sizeof(buf));
+ if (buf[0])
+ dp_dump_line(p, line++, " <state>%s</state>\n", buf);
+
+ dp_dump_line(p, line++, "</neighbour>\n");
+
+#if 0
+ struct rtnl_ncacheinfo n_cacheinfo;
+#endif
+
+ return line;
+}
+
+static int neigh_dump_env(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_neigh *neigh = (struct rtnl_neigh *) obj;
+ char buf[128];
+ int line = 0;
+
+ dp_dump_line(p, line++, "NEIGH_FAMILY=%s\n",
+ nl_af2str(neigh->n_family, buf, sizeof(buf)));
+
+ if (neigh->ce_mask & NEIGH_ATTR_LLADDR)
+ dp_dump_line(p, line++, "NEIGHT_LLADDR=%s\n",
+ nl_addr2str(neigh->n_lladdr, buf, sizeof(buf)));
+
+ if (neigh->ce_mask & NEIGH_ATTR_DST)
+ dp_dump_line(p, line++, "NEIGH_DST=%s\n",
+ nl_addr2str(neigh->n_dst, buf, sizeof(buf)));
+
+ if (neigh->ce_mask & NEIGH_ATTR_IFINDEX) {
+ struct nl_cache *link_cache;
+
+ dp_dump_line(p, line++, "NEIGH_IFINDEX=%u\n",
+ neigh->n_ifindex);
+
+ link_cache = nl_cache_mngt_require("route/link");
+ if (link_cache)
+ dp_dump_line(p, line++, "NEIGH_IFNAME=%s\n",
+ rtnl_link_i2name(link_cache,
+ neigh->n_ifindex,
+ buf, sizeof(buf)));
+ }
+
+ if (neigh->ce_mask & NEIGH_ATTR_PROBES)
+ dp_dump_line(p, line++, "NEIGH_PROBES=%u\n",
+ neigh->n_probes);
+
+ if (neigh->ce_mask & NEIGH_ATTR_TYPE)
+ dp_dump_line(p, line++, "NEIGH_TYPE=%s\n",
+ nl_rtntype2str(neigh->n_type, buf, sizeof(buf)));
+
+ rtnl_neigh_flags2str(neigh->n_flags, buf, sizeof(buf));
+ if (buf[0])
+ dp_dump_line(p, line++, "NEIGH_FLAGS=%s\n", buf);
+
+ rtnl_neigh_state2str(neigh->n_state, buf, sizeof(buf));
+ if (buf[0])
+ dp_dump_line(p, line++, "NEIGH_STATE=%s\n", buf);
+
+ return line;
+}
+
+/**
+ * @name Neighbour Object Allocation/Freeage
+ * @{
+ */
+
+struct rtnl_neigh *rtnl_neigh_alloc(void)
+{
+ return (struct rtnl_neigh *) nl_object_alloc(&neigh_obj_ops);
+}
+
+void rtnl_neigh_put(struct rtnl_neigh *neigh)
+{
+ nl_object_put((struct nl_object *) neigh);
+}
+
+/** @} */
+
+/**
+ * @name Neighbour Cache Managament
+ * @{
+ */
+
+/**
+ * Build a neighbour cache including all neighbours currently configured in the kernel.
+ * @arg handle netlink handle
+ *
+ * Allocates a new neighbour cache, initializes it properly and updates it
+ * to include all neighbours currently configured in the kernel.
+ *
+ * @note The caller is responsible for destroying and freeing the
+ * cache after using it.
+ * @return The new cache or NULL if an error occured.
+ */
+struct nl_cache *rtnl_neigh_alloc_cache(struct nl_handle *handle)
+{
+ struct nl_cache *cache;
+
+ cache = nl_cache_alloc(&rtnl_neigh_ops);
+ if (cache == NULL)
+ return NULL;
+
+ if (handle && nl_cache_refill(handle, cache) < 0) {
+ nl_cache_free(cache);
+ return NULL;
+ }
+
+ NL_DBG(2, "Returning new cache %p\n", cache);
+
+ return cache;
+}
+
+/**
+ * Look up a neighbour by interface index and destination address
+ * @arg cache neighbour cache
+ * @arg ifindex interface index the neighbour is on
+ * @arg dst destination address of the neighbour
+ * @return neighbour handle or NULL if no match was found.
+ */
+struct rtnl_neigh * rtnl_neigh_get(struct nl_cache *cache, int ifindex,
+ struct nl_addr *dst)
+{
+ struct rtnl_neigh *neigh;
+
+ nl_list_for_each_entry(neigh, &cache->c_items, ce_list) {
+ if (neigh->n_ifindex == ifindex &&
+ !nl_addr_cmp(neigh->n_dst, dst)) {
+ nl_object_get((struct nl_object *) neigh);
+ return neigh;
+ }
+ }
+
+ return NULL;
+}
+
+/** @} */
+
+/**
+ * @name Neighbour Addition
+ * @{
+ */
+
+static struct nl_msg * build_neigh_msg(struct rtnl_neigh *tmpl, int cmd,
+ int flags)
+{
+ struct nl_msg *msg;
+ struct ndmsg nhdr = {
+ .ndm_ifindex = tmpl->n_ifindex,
+ .ndm_family = nl_addr_get_family(tmpl->n_dst),
+ .ndm_state = NUD_PERMANENT,
+ };
+
+ if (tmpl->ce_mask & NEIGH_ATTR_STATE)
+ nhdr.ndm_state = tmpl->n_state;
+
+ msg = nlmsg_alloc_simple(cmd, flags);
+ if (!msg)
+ return NULL;
+
+ if (nlmsg_append(msg, &nhdr, sizeof(nhdr), NLMSG_ALIGNTO) < 0)
+ goto nla_put_failure;
+
+ NLA_PUT_ADDR(msg, NDA_DST, tmpl->n_dst);
+
+ if (tmpl->ce_mask & NEIGH_ATTR_LLADDR)
+ NLA_PUT_ADDR(msg, NDA_LLADDR, tmpl->n_lladdr);
+
+ return msg;
+
+nla_put_failure:
+ nlmsg_free(msg);
+ return NULL;
+}
+
+/**
+ * Build netlink request message to add a new neighbour
+ * @arg tmpl template with data of new neighbour
+ * @arg flags additional netlink message flags
+ *
+ * Builds a new netlink message requesting a addition of a new
+ * neighbour. The netlink message header isn't fully equipped with
+ * all relevant fields and must thus be sent out via nl_send_auto_complete()
+ * or supplemented as needed. \a tmpl must contain the attributes of the new
+ * neighbour set via \c rtnl_neigh_set_* functions.
+ *
+ * The following attributes must be set in the template:
+ * - Interface index (rtnl_neigh_set_ifindex())
+ * - State (rtnl_neigh_set_state())
+ * - Destination address (rtnl_neigh_set_dst())
+ * - Link layer address (rtnl_neigh_set_lladdr())
+ *
+ * @return The netlink message
+ */
+struct nl_msg * rtnl_neigh_build_add_request(struct rtnl_neigh *tmpl, int flags)
+{
+ return build_neigh_msg(tmpl, RTM_NEWNEIGH, NLM_F_CREATE | flags);
+}
+
+/**
+ * Add a new neighbour
+ * @arg handle netlink handle
+ * @arg tmpl template with requested changes
+ * @arg flags additional netlink message flags
+ *
+ * Builds a netlink message by calling rtnl_neigh_build_add_request(),
+ * sends the request to the kernel and waits for the next ACK to be
+ * received and thus blocks until the request has been fullfilled.
+ *
+ * The following attributes must be set in the template:
+ * - Interface index (rtnl_neigh_set_ifindex())
+ * - State (rtnl_neigh_set_state())
+ * - Destination address (rtnl_neigh_set_dst())
+ * - Link layer address (rtnl_neigh_set_lladdr())
+ *
+ * @return 0 on sucess or a negative error if an error occured.
+ */
+int rtnl_neigh_add(struct nl_handle *handle, struct rtnl_neigh *tmpl, int flags)
+{
+ int err;
+ struct nl_msg *msg;
+
+ msg = rtnl_neigh_build_add_request(tmpl, flags);
+ if (!msg)
+ return nl_errno(ENOMEM);
+
+ err = nl_send_auto_complete(handle, msg);
+ if (err < 0)
+ return err;
+
+ nlmsg_free(msg);
+ return nl_wait_for_ack(handle);
+}
+
+/** @} */
+
+/**
+ * @name Neighbour Deletion
+ * @{
+ */
+
+/**
+ * Build a netlink request message to delete a neighbour
+ * @arg neigh neighbour to delete
+ * @arg flags additional netlink message flags
+ *
+ * Builds a new netlink message requesting a deletion of a neighbour.
+ * The netlink message header isn't fully equipped with all relevant
+ * fields and must thus be sent out via nl_send_auto_complete()
+ * or supplemented as needed. \a neigh must point to an existing
+ * neighbour.
+ *
+ * @return The netlink message
+ */
+struct nl_msg *rtnl_neigh_build_delete_request(struct rtnl_neigh *neigh,
+ int flags)
+{
+ return build_neigh_msg(neigh, RTM_DELNEIGH, flags);
+}
+
+/**
+ * Delete a neighbour
+ * @arg handle netlink handle
+ * @arg neigh neighbour to delete
+ * @arg flags additional netlink message flags
+ *
+ * Builds a netlink message by calling rtnl_neigh_build_delete_request(),
+ * sends the request to the kernel and waits for the next ACK to be
+ * received and thus blocks until the request has been fullfilled.
+ *
+ * @return 0 on sucess or a negative error if an error occured.
+ */
+int rtnl_neigh_delete(struct nl_handle *handle, struct rtnl_neigh *neigh,
+ int flags)
+{
+ int err;
+ struct nl_msg *msg;
+
+ msg = rtnl_neigh_build_delete_request(neigh, flags);
+ if (!msg)
+ return nl_errno(ENOMEM);
+
+ err = nl_send_auto_complete(handle, msg);
+ if (err < 0)
+ return err;
+
+ nlmsg_free(msg);
+ return nl_wait_for_ack(handle);
+}
+
+/** @} */
+
+/**
+ * @name Neighbour Modification
+ * @{
+ */
+
+/**
+ * Build a netlink request message to change neighbour attributes
+ * @arg neigh the neighbour to change
+ * @arg flags additional netlink message flags
+ *
+ * Builds a new netlink message requesting a change of a neigh
+ * attributes. The netlink message header isn't fully equipped with
+ * all relevant fields and must thus be sent out via nl_send_auto_complete()
+ * or supplemented as needed.
+ *
+ * @return The netlink message
+ * @note Not all attributes can be changed, see
+ * \ref neigh_changeable "Changeable Attributes" for a list.
+ */
+struct nl_msg *rtnl_neigh_build_change_request(struct rtnl_neigh *neigh,
+ int flags)
+{
+ return build_neigh_msg(neigh, RTM_NEWNEIGH, NLM_F_REPLACE | flags);
+}
+
+/**
+ * Change neighbour attributes
+ * @arg handle netlink handle
+ * @arg neigh neighbour to be changed
+ * @arg flags additional netlink message flags
+ *
+ * Builds a netlink message by calling rtnl_neigh_build_change_request(),
+ * sends the request to the kernel and waits for the next ACK to be
+ * received and thus blocks until the request has been fullfilled.
+ *
+ * @return 0 on sucess or a negative error if an error occured.
+ * @note Not all attributes can be changed, see
+ * \ref neigh_changeable "Changeable Attributes" for a list.
+ */
+int rtnl_neigh_change(struct nl_handle *handle, struct rtnl_neigh *neigh,
+ int flags)
+{
+ int err;
+ struct nl_msg *msg;
+
+ msg = rtnl_neigh_build_change_request(neigh, flags);
+ if (!msg)
+ return nl_errno(ENOMEM);
+
+ err = nl_send_auto_complete(handle, msg);
+ if (err < 0)
+ return err;
+
+ nlmsg_free(msg);
+ return nl_wait_for_ack(handle);
+}
+
+/** @} */
+
+/**
+ * @name Neighbour States Translations
+ * @{
+ */
+
+static struct trans_tbl neigh_states[] = {
+ __ADD(NUD_INCOMPLETE, incomplete)
+ __ADD(NUD_REACHABLE, reachable)
+ __ADD(NUD_STALE, stale)
+ __ADD(NUD_DELAY, delay)
+ __ADD(NUD_PROBE, probe)
+ __ADD(NUD_FAILED, failed)
+ __ADD(NUD_NOARP, norarp)
+ __ADD(NUD_PERMANENT, permanent)
+};
+
+char * rtnl_neigh_state2str(int state, char *buf, size_t len)
+{
+ return __flags2str(state, buf, len, neigh_states,
+ ARRAY_SIZE(neigh_states));
+}
+
+int rtnl_neigh_str2state(const char *name)
+{
+ return __str2type(name, neigh_states, ARRAY_SIZE(neigh_states));
+}
+
+/** @} */
+
+/**
+ * @name Neighbour Flags Translations
+ * @{
+ */
+
+static struct trans_tbl neigh_flags[] = {
+ __ADD(NTF_PROXY, proxy)
+ __ADD(NTF_ROUTER, router)
+};
+
+char * rtnl_neigh_flags2str(int flags, char *buf, size_t len)
+{
+ return __flags2str(flags, buf, len, neigh_flags,
+ ARRAY_SIZE(neigh_flags));
+}
+
+int rtnl_neigh_str2flag(const char *name)
+{
+ return __str2type(name, neigh_flags, ARRAY_SIZE(neigh_flags));
+}
+
+/** @} */
+
+/**
+ * @name Attributes
+ * @{
+ */
+
+void rtnl_neigh_set_state(struct rtnl_neigh *neigh, int state)
+{
+ neigh->n_state_mask |= state;
+ neigh->n_state |= state;
+ neigh->ce_mask |= NEIGH_ATTR_STATE;
+}
+
+int rtnl_neigh_get_state(struct rtnl_neigh *neigh)
+{
+ if (neigh->ce_mask & NEIGH_ATTR_STATE)
+ return neigh->n_state;
+ else
+ return -1;
+}
+
+void rtnl_neigh_unset_state(struct rtnl_neigh *neigh, int state)
+{
+ neigh->n_state_mask |= state;
+ neigh->n_state &= ~state;
+ neigh->ce_mask |= NEIGH_ATTR_STATE;
+}
+
+void rtnl_neigh_set_flags(struct rtnl_neigh *neigh, unsigned int flags)
+{
+ neigh->n_flag_mask |= flags;
+ neigh->n_flags |= flags;
+ neigh->ce_mask |= NEIGH_ATTR_FLAGS;
+}
+
+unsigned int rtnl_neigh_get_flags(struct rtnl_neigh *neigh)
+{
+ return neigh->n_flags;
+}
+
+void rtnl_neigh_unset_flags(struct rtnl_neigh *neigh, unsigned int flags)
+{
+ neigh->n_flag_mask |= flags;
+ neigh->n_flags &= ~flags;
+ neigh->ce_mask |= NEIGH_ATTR_FLAGS;
+}
+
+void rtnl_neigh_set_ifindex(struct rtnl_neigh *neigh, int ifindex)
+{
+ neigh->n_ifindex = ifindex;
+ neigh->ce_mask |= NEIGH_ATTR_IFINDEX;
+}
+
+int rtnl_neigh_get_ifindex(struct rtnl_neigh *neigh)
+{
+ if (neigh->ce_mask & NEIGH_ATTR_IFINDEX)
+ return neigh->n_ifindex;
+ else
+ return RTNL_LINK_NOT_FOUND;
+}
+
+static inline int __assign_addr(struct rtnl_neigh *neigh, struct nl_addr **pos,
+ struct nl_addr *new, int flag, int nocheck)
+{
+ if (!nocheck) {
+ if (neigh->ce_mask & NEIGH_ATTR_FAMILY) {
+ if (new->a_family != neigh->n_family)
+ return nl_error(EINVAL,
+ "Address family mismatch");
+ } else {
+ neigh->n_family = new->a_family;
+ neigh->ce_mask |= NEIGH_ATTR_FAMILY;
+ }
+ }
+
+ if (*pos)
+ nl_addr_put(*pos);
+
+ nl_addr_get(new);
+ *pos = new;
+
+ neigh->ce_mask |= flag;
+
+ return 0;
+}
+
+void rtnl_neigh_set_lladdr(struct rtnl_neigh *neigh, struct nl_addr *addr)
+{
+ __assign_addr(neigh, &neigh->n_lladdr, addr, NEIGH_ATTR_LLADDR, 1);
+}
+
+struct nl_addr *rtnl_neigh_get_lladdr(struct rtnl_neigh *neigh)
+{
+ if (neigh->ce_mask & NEIGH_ATTR_LLADDR)
+ return neigh->n_lladdr;
+ else
+ return NULL;
+}
+
+int rtnl_neigh_set_dst(struct rtnl_neigh *neigh, struct nl_addr *addr)
+{
+ return __assign_addr(neigh, &neigh->n_dst, addr,
+ NEIGH_ATTR_DST, 0);
+}
+
+struct nl_addr *rtnl_neigh_get_dst(struct rtnl_neigh *neigh)
+{
+ if (neigh->ce_mask & NEIGH_ATTR_DST)
+ return neigh->n_dst;
+ else
+ return NULL;
+}
+
+void rtnl_neigh_set_family(struct rtnl_neigh *neigh, int family)
+{
+ neigh->n_family = family;
+ neigh->ce_mask |= NEIGH_ATTR_FAMILY;
+}
+
+void rtnl_neigh_set_type(struct rtnl_neigh *neigh, int type)
+{
+ neigh->n_type = type;
+ neigh->ce_mask = NEIGH_ATTR_TYPE;
+}
+
+int rtnl_neigh_get_type(struct rtnl_neigh *neigh)
+{
+ if (neigh->ce_mask & NEIGH_ATTR_TYPE)
+ return neigh->n_type;
+ else
+ return -1;
+}
+
+/** @} */
+
+static struct nl_object_ops neigh_obj_ops = {
+ .oo_name = "route/neigh",
+ .oo_size = sizeof(struct rtnl_neigh),
+ .oo_free_data = neigh_free_data,
+ .oo_clone = neigh_clone,
+ .oo_dump[NL_DUMP_BRIEF] = neigh_dump_brief,
+ .oo_dump[NL_DUMP_FULL] = neigh_dump_full,
+ .oo_dump[NL_DUMP_STATS] = neigh_dump_stats,
+ .oo_dump[NL_DUMP_XML] = neigh_dump_xml,
+ .oo_dump[NL_DUMP_ENV] = neigh_dump_env,
+ .oo_compare = neigh_compare,
+ .oo_attrs2str = neigh_attrs2str,
+ .oo_id_attrs = (NEIGH_ATTR_DST | NEIGH_ATTR_FAMILY),
+};
+
+static struct nl_af_group neigh_groups[] = {
+ { AF_UNSPEC, RTNLGRP_NEIGH },
+ { END_OF_GROUP_LIST },
+};
+
+static struct nl_cache_ops rtnl_neigh_ops = {
+ .co_name = "route/neigh",
+ .co_hdrsize = sizeof(struct ndmsg),
+ .co_msgtypes = {
+ { RTM_NEWNEIGH, NL_ACT_NEW, "new" },
+ { RTM_DELNEIGH, NL_ACT_DEL, "del" },
+ { RTM_GETNEIGH, NL_ACT_GET, "get" },
+ END_OF_MSGTYPES_LIST,
+ },
+ .co_protocol = NETLINK_ROUTE,
+ .co_groups = neigh_groups,
+ .co_request_update = neigh_request_update,
+ .co_msg_parser = neigh_msg_parser,
+ .co_obj_ops = &neigh_obj_ops,
+};
+
+static void __init neigh_init(void)
+{
+ nl_cache_mngt_register(&rtnl_neigh_ops);
+}
+
+static void __exit neigh_exit(void)
+{
+ nl_cache_mngt_unregister(&rtnl_neigh_ops);
+}
+
+/** @} */
diff --git a/lib/route/neightbl.c b/lib/route/neightbl.c
new file mode 100644
index 0000000..afd64a6
--- /dev/null
+++ b/lib/route/neightbl.c
@@ -0,0 +1,825 @@
+/*
+ * lib/route/neightbl.c neighbour tables
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup rtnl
+ * @defgroup neightbl Neighbour Tables
+ * @brief
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/route/rtnl.h>
+#include <netlink/route/neightbl.h>
+#include <netlink/route/link.h>
+
+/** @cond SKIP */
+#define NEIGHTBL_ATTR_FAMILY 0x001
+#define NEIGHTBL_ATTR_STATS 0x002
+#define NEIGHTBL_ATTR_NAME 0x004
+#define NEIGHTBL_ATTR_THRESH1 0x008
+#define NEIGHTBL_ATTR_THRESH2 0x010
+#define NEIGHTBL_ATTR_THRESH3 0x020
+#define NEIGHTBL_ATTR_CONFIG 0x040
+#define NEIGHTBL_ATTR_PARMS 0x080
+#define NEIGHTBL_ATTR_GC_INTERVAL 0x100
+
+#define NEIGHTBLPARM_ATTR_IFINDEX 0x0001
+#define NEIGHTBLPARM_ATTR_REFCNT 0x0002
+#define NEIGHTBLPARM_ATTR_QUEUE_LEN 0x0004
+#define NEIGHTBLPARM_ATTR_APP_PROBES 0x0008
+#define NEIGHTBLPARM_ATTR_UCAST_PROBES 0x0010
+#define NEIGHTBLPARM_ATTR_MCAST_PROBES 0x0020
+#define NEIGHTBLPARM_ATTR_PROXY_QLEN 0x0040
+#define NEIGHTBLPARM_ATTR_REACHABLE_TIME 0x0080
+#define NEIGHTBLPARM_ATTR_BASE_REACHABLE_TIME 0x0100
+#define NEIGHTBLPARM_ATTR_RETRANS_TIME 0x0200
+#define NEIGHTBLPARM_ATTR_GC_STALETIME 0x0400
+#define NEIGHTBLPARM_ATTR_DELAY_PROBE_TIME 0x0800
+#define NEIGHTBLPARM_ATTR_ANYCAST_DELAY 0x1000
+#define NEIGHTBLPARM_ATTR_PROXY_DELAY 0x2000
+#define NEIGHTBLPARM_ATTR_LOCKTIME 0x4000
+
+static struct nl_cache_ops rtnl_neightbl_ops;
+static struct nl_object_ops neightbl_obj_ops;
+/** @endcond */
+
+static int neightbl_compare(struct nl_object *_a, struct nl_object *_b,
+ uint32_t attrs, int flags)
+{
+ struct rtnl_neightbl *a = (struct rtnl_neightbl *) _a;
+ struct rtnl_neightbl *b = (struct rtnl_neightbl *) _b;
+ int diff = 0;
+
+#define NT_DIFF(ATTR, EXPR) ATTR_DIFF(attrs, NEIGHTBL_ATTR_##ATTR, a, b, EXPR)
+
+ diff |= NT_DIFF(FAMILY, a->nt_family != b->nt_family);
+ diff |= NT_DIFF(NAME, strcmp(a->nt_name, b->nt_name));
+ diff |= NT_DIFF(THRESH1, a->nt_gc_thresh1 != b->nt_gc_thresh1);
+ diff |= NT_DIFF(THRESH2, a->nt_gc_thresh2 != b->nt_gc_thresh2);
+ diff |= NT_DIFF(THRESH3, a->nt_gc_thresh3 != b->nt_gc_thresh3);
+ diff |= NT_DIFF(GC_INTERVAL, a->nt_gc_interval != b->nt_gc_interval);
+
+#undef NT_DIFF
+
+ if (!(a->ce_mask & NEIGHTBL_ATTR_PARMS) &&
+ !(b->ce_mask & NEIGHTBL_ATTR_PARMS))
+ return diff;
+
+ /* XXX: FIXME: Compare parameter table */
+
+
+#if 0
+#define REQ(F) (fp->ntp_mask & NEIGHTBLPARM_ATTR_##F)
+#define AVAIL(F) (op->ntp_mask & NEIGHTBLPARM_ATTR_##F)
+#define _C(F, N) (REQ(F) && (!AVAIL(F) || (op->N != fp->N)))
+ if (_C(IFINDEX, ntp_ifindex) ||
+ _C(QUEUE_LEN, ntp_queue_len) ||
+ _C(APP_PROBES, ntp_app_probes) ||
+ _C(UCAST_PROBES, ntp_ucast_probes) ||
+ _C(MCAST_PROBES, ntp_mcast_probes) ||
+ _C(PROXY_QLEN, ntp_proxy_qlen) ||
+ _C(LOCKTIME, ntp_locktime) ||
+ _C(RETRANS_TIME, ntp_retrans_time) ||
+ _C(BASE_REACHABLE_TIME, ntp_base_reachable_time) ||
+ _C(GC_STALETIME, ntp_gc_stale_time) ||
+ _C(DELAY_PROBE_TIME, ntp_probe_delay) ||
+ _C(ANYCAST_DELAY, ntp_anycast_delay) ||
+ _C(PROXY_DELAY, ntp_proxy_delay))
+ return 0;
+#undef REQ
+#undef AVAIL
+#undef _C
+#endif
+
+ return diff;
+}
+
+
+static struct nla_policy neightbl_policy[NDTA_MAX+1] = {
+ [NDTA_NAME] = { .type = NLA_STRING,
+ .maxlen = NTBLNAMSIZ },
+ [NDTA_THRESH1] = { .type = NLA_U32 },
+ [NDTA_THRESH2] = { .type = NLA_U32 },
+ [NDTA_THRESH3] = { .type = NLA_U32 },
+ [NDTA_GC_INTERVAL] = { .type = NLA_U32 },
+ [NDTA_CONFIG] = { .minlen = sizeof(struct ndt_config) },
+ [NDTA_STATS] = { .minlen = sizeof(struct ndt_stats) },
+ [NDTA_PARMS] = { .type = NLA_NESTED },
+};
+
+static int neightbl_msg_parser(struct nl_cache_ops *ops,
+ struct sockaddr_nl *who, struct nlmsghdr *n,
+ void *arg)
+{
+ struct rtnl_neightbl *ntbl;
+ struct nlattr *tb[NDTA_MAX + 1];
+ struct nl_parser_param *pp = arg;
+ struct rtgenmsg *rtmsg;
+ int err;
+
+ ntbl = rtnl_neightbl_alloc();
+ if (!ntbl) {
+ err = nl_errno(ENOMEM);
+ goto errout;
+ }
+
+ ntbl->ce_msgtype = n->nlmsg_type;
+ rtmsg = nlmsg_data(n);
+
+ err = nlmsg_parse(n, sizeof(*rtmsg), tb, NDTA_MAX, neightbl_policy);
+ if (err < 0)
+ goto errout;
+
+ ntbl->nt_family = rtmsg->rtgen_family;
+
+ if (tb[NDTA_NAME] == NULL) {
+ err = nl_error(EINVAL, "NDTA_NAME is missing");
+ goto errout;
+ }
+
+ nla_strlcpy(ntbl->nt_name, tb[NDTA_NAME], NTBLNAMSIZ);
+ ntbl->ce_mask |= NEIGHTBL_ATTR_NAME;
+
+ if (tb[NDTA_THRESH1]) {
+ ntbl->nt_gc_thresh1 = nla_get_u32(tb[NDTA_THRESH1]);
+ ntbl->ce_mask |= NEIGHTBL_ATTR_THRESH1;
+ }
+
+ if (tb[NDTA_THRESH2]) {
+ ntbl->nt_gc_thresh2 = nla_get_u32(tb[NDTA_THRESH2]);
+ ntbl->ce_mask |= NEIGHTBL_ATTR_THRESH2;
+ }
+
+ if (tb[NDTA_THRESH3]) {
+ ntbl->nt_gc_thresh3 = nla_get_u32(tb[NDTA_THRESH3]);
+ ntbl->ce_mask |= NEIGHTBL_ATTR_THRESH3;
+ }
+
+ if (tb[NDTA_GC_INTERVAL]) {
+ ntbl->nt_gc_interval = nla_get_u32(tb[NDTA_GC_INTERVAL]);
+ ntbl->ce_mask |= NEIGHTBL_ATTR_GC_INTERVAL;
+ }
+
+ if (tb[NDTA_CONFIG]) {
+ nla_memcpy(&ntbl->nt_config, tb[NDTA_CONFIG],
+ sizeof(ntbl->nt_config));
+ ntbl->ce_mask |= NEIGHTBL_ATTR_CONFIG;
+ }
+
+ if (tb[NDTA_STATS]) {
+ nla_memcpy(&ntbl->nt_stats, tb[NDTA_STATS],
+ sizeof(ntbl->nt_stats));
+ ntbl->ce_mask |= NEIGHTBL_ATTR_STATS;
+ }
+
+ if (tb[NDTA_PARMS]) {
+ struct nlattr *tbp[NDTPA_MAX + 1];
+ struct rtnl_neightbl_parms *p = &ntbl->nt_parms;
+
+ err = nla_parse_nested(tbp, NDTPA_MAX, tb[NDTA_PARMS], NULL);
+ if (err < 0)
+ goto errout;
+
+#define COPY_ENTRY(name, var) \
+ if (tbp[NDTPA_ ##name]) { \
+ p->ntp_ ##var = nla_get_u32(tbp[NDTPA_ ##name]); \
+ p->ntp_mask |= NEIGHTBLPARM_ATTR_ ##name; \
+ }
+
+ COPY_ENTRY(IFINDEX, ifindex);
+ COPY_ENTRY(REFCNT, refcnt);
+ COPY_ENTRY(QUEUE_LEN, queue_len);
+ COPY_ENTRY(APP_PROBES, app_probes);
+ COPY_ENTRY(UCAST_PROBES, ucast_probes);
+ COPY_ENTRY(MCAST_PROBES, mcast_probes);
+ COPY_ENTRY(PROXY_QLEN, proxy_qlen);
+ COPY_ENTRY(PROXY_DELAY, proxy_delay);
+ COPY_ENTRY(ANYCAST_DELAY, anycast_delay);
+ COPY_ENTRY(LOCKTIME, locktime);
+ COPY_ENTRY(REACHABLE_TIME, reachable_time);
+ COPY_ENTRY(BASE_REACHABLE_TIME, base_reachable_time);
+ COPY_ENTRY(RETRANS_TIME, retrans_time);
+ COPY_ENTRY(GC_STALETIME, gc_stale_time);
+ COPY_ENTRY(DELAY_PROBE_TIME, probe_delay);
+#undef COPY_ENTRY
+
+ ntbl->ce_mask |= NEIGHTBL_ATTR_PARMS;
+ }
+
+ err = pp->pp_cb((struct nl_object *) ntbl, pp);
+ if (err < 0)
+ goto errout;
+
+ return P_ACCEPT;
+errout:
+ rtnl_neightbl_put(ntbl);
+ return err;
+}
+
+static int neightbl_request_update(struct nl_cache *c, struct nl_handle *h)
+{
+ return nl_rtgen_request(h, RTM_GETNEIGHTBL, AF_UNSPEC, NLM_F_DUMP);
+}
+
+
+static int neightbl_dump_brief(struct nl_object *arg, struct nl_dump_params *p)
+{
+ int line = 1;
+ struct rtnl_neightbl *ntbl = (struct rtnl_neightbl *) arg;
+
+ dp_dump(p, "%s", ntbl->nt_name);
+
+ if (ntbl->nt_parms.ntp_mask & NEIGHTBLPARM_ATTR_IFINDEX) {
+ struct nl_cache *link_cache;
+
+ link_cache = nl_cache_mngt_require("route/link");
+
+ if (link_cache) {
+ char buf[32];
+ dp_dump(p, "<%s> ",
+ rtnl_link_i2name(link_cache,
+ ntbl->nt_parms.ntp_ifindex,
+ buf, sizeof(buf)));
+ } else
+ dp_dump(p, "<%u> ", ntbl->nt_parms.ntp_ifindex);
+ } else
+ dp_dump(p, " ");
+
+ if (ntbl->ce_mask & NEIGHTBL_ATTR_CONFIG)
+ dp_dump(p, "entries %u ", ntbl->nt_config.ndtc_entries);
+
+ if (ntbl->ce_mask & NEIGHTBL_ATTR_PARMS) {
+ char rt[32], rt2[32];
+ struct rtnl_neightbl_parms *pa = &ntbl->nt_parms;
+
+ dp_dump(p, "reachable-time %s retransmit-time %s",
+ nl_msec2str(pa->ntp_reachable_time, rt, sizeof(rt)),
+ nl_msec2str(pa->ntp_retrans_time, rt2, sizeof(rt2)));
+ }
+
+ dp_dump(p, "\n");
+
+ return line;
+}
+
+static int neightbl_dump_full(struct nl_object *arg, struct nl_dump_params *p)
+{
+ char x[32], y[32], z[32];
+ struct rtnl_neightbl *ntbl = (struct rtnl_neightbl *) arg;
+
+ int line = neightbl_dump_brief(arg, p);
+
+ if (ntbl->ce_mask & NEIGHTBL_ATTR_CONFIG) {
+ dp_new_line(p, line++);
+ dp_dump(p, " key-len %u entry-size %u last-flush %s\n",
+ ntbl->nt_config.ndtc_key_len,
+ ntbl->nt_config.ndtc_entry_size,
+ nl_msec2str(ntbl->nt_config.ndtc_last_flush,
+ x, sizeof(x)));
+
+ dp_new_line(p, line++);
+ dp_dump(p, " gc threshold %u/%u/%u interval %s " \
+ "chain-position %u\n",
+ ntbl->nt_gc_thresh1, ntbl->nt_gc_thresh2,
+ ntbl->nt_gc_thresh3,
+ nl_msec2str(ntbl->nt_gc_interval, x, sizeof(x)),
+ ntbl->nt_config.ndtc_hash_chain_gc);
+
+ dp_new_line(p, line++);
+ dp_dump(p, " hash-rand 0x%08X/0x%08X last-rand %s\n",
+ ntbl->nt_config.ndtc_hash_rnd,
+ ntbl->nt_config.ndtc_hash_mask,
+ nl_msec2str(ntbl->nt_config.ndtc_last_rand,
+ x, sizeof(x)));
+ }
+
+ if (ntbl->ce_mask & NEIGHTBL_ATTR_PARMS) {
+ struct rtnl_neightbl_parms *pa = &ntbl->nt_parms;
+
+ dp_new_line(p, line++);
+ dp_dump(p, " refcnt %u pending-queue-limit %u " \
+ "proxy-delayed-queue-limit %u\n",
+ pa->ntp_refcnt,
+ pa->ntp_queue_len,
+ pa->ntp_proxy_qlen);
+
+ dp_new_line(p, line++);
+ dp_dump(p, " num-userspace-probes %u num-unicast-probes " \
+ "%u num-multicast-probes %u\n",
+ pa->ntp_app_probes,
+ pa->ntp_ucast_probes,
+ pa->ntp_mcast_probes);
+
+ dp_new_line(p, line++);
+ dp_dump(p, " min-age %s base-reachable-time %s " \
+ "stale-check-interval %s\n",
+ nl_msec2str(pa->ntp_locktime, x, sizeof(x)),
+ nl_msec2str(pa->ntp_base_reachable_time,
+ y, sizeof(y)),
+ nl_msec2str(pa->ntp_gc_stale_time, z, sizeof(z)));
+
+ dp_new_line(p, line++);
+ dp_dump(p, " initial-probe-delay %s answer-delay %s " \
+ "proxy-answer-delay %s\n",
+ nl_msec2str(pa->ntp_probe_delay, x, sizeof(x)),
+ nl_msec2str(pa->ntp_anycast_delay, y, sizeof(y)),
+ nl_msec2str(pa->ntp_proxy_delay, z, sizeof(z)));
+ }
+
+ return line;
+}
+
+static int neightbl_dump_stats(struct nl_object *arg, struct nl_dump_params *p)
+{
+ struct rtnl_neightbl *ntbl = (struct rtnl_neightbl *) arg;
+ int line = neightbl_dump_full(arg, p);
+
+ if (!(ntbl->ce_mask & NEIGHTBL_ATTR_STATS))
+ return line;
+
+ dp_new_line(p, line++);
+ dp_dump(p, " lookups %lld hits %lld failed %lld " \
+ "allocations %lld destroys %lld\n",
+ ntbl->nt_stats.ndts_lookups,
+ ntbl->nt_stats.ndts_hits,
+ ntbl->nt_stats.ndts_res_failed,
+ ntbl->nt_stats.ndts_allocs,
+ ntbl->nt_stats.ndts_destroys);
+
+ dp_new_line(p, line++);
+ dp_dump(p, " hash-grows %lld forced-gc-runs %lld " \
+ "periodic-gc-runs %lld\n",
+ ntbl->nt_stats.ndts_hash_grows,
+ ntbl->nt_stats.ndts_forced_gc_runs,
+ ntbl->nt_stats.ndts_periodic_gc_runs);
+
+ dp_dump(p, " rcv-unicast-probes %lld rcv-multicast-probes %lld\n",
+ ntbl->nt_stats.ndts_rcv_probes_ucast,
+ ntbl->nt_stats.ndts_rcv_probes_mcast);
+
+ return line;
+}
+
+/**
+ * @name Allocation/Freeing
+ * @{
+ */
+
+struct rtnl_neightbl *rtnl_neightbl_alloc(void)
+{
+ return (struct rtnl_neightbl *) nl_object_alloc(&neightbl_obj_ops);
+}
+
+void rtnl_neightbl_put(struct rtnl_neightbl *neightbl)
+{
+ nl_object_put((struct nl_object *) neightbl);
+}
+
+/** @} */
+
+/**
+ * @name Neighbour Table Cache Management
+ * @{
+ */
+
+/**
+ * Build a neighbour table cache including all neighbour tables currently configured in the kernel.
+ * @arg handle netlink handle
+ *
+ * Allocates a new neighbour table cache, initializes it properly and
+ * updates it to include all neighbour tables currently configured in
+ * the kernel.
+ *
+ * @note The caller is responsible for destroying and freeing the
+ * cache after using it.
+ * @return The new cache or NULL if an error occured.
+ */
+struct nl_cache * rtnl_neightbl_alloc_cache(struct nl_handle *handle)
+{
+ struct nl_cache * cache;
+
+ cache = nl_cache_alloc(&rtnl_neightbl_ops);
+ if (cache == NULL)
+ return NULL;
+
+ if (handle && nl_cache_refill(handle, cache) < 0) {
+ nl_cache_free(cache);
+ return NULL;
+ }
+
+ return cache;
+}
+
+/**
+ * Lookup neighbour table by name and optional interface index
+ * @arg cache neighbour table cache
+ * @arg name name of table
+ * @arg ifindex optional interface index
+ *
+ * Looks up the neighbour table matching the specified name and
+ * optionally the specified ifindex to retrieve device specific
+ * parameter sets.
+ *
+ * @return ptr to neighbour table inside the cache or NULL if no
+ * match was found.
+ */
+struct rtnl_neightbl *rtnl_neightbl_get(struct nl_cache *cache,
+ const char *name, int ifindex)
+{
+ struct rtnl_neightbl *nt;
+
+ if (cache->c_ops != &rtnl_neightbl_ops)
+ return NULL;
+
+ nl_list_for_each_entry(nt, &cache->c_items, ce_list) {
+ if (!strcasecmp(nt->nt_name, name) &&
+ ((!ifindex && !nt->nt_parms.ntp_ifindex) ||
+ (ifindex && ifindex == nt->nt_parms.ntp_ifindex))) {
+ nl_object_get((struct nl_object *) nt);
+ return nt;
+ }
+ }
+
+ return NULL;
+}
+
+/** @} */
+
+/**
+ * @name Neighbour Table Modifications
+ * @{
+ */
+
+/**
+ * Builds a netlink change request message to change neighbour table attributes
+ * @arg old neighbour table to change
+ * @arg tmpl template with requested changes
+ *
+ * Builds a new netlink message requesting a change of neighbour table
+ * attributes. The netlink message header isn't fully equipped with all
+ * relevant fields and must be sent out via nl_send_auto_complete() or
+ * supplemented as needed.
+ * \a old must point to a neighbour table currently configured in the
+ * kernel and \a tmpl must contain the attributes to be changed set via
+ * \c rtnl_neightbl_set_* functions.
+ *
+ * @return New netlink message
+ */
+struct nl_msg * rtnl_neightbl_build_change_request(struct rtnl_neightbl *old,
+ struct rtnl_neightbl *tmpl)
+{
+ struct nl_msg *m;
+ struct ndtmsg ndt = {
+ .ndtm_family = old->nt_family,
+ };
+
+ m = nlmsg_alloc_simple(RTM_SETNEIGHTBL, 0);
+ nlmsg_append(m, &ndt, sizeof(ndt), NLMSG_ALIGNTO);
+
+ nla_put_string(m, NDTA_NAME, old->nt_name);
+
+ if (tmpl->ce_mask & NEIGHTBL_ATTR_THRESH1)
+ nla_put_u32(m, NDTA_THRESH1, tmpl->nt_gc_thresh1);
+
+ if (tmpl->ce_mask & NEIGHTBL_ATTR_THRESH2)
+ nla_put_u32(m, NDTA_THRESH2, tmpl->nt_gc_thresh2);
+
+ if (tmpl->ce_mask & NEIGHTBL_ATTR_THRESH2)
+ nla_put_u32(m, NDTA_THRESH2, tmpl->nt_gc_thresh2);
+
+ if (tmpl->ce_mask & NEIGHTBL_ATTR_GC_INTERVAL)
+ nla_put_u64(m, NDTA_GC_INTERVAL,
+ tmpl->nt_gc_interval);
+
+ if (tmpl->ce_mask & NEIGHTBL_ATTR_PARMS) {
+ struct rtnl_neightbl_parms *p = &tmpl->nt_parms;
+ struct nl_msg *parms = nlmsg_alloc();
+
+ if (old->nt_parms.ntp_mask & NEIGHTBLPARM_ATTR_IFINDEX)
+ nla_put_u32(parms, NDTPA_IFINDEX,
+ old->nt_parms.ntp_ifindex);
+
+
+ if (p->ntp_mask & NEIGHTBLPARM_ATTR_QUEUE_LEN)
+ nla_put_u32(parms, NDTPA_QUEUE_LEN, p->ntp_queue_len);
+
+ if (p->ntp_mask & NEIGHTBLPARM_ATTR_APP_PROBES)
+ nla_put_u32(parms, NDTPA_APP_PROBES, p->ntp_app_probes);
+
+ if (p->ntp_mask & NEIGHTBLPARM_ATTR_UCAST_PROBES)
+ nla_put_u32(parms, NDTPA_UCAST_PROBES,
+ p->ntp_ucast_probes);
+
+ if (p->ntp_mask & NEIGHTBLPARM_ATTR_MCAST_PROBES)
+ nla_put_u32(parms, NDTPA_MCAST_PROBES,
+ p->ntp_mcast_probes);
+
+ if (p->ntp_mask & NEIGHTBLPARM_ATTR_PROXY_QLEN)
+ nla_put_u32(parms, NDTPA_PROXY_QLEN,
+ p->ntp_proxy_qlen);
+
+ if (p->ntp_mask & NEIGHTBLPARM_ATTR_BASE_REACHABLE_TIME)
+ nla_put_u64(parms, NDTPA_BASE_REACHABLE_TIME,
+ p->ntp_base_reachable_time);
+
+ if (p->ntp_mask & NEIGHTBLPARM_ATTR_RETRANS_TIME)
+ nla_put_u64(parms, NDTPA_RETRANS_TIME,
+ p->ntp_retrans_time);
+
+ if (p->ntp_mask & NEIGHTBLPARM_ATTR_GC_STALETIME)
+ nla_put_u64(parms, NDTPA_GC_STALETIME,
+ p->ntp_gc_stale_time);
+
+ if (p->ntp_mask & NEIGHTBLPARM_ATTR_DELAY_PROBE_TIME)
+ nla_put_u64(parms, NDTPA_DELAY_PROBE_TIME,
+ p->ntp_proxy_delay);
+
+ if (p->ntp_mask & NEIGHTBLPARM_ATTR_ANYCAST_DELAY)
+ nla_put_u64(parms, NDTPA_ANYCAST_DELAY,
+ p->ntp_anycast_delay);
+
+ if (p->ntp_mask & NEIGHTBLPARM_ATTR_PROXY_DELAY)
+ nla_put_u64(parms, NDTPA_PROXY_DELAY,
+ p->ntp_proxy_delay);
+
+ if (p->ntp_mask & NEIGHTBLPARM_ATTR_LOCKTIME)
+ nla_put_u64(parms, NDTPA_LOCKTIME, p->ntp_locktime);
+
+ nla_put_nested(m, NDTA_PARMS, parms);
+ nlmsg_free(parms);
+ }
+
+ return m;
+}
+
+/**
+ * Change neighbour table attributes
+ * @arg handle netlink handle
+ * @arg old neighbour table to be changed
+ * @arg tmpl template with requested changes
+ *
+ * Builds a new netlink message by calling
+ * rtnl_neightbl_build_change_request(), sends the request to the
+ * kernel and waits for the next ACK to be received, i.e. blocks
+ * until the request has been processed.
+ *
+ * @return 0 on success or a negative error code
+ */
+int rtnl_neightbl_change(struct nl_handle *handle, struct rtnl_neightbl *old,
+ struct rtnl_neightbl *tmpl)
+{
+ int err;
+ struct nl_msg *msg;
+
+ msg = rtnl_neightbl_build_change_request(old, tmpl);
+ err = nl_send_auto_complete(handle, msg);
+ if (err < 0)
+ return err;
+
+ nlmsg_free(msg);
+ return nl_wait_for_ack(handle);
+}
+
+/** @} */
+
+/**
+ * @name Attribute Modification
+ * @{
+ */
+
+void rtnl_neightbl_set_family(struct rtnl_neightbl *ntbl, int family)
+{
+ ntbl->nt_family = family;
+ ntbl->ce_mask |= NEIGHTBL_ATTR_FAMILY;
+}
+
+void rtnl_neightbl_set_gc_interval(struct rtnl_neightbl *ntbl, uint64_t ms)
+{
+ ntbl->nt_gc_interval = ms;
+ ntbl->ce_mask |= NEIGHTBL_ATTR_GC_INTERVAL;
+}
+
+void rtnl_neightbl_set_gc_tresh1(struct rtnl_neightbl *ntbl, int thresh)
+{
+ ntbl->nt_gc_thresh1 = thresh;
+ ntbl->ce_mask |= NEIGHTBL_ATTR_THRESH1;
+}
+
+void rtnl_neightbl_set_gc_tresh2(struct rtnl_neightbl *ntbl, int thresh)
+{
+ ntbl->nt_gc_thresh2 = thresh;
+ ntbl->ce_mask |= NEIGHTBL_ATTR_THRESH2;
+}
+
+void rtnl_neightbl_set_gc_tresh3(struct rtnl_neightbl *ntbl, int thresh)
+{
+ ntbl->nt_gc_thresh3 = thresh;
+ ntbl->ce_mask |= NEIGHTBL_ATTR_THRESH3;
+}
+
+void rtnl_neightbl_set_name(struct rtnl_neightbl *ntbl, const char *name)
+{
+ strncpy(ntbl->nt_name, name, sizeof(ntbl->nt_name) - 1);
+ ntbl->ce_mask |= NEIGHTBL_ATTR_NAME;
+}
+
+void rtnl_neightbl_set_dev(struct rtnl_neightbl *ntbl, int ifindex)
+{
+ ntbl->nt_parms.ntp_ifindex = ifindex;
+ ntbl->nt_parms.ntp_mask |= NEIGHTBLPARM_ATTR_IFINDEX;
+ ntbl->ce_mask |= NEIGHTBL_ATTR_PARMS;
+}
+
+/**
+ * Set the queue length for pending requests of a neighbour table to the specified value
+ * @arg ntbl neighbour table to change
+ * @arg len new queue len
+ */
+void rtnl_neightbl_set_queue_len(struct rtnl_neightbl *ntbl, int len)
+{
+ ntbl->nt_parms.ntp_queue_len = len;
+ ntbl->nt_parms.ntp_mask |= NEIGHTBLPARM_ATTR_QUEUE_LEN;
+ ntbl->ce_mask |= NEIGHTBL_ATTR_PARMS;
+}
+
+/**
+ * Set the queue length for delay proxy arp requests of a neighbour table to the specified value
+ * @arg ntbl neighbour table to change
+ * @arg len new queue len
+ */
+void rtnl_neightbl_set_proxy_queue_len(struct rtnl_neightbl *ntbl, int len)
+{
+ ntbl->nt_parms.ntp_proxy_qlen = len;
+ ntbl->nt_parms.ntp_mask |= NEIGHTBLPARM_ATTR_PROXY_QLEN;
+ ntbl->ce_mask |= NEIGHTBL_ATTR_PARMS;
+}
+
+/**
+ * Set the number of application probes of a neighbour table to the specified value
+ * @arg ntbl neighbour table to change
+ * @arg probes new probes value
+ */
+void rtnl_neightbl_set_app_probes(struct rtnl_neightbl *ntbl, int probes)
+{
+ ntbl->nt_parms.ntp_app_probes = probes;
+ ntbl->nt_parms.ntp_mask |= NEIGHTBLPARM_ATTR_APP_PROBES;
+ ntbl->ce_mask |= NEIGHTBL_ATTR_PARMS;
+}
+
+/**
+ * Set the number of unicast probes of a neighbour table to the specified value
+ * @arg ntbl neighbour table to change
+ * @arg probes new probes value
+ */
+void rtnl_neightbl_set_ucast_probes(struct rtnl_neightbl *ntbl, int probes)
+{
+ ntbl->nt_parms.ntp_ucast_probes = probes;
+ ntbl->nt_parms.ntp_mask |= NEIGHTBLPARM_ATTR_UCAST_PROBES;
+ ntbl->ce_mask |= NEIGHTBL_ATTR_PARMS;
+}
+
+/**
+ * Set the number of multicast probes of a neighbour table to the specified value
+ * @arg ntbl neighbour table to change
+ * @arg probes new probes value
+ */
+void rtnl_neightbl_set_mcast_probes(struct rtnl_neightbl *ntbl, int probes)
+{
+ ntbl->nt_parms.ntp_mcast_probes = probes;
+ ntbl->nt_parms.ntp_mask |= NEIGHTBLPARM_ATTR_MCAST_PROBES;
+ ntbl->ce_mask |= NEIGHTBL_ATTR_PARMS;
+}
+
+/**
+ * Set the base reachable time of a neighbour table to the specified value
+ * @arg ntbl neighbour table to change
+ * @arg ms new base reachable time in milliseconds
+ */
+void rtnl_neightbl_set_base_reachable_time(struct rtnl_neightbl *ntbl,
+ uint64_t ms)
+{
+ ntbl->nt_parms.ntp_base_reachable_time = ms;
+ ntbl->nt_parms.ntp_mask |= NEIGHTBLPARM_ATTR_BASE_REACHABLE_TIME;
+ ntbl->ce_mask |= NEIGHTBL_ATTR_PARMS;
+}
+
+/**
+ * Set the retransmit time of a neighbour table to the specified value
+ * @arg ntbl neighbour table to change
+ * @arg ms new retransmit time
+ */
+void rtnl_neightbl_set_retrans_time(struct rtnl_neightbl *ntbl, uint64_t ms)
+{
+ ntbl->nt_parms.ntp_retrans_time = ms;
+ ntbl->nt_parms.ntp_mask |= NEIGHTBLPARM_ATTR_RETRANS_TIME;
+ ntbl->ce_mask |= NEIGHTBL_ATTR_PARMS;
+}
+
+/**
+ * Set the gc stale time of a neighbour table to the specified value
+ * @arg ntbl neighbour table to change
+ * @arg ms new gc stale time in milliseconds
+ */
+void rtnl_neightbl_set_gc_stale_time(struct rtnl_neightbl *ntbl, uint64_t ms)
+{
+ ntbl->nt_parms.ntp_gc_stale_time = ms;
+ ntbl->nt_parms.ntp_mask |= NEIGHTBLPARM_ATTR_GC_STALETIME;
+ ntbl->ce_mask |= NEIGHTBL_ATTR_PARMS;
+}
+
+/**
+ * Set the first probe delay time of a neighbour table to the specified value
+ * @arg ntbl neighbour table to change
+ * @arg ms new first probe delay time in milliseconds
+ */
+void rtnl_neightbl_set_delay_probe_time(struct rtnl_neightbl *ntbl, uint64_t ms)
+{
+ ntbl->nt_parms.ntp_probe_delay = ms;
+ ntbl->nt_parms.ntp_mask |= NEIGHTBLPARM_ATTR_DELAY_PROBE_TIME;
+ ntbl->ce_mask |= NEIGHTBL_ATTR_PARMS;
+}
+
+/**
+ * Set the anycast delay of a neighbour table to the specified value
+ * @arg ntbl neighbour table to change
+ * @arg ms new anycast delay in milliseconds
+ */
+void rtnl_neightbl_set_anycast_delay(struct rtnl_neightbl *ntbl, uint64_t ms)
+{
+ ntbl->nt_parms.ntp_anycast_delay = ms;
+ ntbl->nt_parms.ntp_mask |= NEIGHTBLPARM_ATTR_ANYCAST_DELAY;
+ ntbl->ce_mask |= NEIGHTBL_ATTR_PARMS;
+}
+
+/**
+ * Set the proxy delay of a neighbour table to the specified value
+ * @arg ntbl neighbour table to change
+ * @arg ms new proxy delay in milliseconds
+ */
+void rtnl_neightbl_set_proxy_delay(struct rtnl_neightbl *ntbl, uint64_t ms)
+{
+ ntbl->nt_parms.ntp_proxy_delay = ms;
+ ntbl->nt_parms.ntp_mask |= NEIGHTBLPARM_ATTR_PROXY_DELAY;
+ ntbl->ce_mask |= NEIGHTBL_ATTR_PARMS;
+}
+
+/**
+ * Set the locktime of a neighbour table to the specified value
+ * @arg ntbl neighbour table to change
+ * @arg ms new locktime in milliseconds
+ */
+void rtnl_neightbl_set_locktime(struct rtnl_neightbl *ntbl, uint64_t ms)
+{
+ ntbl->nt_parms.ntp_locktime = ms;
+ ntbl->nt_parms.ntp_mask |= NEIGHTBLPARM_ATTR_LOCKTIME;
+ ntbl->ce_mask |= NEIGHTBL_ATTR_PARMS;
+}
+
+/** @} */
+
+static struct nl_object_ops neightbl_obj_ops = {
+ .oo_name = "route/neightbl",
+ .oo_size = sizeof(struct rtnl_neightbl),
+ .oo_dump[NL_DUMP_BRIEF] = neightbl_dump_brief,
+ .oo_dump[NL_DUMP_FULL] = neightbl_dump_full,
+ .oo_dump[NL_DUMP_STATS] = neightbl_dump_stats,
+ .oo_compare = neightbl_compare,
+};
+
+static struct nl_cache_ops rtnl_neightbl_ops = {
+ .co_name = "route/neightbl",
+ .co_hdrsize = sizeof(struct rtgenmsg),
+ .co_msgtypes = {
+ { RTM_NEWNEIGHTBL, NL_ACT_NEW, "new" },
+ { RTM_SETNEIGHTBL, NL_ACT_SET, "set" },
+ { RTM_GETNEIGHTBL, NL_ACT_GET, "get" },
+ END_OF_MSGTYPES_LIST,
+ },
+ .co_protocol = NETLINK_ROUTE,
+ .co_request_update = neightbl_request_update,
+ .co_msg_parser = neightbl_msg_parser,
+ .co_obj_ops = &neightbl_obj_ops,
+};
+
+static void __init neightbl_init(void)
+{
+ nl_cache_mngt_register(&rtnl_neightbl_ops);
+}
+
+static void __exit neightbl_exit(void)
+{
+ nl_cache_mngt_unregister(&rtnl_neightbl_ops);
+}
+
+/** @} */
diff --git a/lib/route/nexthop.c b/lib/route/nexthop.c
new file mode 100644
index 0000000..7486769
--- /dev/null
+++ b/lib/route/nexthop.c
@@ -0,0 +1,151 @@
+/*
+ * lib/route/nexthop.c Routing Nexthop
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup route_obj
+ * @defgroup nexthop Nexthop
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/route/rtnl.h>
+#include <netlink/route/route.h>
+
+/**
+ * @name Allocation/Freeing
+ * @{
+ */
+
+struct rtnl_nexthop *rtnl_route_nh_alloc(void)
+{
+ struct rtnl_nexthop *nh;
+
+ nh = calloc(1, sizeof(*nh));
+ if (!nh) {
+ nl_errno(ENOMEM);
+ return NULL;
+ }
+
+ nl_init_list_head(&nh->rtnh_list);
+
+ return nh;
+}
+
+struct rtnl_nexthop *rtnl_route_nh_clone(struct rtnl_nexthop *src)
+{
+ struct rtnl_nexthop *nh;
+
+ nh = rtnl_route_nh_alloc();
+ if (!nh)
+ return NULL;
+
+ nh->rtnh_flags = src->rtnh_flags;
+ nh->rtnh_flag_mask = src->rtnh_flag_mask;
+ nh->rtnh_weight = src->rtnh_weight;
+ nh->rtnh_ifindex = src->rtnh_ifindex;
+ nh->rtnh_mask = src->rtnh_mask;
+
+ if (src->rtnh_gateway) {
+ nh->rtnh_gateway = nl_addr_clone(src->rtnh_gateway);
+ if (!nh->rtnh_gateway) {
+ free(nh);
+ return NULL;
+ }
+ }
+
+ return nh;
+}
+
+void rtnl_route_nh_free(struct rtnl_nexthop *nh)
+{
+ nl_addr_put(nh->rtnh_gateway);
+ free(nh);
+}
+
+/** @} */
+
+/**
+ * @name Attributes
+ */
+
+void rtnl_route_nh_set_weight(struct rtnl_nexthop *nh, int weight)
+{
+ nh->rtnh_weight = weight;
+ nh->rtnh_mask |= NEXTHOP_HAS_WEIGHT;
+}
+
+int rtnl_route_nh_get_weight(struct rtnl_nexthop *nh)
+{
+ if (nh->rtnh_mask & NEXTHOP_HAS_WEIGHT)
+ return nh->rtnh_weight;
+ else
+ return 0;
+}
+
+void rtnl_route_nh_set_ifindex(struct rtnl_nexthop *nh, int ifindex)
+{
+ nh->rtnh_ifindex = ifindex;
+ nh->rtnh_mask |= NEXTHOP_HAS_IFINDEX;
+}
+
+int rtnl_route_nh_get_ifindex(struct rtnl_nexthop *nh)
+{
+ if (nh->rtnh_mask & NEXTHOP_HAS_IFINDEX)
+ return nh->rtnh_ifindex;
+ else
+ return -1;
+}
+
+void rtnl_route_nh_set_gateway(struct rtnl_nexthop *nh, struct nl_addr *addr)
+{
+ struct nl_addr *old = nh->rtnh_gateway;
+
+ nh->rtnh_gateway = nl_addr_get(addr);
+ if (old)
+ nl_addr_put(old);
+
+ nh->rtnh_mask |= NEXTHOP_HAS_GATEWAY;
+}
+
+struct nl_addr *rtnl_route_nh_get_gateway(struct rtnl_nexthop *nh)
+{
+ if (nh->rtnh_mask & NEXTHOP_HAS_GATEWAY)
+ return nh->rtnh_gateway;
+ else
+ return NULL;
+}
+
+void rtnl_route_nh_set_flags(struct rtnl_nexthop *nh, unsigned int flags)
+{
+ nh->rtnh_flag_mask |= flags;
+ nh->rtnh_flags |= flags;
+ nh->rtnh_mask |= NEXTHOP_HAS_FLAGS;
+}
+
+void rtnl_route_nh_unset_flags(struct rtnl_nexthop *nh, unsigned int flags)
+{
+ nh->rtnh_flag_mask |= flags;
+ nh->rtnh_flags &= ~flags;
+ nh->rtnh_mask |= NEXTHOP_HAS_FLAGS;
+}
+
+unsigned int rtnl_route_nh_get_flags(struct rtnl_nexthop *nh)
+{
+ if (nh->rtnh_mask & NEXTHOP_HAS_FLAGS)
+ return nh->rtnh_flags;
+ else
+ return 0;
+}
+
+/** @} */
+/** @} */
diff --git a/lib/route/qdisc.c b/lib/route/qdisc.c
new file mode 100644
index 0000000..818ca7b
--- /dev/null
+++ b/lib/route/qdisc.c
@@ -0,0 +1,478 @@
+/*
+ * lib/route/qdisc.c Queueing Disciplines
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup tc
+ * @defgroup qdisc Queueing Disciplines
+ *
+ * @par Qdisc Handles
+ * In general, qdiscs are identified by the major part of a traffic control
+ * handle (the upper 16 bits). A few special values exist though:
+ * - \c TC_H_ROOT: root qdisc (directly attached to the device)
+ * - \c TC_H_INGRESS: ingress qdisc (directly attached to the device)
+ * - \c TC_H_UNSPEC: unspecified qdisc (no reference)
+ *
+ * @par 1) Adding a Qdisc
+ * @code
+ * // Allocate a new empty qdisc to be filled out
+ * struct rtnl_qdisc *qdisc = rtnl_qdisc_alloc();
+ *
+ * // ... specify the kind of the Qdisc
+ * rtnl_qdisc_set_kind(qdisc, "pfifo");
+ *
+ * // Specify the device the qdisc should be attached to
+ * rtnl_qdisc_set_ifindex(qdisc, ifindex);
+ *
+ * // ... specify the parent qdisc
+ * rtnl_qdisc_set_parent(qdisc, TC_H_ROOT);
+ *
+ * // Specifying the handle is not required but makes reidentifying easier
+ * // and may help to avoid adding a qdisc twice.
+ * rtnl_qdisc_set_handle(qdisc, 0x000A0000);
+ *
+ * // Now on to specify the qdisc specific options, see the relevant qdisc
+ * // modules for documentation, in this example we set the upper limit of
+ * // the packet fifo qdisc to 64
+ * rtnl_qdisc_fifo_set_limit(qdisc, 64);
+ *
+ * rtnl_qdisc_add(handle, qdisc, NLM_R_REPLACE);
+ *
+ * // Free up the memory
+ * rtnl_qdisc_put(qdisc);
+ * @endcode
+ *
+ * @par 2) Deleting a Qdisc
+ * @code
+ * // Allocate a new empty qdisc to be filled out with the parameters
+ * // specifying the qdisc to be deleted. Alternatively a fully equiped
+ * // Qdisc object from a cache can be used.
+ * struct rtnl_qdisc *qdisc = rtnl_qdisc_alloc();
+ *
+ * // The interface index of the device the qdisc is on and the parent handle
+ * // are the least required fields to be filled out.
+ * // Note: Specify TC_H_ROOT or TC_H_INGRESS as parent handle to delete the
+ * // root respectively root ingress qdisc.
+ * rtnl_qdisc_set_ifindex(qdisc, ifindex);
+ * rtnl_qdisc_set_parent(qdisc, parent_handle);
+ *
+ * // If required for identification, the handle can be specified as well.
+ * rtnl_qdisc_set_handle(qdisc, qdisc_handle);
+ *
+ * // Not required but maybe helpful as sanity check, the kind of the qdisc
+ * // can be specified to avoid mistakes.
+ * rtnl_qdisc_set_kind(qdisc, "pfifo");
+ *
+ * // Finally delete the qdisc with rtnl_qdisc_delete(), alternatively
+ * // rtnl_qdisc_build_delete_request() can be invoked to generate an
+ * // appropritate netlink message to send out.
+ * rtnl_qdisc_delete(handle, qdisc);
+ *
+ * // Free up the memory
+ * rtnl_qdisc_put(qdisc);
+ * @endcode
+ *
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/route/link.h>
+#include <netlink/route/tc.h>
+#include <netlink/route/qdisc.h>
+#include <netlink/route/class.h>
+#include <netlink/route/classifier.h>
+#include <netlink/route/qdisc-modules.h>
+
+static struct nl_cache_ops rtnl_qdisc_ops;
+
+static int qdisc_msg_parser(struct nl_cache_ops *ops, struct sockaddr_nl *who,
+ struct nlmsghdr *n, void *arg)
+{
+ int err = -ENOMEM;
+ struct nl_parser_param *pp = arg;
+ struct rtnl_qdisc *qdisc;
+ struct rtnl_qdisc_ops *qops;
+
+ qdisc = rtnl_qdisc_alloc();
+ if (!qdisc) {
+ err = nl_errno(ENOMEM);
+ goto errout;
+ }
+
+ qdisc->ce_msgtype = n->nlmsg_type;
+
+ err = tca_msg_parser(n, (struct rtnl_tca *) qdisc);
+ if (err < 0)
+ goto errout_free;
+
+ qops = rtnl_qdisc_lookup_ops(qdisc);
+ if (qops && qops->qo_msg_parser) {
+ err = qops->qo_msg_parser(qdisc);
+ if (err < 0)
+ goto errout_free;
+ }
+
+ err = pp->pp_cb((struct nl_object *) qdisc, pp);
+ if (err < 0)
+ goto errout_free;
+
+ return P_ACCEPT;
+
+errout_free:
+ rtnl_qdisc_put(qdisc);
+errout:
+ return err;
+}
+
+static int qdisc_request_update(struct nl_cache *c, struct nl_handle *h)
+{
+ struct tcmsg tchdr = {
+ .tcm_family = AF_UNSPEC,
+ .tcm_ifindex = c->c_iarg1,
+ };
+
+ return nl_send_simple(h, RTM_GETQDISC, NLM_F_DUMP, &tchdr,
+ sizeof(tchdr));
+}
+
+/**
+ * @name QDisc Addition
+ * @{
+ */
+
+static struct nl_msg *qdisc_build(struct rtnl_qdisc *qdisc, int type, int flags)
+{
+ struct rtnl_qdisc_ops *qops;
+ struct nl_msg *msg;
+ int err;
+
+ msg = tca_build_msg((struct rtnl_tca *) qdisc, type, flags);
+ if (!msg)
+ goto errout;
+
+ qops = rtnl_qdisc_lookup_ops(qdisc);
+ if (qops && qops->qo_get_opts) {
+ struct nl_msg *opts;
+
+ opts = qops->qo_get_opts(qdisc);
+ if (opts) {
+ err = nla_put_nested(msg, TCA_OPTIONS, opts);
+ nlmsg_free(opts);
+ if (err < 0)
+ goto errout;
+ }
+ }
+
+ return msg;
+errout:
+ nlmsg_free(msg);
+
+ return NULL;
+}
+
+/**
+ * Build a netlink message to add a new qdisc
+ * @arg qdisc qdisc to add
+ * @arg flags additional netlink message flags
+ *
+ * Builds a new netlink message requesting an addition of a qdisc.
+ * The netlink message header isn't fully equipped with all relevant
+ * fields and must be sent out via nl_send_auto_complete() or
+ * supplemented as needed.
+ *
+ * Common message flags used:
+ * - NLM_F_REPLACE - replace a potential existing qdisc
+ *
+ * @return New netlink message
+ */
+struct nl_msg *rtnl_qdisc_build_add_request(struct rtnl_qdisc *qdisc,
+ int flags)
+{
+ struct nl_msg *msg;
+
+ msg = qdisc_build(qdisc, RTM_NEWQDISC, NLM_F_CREATE | flags);
+ if (!msg)
+ nl_errno(ENOMEM);
+
+ return msg;
+}
+
+/**
+ * Add a new qdisc
+ * @arg handle netlink handle
+ * @arg qdisc qdisc to delete
+ * @arg flags additional netlink message flags
+ *
+ * Builds a netlink message by calling rtnl_qdisc_build_add_request(),
+ * sends the request to the kernel and waits for the ACK to be
+ * received and thus blocks until the request has been processed.
+ *
+ * Common message flags used:
+ * - NLM_F_REPLACE - replace a potential existing qdisc
+ *
+ * @return 0 on success or a negative error code
+ */
+int rtnl_qdisc_add(struct nl_handle *handle, struct rtnl_qdisc *qdisc,
+ int flags)
+{
+ struct nl_msg *msg;
+ int err;
+
+ msg = rtnl_qdisc_build_add_request(qdisc, flags);
+ if (!msg)
+ return nl_errno(ENOMEM);
+
+ err = nl_send_auto_complete(handle, msg);
+ if (err < 0)
+ return err;
+
+ nlmsg_free(msg);
+ return nl_wait_for_ack(handle);
+}
+
+/** @} */
+
+/**
+ * @name QDisc Modification
+ * @{
+ */
+
+/**
+ * Build a netlink message to change attributes of a existing qdisc
+ * @arg qdisc qdisc to change
+ * @arg new new qdisc attributes
+ *
+ * Builds a new netlink message requesting an change of qdisc
+ * attributes. The netlink message header isn't fully equipped
+ * with all relevant fields and must be sent out via
+ * nl_send_auto_complete() or supplemented as needed.
+ *
+ * @return New netlink message
+ */
+struct nl_msg *rtnl_qdisc_build_change_request(struct rtnl_qdisc *qdisc,
+ struct rtnl_qdisc *new)
+{
+ return qdisc_build(qdisc, RTM_NEWQDISC, NLM_F_REPLACE);
+}
+
+/**
+ * Change attributes of a qdisc
+ * @arg handle netlink handle
+ * @arg qdisc qdisc to change
+ * @arg new new qdisc attributes
+ *
+ * Builds a netlink message by calling rtnl_qdisc_build_change_request(),
+ * sends the request to the kernel and waits for the ACK to be
+ * received and thus blocks until the request has been processed.
+ *
+ * @return 0 on success or a negative error code
+ */
+int rtnl_qdisc_change(struct nl_handle *handle, struct rtnl_qdisc *qdisc,
+ struct rtnl_qdisc *new)
+{
+ struct nl_msg *msg;
+ int err;
+
+ msg = rtnl_qdisc_build_change_request(qdisc, new);
+ if (!msg)
+ return nl_errno(ENOMEM);
+
+ err = nl_send_auto_complete(handle, msg);
+ if (err < 0)
+ return err;
+
+ nlmsg_free(msg);
+ return nl_wait_for_ack(handle);
+}
+
+/** @} */
+
+/**
+ * @name QDisc Deletion
+ * @{
+ */
+
+/**
+ * Build a netlink request message to delete a qdisc
+ * @arg qdisc qdisc to delete
+ *
+ * Builds a new netlink message requesting a deletion of a qdisc.
+ * The netlink message header isn't fully equipped with all relevant
+ * fields and must thus be sent out via nl_send_auto_complete()
+ * or supplemented as needed.
+ *
+ * @return New netlink message
+ */
+struct nl_msg *rtnl_qdisc_build_delete_request(struct rtnl_qdisc *qdisc)
+{
+ struct nl_msg *msg;
+ struct tcmsg tchdr;
+ int required = TCA_ATTR_IFINDEX | TCA_ATTR_PARENT;
+
+ if ((qdisc->ce_mask & required) != required)
+ BUG();
+
+ msg = nlmsg_alloc_simple(RTM_DELQDISC, 0);
+ if (!msg)
+ return NULL;
+
+ tchdr.tcm_family = AF_UNSPEC,
+ tchdr.tcm_handle = qdisc->q_handle,
+ tchdr.tcm_parent = qdisc->q_parent,
+ tchdr.tcm_ifindex = qdisc->q_ifindex,
+ nlmsg_append(msg, &tchdr, sizeof(tchdr), NLMSG_ALIGNTO);
+
+ return msg;
+}
+
+/**
+ * Delete a qdisc
+ * @arg handle netlink handle
+ * @arg qdisc qdisc to delete
+ *
+ * Builds a netlink message by calling rtnl_qdisc_build_delete_request(),
+ * sends the request to the kernel and waits for the ACK to be
+ * received and thus blocks until the request has been processed.
+ *
+ * @return 0 on success or a negative error code
+ */
+int rtnl_qdisc_delete(struct nl_handle *handle, struct rtnl_qdisc *qdisc)
+{
+ struct nl_msg *msg;
+ int err;
+
+ msg = rtnl_qdisc_build_delete_request(qdisc);
+ if (!msg)
+ return nl_errno(ENOMEM);
+
+ err = nl_send_auto_complete(handle, msg);
+ if (err < 0)
+ return err;
+
+ nlmsg_free(msg);
+ return nl_wait_for_ack(handle);
+}
+
+/** @} */
+
+/**
+ * @name Qdisc Cache Management
+ * @{
+ */
+
+/**
+ * Build a qdisc cache including all qdiscs currently configured in
+ * the kernel
+ * @arg handle netlink handle
+ *
+ * Allocates a new cache, initializes it properly and updates it to
+ * include all qdiscs currently configured in the kernel.
+ *
+ * @note The caller is responsible for destroying and freeing the
+ * cache after using it.
+ * @return The cache or NULL if an error has occured.
+ */
+struct nl_cache * rtnl_qdisc_alloc_cache(struct nl_handle *handle)
+{
+ struct nl_cache * cache;
+
+ cache = nl_cache_alloc(&rtnl_qdisc_ops);
+ if (cache == NULL)
+ return NULL;
+
+ if (handle && nl_cache_refill(handle, cache) < 0) {
+ nl_cache_free(cache);
+ return NULL;
+ }
+
+ return cache;
+}
+
+/**
+ * Look up qdisc by its parent in the provided cache
+ * @arg cache qdisc cache
+ * @arg ifindex interface the qdisc is attached to
+ * @arg parent parent handle
+ * @return pointer to qdisc inside the cache or NULL if no match was found.
+ */
+struct rtnl_qdisc * rtnl_qdisc_get_by_parent(struct nl_cache *cache,
+ int ifindex, uint32_t parent)
+{
+ struct rtnl_qdisc *q;
+
+ if (cache->c_ops != &rtnl_qdisc_ops)
+ return NULL;
+
+ nl_list_for_each_entry(q, &cache->c_items, ce_list) {
+ if (q->q_parent == parent && q->q_ifindex == ifindex) {
+ nl_object_get((struct nl_object *) q);
+ return q;
+ }
+ }
+
+ return NULL;
+}
+
+/**
+ * Look up qdisc by its handle in the provided cache
+ * @arg cache qdisc cache
+ * @arg ifindex interface the qdisc is attached to
+ * @arg handle qdisc handle
+ * @return pointer to qdisc inside the cache or NULL if no match was found.
+ */
+struct rtnl_qdisc * rtnl_qdisc_get(struct nl_cache *cache,
+ int ifindex, uint32_t handle)
+{
+ struct rtnl_qdisc *q;
+
+ if (cache->c_ops != &rtnl_qdisc_ops)
+ return NULL;
+
+ nl_list_for_each_entry(q, &cache->c_items, ce_list) {
+ if (q->q_handle == handle && q->q_ifindex == ifindex) {
+ nl_object_get((struct nl_object *) q);
+ return q;
+ }
+ }
+
+ return NULL;
+}
+
+/** @} */
+
+static struct nl_cache_ops rtnl_qdisc_ops = {
+ .co_name = "route/qdisc",
+ .co_hdrsize = sizeof(struct tcmsg),
+ .co_msgtypes = {
+ { RTM_NEWQDISC, NL_ACT_NEW, "new" },
+ { RTM_DELQDISC, NL_ACT_DEL, "del" },
+ { RTM_GETQDISC, NL_ACT_GET, "get" },
+ END_OF_MSGTYPES_LIST,
+ },
+ .co_protocol = NETLINK_ROUTE,
+ .co_request_update = qdisc_request_update,
+ .co_msg_parser = qdisc_msg_parser,
+ .co_obj_ops = &qdisc_obj_ops,
+};
+
+static void __init qdisc_init(void)
+{
+ nl_cache_mngt_register(&rtnl_qdisc_ops);
+}
+
+static void __exit qdisc_exit(void)
+{
+ nl_cache_mngt_unregister(&rtnl_qdisc_ops);
+}
+
+/** @} */
diff --git a/lib/route/qdisc_api.c b/lib/route/qdisc_api.c
new file mode 100644
index 0000000..ef4d07a
--- /dev/null
+++ b/lib/route/qdisc_api.c
@@ -0,0 +1,98 @@
+/*
+ * lib/route/qdisc_api.c Queueing Discipline Module API
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup qdisc
+ * @defgroup qdisc_api Queueing Discipline Modules
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/route/link.h>
+#include <netlink/route/tc.h>
+#include <netlink/route/qdisc.h>
+#include <netlink/route/class.h>
+#include <netlink/route/classifier.h>
+#include <netlink/route/qdisc-modules.h>
+
+static struct rtnl_qdisc_ops *qdisc_ops_list;
+
+/**
+ * @name Module API
+ * @{
+ */
+
+/**
+ * Register a qdisc module
+ * @arg qops qdisc module operations
+ */
+int rtnl_qdisc_register(struct rtnl_qdisc_ops *qops)
+{
+ struct rtnl_qdisc_ops *o, **op;
+
+ if (!qops->qo_kind[0])
+ BUG();
+
+ for (op = &qdisc_ops_list; (o = *op) != NULL; op = &o->qo_next)
+ if (!strcasecmp(qops->qo_kind, o->qo_kind))
+ return nl_errno(EEXIST);
+
+ qops->qo_next = NULL;
+ *op = qops;
+
+ return 0;
+}
+
+/**
+ * Unregister a qdisc module
+ * @arg qops qdisc module operations
+ */
+int rtnl_qdisc_unregister(struct rtnl_qdisc_ops *qops)
+{
+ struct rtnl_qdisc_ops *o, **op;
+
+ for (op = &qdisc_ops_list; (o = *op) != NULL; op = &o->qo_next)
+ if (!strcasecmp(qops->qo_kind, o->qo_kind))
+ break;
+
+ if (!o)
+ return nl_errno(ENOENT);
+
+ *op = qops->qo_next;
+
+ return 0;
+}
+
+struct rtnl_qdisc_ops *__rtnl_qdisc_lookup_ops(const char *kind)
+{
+ struct rtnl_qdisc_ops *qops;
+
+ for (qops = qdisc_ops_list; qops; qops = qops->qo_next)
+ if (!strcmp(kind, qops->qo_kind))
+ return qops;
+
+ return NULL;
+}
+
+struct rtnl_qdisc_ops *rtnl_qdisc_lookup_ops(struct rtnl_qdisc *qdisc)
+{
+ if (!qdisc->q_ops)
+ qdisc->q_ops = __rtnl_qdisc_lookup_ops(qdisc->q_kind);
+
+ return qdisc->q_ops;
+}
+
+/** @} */
+
+/** @} */
diff --git a/lib/route/qdisc_obj.c b/lib/route/qdisc_obj.c
new file mode 100644
index 0000000..bbbb954
--- /dev/null
+++ b/lib/route/qdisc_obj.c
@@ -0,0 +1,273 @@
+/*
+ * lib/route/qdisc_obj.c Queueing Discipline Object
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup qdisc
+ * @defgroup qdisc_obj Queueing Discipline Object
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/route/link.h>
+#include <netlink/route/tc.h>
+#include <netlink/route/qdisc.h>
+#include <netlink/route/class.h>
+#include <netlink/route/classifier.h>
+#include <netlink/route/qdisc-modules.h>
+
+static void qdisc_free_data(struct nl_object *obj)
+{
+ struct rtnl_qdisc *qdisc = (struct rtnl_qdisc *) obj;
+ struct rtnl_qdisc_ops *qops;
+
+ tca_free_data((struct rtnl_tca *) qdisc);
+
+ qops = rtnl_qdisc_lookup_ops(qdisc);
+ if (qops && qops->qo_free_data)
+ qops->qo_free_data(qdisc);
+}
+
+static int qdisc_clone(struct nl_object *_dst, struct nl_object *_src)
+{
+ struct rtnl_qdisc *dst = (struct rtnl_qdisc *) _dst;
+ struct rtnl_qdisc *src = (struct rtnl_qdisc *) _src;
+ struct rtnl_qdisc_ops *qops;
+ int err;
+
+ err = tca_clone((struct rtnl_tca *) dst, (struct rtnl_tca *) src);
+ if (err < 0)
+ goto errout;
+
+ qops = rtnl_qdisc_lookup_ops(src);
+ if (qops && qops->qo_clone)
+ err = qops->qo_clone(dst, src);
+errout:
+ return err;
+}
+
+static int qdisc_dump_brief(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_qdisc *qdisc = (struct rtnl_qdisc *) obj;
+ struct rtnl_qdisc_ops *qops;
+
+ int line = tca_dump_brief((struct rtnl_tca *) qdisc, "qdisc", p, 0);
+
+ qops = rtnl_qdisc_lookup_ops(qdisc);
+ if (qops && qops->qo_dump[NL_DUMP_BRIEF])
+ line = qops->qo_dump[NL_DUMP_BRIEF](qdisc, p, line);
+
+ dp_dump(p, "\n");
+
+ return line;
+}
+
+static int qdisc_dump_full(struct nl_object *arg, struct nl_dump_params *p)
+{
+ struct rtnl_qdisc *qdisc = (struct rtnl_qdisc *) arg;
+ struct rtnl_qdisc_ops *qops;
+
+ int line = qdisc_dump_brief(arg, p);
+
+ line = tca_dump_full((struct rtnl_tca *) qdisc, p, line);
+ dp_dump(p, "refcnt %u ", qdisc->q_info);
+
+ qops = rtnl_qdisc_lookup_ops(qdisc);
+ if (qops && qops->qo_dump[NL_DUMP_FULL])
+ line = qops->qo_dump[NL_DUMP_FULL](qdisc, p, line);
+
+ dp_dump(p, "\n");
+ return line;
+}
+
+static int qdisc_dump_stats(struct nl_object *arg, struct nl_dump_params *p)
+{
+ struct rtnl_qdisc *qdisc = (struct rtnl_qdisc *) arg;
+ struct rtnl_qdisc_ops *qops;
+
+ int line = qdisc_dump_full(arg, p);
+ line = tca_dump_stats((struct rtnl_tca *) qdisc, p, line );
+ dp_dump(p, "\n");
+
+ qops = rtnl_qdisc_lookup_ops(qdisc);
+ if (qops && qops->qo_dump[NL_DUMP_STATS])
+ line = qops->qo_dump[NL_DUMP_STATS](qdisc, p, line);
+
+ return line;
+}
+
+/**
+ * @name Allocation/Freeing
+ * @{
+ */
+
+struct rtnl_qdisc *rtnl_qdisc_alloc(void)
+{
+ return (struct rtnl_qdisc *) nl_object_alloc(&qdisc_obj_ops);
+}
+
+void rtnl_qdisc_put(struct rtnl_qdisc *qdisc)
+{
+ nl_object_put((struct nl_object *) qdisc);
+}
+
+/** @} */
+
+/**
+ * @name Iterators
+ * @{
+ */
+
+/**
+ * Call a callback for each child class of a qdisc
+ * @arg qdisc the parent qdisc
+ * @arg cache a class cache including all classes of the interface
+ * the specified qdisc is attached to
+ * @arg cb callback function
+ * @arg arg argument to be passed to callback function
+ */
+void rtnl_qdisc_foreach_child(struct rtnl_qdisc *qdisc, struct nl_cache *cache,
+ void (*cb)(struct nl_object *, void *), void *arg)
+{
+ struct rtnl_class *filter;
+
+ filter = rtnl_class_alloc();
+ if (!filter)
+ return;
+
+ rtnl_class_set_parent(filter, qdisc->q_handle);
+ rtnl_class_set_ifindex(filter, qdisc->q_ifindex);
+ rtnl_class_set_kind(filter, qdisc->q_kind);
+
+ nl_cache_foreach_filter(cache, (struct nl_object *) filter, cb, arg);
+
+ rtnl_class_put(filter);
+}
+
+/**
+ * Call a callback for each filter attached to the qdisc
+ * @arg qdisc the parent qdisc
+ * @arg cache a filter cache including at least all the filters
+ * attached to the specified qdisc
+ * @arg cb callback function
+ * @arg arg argument to be passed to callback function
+ */
+void rtnl_qdisc_foreach_cls(struct rtnl_qdisc *qdisc, struct nl_cache *cache,
+ void (*cb)(struct nl_object *, void *), void *arg)
+{
+ struct rtnl_cls *filter;
+
+ filter = rtnl_cls_alloc();
+ if (!filter)
+ return;
+
+ rtnl_cls_set_ifindex(filter, qdisc->q_ifindex);
+ rtnl_cls_set_parent(filter, qdisc->q_parent);
+
+ nl_cache_foreach_filter(cache, (struct nl_object *) filter, cb, arg);
+ rtnl_cls_put(filter);
+}
+
+/** @} */
+
+/**
+ * @name Attributes
+ * @{
+ */
+
+void rtnl_qdisc_set_ifindex(struct rtnl_qdisc *qdisc, int ifindex)
+{
+ tca_set_ifindex((struct rtnl_tca *) qdisc, ifindex);
+}
+
+int rtnl_qdisc_get_ifindex(struct rtnl_qdisc *qdisc)
+{
+ return tca_get_ifindex((struct rtnl_tca *) qdisc);
+}
+
+void rtnl_qdisc_set_handle(struct rtnl_qdisc *qdisc, uint32_t handle)
+{
+ tca_set_handle((struct rtnl_tca *) qdisc, handle);
+}
+
+uint32_t rtnl_qdisc_get_handle(struct rtnl_qdisc *qdisc)
+{
+ return tca_get_handle((struct rtnl_tca *) qdisc);
+}
+
+void rtnl_qdisc_set_parent(struct rtnl_qdisc *qdisc, uint32_t parent)
+{
+ tca_set_parent((struct rtnl_tca *) qdisc, parent);
+}
+
+uint32_t rtnl_qdisc_get_parent(struct rtnl_qdisc *qdisc)
+{
+ return tca_get_parent((struct rtnl_tca *) qdisc);
+}
+
+void rtnl_qdisc_set_kind(struct rtnl_qdisc *qdisc, const char *name)
+{
+ tca_set_kind((struct rtnl_tca *) qdisc, name);
+ qdisc->q_ops = __rtnl_qdisc_lookup_ops(name);
+}
+
+char *rtnl_qdisc_get_kind(struct rtnl_qdisc *qdisc)
+{
+ return tca_get_kind((struct rtnl_tca *) qdisc);
+}
+
+uint64_t rtnl_qdisc_get_stat(struct rtnl_qdisc *qdisc,
+ enum rtnl_tc_stats_id id)
+{
+ return tca_get_stat((struct rtnl_tca *) qdisc, id);
+}
+
+/** @} */
+
+/**
+ * @name Qdisc Specific Options
+ * @{
+ */
+
+/**
+ * Return qdisc specific options for use in TCA_OPTIONS
+ * @arg qdisc qdisc carrying the optiosn
+ *
+ * @return new headerless netlink message carrying the options as payload
+ */
+struct nl_msg *rtnl_qdisc_get_opts(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_qdisc_ops *ops;
+
+ ops = rtnl_qdisc_lookup_ops(qdisc);
+ if (ops && ops->qo_get_opts)
+ return ops->qo_get_opts(qdisc);
+
+ return NULL;
+}
+
+/** @} */
+
+struct nl_object_ops qdisc_obj_ops = {
+ .oo_name = "route/qdisc",
+ .oo_size = sizeof(struct rtnl_qdisc),
+ .oo_free_data = qdisc_free_data,
+ .oo_clone = qdisc_clone,
+ .oo_dump[NL_DUMP_BRIEF] = qdisc_dump_brief,
+ .oo_dump[NL_DUMP_FULL] = qdisc_dump_full,
+ .oo_dump[NL_DUMP_STATS] = qdisc_dump_stats,
+ .oo_compare = tca_compare,
+ .oo_id_attrs = (TCA_ATTR_IFINDEX | TCA_ATTR_HANDLE),
+};
+
+/** @} */
diff --git a/lib/route/route.c b/lib/route/route.c
new file mode 100644
index 0000000..4382e19
--- /dev/null
+++ b/lib/route/route.c
@@ -0,0 +1,444 @@
+/*
+ * lib/route/route.c Routes
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup rtnl
+ * @defgroup route Routing
+ * @brief
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/cache.h>
+#include <netlink/utils.h>
+#include <netlink/data.h>
+#include <netlink/route/rtnl.h>
+#include <netlink/route/route.h>
+#include <netlink/route/link.h>
+
+static struct nl_cache_ops rtnl_route_ops;
+
+static struct nla_policy route_policy[RTA_MAX+1] = {
+ [RTA_IIF] = { .type = NLA_STRING,
+ .maxlen = IFNAMSIZ, },
+ [RTA_OIF] = { .type = NLA_U32 },
+ [RTA_PRIORITY] = { .type = NLA_U32 },
+ [RTA_FLOW] = { .type = NLA_U32 },
+ [RTA_MP_ALGO] = { .type = NLA_U32 },
+ [RTA_CACHEINFO] = { .minlen = sizeof(struct rta_cacheinfo) },
+ [RTA_METRICS] = { .type = NLA_NESTED },
+ [RTA_MULTIPATH] = { .type = NLA_NESTED },
+};
+
+static void copy_cacheinfo_into_route(struct rta_cacheinfo *ci,
+ struct rtnl_route *route)
+{
+ struct rtnl_rtcacheinfo nci = {
+ .rtci_clntref = ci->rta_clntref,
+ .rtci_last_use = ci->rta_lastuse,
+ .rtci_expires = ci->rta_expires,
+ .rtci_error = ci->rta_error,
+ .rtci_used = ci->rta_used,
+ .rtci_id = ci->rta_id,
+ .rtci_ts = ci->rta_ts,
+ .rtci_tsage = ci->rta_tsage,
+ };
+
+ rtnl_route_set_cacheinfo(route, &nci);
+}
+
+static int route_msg_parser(struct nl_cache_ops *ops, struct sockaddr_nl *who,
+ struct nlmsghdr *nlh, void *arg)
+{
+ struct nl_parser_param *pp = arg;
+ struct rtmsg *rtm;
+ struct rtnl_route *route;
+ struct nlattr *tb[RTA_MAX + 1];
+ struct nl_addr *src = NULL, *dst = NULL, *addr;
+ int err;
+
+ route = rtnl_route_alloc();
+ if (!route) {
+ err = nl_errno(ENOMEM);
+ goto errout;
+ }
+
+ route->ce_msgtype = nlh->nlmsg_type;
+
+ err = nlmsg_parse(nlh, sizeof(struct rtmsg), tb, RTA_MAX,
+ route_policy);
+ if (err < 0)
+ goto errout;
+
+ rtm = nlmsg_data(nlh);
+ rtnl_route_set_family(route, rtm->rtm_family);
+ rtnl_route_set_tos(route, rtm->rtm_tos);
+ rtnl_route_set_table(route, rtm->rtm_table);
+ rtnl_route_set_type(route, rtm->rtm_type);
+ rtnl_route_set_scope(route, rtm->rtm_scope);
+ rtnl_route_set_protocol(route, rtm->rtm_protocol);
+ rtnl_route_set_flags(route, rtm->rtm_flags);
+
+ if (tb[RTA_DST]) {
+ dst = nla_get_addr(tb[RTA_DST], rtm->rtm_family);
+ if (dst == NULL)
+ goto errout_errno;
+ } else if (rtm->rtm_dst_len)
+ dst = nl_addr_alloc(0);
+
+ if (dst) {
+ nl_addr_set_prefixlen(dst, rtm->rtm_dst_len);
+ rtnl_route_set_dst(route, dst);
+ nl_addr_put(dst);
+ }
+
+ if (tb[RTA_SRC]) {
+ src = nla_get_addr(tb[RTA_SRC], rtm->rtm_family);
+ if (src == NULL)
+ goto errout_errno;
+ } else if (rtm->rtm_src_len)
+ src = nl_addr_alloc(0);
+
+ if (src) {
+ nl_addr_set_prefixlen(src, rtm->rtm_src_len);
+ rtnl_route_set_src(route, src);
+ nl_addr_put(src);
+ }
+
+ if (tb[RTA_IIF])
+ rtnl_route_set_iif(route, nla_get_string(tb[RTA_IIF]));
+
+ if (tb[RTA_OIF])
+ rtnl_route_set_oif(route, nla_get_u32(tb[RTA_OIF]));
+
+ if (tb[RTA_GATEWAY]) {
+ addr = nla_get_addr(tb[RTA_GATEWAY], route->rt_family);
+ if (addr == NULL)
+ goto errout_errno;
+ rtnl_route_set_gateway(route, addr);
+ nl_addr_put(addr);
+ }
+
+ if (tb[RTA_PRIORITY])
+ rtnl_route_set_prio(route, nla_get_u32(tb[RTA_PRIORITY]));
+
+ if (tb[RTA_PREFSRC]) {
+ addr = nla_get_addr(tb[RTA_PREFSRC], route->rt_family);
+ if (addr == NULL)
+ goto errout_errno;
+ rtnl_route_set_pref_src(route, addr);
+ nl_addr_put(addr);
+ }
+
+ if (tb[RTA_METRICS]) {
+ struct nlattr *mtb[RTAX_MAX + 1];
+ int i;
+
+ err = nla_parse_nested(mtb, RTAX_MAX, tb[RTA_METRICS], NULL);
+ if (err < 0)
+ goto errout;
+
+ for (i = 1; i <= RTAX_MAX; i++) {
+ if (mtb[i] && nla_len(mtb[i]) >= sizeof(uint32_t)) {
+ uint32_t m = nla_get_u32(mtb[i]);
+ if (rtnl_route_set_metric(route, i, m) < 0)
+ goto errout_errno;
+ }
+ }
+ }
+
+ if (tb[RTA_MULTIPATH]) {
+ struct rtnl_nexthop *nh;
+ struct rtnexthop *rtnh = nla_data(tb[RTA_MULTIPATH]);
+ size_t tlen = nla_len(tb[RTA_MULTIPATH]);
+
+ while (tlen >= sizeof(*rtnh) && tlen >= rtnh->rtnh_len) {
+ nh = rtnl_route_nh_alloc();
+ if (!nh)
+ goto errout;
+
+ rtnl_route_nh_set_weight(nh, rtnh->rtnh_hops);
+ rtnl_route_nh_set_ifindex(nh, rtnh->rtnh_ifindex);
+ rtnl_route_nh_set_flags(nh, rtnh->rtnh_flags);
+
+ if (rtnh->rtnh_len > sizeof(*rtnh)) {
+ struct nlattr *ntb[RTA_MAX + 1];
+ nla_parse(ntb, RTA_MAX, (struct nlattr *)
+ RTNH_DATA(rtnh),
+ rtnh->rtnh_len - sizeof(*rtnh),
+ route_policy);
+
+ if (ntb[RTA_GATEWAY]) {
+ nh->rtnh_gateway = nla_get_addr(
+ ntb[RTA_GATEWAY],
+ route->rt_family);
+ nh->rtnh_mask = NEXTHOP_HAS_GATEWAY;
+ }
+ }
+
+ rtnl_route_add_nexthop(route, nh);
+ tlen -= RTNH_ALIGN(rtnh->rtnh_len);
+ rtnh = RTNH_NEXT(rtnh);
+ }
+ }
+
+ if (tb[RTA_FLOW])
+ rtnl_route_set_realms(route, nla_get_u32(tb[RTA_FLOW]));
+
+ if (tb[RTA_CACHEINFO])
+ copy_cacheinfo_into_route(nla_data(tb[RTA_CACHEINFO]), route);
+
+ if (tb[RTA_MP_ALGO])
+ rtnl_route_set_mp_algo(route, nla_get_u32(tb[RTA_MP_ALGO]));
+
+ err = pp->pp_cb((struct nl_object *) route, pp);
+ if (err < 0)
+ goto errout;
+
+ return P_ACCEPT;
+
+errout_errno:
+ err = nl_get_errno();
+errout:
+ rtnl_route_put(route);
+ return err;
+
+}
+
+static int route_request_update(struct nl_cache *c, struct nl_handle *h)
+{
+ return nl_rtgen_request(h, RTM_GETROUTE, AF_UNSPEC, NLM_F_DUMP);
+}
+
+/**
+ * @name Cache Management
+ * @{
+ */
+
+/**
+ * Build a route cache holding all routes currently configured in the kernel
+ * @arg handle netlink handle
+ *
+ * Allocates a new cache, initializes it properly and updates it to
+ * contain all routes currently configured in the kernel.
+ *
+ * @note The caller is responsible for destroying and freeing the
+ * cache after using it.
+ * @return The cache or NULL if an error has occured.
+ */
+struct nl_cache *rtnl_route_alloc_cache(struct nl_handle *handle)
+{
+ struct nl_cache *cache;
+
+ cache = nl_cache_alloc(&rtnl_route_ops);
+ if (!cache)
+ return NULL;
+
+ if (handle && nl_cache_refill(handle, cache) < 0) {
+ free(cache);
+ return NULL;
+ }
+
+ return cache;
+}
+
+/** @} */
+
+/**
+ * @name Route Addition
+ * @{
+ */
+
+static struct nl_msg *build_route_msg(struct rtnl_route *tmpl, int cmd,
+ int flags)
+{
+ struct nl_msg *msg;
+ struct nl_addr *addr;
+ int scope, i, oif, nmetrics = 0;
+ struct nlattr *metrics;
+ struct rtmsg rtmsg = {
+ .rtm_family = rtnl_route_get_family(tmpl),
+ .rtm_dst_len = rtnl_route_get_dst_len(tmpl),
+ .rtm_src_len = rtnl_route_get_src_len(tmpl),
+ .rtm_tos = rtnl_route_get_tos(tmpl),
+ .rtm_table = rtnl_route_get_table(tmpl),
+ .rtm_type = rtnl_route_get_type(tmpl),
+ .rtm_protocol = rtnl_route_get_protocol(tmpl),
+ .rtm_flags = rtnl_route_get_flags(tmpl),
+ };
+
+ if (rtmsg.rtm_family == AF_UNSPEC) {
+ nl_error(EINVAL, "Cannot build route message, address " \
+ "family is unknown.");
+ return NULL;
+ }
+
+ scope = rtnl_route_get_scope(tmpl);
+ if (scope == RT_SCOPE_NOWHERE) {
+ if (rtmsg.rtm_type == RTN_LOCAL)
+ scope = RT_SCOPE_HOST;
+ else {
+ /* XXX Change to UNIVERSE if gw || nexthops */
+ scope = RT_SCOPE_LINK;
+ }
+ }
+
+ rtmsg.rtm_scope = scope;
+
+ msg = nlmsg_alloc_simple(cmd, flags);
+ if (msg == NULL)
+ return NULL;
+
+ if (nlmsg_append(msg, &rtmsg, sizeof(rtmsg), NLMSG_ALIGNTO) < 0)
+ goto nla_put_failure;
+
+ addr = rtnl_route_get_dst(tmpl);
+ if (addr)
+ NLA_PUT_ADDR(msg, RTA_DST, addr);
+
+ addr = rtnl_route_get_src(tmpl);
+ if (addr)
+ NLA_PUT_ADDR(msg, RTA_SRC, addr);
+
+ addr = rtnl_route_get_gateway(tmpl);
+ if (addr)
+ NLA_PUT_ADDR(msg, RTA_GATEWAY, addr);
+
+ addr = rtnl_route_get_pref_src(tmpl);
+ if (addr)
+ NLA_PUT_ADDR(msg, RTA_PREFSRC, addr);
+
+ NLA_PUT_U32(msg, RTA_PRIORITY, rtnl_route_get_prio(tmpl));
+
+ oif = rtnl_route_get_oif(tmpl);
+ if (oif != RTNL_LINK_NOT_FOUND)
+ NLA_PUT_U32(msg, RTA_OIF, oif);
+
+ for (i = 1; i <= RTAX_MAX; i++)
+ if (rtnl_route_get_metric(tmpl, i) != UINT_MAX)
+ nmetrics++;
+
+ if (nmetrics > 0) {
+ unsigned int val;
+
+ metrics = nla_nest_start(msg, RTA_METRICS);
+ if (metrics == NULL)
+ goto nla_put_failure;
+
+ for (i = 1; i <= RTAX_MAX; i++) {
+ val = rtnl_route_get_metric(tmpl, i);
+ if (val != UINT_MAX)
+ NLA_PUT_U32(msg, i, val);
+ }
+
+ nla_nest_end(msg, metrics);
+ }
+
+#if 0
+ RTA_IIF,
+ RTA_MULTIPATH,
+ RTA_PROTOINFO,
+ RTA_FLOW,
+ RTA_CACHEINFO,
+ RTA_SESSION,
+ RTA_MP_ALGO,
+#endif
+
+ return msg;
+
+nla_put_failure:
+ nlmsg_free(msg);
+ return NULL;
+}
+
+struct nl_msg *rtnl_route_build_add_request(struct rtnl_route *tmpl, int flags)
+{
+ return build_route_msg(tmpl, RTM_NEWROUTE, NLM_F_CREATE | flags);
+}
+
+int rtnl_route_add(struct nl_handle *handle, struct rtnl_route *route,
+ int flags)
+{
+ struct nl_msg *msg;
+ int err;
+
+ msg = rtnl_route_build_add_request(route, flags);
+ if (!msg)
+ return nl_get_errno();
+
+ err = nl_send_auto_complete(handle, msg);
+ nlmsg_free(msg);
+ if (err < 0)
+ return err;
+
+ return nl_wait_for_ack(handle);
+}
+
+struct nl_msg *rtnl_route_build_del_request(struct rtnl_route *tmpl, int flags)
+{
+ return build_route_msg(tmpl, RTM_DELROUTE, flags);
+}
+
+int rtnl_route_del(struct nl_handle *handle, struct rtnl_route *route,
+ int flags)
+{
+ struct nl_msg *msg;
+ int err;
+
+ msg = rtnl_route_build_del_request(route, flags);
+ if (!msg)
+ return nl_get_errno();
+
+ err = nl_send_auto_complete(handle, msg);
+ nlmsg_free(msg);
+ if (err < 0)
+ return err;
+
+ return nl_wait_for_ack(handle);
+}
+
+/** @} */
+
+static struct nl_af_group route_groups[] = {
+ { AF_INET, RTNLGRP_IPV4_ROUTE },
+ { AF_INET6, RTNLGRP_IPV6_ROUTE },
+ { AF_DECnet, RTNLGRP_DECnet_ROUTE },
+ { END_OF_GROUP_LIST },
+};
+
+static struct nl_cache_ops rtnl_route_ops = {
+ .co_name = "route/route",
+ .co_hdrsize = sizeof(struct rtmsg),
+ .co_msgtypes = {
+ { RTM_NEWROUTE, NL_ACT_NEW, "new" },
+ { RTM_DELROUTE, NL_ACT_DEL, "del" },
+ { RTM_GETROUTE, NL_ACT_GET, "get" },
+ END_OF_MSGTYPES_LIST,
+ },
+ .co_protocol = NETLINK_ROUTE,
+ .co_groups = route_groups,
+ .co_request_update = route_request_update,
+ .co_msg_parser = route_msg_parser,
+ .co_obj_ops = &route_obj_ops,
+};
+
+static void __init route_init(void)
+{
+ nl_cache_mngt_register(&rtnl_route_ops);
+}
+
+static void __exit route_exit(void)
+{
+ nl_cache_mngt_unregister(&rtnl_route_ops);
+}
+
+/** @} */
diff --git a/lib/route/route_obj.c b/lib/route/route_obj.c
new file mode 100644
index 0000000..7d954fc
--- /dev/null
+++ b/lib/route/route_obj.c
@@ -0,0 +1,908 @@
+/*
+ * lib/route/route_obj.c Route Object
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup route
+ * @defgroup route_obj Route Object
+ *
+ * @par Attributes
+ * @code
+ * Name Default
+ * -------------------------------------------------------------
+ * routing table RT_TABLE_MAIN
+ * scope RT_SCOPE_NOWHERE
+ * tos 0
+ * realms 0
+ * protocol RTPROT_STATIC
+ * prio 0
+ * family AF_UNSPEC
+ * type RTN_UNICAST
+ * oif RTNL_LINK_NOT_FOUND
+ * iif NULL
+ * mpalgo IP_MP_ALG_NONE
+ * @endcode
+ *
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/cache.h>
+#include <netlink/utils.h>
+#include <netlink/data.h>
+#include <netlink/route/rtnl.h>
+#include <netlink/route/route.h>
+#include <netlink/route/link.h>
+
+/** @cond SKIP */
+#define ROUTE_ATTR_FAMILY 0x000001
+#define ROUTE_ATTR_TOS 0x000002
+#define ROUTE_ATTR_TABLE 0x000004
+#define ROUTE_ATTR_PROTOCOL 0x000008
+#define ROUTE_ATTR_SCOPE 0x000010
+#define ROUTE_ATTR_TYPE 0x000020
+#define ROUTE_ATTR_FLAGS 0x000040
+#define ROUTE_ATTR_DST 0x000080
+#define ROUTE_ATTR_SRC 0x000100
+#define ROUTE_ATTR_IIF 0x000200
+#define ROUTE_ATTR_OIF 0x000400
+#define ROUTE_ATTR_GATEWAY 0x000800
+#define ROUTE_ATTR_PRIO 0x001000
+#define ROUTE_ATTR_PREF_SRC 0x002000
+#define ROUTE_ATTR_METRICS 0x004000
+#define ROUTE_ATTR_MULTIPATH 0x008000
+#define ROUTE_ATTR_REALMS 0x010000
+#define ROUTE_ATTR_CACHEINFO 0x020000
+#define ROUTE_ATTR_MP_ALGO 0x040000
+/** @endcond */
+
+static int route_dump_brief(struct nl_object *a, struct nl_dump_params *p);
+
+static void route_constructor(struct nl_object *c)
+{
+ struct rtnl_route *r = (struct rtnl_route *) c;
+
+ nl_init_list_head(&r->rt_nexthops);
+}
+
+static void route_free_data(struct nl_object *c)
+{
+ struct rtnl_route *r = (struct rtnl_route *) c;
+ struct rtnl_nexthop *nh, *tmp;
+
+ if (r == NULL)
+ return;
+
+ nl_addr_put(r->rt_dst);
+ nl_addr_put(r->rt_src);
+ nl_addr_put(r->rt_gateway);
+ nl_addr_put(r->rt_pref_src);
+
+ nl_list_for_each_entry_safe(nh, tmp, &r->rt_nexthops, rtnh_list) {
+ rtnl_route_remove_nexthop(nh);
+ rtnl_route_nh_free(nh);
+ }
+}
+
+static int route_clone(struct nl_object *_dst, struct nl_object *_src)
+{
+ struct rtnl_route *dst = (struct rtnl_route *) _dst;
+ struct rtnl_route *src = (struct rtnl_route *) _src;
+ struct rtnl_nexthop *nh, *new;
+
+ if (src->rt_dst)
+ if (!(dst->rt_dst = nl_addr_clone(src->rt_dst)))
+ goto errout;
+
+ if (src->rt_src)
+ if (!(dst->rt_src = nl_addr_clone(src->rt_src)))
+ goto errout;
+
+ if (src->rt_gateway)
+ if (!(dst->rt_gateway = nl_addr_clone(src->rt_gateway)))
+ goto errout;
+
+ if (src->rt_pref_src)
+ if (!(dst->rt_pref_src = nl_addr_clone(src->rt_pref_src)))
+ goto errout;
+
+ nl_init_list_head(&dst->rt_nexthops);
+ nl_list_for_each_entry(nh, &src->rt_nexthops, rtnh_list) {
+ new = rtnl_route_nh_clone(nh);
+ if (!new)
+ goto errout;
+
+ rtnl_route_add_nexthop(dst, new);
+ }
+
+ return 0;
+errout:
+ return nl_get_errno();
+}
+
+static int route_dump_brief(struct nl_object *a, struct nl_dump_params *p)
+{
+ struct rtnl_route *r = (struct rtnl_route *) a;
+ struct nl_cache *link_cache;
+ char buf[64];
+
+ link_cache = nl_cache_mngt_require("route/link");
+
+ if (r->ce_mask & ROUTE_ATTR_DST)
+ dp_dump(p, "%s ", nl_addr2str(r->rt_dst, buf, sizeof(buf)));
+ else
+ dp_dump(p, "default ");
+
+ if (r->ce_mask & ROUTE_ATTR_OIF) {
+ if (link_cache)
+ dp_dump(p, "dev %s ",
+ rtnl_link_i2name(link_cache, r->rt_oif,
+ buf, sizeof(buf)));
+ else
+ dp_dump(p, "dev %d ", r->rt_oif);
+ }
+
+ if (r->ce_mask & ROUTE_ATTR_GATEWAY)
+ dp_dump(p, "via %s ", nl_addr2str(r->rt_gateway, buf,
+ sizeof(buf)));
+ else if (r->ce_mask & ROUTE_ATTR_MULTIPATH)
+ dp_dump(p, "via nexthops ");
+
+ if (r->ce_mask & ROUTE_ATTR_SCOPE)
+ dp_dump(p, "scope %s ",
+ rtnl_scope2str(r->rt_scope, buf, sizeof(buf)));
+
+ if (r->ce_mask & ROUTE_ATTR_FLAGS && r->rt_flags) {
+ int flags = r->rt_flags;
+
+ dp_dump(p, "<");
+
+#define PRINT_FLAG(f) if (flags & RTNH_F_##f) { \
+ flags &= ~RTNH_F_##f; dp_dump(p, #f "%s", flags ? "," : ""); }
+ PRINT_FLAG(DEAD);
+ PRINT_FLAG(ONLINK);
+ PRINT_FLAG(PERVASIVE);
+#undef PRINT_FLAG
+
+#define PRINT_FLAG(f) if (flags & RTM_F_##f) { \
+ flags &= ~RTM_F_##f; dp_dump(p, #f "%s", flags ? "," : ""); }
+ PRINT_FLAG(NOTIFY);
+ PRINT_FLAG(CLONED);
+ PRINT_FLAG(EQUALIZE);
+ PRINT_FLAG(PREFIX);
+#undef PRINT_FLAG
+
+ dp_dump(p, ">");
+ }
+
+ dp_dump(p, "\n");
+
+ return 1;
+}
+
+static int route_dump_full(struct nl_object *a, struct nl_dump_params *p)
+{
+ struct rtnl_route *r = (struct rtnl_route *) a;
+ struct nl_cache *link_cache;
+ char buf[128];
+ int i, line;
+
+ link_cache = nl_cache_mngt_require("route/link");
+ line = route_dump_brief(a, p);
+
+ if (r->ce_mask & ROUTE_ATTR_MULTIPATH) {
+ struct rtnl_nexthop *nh;
+
+ nl_list_for_each_entry(nh, &r->rt_nexthops, rtnh_list) {
+ dp_dump_line(p, line++, " via ");
+
+ if (nh->rtnh_mask & NEXTHOP_HAS_GATEWAY)
+ dp_dump(p, "%s ",
+ nl_addr2str(nh->rtnh_gateway,
+ buf, sizeof(buf)));
+ if (link_cache) {
+ dp_dump(p, "dev %s ",
+ rtnl_link_i2name(link_cache,
+ nh->rtnh_ifindex,
+ buf, sizeof(buf)));
+ } else
+ dp_dump(p, "dev %d ", nh->rtnh_ifindex);
+
+ dp_dump(p, "weight %u <%s>\n", nh->rtnh_weight,
+ rtnl_route_nh_flags2str(nh->rtnh_flags,
+ buf, sizeof(buf)));
+ }
+ }
+
+ dp_dump_line(p, line++, " ");
+
+ if (r->ce_mask & ROUTE_ATTR_PREF_SRC)
+ dp_dump(p, "preferred-src %s ",
+ nl_addr2str(r->rt_pref_src, buf, sizeof(buf)));
+
+ if (r->ce_mask & ROUTE_ATTR_TABLE)
+ dp_dump(p, "table %s ",
+ rtnl_route_table2str(r->rt_table, buf, sizeof(buf)));
+
+ if (r->ce_mask & ROUTE_ATTR_TYPE)
+ dp_dump(p, "type %s ",
+ nl_rtntype2str(r->rt_type, buf, sizeof(buf)));
+
+ if (r->ce_mask & ROUTE_ATTR_PRIO)
+ dp_dump(p, "metric %#x ", r->rt_prio);
+
+ if (r->ce_mask & ROUTE_ATTR_FAMILY)
+ dp_dump(p, "family %s ",
+ nl_af2str(r->rt_family, buf, sizeof(buf)));
+
+ if (r->ce_mask & ROUTE_ATTR_PROTOCOL)
+ dp_dump(p, "protocol %s ",
+ rtnl_route_proto2str(r->rt_protocol, buf, sizeof(buf)));
+
+ dp_dump(p, "\n");
+
+ if ((r->ce_mask & (ROUTE_ATTR_IIF | ROUTE_ATTR_SRC | ROUTE_ATTR_TOS |
+ ROUTE_ATTR_REALMS)) ||
+ ((r->ce_mask & ROUTE_ATTR_CACHEINFO) &&
+ r->rt_cacheinfo.rtci_error)) {
+ dp_dump_line(p, line++, " ");
+
+ if (r->ce_mask & ROUTE_ATTR_IIF)
+ dp_dump(p, "iif %s ", r->rt_iif);
+
+ if (r->ce_mask & ROUTE_ATTR_SRC)
+ dp_dump(p, "src %s ",
+ nl_addr2str(r->rt_src, buf, sizeof(buf)));
+
+ if (r->ce_mask & ROUTE_ATTR_TOS)
+ dp_dump(p, "tos %#x ", r->rt_tos);
+
+ if (r->ce_mask & ROUTE_ATTR_REALMS)
+ dp_dump(p, "realm %04x:%04x ",
+ RTNL_REALM_FROM(r->rt_realms),
+ RTNL_REALM_TO(r->rt_realms));
+
+ if ((r->ce_mask & ROUTE_ATTR_CACHEINFO) &&
+ r->rt_cacheinfo.rtci_error)
+ dp_dump(p, "error %d (%s) ", r->rt_cacheinfo.rtci_error,
+ strerror(-r->rt_cacheinfo.rtci_error));
+
+ dp_dump(p, "\n");
+ }
+
+ if (r->ce_mask & ROUTE_ATTR_METRICS) {
+ dp_dump_line(p, line++, " ");
+ for (i = 0; i < RTAX_MAX; i++)
+ if (r->rt_metrics_mask & (1 << i))
+ dp_dump(p, "%s %u ",
+ rtnl_route_metric2str(i+1,
+ buf, sizeof(buf)),
+ r->rt_metrics[i]);
+ dp_dump(p, "\n");
+ }
+
+ return line;
+}
+
+static int route_dump_stats(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_route *route = (struct rtnl_route *) obj;
+ int line;
+
+ line = route_dump_full(obj, p);
+
+ if (route->ce_mask & ROUTE_ATTR_CACHEINFO) {
+ struct rtnl_rtcacheinfo *ci = &route->rt_cacheinfo;
+ dp_dump_line(p, line++, " used %u refcnt %u ",
+ ci->rtci_used, ci->rtci_clntref);
+ dp_dump_line(p, line++, "last-use %us expires %us\n",
+ ci->rtci_last_use / nl_get_hz(),
+ ci->rtci_expires / nl_get_hz());
+ }
+
+ return line;
+}
+
+static int route_dump_xml(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_route *route = (struct rtnl_route *) obj;
+ char buf[128];
+ int line = 0;
+
+ dp_dump_line(p, line++, "<route>\n");
+ dp_dump_line(p, line++, " <family>%s</family>\n",
+ nl_af2str(route->rt_family, buf, sizeof(buf)));
+
+ if (route->ce_mask & ROUTE_ATTR_DST)
+ dp_dump_line(p, line++, " <dst>%s</dst>\n",
+ nl_addr2str(route->rt_dst, buf, sizeof(buf)));
+
+ if (route->ce_mask & ROUTE_ATTR_SRC)
+ dp_dump_line(p, line++, " <src>%s</src>\n",
+ nl_addr2str(route->rt_src, buf, sizeof(buf)));
+
+ if (route->ce_mask & ROUTE_ATTR_GATEWAY)
+ dp_dump_line(p, line++, " <gateway>%s</gateway>\n",
+ nl_addr2str(route->rt_gateway, buf, sizeof(buf)));
+
+ if (route->ce_mask & ROUTE_ATTR_PREF_SRC)
+ dp_dump_line(p, line++, " <prefsrc>%s</prefsrc>\n",
+ nl_addr2str(route->rt_pref_src, buf, sizeof(buf)));
+
+ if (route->ce_mask & ROUTE_ATTR_IIF)
+ dp_dump_line(p, line++, " <iif>%s</iif>\n", route->rt_iif);
+
+ if (route->ce_mask & ROUTE_ATTR_REALMS)
+ dp_dump_line(p, line++, " <realms>%u</realms>\n",
+ route->rt_realms);
+
+ if (route->ce_mask & ROUTE_ATTR_TOS)
+ dp_dump_line(p, line++, " <tos>%u</tos>\n", route->rt_tos);
+
+ if (route->ce_mask & ROUTE_ATTR_TABLE)
+ dp_dump_line(p, line++, " <table>%u</table>\n",
+ route->rt_table);
+
+ if (route->ce_mask & ROUTE_ATTR_SCOPE)
+ dp_dump_line(p, line++, " <scope>%s</scope>\n",
+ rtnl_scope2str(route->rt_scope, buf, sizeof(buf)));
+
+ if (route->ce_mask & ROUTE_ATTR_PRIO)
+ dp_dump_line(p, line++, " <metric>%u</metric>\n",
+ route->rt_prio);
+
+ if (route->ce_mask & ROUTE_ATTR_OIF) {
+ struct nl_cache *link_cache;
+
+ link_cache = nl_cache_mngt_require("route/link");
+ if (link_cache)
+ dp_dump_line(p, line++, " <oif>%s</oif>\n",
+ rtnl_link_i2name(link_cache,
+ route->rt_oif,
+ buf, sizeof(buf)));
+ else
+ dp_dump_line(p, line++, " <oif>%u</oif>\n",
+ route->rt_oif);
+ }
+
+ if (route->ce_mask & ROUTE_ATTR_TYPE)
+ dp_dump_line(p, line++, " <type>%s</type>\n",
+ nl_rtntype2str(route->rt_type, buf, sizeof(buf)));
+
+ dp_dump_line(p, line++, "</route>\n");
+
+#if 0
+ uint8_t rt_protocol;
+ uint32_t rt_flags;
+ uint32_t rt_metrics[RTAX_MAX];
+ uint32_t rt_metrics_mask;
+ struct rtnl_nexthop * rt_nexthops;
+ struct rtnl_rtcacheinfo rt_cacheinfo;
+ uint32_t rt_mp_algo;
+
+#endif
+
+ return line;
+}
+
+static int route_dump_env(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_route *route = (struct rtnl_route *) obj;
+ char buf[128];
+ int line = 0;
+
+ dp_dump_line(p, line++, "ROUTE_FAMILY=%s\n",
+ nl_af2str(route->rt_family, buf, sizeof(buf)));
+
+ if (route->ce_mask & ROUTE_ATTR_DST)
+ dp_dump_line(p, line++, "ROUTE_DST=%s\n",
+ nl_addr2str(route->rt_dst, buf, sizeof(buf)));
+
+ if (route->ce_mask & ROUTE_ATTR_SRC)
+ dp_dump_line(p, line++, "ROUTE_SRC=%s\n",
+ nl_addr2str(route->rt_src, buf, sizeof(buf)));
+
+ if (route->ce_mask & ROUTE_ATTR_GATEWAY)
+ dp_dump_line(p, line++, "ROUTE_GATEWAY=%s\n",
+ nl_addr2str(route->rt_gateway, buf, sizeof(buf)));
+
+ if (route->ce_mask & ROUTE_ATTR_PREF_SRC)
+ dp_dump_line(p, line++, "ROUTE_PREFSRC=%s\n",
+ nl_addr2str(route->rt_pref_src, buf, sizeof(buf)));
+
+ if (route->ce_mask & ROUTE_ATTR_IIF)
+ dp_dump_line(p, line++, "ROUTE_IIF=%s\n", route->rt_iif);
+
+ if (route->ce_mask & ROUTE_ATTR_REALMS)
+ dp_dump_line(p, line++, "ROUTE_REALM=%u\n",
+ route->rt_realms);
+
+ if (route->ce_mask & ROUTE_ATTR_TOS)
+ dp_dump_line(p, line++, "ROUTE_TOS=%u\n", route->rt_tos);
+
+ if (route->ce_mask & ROUTE_ATTR_TABLE)
+ dp_dump_line(p, line++, "ROUTE_TABLE=%u\n",
+ route->rt_table);
+
+ if (route->ce_mask & ROUTE_ATTR_SCOPE)
+ dp_dump_line(p, line++, "ROUTE_SCOPE=%s\n",
+ rtnl_scope2str(route->rt_scope, buf, sizeof(buf)));
+
+ if (route->ce_mask & ROUTE_ATTR_PRIO)
+ dp_dump_line(p, line++, "ROUTE_METRIC=%u\n",
+ route->rt_prio);
+
+ if (route->ce_mask & ROUTE_ATTR_OIF) {
+ struct nl_cache *link_cache;
+
+ dp_dump_line(p, line++, "ROUTE_OIF_IFINDEX=%u\n",
+ route->rt_oif);
+
+ link_cache = nl_cache_mngt_require("route/link");
+ if (link_cache)
+ dp_dump_line(p, line++, "ROUTE_OIF_IFNAME=%s\n",
+ rtnl_link_i2name(link_cache,
+ route->rt_oif,
+ buf, sizeof(buf)));
+ }
+
+ if (route->ce_mask & ROUTE_ATTR_TYPE)
+ dp_dump_line(p, line++, "ROUTE_TYPE=%s\n",
+ nl_rtntype2str(route->rt_type, buf, sizeof(buf)));
+
+ return line;
+}
+
+static int route_compare(struct nl_object *_a, struct nl_object *_b,
+ uint32_t attrs, int flags)
+{
+ struct rtnl_route *a = (struct rtnl_route *) _a;
+ struct rtnl_route *b = (struct rtnl_route *) _b;
+ int diff = 0;
+
+#define ROUTE_DIFF(ATTR, EXPR) ATTR_DIFF(attrs, ROUTE_ATTR_##ATTR, a, b, EXPR)
+
+ diff |= ROUTE_DIFF(FAMILY, a->rt_family != b->rt_family);
+ diff |= ROUTE_DIFF(TOS, a->rt_tos != b->rt_tos);
+ diff |= ROUTE_DIFF(TABLE, a->rt_table != b->rt_table);
+ diff |= ROUTE_DIFF(PROTOCOL, a->rt_protocol != b->rt_protocol);
+ diff |= ROUTE_DIFF(SCOPE, a->rt_scope != b->rt_scope);
+ diff |= ROUTE_DIFF(TYPE, a->rt_type != b->rt_type);
+ diff |= ROUTE_DIFF(OIF, a->rt_oif != b->rt_oif);
+ diff |= ROUTE_DIFF(PRIO, a->rt_prio != b->rt_prio);
+ diff |= ROUTE_DIFF(REALMS, a->rt_realms != b->rt_realms);
+ diff |= ROUTE_DIFF(MP_ALGO, a->rt_mp_algo != b->rt_mp_algo);
+ diff |= ROUTE_DIFF(DST, nl_addr_cmp(a->rt_dst, b->rt_dst));
+ diff |= ROUTE_DIFF(SRC, nl_addr_cmp(a->rt_src, b->rt_src));
+ diff |= ROUTE_DIFF(IIF, strcmp(a->rt_iif, b->rt_iif));
+ diff |= ROUTE_DIFF(PREF_SRC, nl_addr_cmp(a->rt_pref_src,
+ b->rt_pref_src));
+ diff |= ROUTE_DIFF(GATEWAY, nl_addr_cmp(a->rt_gateway,
+ b->rt_gateway));
+
+ /* FIXME: Compare metrics, multipath config */
+
+ if (flags & LOOSE_FLAG_COMPARISON)
+ diff |= ROUTE_DIFF(FLAGS,
+ (a->rt_flags ^ b->rt_flags) & b->rt_flag_mask);
+ else
+ diff |= ROUTE_DIFF(FLAGS, a->rt_flags != b->rt_flags);
+
+#undef ROUTE_DIFF
+
+ return diff;
+}
+
+static struct trans_tbl route_attrs[] = {
+ __ADD(ROUTE_ATTR_FAMILY, family)
+ __ADD(ROUTE_ATTR_TOS, tos)
+ __ADD(ROUTE_ATTR_TABLE, table)
+ __ADD(ROUTE_ATTR_PROTOCOL, protocol)
+ __ADD(ROUTE_ATTR_SCOPE, scope)
+ __ADD(ROUTE_ATTR_TYPE, type)
+ __ADD(ROUTE_ATTR_FLAGS, flags)
+ __ADD(ROUTE_ATTR_DST, dst)
+ __ADD(ROUTE_ATTR_SRC, src)
+ __ADD(ROUTE_ATTR_IIF, iif)
+ __ADD(ROUTE_ATTR_OIF, oif)
+ __ADD(ROUTE_ATTR_GATEWAY, gateway)
+ __ADD(ROUTE_ATTR_PRIO, prio)
+ __ADD(ROUTE_ATTR_PREF_SRC, pref_src)
+ __ADD(ROUTE_ATTR_METRICS, metrics)
+ __ADD(ROUTE_ATTR_MULTIPATH, multipath)
+ __ADD(ROUTE_ATTR_REALMS, realms)
+ __ADD(ROUTE_ATTR_CACHEINFO, cacheinfo)
+ __ADD(ROUTE_ATTR_MP_ALGO, mp_algo)
+};
+
+static char *route_attrs2str(int attrs, char *buf, size_t len)
+{
+ return __flags2str(attrs, buf, len, route_attrs,
+ ARRAY_SIZE(route_attrs));
+}
+
+/**
+ * @name Allocation/Freeing
+ * @{
+ */
+
+struct rtnl_route *rtnl_route_alloc(void)
+{
+ return (struct rtnl_route *) nl_object_alloc(&route_obj_ops);
+}
+
+void rtnl_route_get(struct rtnl_route *route)
+{
+ nl_object_get((struct nl_object *) route);
+}
+
+void rtnl_route_put(struct rtnl_route *route)
+{
+ nl_object_put((struct nl_object *) route);
+}
+
+/** @} */
+
+/**
+ * @name Attributes
+ * @{
+ */
+
+void rtnl_route_set_table(struct rtnl_route *route, int table)
+{
+ route->rt_table = table;
+ route->ce_mask |= ROUTE_ATTR_TABLE;
+}
+
+int rtnl_route_get_table(struct rtnl_route *route)
+{
+ if (route->ce_mask & ROUTE_ATTR_TABLE)
+ return route->rt_table;
+ else
+ return RT_TABLE_MAIN;
+}
+
+void rtnl_route_set_scope(struct rtnl_route *route, int scope)
+{
+ route->rt_scope = scope;
+ route->ce_mask |= ROUTE_ATTR_SCOPE;
+}
+
+int rtnl_route_get_scope(struct rtnl_route *route)
+{
+ if (route->ce_mask & ROUTE_ATTR_SCOPE)
+ return route->rt_scope;
+ else
+ return RT_SCOPE_NOWHERE;
+}
+
+void rtnl_route_set_tos(struct rtnl_route *route, int tos)
+{
+ route->rt_tos = tos;
+ route->ce_mask |= ROUTE_ATTR_TOS;
+}
+
+int rtnl_route_get_tos(struct rtnl_route *route)
+{
+ return route->rt_tos;
+}
+
+void rtnl_route_set_realms(struct rtnl_route *route, realm_t realms)
+{
+ route->rt_realms = realms;
+ route->ce_mask |= ROUTE_ATTR_REALMS;
+}
+
+realm_t rtnl_route_get_realms(struct rtnl_route *route)
+{
+ return route->rt_realms;
+}
+
+void rtnl_route_set_protocol(struct rtnl_route *route, int proto)
+{
+ route->rt_protocol = proto;
+ route->ce_mask |= ROUTE_ATTR_PROTOCOL;
+}
+
+int rtnl_route_get_protocol(struct rtnl_route *route)
+{
+ if (route->ce_mask & ROUTE_ATTR_PROTOCOL)
+ return route->rt_protocol;
+ else
+ return RTPROT_STATIC;
+}
+
+void rtnl_route_set_prio(struct rtnl_route *route, int prio)
+{
+ route->rt_prio = prio;
+ route->ce_mask |= ROUTE_ATTR_PRIO;
+}
+
+int rtnl_route_get_prio(struct rtnl_route *route)
+{
+ return route->rt_prio;
+}
+
+void rtnl_route_set_family(struct rtnl_route *route, int family)
+{
+ route->rt_family = family;
+ route->ce_mask |= ROUTE_ATTR_FAMILY;
+}
+
+int rtnl_route_get_family(struct rtnl_route *route)
+{
+ if (route->ce_mask & ROUTE_ATTR_FAMILY)
+ return route->rt_family;
+ else
+ return AF_UNSPEC;
+}
+
+int rtnl_route_set_dst(struct rtnl_route *route, struct nl_addr *addr)
+{
+ if (route->ce_mask & ROUTE_ATTR_FAMILY) {
+ if (addr->a_family != route->rt_family)
+ return nl_error(EINVAL, "Address family mismatch");
+ } else
+ route->rt_family = addr->a_family;
+
+ if (route->rt_dst)
+ nl_addr_put(route->rt_dst);
+
+ nl_addr_get(addr);
+ route->rt_dst = addr;
+
+ route->ce_mask |= (ROUTE_ATTR_DST | ROUTE_ATTR_FAMILY);
+
+ return 0;
+}
+
+struct nl_addr *rtnl_route_get_dst(struct rtnl_route *route)
+{
+ return route->rt_dst;
+}
+
+int rtnl_route_get_dst_len(struct rtnl_route *route)
+{
+ if (route->ce_mask & ROUTE_ATTR_DST)
+ return nl_addr_get_prefixlen(route->rt_dst);
+ else
+ return 0;
+}
+
+int rtnl_route_set_src(struct rtnl_route *route, struct nl_addr *addr)
+{
+ if (route->ce_mask & ROUTE_ATTR_FAMILY) {
+ if (addr->a_family != route->rt_family)
+ return nl_error(EINVAL, "Address family mismatch");
+ } else
+ route->rt_family = addr->a_family;
+
+ if (route->rt_src)
+ nl_addr_put(route->rt_src);
+
+ nl_addr_get(addr);
+ route->rt_src = addr;
+ route->ce_mask |= (ROUTE_ATTR_SRC | ROUTE_ATTR_FAMILY);
+
+ return 0;
+}
+
+struct nl_addr *rtnl_route_get_src(struct rtnl_route *route)
+{
+ return route->rt_src;
+}
+
+int rtnl_route_get_src_len(struct rtnl_route *route)
+{
+ if (route->ce_mask & ROUTE_ATTR_SRC)
+ return nl_addr_get_prefixlen(route->rt_src);
+ else
+ return 0;
+}
+
+int rtnl_route_set_gateway(struct rtnl_route *route, struct nl_addr *addr)
+{
+ if (route->ce_mask & ROUTE_ATTR_FAMILY) {
+ if (addr->a_family != route->rt_family)
+ return nl_error(EINVAL, "Address family mismatch");
+ } else
+ route->rt_family = addr->a_family;
+
+ if (route->rt_gateway)
+ nl_addr_put(route->rt_gateway);
+
+ nl_addr_get(addr);
+ route->rt_gateway = addr;
+ route->ce_mask |= (ROUTE_ATTR_GATEWAY | ROUTE_ATTR_FAMILY);
+
+ return 0;
+}
+
+struct nl_addr *rtnl_route_get_gateway(struct rtnl_route *route)
+{
+ return route->rt_gateway;
+}
+
+void rtnl_route_set_type(struct rtnl_route *route, int type)
+{
+ route->rt_type = type;
+ route->ce_mask |= ROUTE_ATTR_TYPE;
+}
+
+int rtnl_route_get_type(struct rtnl_route *route)
+{
+ if (route->ce_mask & ROUTE_ATTR_TYPE)
+ return route->rt_type;
+ else
+ return RTN_UNICAST;
+}
+
+void rtnl_route_set_flags(struct rtnl_route *route, unsigned int flags)
+{
+ route->rt_flag_mask |= flags;
+ route->rt_flags |= flags;
+ route->ce_mask |= ROUTE_ATTR_FLAGS;
+}
+
+void rtnl_route_unset_flags(struct rtnl_route *route, unsigned int flags)
+{
+ route->rt_flag_mask |= flags;
+ route->rt_flags &= ~flags;
+ route->ce_mask |= ROUTE_ATTR_FLAGS;
+}
+
+unsigned int rtnl_route_get_flags(struct rtnl_route *route)
+{
+ return route->rt_flags;
+}
+
+int rtnl_route_set_metric(struct rtnl_route *route, int metric, uint32_t value)
+{
+ if (metric > RTAX_MAX || metric < 1)
+ return nl_error(EINVAL, "Metric out of range (1..%d)",
+ RTAX_MAX);
+
+ route->rt_metrics[metric - 1] = value;
+ route->rt_metrics_mask |= (1 << (metric - 1));
+
+ return 0;
+}
+
+int rtnl_route_unset_metric(struct rtnl_route *route, int metric)
+{
+ if (metric > RTAX_MAX || metric < 1)
+ return nl_error(EINVAL, "Metric out of range (1..%d)",
+ RTAX_MAX);
+
+ route->rt_metrics_mask &= ~(1 << (metric - 1));
+
+ return 0;
+}
+
+unsigned int rtnl_route_get_metric(struct rtnl_route *route, int metric)
+{
+ if (metric > RTAX_MAX || metric < 1)
+ return UINT_MAX;
+
+ if (!(route->rt_metrics_mask & (1 << (metric - 1))))
+ return UINT_MAX;
+
+ return route->rt_metrics[metric - 1];
+}
+
+int rtnl_route_set_pref_src(struct rtnl_route *route, struct nl_addr *addr)
+{
+ if (route->ce_mask & ROUTE_ATTR_FAMILY) {
+ if (addr->a_family != route->rt_family)
+ return nl_error(EINVAL, "Address family mismatch");
+ } else
+ route->rt_family = addr->a_family;
+
+ if (route->rt_pref_src)
+ nl_addr_put(route->rt_pref_src);
+
+ nl_addr_get(addr);
+ route->rt_pref_src = addr;
+ route->ce_mask |= (ROUTE_ATTR_PREF_SRC | ROUTE_ATTR_FAMILY);
+
+ return 0;
+}
+
+struct nl_addr *rtnl_route_get_pref_src(struct rtnl_route *route)
+{
+ return route->rt_pref_src;
+}
+
+void rtnl_route_set_oif(struct rtnl_route *route, int ifindex)
+{
+ route->rt_oif = ifindex;
+ route->ce_mask |= ROUTE_ATTR_OIF;
+}
+
+int rtnl_route_get_oif(struct rtnl_route *route)
+{
+ if (route->ce_mask & ROUTE_ATTR_OIF)
+ return route->rt_oif;
+ else
+ return RTNL_LINK_NOT_FOUND;
+}
+
+void rtnl_route_set_iif(struct rtnl_route *route, const char *name)
+{
+ strncpy(route->rt_iif, name, sizeof(route->rt_iif) - 1);
+ route->ce_mask |= ROUTE_ATTR_IIF;
+}
+
+char *rtnl_route_get_iif(struct rtnl_route *route)
+{
+ if (route->ce_mask & ROUTE_ATTR_IIF)
+ return route->rt_iif;
+ else
+ return NULL;
+}
+
+void rtnl_route_add_nexthop(struct rtnl_route *route, struct rtnl_nexthop *nh)
+{
+ nl_list_add_tail(&nh->rtnh_list, &route->rt_nexthops);
+ route->ce_mask |= ROUTE_ATTR_MULTIPATH;
+}
+
+void rtnl_route_remove_nexthop(struct rtnl_nexthop *nh)
+{
+ nl_list_del(&nh->rtnh_list);
+}
+
+struct nl_list_head *rtnl_route_get_nexthops(struct rtnl_route *route)
+{
+ return &route->rt_nexthops;
+}
+
+void rtnl_route_set_cacheinfo(struct rtnl_route *route,
+ struct rtnl_rtcacheinfo *ci)
+{
+ memcpy(&route->rt_cacheinfo, ci, sizeof(*ci));
+ route->ce_mask |= ROUTE_ATTR_CACHEINFO;
+}
+
+uint32_t rtnl_route_get_mp_algo(struct rtnl_route *route)
+{
+ if (route->ce_mask & ROUTE_ATTR_MP_ALGO)
+ return route->rt_mp_algo;
+ else
+ return IP_MP_ALG_NONE;
+}
+
+void rtnl_route_set_mp_algo(struct rtnl_route *route, uint32_t algo)
+{
+ route->rt_mp_algo = algo;
+ route->ce_mask |= ROUTE_ATTR_MP_ALGO;
+}
+
+/** @} */
+
+struct nl_object_ops route_obj_ops = {
+ .oo_name = "route/route",
+ .oo_size = sizeof(struct rtnl_route),
+ .oo_constructor = route_constructor,
+ .oo_free_data = route_free_data,
+ .oo_clone = route_clone,
+ .oo_dump[NL_DUMP_BRIEF] = route_dump_brief,
+ .oo_dump[NL_DUMP_FULL] = route_dump_full,
+ .oo_dump[NL_DUMP_STATS] = route_dump_stats,
+ .oo_dump[NL_DUMP_XML] = route_dump_xml,
+ .oo_dump[NL_DUMP_ENV] = route_dump_env,
+ .oo_compare = route_compare,
+ .oo_attrs2str = route_attrs2str,
+ .oo_id_attrs = (ROUTE_ATTR_FAMILY | ROUTE_ATTR_TOS |
+ ROUTE_ATTR_TABLE | ROUTE_ATTR_DST),
+};
+
+/** @} */
diff --git a/lib/route/route_utils.c b/lib/route/route_utils.c
new file mode 100644
index 0000000..a12d169
--- /dev/null
+++ b/lib/route/route_utils.c
@@ -0,0 +1,183 @@
+/*
+ * lib/route/route_utils.c Routing Utilities
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup route
+ * @defgroup route_utils Utilities
+ * @brief Routing Utility Functions
+ *
+ *
+ * @par 1) Translating Routing Table Names
+ * @code
+ * // libnl is only aware of the de facto standard routing table names.
+ * // Additional name <-> identifier associations have to be read in via
+ * // a configuration file, f.e. /etc/iproute2/rt_tables
+ * err = rtnl_route_read_table_names("/etc/iproute2/rt_tables");
+ *
+ * // Translating a table name to its idenfier
+ * int table = rtnl_route_str2table("main");
+ *
+ * // ... and the other way around.
+ * char buf[32];
+ * printf("Name: %s\n",
+ * rtnl_route_table2str(table, buf, sizeof(buf)));
+ * @endcode
+ *
+ *
+ *
+ *
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/route/rtnl.h>
+#include <netlink/route/route.h>
+
+/**
+ * @name Routing Table Identifier Translations
+ * @{
+ */
+
+static NL_LIST_HEAD(table_names);
+
+static int add_routing_table_name(long id, const char *name)
+{
+ return __trans_list_add(id, name, &table_names);
+}
+
+static void __init init_routing_table_names(void)
+{
+ add_routing_table_name(RT_TABLE_UNSPEC, "unspec");
+ add_routing_table_name(RT_TABLE_DEFAULT, "default");
+ add_routing_table_name(RT_TABLE_MAIN, "main");
+ add_routing_table_name(RT_TABLE_LOCAL, "local");
+};
+
+int rtnl_route_read_table_names(const char *path)
+{
+ __trans_list_clear(&table_names);
+
+ return __nl_read_num_str_file(path, &add_routing_table_name);
+}
+
+char *rtnl_route_table2str(int table, char *buf, size_t size)
+{
+ return __list_type2str(table, buf, size, &table_names);
+}
+
+int rtnl_route_str2table(const char *name)
+{
+ return __list_str2type(name, &table_names);
+}
+
+
+/** @} */
+
+/**
+ * @name Routing Protocol Translations
+ * @{
+ */
+
+static NL_LIST_HEAD(proto_names);
+
+static int add_proto_name(long id, const char *name)
+{
+ return __trans_list_add(id, name, &proto_names);
+}
+
+static void __init init_proto_names(void)
+{
+ add_proto_name(RTPROT_UNSPEC, "unspec");
+ add_proto_name(RTPROT_REDIRECT, "redirect");
+ add_proto_name(RTPROT_KERNEL, "kernel");
+ add_proto_name(RTPROT_BOOT, "boot");
+ add_proto_name(RTPROT_STATIC, "static");
+};
+
+int rtnl_route_read_protocol_names(const char *path)
+{
+ __trans_list_clear(&proto_names);
+
+ return __nl_read_num_str_file(path, &add_proto_name);
+}
+
+char *rtnl_route_proto2str(int proto, char *buf, size_t size)
+{
+ return __list_type2str(proto, buf, size, &proto_names);
+}
+
+int rtnl_route_str2proto(const char *name)
+{
+ return __list_str2type(name, &proto_names);
+}
+
+/** @} */
+
+/**
+ * @name Routing Metrices Translations
+ * @{
+ */
+
+static struct trans_tbl route_metrices[] = {
+ __ADD(RTAX_UNSPEC, unspec)
+ __ADD(RTAX_LOCK, lock)
+ __ADD(RTAX_MTU, mtu)
+ __ADD(RTAX_WINDOW, window)
+ __ADD(RTAX_RTT, rtt)
+ __ADD(RTAX_RTTVAR, rttvar)
+ __ADD(RTAX_SSTHRESH, ssthresh)
+ __ADD(RTAX_CWND, cwnd)
+ __ADD(RTAX_ADVMSS, advmss)
+ __ADD(RTAX_REORDERING, reordering)
+ __ADD(RTAX_HOPLIMIT, hoplimit)
+ __ADD(RTAX_INITCWND, initcwnd)
+ __ADD(RTAX_FEATURES, features)
+};
+
+char *rtnl_route_metric2str(int metric, char *buf, size_t size)
+{
+ return __type2str(metric, buf, size, route_metrices,
+ ARRAY_SIZE(route_metrices));
+}
+
+int rtnl_route_str2metric(const char *name)
+{
+ return __str2type(name, route_metrices, ARRAY_SIZE(route_metrices));
+}
+
+/** @} */
+
+/**
+ * @name Nexthop Flags Translations
+ * @{
+ */
+
+static struct trans_tbl nh_flags[] = {
+ __ADD(RTNH_F_DEAD, dead)
+ __ADD(RTNH_F_PERVASIVE, pervasive)
+ __ADD(RTNH_F_ONLINK, onlink)
+};
+
+char * rtnl_route_nh_flags2str(int flags, char *buf, size_t len)
+{
+ return __flags2str(flags, buf, len, nh_flags, ARRAY_SIZE(nh_flags));
+}
+
+int rtnl_route_nh_str2flags(const char *name)
+{
+ return __str2flags(name, nh_flags, ARRAY_SIZE(nh_flags));
+}
+
+/** @} */
+
+/** @} */
diff --git a/lib/route/rtnl.c b/lib/route/rtnl.c
new file mode 100644
index 0000000..81ddf94
--- /dev/null
+++ b/lib/route/rtnl.c
@@ -0,0 +1,125 @@
+/*
+ * lib/route/rtnl.c Routing Netlink
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup nlfam
+ * @defgroup rtnl Routing Netlink
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/route/rtnl.h>
+
+/**
+ * @name Sending
+ * @{
+ */
+
+/**
+ * Send routing netlink request message
+ * @arg handle Netlink handle.
+ * @arg type Netlink message type.
+ * @arg family Address family.
+ * @arg flags Additional netlink message flags.
+ *
+ * Fills out a routing netlink request message and sends it out
+ * using nl_send_simple().
+ *
+ * @return 0 on success or a negative error code.
+ */
+int nl_rtgen_request(struct nl_handle *handle, int type, int family, int flags)
+{
+ struct rtgenmsg gmsg = {
+ .rtgen_family = family,
+ };
+
+ return nl_send_simple(handle, type, flags, &gmsg, sizeof(gmsg));
+}
+
+/** @} */
+
+/**
+ * @name Routing Type Translations
+ * @{
+ */
+
+static struct trans_tbl rtntypes[] = {
+ __ADD(RTN_UNSPEC,unspec)
+ __ADD(RTN_UNICAST,unicast)
+ __ADD(RTN_LOCAL,local)
+ __ADD(RTN_BROADCAST,broadcast)
+ __ADD(RTN_ANYCAST,anycast)
+ __ADD(RTN_MULTICAST,multicast)
+ __ADD(RTN_BLACKHOLE,blackhole)
+ __ADD(RTN_UNREACHABLE,unreachable)
+ __ADD(RTN_PROHIBIT,prohibit)
+ __ADD(RTN_THROW,throw)
+ __ADD(RTN_NAT,nat)
+ __ADD(RTN_XRESOLVE,xresolve)
+};
+
+char *nl_rtntype2str(int type, char *buf, size_t size)
+{
+ return __type2str(type, buf, size, rtntypes, ARRAY_SIZE(rtntypes));
+}
+
+int nl_str2rtntype(const char *name)
+{
+ return __str2type(name, rtntypes, ARRAY_SIZE(rtntypes));
+}
+
+/** @} */
+
+/**
+ * @name Scope Translations
+ * @{
+ */
+
+static struct trans_tbl scopes[] = {
+ __ADD(255,nowhere)
+ __ADD(254,host)
+ __ADD(253,link)
+ __ADD(200,site)
+ __ADD(0,universe)
+};
+
+char *rtnl_scope2str(int scope, char *buf, size_t size)
+{
+ return __type2str(scope, buf, size, scopes, ARRAY_SIZE(scopes));
+}
+
+int rtnl_str2scope(const char *name)
+{
+ return __str2type(name, scopes, ARRAY_SIZE(scopes));
+}
+
+/** @} */
+
+/**
+ * @name Realms Translations
+ * @{
+ */
+
+char * rtnl_realms2str(uint32_t realms, char *buf, size_t len)
+{
+ int from = RTNL_REALM_FROM(realms);
+ int to = RTNL_REALM_TO(realms);
+
+ snprintf(buf, len, "%d/%d", from, to);
+
+ return buf;
+}
+
+/** @} */
+
+/** @} */
diff --git a/lib/route/rule.c b/lib/route/rule.c
new file mode 100644
index 0000000..76e0060
--- /dev/null
+++ b/lib/route/rule.c
@@ -0,0 +1,900 @@
+/*
+ * lib/route/rule.c Routing Rules
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup rtnl
+ * @defgroup rule Routing Rules
+ * @brief
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/route/rtnl.h>
+#include <netlink/route/rule.h>
+#include <inttypes.h>
+
+/** @cond SKIP */
+#define RULE_ATTR_FAMILY 0x0001
+#define RULE_ATTR_PRIO 0x0002
+#define RULE_ATTR_MARK 0x0004
+#define RULE_ATTR_IIF 0x0008
+#define RULE_ATTR_REALMS 0x0010
+#define RULE_ATTR_SRC 0x0020
+#define RULE_ATTR_DST 0x0040
+#define RULE_ATTR_DSFIELD 0x0080
+#define RULE_ATTR_TABLE 0x0100
+#define RULE_ATTR_TYPE 0x0200
+#define RULE_ATTR_SRC_LEN 0x0400
+#define RULE_ATTR_DST_LEN 0x0800
+#define RULE_ATTR_SRCMAP 0x1000
+
+static struct nl_cache_ops rtnl_rule_ops;
+static struct nl_object_ops rule_obj_ops;
+/** @endcond */
+
+static void rule_free_data(struct nl_object *c)
+{
+ struct rtnl_rule *rule = nl_object_priv(c);
+
+ if (!rule)
+ return;
+
+ nl_addr_put(rule->r_src);
+ nl_addr_put(rule->r_dst);
+}
+
+static int rule_clone(struct nl_object *_dst, struct nl_object *_src)
+{
+ struct rtnl_rule *dst = nl_object_priv(_dst);
+ struct rtnl_rule *src = nl_object_priv(_src);
+
+ if (src->r_src)
+ if (!(dst->r_src = nl_addr_clone(src->r_src)))
+ goto errout;
+
+ if (src->r_dst)
+ if (!(dst->r_dst = nl_addr_clone(src->r_dst)))
+ goto errout;
+
+ return 0;
+errout:
+ return nl_get_errno();
+}
+
+static struct nla_policy rule_policy[RTA_MAX+1] = {
+ [RTA_PRIORITY] = { .type = NLA_U32 },
+ [RTA_FLOW] = { .type = NLA_U32 },
+ [RTA_PROTOINFO] = { .type = NLA_U32 },
+ [RTA_IIF] = { .type = NLA_STRING,
+ .maxlen = IFNAMSIZ, },
+};
+
+static int rule_msg_parser(struct nl_cache_ops *ops, struct sockaddr_nl *who,
+ struct nlmsghdr *n, void *arg)
+{
+ struct rtnl_rule *rule;
+ struct rtmsg *r;
+ struct nlattr *tb[RTA_MAX+1];
+ struct nl_parser_param *pp = arg;
+ int err = 1;
+
+ rule = rtnl_rule_alloc();
+ if (!rule) {
+ err = nl_errno(ENOMEM);
+ goto errout;
+ }
+
+ rule->ce_msgtype = n->nlmsg_type;
+ r = nlmsg_data(n);
+
+ err = nlmsg_parse(n, sizeof(*r), tb, RTA_MAX, rule_policy);
+ if (err < 0)
+ goto errout;
+
+ rule->r_family = r->rtm_family;
+ rule->r_type = r->rtm_type;
+ rule->r_dsfield = r->rtm_tos;
+ rule->r_src_len = r->rtm_src_len;
+ rule->r_dst_len = r->rtm_dst_len;
+ rule->r_table = r->rtm_table;
+ rule->ce_mask = (RULE_ATTR_FAMILY | RULE_ATTR_TYPE | RULE_ATTR_DSFIELD |
+ RULE_ATTR_SRC_LEN | RULE_ATTR_DST_LEN |RULE_ATTR_TYPE);
+
+ if (tb[RTA_PRIORITY]) {
+ rule->r_prio = nla_get_u32(tb[RTA_PRIORITY]);
+ rule->ce_mask |= RULE_ATTR_PRIO;
+ }
+
+ if (tb[RTA_SRC]) {
+ rule->r_src = nla_get_addr(tb[RTA_SRC], r->rtm_family);
+ if (!rule->r_src) {
+ err = nl_errno(ENOMEM);
+ goto errout;
+ }
+ nl_addr_set_prefixlen(rule->r_src, r->rtm_src_len);
+ rule->ce_mask |= RULE_ATTR_SRC;
+ }
+
+ if (tb[RTA_DST]) {
+ rule->r_dst = nla_get_addr(tb[RTA_DST], r->rtm_family);
+ if (!rule->r_dst) {
+ err = nl_errno(ENOMEM);
+ goto errout;
+ }
+ nl_addr_set_prefixlen(rule->r_dst, r->rtm_dst_len);
+ rule->ce_mask |= RULE_ATTR_DST;
+ }
+
+ if (tb[RTA_PROTOINFO]) {
+ rule->r_mark = nla_get_u32(tb[RTA_PROTOINFO]);
+ rule->ce_mask |= RULE_ATTR_MARK;
+ }
+
+ if (tb[RTA_IIF]) {
+ nla_strlcpy(rule->r_iif, tb[RTA_IIF], IFNAMSIZ);
+ rule->ce_mask |= RULE_ATTR_IIF;
+ }
+
+ if (tb[RTA_FLOW]) {
+ rule->r_realms = nla_get_u32(tb[RTA_FLOW]);
+ rule->ce_mask |= RULE_ATTR_REALMS;
+ }
+
+ if (tb[RTA_GATEWAY]) {
+ rule->r_srcmap = nla_get_addr(tb[RTA_GATEWAY], r->rtm_family);
+ if (!rule->r_srcmap) {
+ err = nl_errno(ENOMEM);
+ goto errout;
+ }
+ rule->ce_mask |= RULE_ATTR_SRCMAP;
+ }
+
+ err = pp->pp_cb((struct nl_object *) rule, pp);
+ if (err < 0)
+ goto errout;
+
+ return P_ACCEPT;
+
+errout:
+ rtnl_rule_put(rule);
+ return err;
+}
+
+static int rule_request_update(struct nl_cache *c, struct nl_handle *h)
+{
+ return nl_rtgen_request(h, RTM_GETRULE, AF_UNSPEC, NLM_F_DUMP);
+}
+
+static int rule_dump_brief(struct nl_object *o, struct nl_dump_params *p)
+{
+ struct rtnl_rule *r = (struct rtnl_rule *) o;
+ char buf[128];
+
+ if (r->ce_mask & RULE_ATTR_PRIO)
+ dp_dump(p, "%d:\t", r->r_prio);
+ else
+ dp_dump(p, "0:\t");
+
+ if (r->ce_mask & RULE_ATTR_SRC)
+ dp_dump(p, "from %s ",
+ nl_addr2str(r->r_src, buf, sizeof(buf)));
+ else if (r->ce_mask & RULE_ATTR_SRC_LEN && r->r_src_len)
+ dp_dump(p, "from 0/%d ", r->r_src_len);
+
+ if (r->ce_mask & RULE_ATTR_DST)
+ dp_dump(p, "to %s ",
+ nl_addr2str(r->r_dst, buf, sizeof(buf)));
+ else if (r->ce_mask & RULE_ATTR_DST_LEN && r->r_dst_len)
+ dp_dump(p, "to 0/%d ", r->r_dst_len);
+
+ if (r->ce_mask & RULE_ATTR_DSFIELD && r->r_dsfield)
+ dp_dump(p, "tos %d ", r->r_dsfield);
+
+ if (r->ce_mask & RULE_ATTR_MARK)
+ dp_dump(p, "mark %" PRIx64 , r->r_mark);
+
+ if (r->ce_mask & RULE_ATTR_IIF)
+ dp_dump(p, "iif %s ", r->r_iif);
+
+ if (r->ce_mask & RULE_ATTR_TABLE)
+ dp_dump(p, "lookup %s ",
+ rtnl_route_table2str(r->r_table, buf, sizeof(buf)));
+
+ if (r->ce_mask & RULE_ATTR_REALMS)
+ dp_dump(p, "realms %s ",
+ rtnl_realms2str(r->r_realms, buf, sizeof(buf)));
+
+ dp_dump(p, "action %s\n",
+ nl_rtntype2str(r->r_type, buf, sizeof(buf)));
+
+ return 1;
+}
+
+static int rule_dump_full(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_rule *rule = (struct rtnl_rule *) obj;
+ char buf[128];
+ int line;
+
+ line = rule_dump_brief(obj, p);
+
+ dp_dump_line(p, line++, " family %s",
+ nl_af2str(rule->r_family, buf, sizeof(buf)));
+
+ if (rule->ce_mask & RULE_ATTR_SRCMAP)
+ dp_dump(p, " srcmap %s",
+ nl_addr2str(rule->r_srcmap, buf, sizeof(buf)));
+
+ dp_dump(p, "\n");
+
+ return line;
+}
+
+static int rule_dump_stats(struct nl_object *obj, struct nl_dump_params *p)
+{
+ return rule_dump_full(obj, p);
+}
+
+static int rule_dump_xml(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_rule *rule = (struct rtnl_rule *) obj;
+ char buf[128];
+ int line = 0;
+
+ dp_dump_line(p, line++, "<rule>\n");
+
+ dp_dump_line(p, line++, " <priority>%u</priority>\n",
+ rule->r_prio);
+ dp_dump_line(p, line++, " <family>%s</family>\n",
+ nl_af2str(rule->r_family, buf, sizeof(buf)));
+
+ if (rule->ce_mask & RULE_ATTR_DST)
+ dp_dump_line(p, line++, " <dst>%s</dst>\n",
+ nl_addr2str(rule->r_dst, buf, sizeof(buf)));
+
+ if (rule->ce_mask & RULE_ATTR_DST_LEN)
+ dp_dump_line(p, line++, " <dstlen>%u</dstlen>\n",
+ rule->r_dst_len);
+
+ if (rule->ce_mask & RULE_ATTR_SRC)
+ dp_dump_line(p, line++, " <src>%s</src>\n",
+ nl_addr2str(rule->r_src, buf, sizeof(buf)));
+
+ if (rule->ce_mask & RULE_ATTR_SRC_LEN)
+ dp_dump_line(p, line++, " <srclen>%u</srclen>\n",
+ rule->r_src_len);
+
+ if (rule->ce_mask & RULE_ATTR_IIF)
+ dp_dump_line(p, line++, " <iif>%s</iif>\n", rule->r_iif);
+
+ if (rule->ce_mask & RULE_ATTR_TABLE)
+ dp_dump_line(p, line++, " <table>%u</table>\n",
+ rule->r_table);
+
+ if (rule->ce_mask & RULE_ATTR_REALMS)
+ dp_dump_line(p, line++, " <realms>%u</realms>\n",
+ rule->r_realms);
+
+ if (rule->ce_mask & RULE_ATTR_MARK)
+ dp_dump_line(p, line++, " <mark>%" PRIx64 "</mark>\n",
+ rule->r_mark);
+
+ if (rule->ce_mask & RULE_ATTR_DSFIELD)
+ dp_dump_line(p, line++, " <dsfield>%u</dsfield>\n",
+ rule->r_dsfield);
+
+ if (rule->ce_mask & RULE_ATTR_TYPE)
+ dp_dump_line(p, line++, "<type>%s</type>\n",
+ nl_rtntype2str(rule->r_type, buf, sizeof(buf)));
+
+ if (rule->ce_mask & RULE_ATTR_SRCMAP)
+ dp_dump_line(p, line++, "<srcmap>%s</srcmap>\n",
+ nl_addr2str(rule->r_srcmap, buf, sizeof(buf)));
+
+ dp_dump_line(p, line++, "</rule>\n");
+
+ return line;
+}
+
+static int rule_dump_env(struct nl_object *obj, struct nl_dump_params *p)
+{
+ struct rtnl_rule *rule = (struct rtnl_rule *) obj;
+ char buf[128];
+ int line = 0;
+
+ dp_dump_line(p, line++, "RULE_PRIORITY=%u\n",
+ rule->r_prio);
+ dp_dump_line(p, line++, "RULE_FAMILY=%s\n",
+ nl_af2str(rule->r_family, buf, sizeof(buf)));
+
+ if (rule->ce_mask & RULE_ATTR_DST)
+ dp_dump_line(p, line++, "RULE_DST=%s\n",
+ nl_addr2str(rule->r_dst, buf, sizeof(buf)));
+
+ if (rule->ce_mask & RULE_ATTR_DST_LEN)
+ dp_dump_line(p, line++, "RULE_DSTLEN=%u\n",
+ rule->r_dst_len);
+
+ if (rule->ce_mask & RULE_ATTR_SRC)
+ dp_dump_line(p, line++, "RULE_SRC=%s\n",
+ nl_addr2str(rule->r_src, buf, sizeof(buf)));
+
+ if (rule->ce_mask & RULE_ATTR_SRC_LEN)
+ dp_dump_line(p, line++, "RULE_SRCLEN=%u\n",
+ rule->r_src_len);
+
+ if (rule->ce_mask & RULE_ATTR_IIF)
+ dp_dump_line(p, line++, "RULE_IIF=%s\n", rule->r_iif);
+
+ if (rule->ce_mask & RULE_ATTR_TABLE)
+ dp_dump_line(p, line++, "RULE_TABLE=%u\n",
+ rule->r_table);
+
+ if (rule->ce_mask & RULE_ATTR_REALMS)
+ dp_dump_line(p, line++, "RULE_REALM=%u\n",
+ rule->r_realms);
+
+ if (rule->ce_mask & RULE_ATTR_MARK)
+ dp_dump_line(p, line++, "RULE_MARK=0x%" PRIx64 "\n",
+ rule->r_mark);
+
+ if (rule->ce_mask & RULE_ATTR_DSFIELD)
+ dp_dump_line(p, line++, "RULE_DSFIELD=%u\n",
+ rule->r_dsfield);
+
+ if (rule->ce_mask & RULE_ATTR_TYPE)
+ dp_dump_line(p, line++, "RULE_TYPE=%s\n",
+ nl_rtntype2str(rule->r_type, buf, sizeof(buf)));
+
+ if (rule->ce_mask & RULE_ATTR_SRCMAP)
+ dp_dump_line(p, line++, "RULE_SRCMAP=%s\n",
+ nl_addr2str(rule->r_srcmap, buf, sizeof(buf)));
+
+ return line;
+}
+
+static int rule_compare(struct nl_object *_a, struct nl_object *_b,
+ uint32_t attrs, int flags)
+{
+ struct rtnl_rule *a = (struct rtnl_rule *) _a;
+ struct rtnl_rule *b = (struct rtnl_rule *) _b;
+ int diff = 0;
+
+#define RULE_DIFF(ATTR, EXPR) ATTR_DIFF(attrs, RULE_ATTR_##ATTR, a, b, EXPR)
+
+ diff |= RULE_DIFF(FAMILY, a->r_family != b->r_family);
+ diff |= RULE_DIFF(TABLE, a->r_table != b->r_table);
+ diff |= RULE_DIFF(REALMS, a->r_realms != b->r_realms);
+ diff |= RULE_DIFF(DSFIELD, a->r_dsfield != b->r_dsfield);
+ diff |= RULE_DIFF(TYPE, a->r_type != b->r_type);
+ diff |= RULE_DIFF(PRIO, a->r_prio != b->r_prio);
+ diff |= RULE_DIFF(MARK, a->r_mark != b->r_mark);
+ diff |= RULE_DIFF(SRC_LEN, a->r_src_len != b->r_src_len);
+ diff |= RULE_DIFF(DST_LEN, a->r_dst_len != b->r_dst_len);
+ diff |= RULE_DIFF(SRC, nl_addr_cmp(a->r_src, b->r_src));
+ diff |= RULE_DIFF(DST, nl_addr_cmp(a->r_dst, b->r_dst));
+ diff |= RULE_DIFF(IIF, strcmp(a->r_iif, b->r_iif));
+
+#undef RULE_DIFF
+
+ return diff;
+}
+
+static struct trans_tbl rule_attrs[] = {
+ __ADD(RULE_ATTR_FAMILY, family)
+ __ADD(RULE_ATTR_PRIO, prio)
+ __ADD(RULE_ATTR_MARK, mark)
+ __ADD(RULE_ATTR_IIF, iif)
+ __ADD(RULE_ATTR_REALMS, realms)
+ __ADD(RULE_ATTR_SRC, src)
+ __ADD(RULE_ATTR_DST, dst)
+ __ADD(RULE_ATTR_DSFIELD, dsfield)
+ __ADD(RULE_ATTR_TABLE, table)
+ __ADD(RULE_ATTR_TYPE, type)
+ __ADD(RULE_ATTR_SRC_LEN, src_len)
+ __ADD(RULE_ATTR_DST_LEN, dst_len)
+ __ADD(RULE_ATTR_SRCMAP, srcmap)
+};
+
+static char *rule_attrs2str(int attrs, char *buf, size_t len)
+{
+ return __flags2str(attrs, buf, len, rule_attrs,
+ ARRAY_SIZE(rule_attrs));
+}
+
+/**
+ * @name Allocation/Freeing
+ * @{
+ */
+
+struct rtnl_rule *rtnl_rule_alloc(void)
+{
+ return (struct rtnl_rule *) nl_object_alloc(&rule_obj_ops);
+}
+
+void rtnl_rule_put(struct rtnl_rule *rule)
+{
+ nl_object_put((struct nl_object *) rule);
+}
+
+/** @} */
+
+/**
+ * @name Cache Management
+ * @{
+ */
+
+/**
+ * Build a rule cache including all rules of the specified family currently configured in the kernel.
+ * @arg handle netlink handle
+ * @arg family address family
+ *
+ * Allocates a new rule cache, initializes it properly and updates it
+ * to include all rules of the specified address family currently
+ * configured in the kernel.
+ *
+ * @note The caller is responsible for destroying and freeing the
+ * cache after using it. (nl_cache_destroy_and_free())
+ * @return The new cache or NULL if an error occured.
+ */
+struct nl_cache * rtnl_rule_alloc_cache_by_family(struct nl_handle *handle,
+ int family)
+{
+ struct nl_cache * cache;
+
+ cache = nl_cache_alloc(&rtnl_rule_ops);
+ if (cache == NULL)
+ return NULL;
+
+ /* XXX RULE_CACHE_FAMILY(cache) = family; */
+
+ if (handle && nl_cache_refill(handle, cache) < 0) {
+ free(cache);
+ return NULL;
+ }
+
+ return cache;
+}
+
+/**
+ * Build a rule cache including all rules currently configured in the kernel.
+ * @arg handle netlink handle
+ *
+ * Allocates a new rule cache, initializes it properly and updates it
+ * to include all rules currently configured in the kernel.
+ *
+ * @note The caller is responsible for destroying and freeing the
+ * cache after using it. (nl_cache_destroy_and_free())
+ * @return The new cache or NULL if an error occured.
+ */
+struct nl_cache * rtnl_rule_alloc_cache(struct nl_handle *handle)
+{
+ return rtnl_rule_alloc_cache_by_family(handle, AF_UNSPEC);
+}
+
+/** @} */
+
+/**
+ * @name Rule Addition
+ * @{
+ */
+
+static struct nl_msg *build_rule_msg(struct rtnl_rule *tmpl, int cmd, int flags)
+{
+ struct nl_msg *msg;
+ struct rtmsg rtm = {
+ .rtm_type = RTN_UNSPEC
+ };
+
+ if (cmd == RTM_NEWRULE)
+ rtm.rtm_type = RTN_UNICAST;
+
+ if (tmpl->ce_mask & RULE_ATTR_FAMILY)
+ rtm.rtm_family = tmpl->r_family;
+
+ if (tmpl->ce_mask & RULE_ATTR_TABLE)
+ rtm.rtm_table = tmpl->r_table;
+
+ if (tmpl->ce_mask & RULE_ATTR_DSFIELD)
+ rtm.rtm_tos = tmpl->r_dsfield;
+
+ if (tmpl->ce_mask & RULE_ATTR_TYPE)
+ rtm.rtm_type = tmpl->r_type;
+
+ if (tmpl->ce_mask & RULE_ATTR_SRC_LEN)
+ rtm.rtm_src_len = tmpl->r_src_len;
+
+ if (tmpl->ce_mask & RULE_ATTR_DST_LEN)
+ rtm.rtm_dst_len = tmpl->r_dst_len;
+
+ msg = nlmsg_alloc_simple(cmd, flags);
+ if (!msg)
+ goto nla_put_failure;
+
+ if (nlmsg_append(msg, &rtm, sizeof(rtm), NLMSG_ALIGNTO) < 0)
+ goto nla_put_failure;
+
+ if (tmpl->ce_mask & RULE_ATTR_SRC)
+ NLA_PUT_ADDR(msg, RTA_SRC, tmpl->r_src);
+
+ if (tmpl->ce_mask & RULE_ATTR_DST)
+ NLA_PUT_ADDR(msg, RTA_DST, tmpl->r_dst);
+
+ if (tmpl->ce_mask & RULE_ATTR_PRIO)
+ NLA_PUT_U32(msg, RTA_PRIORITY, tmpl->r_prio);
+
+ if (tmpl->ce_mask & RULE_ATTR_MARK)
+ NLA_PUT_U32(msg, RTA_PROTOINFO, tmpl->r_mark);
+
+ if (tmpl->ce_mask & RULE_ATTR_REALMS)
+ NLA_PUT_U32(msg, RTA_FLOW, tmpl->r_realms);
+
+ if (tmpl->ce_mask & RULE_ATTR_IIF)
+ NLA_PUT_STRING(msg, RTA_IIF, tmpl->r_iif);
+
+ return msg;
+
+nla_put_failure:
+ nlmsg_free(msg);
+ return NULL;
+}
+
+/**
+ * Build netlink request message to add a new rule
+ * @arg tmpl template with data of new rule
+ * @arg flags additional netlink message flags
+ *
+ * Builds a new netlink message requesting a addition of a new
+ * rule. The netlink message header isn't fully equipped with
+ * all relevant fields and must thus be sent out via nl_send_auto_complete()
+ * or supplemented as needed. \a tmpl must contain the attributes of the new
+ * address set via \c rtnl_rule_set_* functions.
+ *
+ * @return The netlink message
+ */
+struct nl_msg *rtnl_rule_build_add_request(struct rtnl_rule *tmpl, int flags)
+{
+ return build_rule_msg(tmpl, RTM_NEWRULE, NLM_F_CREATE | flags);
+}
+
+/**
+ * Add a new rule
+ * @arg handle netlink handle
+ * @arg tmpl template with requested changes
+ * @arg flags additional netlink message flags
+ *
+ * Builds a netlink message by calling rtnl_rule_build_add_request(),
+ * sends the request to the kernel and waits for the next ACK to be
+ * received and thus blocks until the request has been fullfilled.
+ *
+ * @return 0 on sucess or a negative error if an error occured.
+ */
+int rtnl_rule_add(struct nl_handle *handle, struct rtnl_rule *tmpl, int flags)
+{
+ int err;
+ struct nl_msg *msg;
+
+ msg = rtnl_rule_build_add_request(tmpl, flags);
+ if (!msg)
+ return nl_errno(ENOMEM);
+
+ err = nl_send_auto_complete(handle, msg);
+ if (err < 0)
+ return err;
+
+ nlmsg_free(msg);
+ return nl_wait_for_ack(handle);
+}
+
+/** @} */
+
+/**
+ * @name Rule Deletion
+ * @{
+ */
+
+/**
+ * Build a netlink request message to delete a rule
+ * @arg rule rule to delete
+ * @arg flags additional netlink message flags
+ *
+ * Builds a new netlink message requesting a deletion of a rule.
+ * The netlink message header isn't fully equipped with all relevant
+ * fields and must thus be sent out via nl_send_auto_complete()
+ * or supplemented as needed. \a rule must point to an existing
+ * address.
+ *
+ * @return The netlink message
+ */
+struct nl_msg *rtnl_rule_build_delete_request(struct rtnl_rule *rule, int flags)
+{
+ return build_rule_msg(rule, RTM_DELRULE, flags);
+}
+
+/**
+ * Delete a rule
+ * @arg handle netlink handle
+ * @arg rule rule to delete
+ * @arg flags additional netlink message flags
+ *
+ * Builds a netlink message by calling rtnl_rule_build_delete_request(),
+ * sends the request to the kernel and waits for the next ACK to be
+ * received and thus blocks until the request has been fullfilled.
+ *
+ * @return 0 on sucess or a negative error if an error occured.
+ */
+int rtnl_rule_delete(struct nl_handle *handle, struct rtnl_rule *rule,
+ int flags)
+{
+ int err;
+ struct nl_msg *msg;
+
+ msg = rtnl_rule_build_delete_request(rule, flags);
+ if (!msg)
+ return nl_errno(ENOMEM);
+
+ err = nl_send_auto_complete(handle, msg);
+ if (err < 0)
+ return err;
+
+ nlmsg_free(msg);
+ return nl_wait_for_ack(handle);
+}
+
+/** @} */
+
+/**
+ * @name Attribute Modification
+ * @{
+ */
+
+void rtnl_rule_set_family(struct rtnl_rule *rule, int family)
+{
+ rule->r_family = family;
+ rule->ce_mask |= RULE_ATTR_FAMILY;
+}
+
+int rtnl_rule_get_family(struct rtnl_rule *rule)
+{
+ if (rule->ce_mask & RULE_ATTR_FAMILY)
+ return rule->r_family;
+ else
+ return AF_UNSPEC;
+}
+
+void rtnl_rule_set_prio(struct rtnl_rule *rule, int prio)
+{
+ rule->r_prio = prio;
+ rule->ce_mask |= RULE_ATTR_PRIO;
+}
+
+int rtnl_rule_get_prio(struct rtnl_rule *rule)
+{
+ if (rule->ce_mask & RULE_ATTR_PRIO)
+ return rule->r_prio;
+ else
+ return -1;
+}
+
+void rtnl_rule_set_mark(struct rtnl_rule *rule, uint64_t mark)
+{
+ rule->r_mark = mark;
+ rule->ce_mask |= RULE_ATTR_MARK;
+}
+
+uint64_t rtnl_rule_get_mark(struct rtnl_rule *rule)
+{
+ if (rule->ce_mask & RULE_ATTR_MARK)
+ return rule->r_mark;
+ else
+ return UINT_LEAST64_MAX;
+}
+
+void rtnl_rule_set_table(struct rtnl_rule *rule, int table)
+{
+ rule->r_table = table;
+ rule->ce_mask |= RULE_ATTR_TABLE;
+}
+
+int rtnl_rule_get_table(struct rtnl_rule *rule)
+{
+ if (rule->ce_mask & RULE_ATTR_TABLE)
+ return rule->r_table;
+ else
+ return -1;
+}
+
+void rtnl_rule_set_dsfield(struct rtnl_rule *rule, int dsfield)
+{
+ rule->r_dsfield = dsfield;
+ rule->ce_mask |= RULE_ATTR_DSFIELD;
+}
+
+int rtnl_rule_get_dsfield(struct rtnl_rule *rule)
+{
+ if (rule->ce_mask & RULE_ATTR_DSFIELD)
+ return rule->r_dsfield;
+ else
+ return -1;
+}
+
+void rtnl_rule_set_src_len(struct rtnl_rule *rule, int len)
+{
+ rule->r_src_len = len;
+ if (rule->ce_mask & RULE_ATTR_SRC)
+ nl_addr_set_prefixlen(rule->r_src, len);
+ rule->ce_mask |= RULE_ATTR_SRC_LEN;
+}
+
+int rtnl_rule_get_src_len(struct rtnl_rule *rule)
+{
+ if (rule->ce_mask & RULE_ATTR_SRC_LEN)
+ return rule->r_src_len;
+ else
+ return -1;
+}
+
+void rtnl_rule_set_dst_len(struct rtnl_rule *rule, int len)
+{
+ rule->r_dst_len = len;
+ if (rule->ce_mask & RULE_ATTR_DST)
+ nl_addr_set_prefixlen(rule->r_dst, len);
+ rule->ce_mask |= RULE_ATTR_DST_LEN;
+}
+
+int rtnl_rule_get_dst_len(struct rtnl_rule *rule)
+{
+ if (rule->ce_mask & RULE_ATTR_DST_LEN)
+ return rule->r_dst_len;
+ else
+ return -1;
+}
+
+static inline int __assign_addr(struct rtnl_rule *rule, struct nl_addr **pos,
+ struct nl_addr *new, uint8_t *len, int flag)
+{
+ if (rule->ce_mask & RULE_ATTR_FAMILY) {
+ if (new->a_family != rule->r_family)
+ return nl_error(EINVAL, "Address family mismatch");
+ } else
+ rule->r_family = new->a_family;
+
+ if (*pos)
+ nl_addr_put(*pos);
+
+ nl_addr_get(new);
+ *pos = new;
+ *len = nl_addr_get_prefixlen(new);
+
+ rule->ce_mask |= (flag | RULE_ATTR_FAMILY);
+
+ return 0;
+}
+
+int rtnl_rule_set_src(struct rtnl_rule *rule, struct nl_addr *src)
+{
+ return __assign_addr(rule, &rule->r_src, src, &rule->r_src_len,
+ RULE_ATTR_SRC | RULE_ATTR_SRC_LEN);
+}
+
+struct nl_addr *rtnl_rule_get_src(struct rtnl_rule *rule)
+{
+ if (rule->ce_mask & RULE_ATTR_SRC)
+ return rule->r_src;
+ else
+ return NULL;
+}
+
+int rtnl_rule_set_dst(struct rtnl_rule *rule, struct nl_addr *dst)
+{
+ return __assign_addr(rule, &rule->r_dst, dst, &rule->r_dst_len,
+ RULE_ATTR_DST | RULE_ATTR_DST_LEN);
+}
+
+struct nl_addr *rtnl_rule_get_dst(struct rtnl_rule *rule)
+{
+ if (rule->ce_mask & RULE_ATTR_DST)
+ return rule->r_dst;
+ else
+ return NULL;
+}
+
+int rtnl_rule_set_iif(struct rtnl_rule *rule, const char *dev)
+{
+ if (strlen(dev) > IFNAMSIZ-1)
+ return nl_errno(ERANGE);
+
+ strcpy(rule->r_iif, dev);
+ rule->ce_mask |= RULE_ATTR_IIF;
+ return 0;
+}
+
+char *rtnl_rule_get_iif(struct rtnl_rule *rule)
+{
+ if (rule->ce_mask & RULE_ATTR_IIF)
+ return rule->r_iif;
+ else
+ return NULL;
+}
+
+void rtnl_rule_set_action(struct rtnl_rule *rule, int type)
+{
+ rule->r_type = type;
+ rule->ce_mask |= RULE_ATTR_TYPE;
+}
+
+int rtnl_rule_get_action(struct rtnl_rule *rule)
+{
+ if (rule->ce_mask & RULE_ATTR_TYPE)
+ return rule->r_type;
+ else
+ return nl_errno(ENOENT);
+}
+
+void rtnl_rule_set_realms(struct rtnl_rule *rule, realm_t realms)
+{
+ rule->r_realms = realms;
+ rule->ce_mask |= RULE_ATTR_REALMS;
+}
+
+realm_t rtnl_rule_get_realms(struct rtnl_rule *rule)
+{
+ if (rule->ce_mask & RULE_ATTR_REALMS)
+ return rule->r_realms;
+ else
+ return 0;
+}
+
+/** @} */
+
+static struct nl_object_ops rule_obj_ops = {
+ .oo_name = "route/rule",
+ .oo_size = sizeof(struct rtnl_rule),
+ .oo_free_data = rule_free_data,
+ .oo_clone = rule_clone,
+ .oo_dump[NL_DUMP_BRIEF] = rule_dump_brief,
+ .oo_dump[NL_DUMP_FULL] = rule_dump_full,
+ .oo_dump[NL_DUMP_STATS] = rule_dump_stats,
+ .oo_dump[NL_DUMP_XML] = rule_dump_xml,
+ .oo_dump[NL_DUMP_ENV] = rule_dump_env,
+ .oo_compare = rule_compare,
+ .oo_attrs2str = rule_attrs2str,
+ .oo_id_attrs = ~0,
+};
+
+static struct nl_cache_ops rtnl_rule_ops = {
+ .co_name = "route/rule",
+ .co_hdrsize = sizeof(struct rtmsg),
+ .co_msgtypes = {
+ { RTM_NEWRULE, NL_ACT_NEW, "new" },
+ { RTM_DELRULE, NL_ACT_DEL, "del" },
+ { RTM_GETRULE, NL_ACT_GET, "get" },
+ END_OF_MSGTYPES_LIST,
+ },
+ .co_protocol = NETLINK_ROUTE,
+ .co_request_update = rule_request_update,
+ .co_msg_parser = rule_msg_parser,
+ .co_obj_ops = &rule_obj_ops,
+};
+
+static void __init rule_init(void)
+{
+ nl_cache_mngt_register(&rtnl_rule_ops);
+}
+
+static void __exit rule_exit(void)
+{
+ nl_cache_mngt_unregister(&rtnl_rule_ops);
+}
+
+/** @} */
diff --git a/lib/route/sch/blackhole.c b/lib/route/sch/blackhole.c
new file mode 100644
index 0000000..a30b693
--- /dev/null
+++ b/lib/route/sch/blackhole.c
@@ -0,0 +1,38 @@
+/*
+ * lib/route/sch/blackhole.c Blackhole Qdisc
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup qdisc_api
+ * @defgroup blackhole Blackhole
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/route/qdisc.h>
+#include <netlink/route/qdisc-modules.h>
+
+static struct rtnl_qdisc_ops blackhole_ops = {
+ .qo_kind = "blackhole",
+};
+
+static void __init blackhole_init(void)
+{
+ rtnl_qdisc_register(&blackhole_ops);
+}
+
+static void __exit blackhole_exit(void)
+{
+ rtnl_qdisc_unregister(&blackhole_ops);
+}
+
+/** @} */
diff --git a/lib/route/sch/cbq.c b/lib/route/sch/cbq.c
new file mode 100644
index 0000000..9808509
--- /dev/null
+++ b/lib/route/sch/cbq.c
@@ -0,0 +1,306 @@
+/*
+ * lib/route/sch/cbq.c Class Based Queueing
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/route/qdisc.h>
+#include <netlink/route/qdisc-modules.h>
+#include <netlink/route/class.h>
+#include <netlink/route/class-modules.h>
+#include <netlink/route/link.h>
+#include <netlink/route/sch/cbq.h>
+#include <netlink/route/cls/police.h>
+
+/**
+ * @ingroup qdisc_api
+ * @ingroup class_api
+ * @defgroup cbq Class Based Queueing (CBQ)
+ * @{
+ */
+
+static struct trans_tbl ovl_strategies[] = {
+ __ADD(TC_CBQ_OVL_CLASSIC,classic)
+ __ADD(TC_CBQ_OVL_DELAY,delay)
+ __ADD(TC_CBQ_OVL_LOWPRIO,lowprio)
+ __ADD(TC_CBQ_OVL_DROP,drop)
+ __ADD(TC_CBQ_OVL_RCLASSIC,rclassic)
+};
+
+/**
+ * Convert a CBQ OVL strategy to a character string
+ * @arg type CBQ OVL strategy
+ * @arg buf destination buffer
+ * @arg len length of destination buffer
+ *
+ * Converts a CBQ OVL strategy to a character string and stores in the
+ * provided buffer. Returns the destination buffer or the type
+ * encoded in hex if no match was found.
+ */
+char *nl_ovl_strategy2str(int type, char *buf, size_t len)
+{
+ return __type2str(type, buf, len, ovl_strategies,
+ ARRAY_SIZE(ovl_strategies));
+}
+
+/**
+ * Convert a string to a CBQ OVL strategy
+ * @arg name CBQ OVL stragegy name
+ *
+ * Converts a CBQ OVL stragegy name to it's corresponding CBQ OVL strategy
+ * type. Returns the type or -1 if none was found.
+ */
+int nl_str2ovl_strategy(const char *name)
+{
+ return __str2type(name, ovl_strategies, ARRAY_SIZE(ovl_strategies));
+}
+
+static struct nla_policy cbq_policy[TCA_CBQ_MAX+1] = {
+ [TCA_CBQ_LSSOPT] = { .minlen = sizeof(struct tc_cbq_lssopt) },
+ [TCA_CBQ_RATE] = { .minlen = sizeof(struct tc_ratespec) },
+ [TCA_CBQ_WRROPT] = { .minlen = sizeof(struct tc_cbq_wrropt) },
+ [TCA_CBQ_OVL_STRATEGY] = { .minlen = sizeof(struct tc_cbq_ovl) },
+ [TCA_CBQ_FOPT] = { .minlen = sizeof(struct tc_cbq_fopt) },
+ [TCA_CBQ_POLICE] = { .minlen = sizeof(struct tc_cbq_police) },
+};
+
+static inline struct rtnl_cbq *cbq_qdisc(struct rtnl_tca *tca)
+{
+ return (struct rtnl_cbq *) tca->tc_subdata;
+}
+
+static inline struct rtnl_cbq *cbq_alloc(struct rtnl_tca *tca)
+{
+ if (!tca->tc_subdata)
+ tca->tc_subdata = calloc(1, sizeof(struct rtnl_qdisc));
+
+ return cbq_qdisc(tca);
+}
+
+
+static int cbq_msg_parser(struct rtnl_tca *tca)
+{
+ struct nlattr *tb[TCA_CBQ_MAX + 1];
+ struct rtnl_cbq *cbq;
+ int err;
+
+ err = tca_parse(tb, TCA_CBQ_MAX, tca, cbq_policy);
+ if (err < 0)
+ return err;
+
+ cbq = cbq_alloc(tca);
+ if (!cbq)
+ return nl_errno(ENOMEM);
+
+ nla_memcpy(&cbq->cbq_lss, tb[TCA_CBQ_LSSOPT], sizeof(cbq->cbq_lss));
+ nla_memcpy(&cbq->cbq_rate, tb[TCA_CBQ_RATE], sizeof(cbq->cbq_rate));
+ nla_memcpy(&cbq->cbq_wrr, tb[TCA_CBQ_WRROPT], sizeof(cbq->cbq_wrr));
+ nla_memcpy(&cbq->cbq_fopt, tb[TCA_CBQ_FOPT], sizeof(cbq->cbq_fopt));
+ nla_memcpy(&cbq->cbq_ovl, tb[TCA_CBQ_OVL_STRATEGY],
+ sizeof(cbq->cbq_ovl));
+ nla_memcpy(&cbq->cbq_police, tb[TCA_CBQ_POLICE],
+ sizeof(cbq->cbq_police));
+
+ return 0;
+}
+
+static int cbq_qdisc_msg_parser(struct rtnl_qdisc *qdisc)
+{
+ return cbq_msg_parser((struct rtnl_tca *) qdisc);
+}
+
+static int cbq_class_msg_parser(struct rtnl_class *class)
+{
+ return cbq_msg_parser((struct rtnl_tca *) class);
+}
+
+static void cbq_qdisc_free_data(struct rtnl_qdisc *qdisc)
+{
+ free(qdisc->q_subdata);
+}
+
+static int cbq_clone(struct rtnl_tca *_dst, struct rtnl_tca *_src)
+{
+ struct rtnl_cbq *src = cbq_qdisc(_src);
+
+ if (src && !cbq_alloc(_dst))
+ return nl_errno(ENOMEM);
+ else
+ return 0;
+}
+
+static int cbq_qdisc_clone(struct rtnl_qdisc *dst, struct rtnl_qdisc *src)
+{
+ return cbq_clone((struct rtnl_tca *) dst, (struct rtnl_tca *) src);
+}
+
+static void cbq_class_free_data(struct rtnl_class *class)
+{
+ free(class->c_subdata);
+}
+
+static int cbq_class_clone(struct rtnl_class *dst, struct rtnl_class *src)
+{
+ return cbq_clone((struct rtnl_tca *) dst, (struct rtnl_tca *) src);
+}
+
+static int cbq_dump_brief(struct rtnl_tca *tca, struct nl_dump_params *p,
+ int line)
+{
+ struct rtnl_cbq *cbq;
+ double r, rbit;
+ char *ru, *rubit;
+
+ cbq = cbq_qdisc(tca);
+ if (!cbq)
+ goto ignore;
+
+ r = nl_cancel_down_bytes(cbq->cbq_rate.rate, &ru);
+ rbit = nl_cancel_down_bits(cbq->cbq_rate.rate * 8, &rubit);
+
+ dp_dump(p, " rate %.2f%s/s (%.0f%s) prio %u",
+ r, ru, rbit, rubit, cbq->cbq_wrr.priority);
+
+ignore:
+ return line;
+}
+
+static int cbq_qdisc_dump_brief(struct rtnl_qdisc *qdisc,
+ struct nl_dump_params *p, int line)
+{
+ return cbq_dump_brief((struct rtnl_tca *) qdisc, p, line);
+}
+
+static int cbq_class_dump_brief(struct rtnl_class *class,
+ struct nl_dump_params *p, int line)
+{
+ return cbq_dump_brief((struct rtnl_tca *) class, p, line);
+}
+
+static int cbq_dump_full(struct rtnl_tca *tca, struct nl_dump_params *p,
+ int line)
+{
+ struct rtnl_cbq *cbq;
+ char *unit, buf[32];
+ double w;
+ uint32_t el;
+
+ cbq = cbq_qdisc(tca);
+ if (!cbq)
+ goto ignore;
+
+ w = nl_cancel_down_bits(cbq->cbq_wrr.weight * 8, &unit);
+
+ dp_dump(p, "avgpkt %u mpu %u cell %u allot %u weight %.0f%s\n",
+ cbq->cbq_lss.avpkt,
+ cbq->cbq_rate.mpu,
+ 1 << cbq->cbq_rate.cell_log,
+ cbq->cbq_wrr.allot, w, unit);
+
+ el = cbq->cbq_lss.ewma_log;
+ dp_dump_line(p, line++, " minidle %uus maxidle %uus offtime "
+ "%uus level %u ewma_log %u\n",
+ nl_ticks2us(cbq->cbq_lss.minidle >> el),
+ nl_ticks2us(cbq->cbq_lss.maxidle >> el),
+ nl_ticks2us(cbq->cbq_lss.offtime >> el),
+ cbq->cbq_lss.level,
+ cbq->cbq_lss.ewma_log);
+
+ dp_dump_line(p, line++, " penalty %uus strategy %s ",
+ nl_ticks2us(cbq->cbq_ovl.penalty),
+ nl_ovl_strategy2str(cbq->cbq_ovl.strategy, buf, sizeof(buf)));
+
+ dp_dump(p, "split %s defmap 0x%08x ",
+ rtnl_tc_handle2str(cbq->cbq_fopt.split, buf, sizeof(buf)),
+ cbq->cbq_fopt.defmap);
+
+ dp_dump(p, "police %s",
+ nl_police2str(cbq->cbq_police.police, buf, sizeof(buf)));
+
+ignore:
+ return line;
+}
+
+static int cbq_qdisc_dump_full(struct rtnl_qdisc *qdisc,
+ struct nl_dump_params *p, int line)
+{
+ return cbq_dump_full((struct rtnl_tca *) qdisc, p, line);
+}
+
+static int cbq_class_dump_full(struct rtnl_class *class,
+ struct nl_dump_params *p, int line)
+{
+ return cbq_dump_full((struct rtnl_tca *) class, p, line);
+}
+
+static int cbq_dump_with_stats(struct rtnl_tca *tca, struct nl_dump_params *p,
+ int line)
+{
+ struct tc_cbq_xstats *x = tca_xstats(tca);
+
+ if (!x)
+ goto ignore;
+
+ dp_dump_line(p, line++, " borrows overact "
+ " avgidle undertime\n");
+ dp_dump_line(p, line++, " %10u %10u %10u %10u\n",
+ x->borrows, x->overactions, x->avgidle, x->undertime);
+
+ignore:
+ return line;
+}
+
+static int cbq_qdisc_dump_with_stats(struct rtnl_qdisc *qdisc,
+ struct nl_dump_params *p, int line)
+{
+ return cbq_dump_with_stats((struct rtnl_tca *) qdisc, p, line);
+}
+
+static int cbq_class_dump_with_stats(struct rtnl_class *class,
+ struct nl_dump_params *p, int line)
+{
+ return cbq_dump_with_stats((struct rtnl_tca *) class, p, line);
+}
+
+static struct rtnl_qdisc_ops cbq_qdisc_ops = {
+ .qo_kind = "cbq",
+ .qo_msg_parser = cbq_qdisc_msg_parser,
+ .qo_free_data = cbq_qdisc_free_data,
+ .qo_clone = cbq_qdisc_clone,
+ .qo_dump[NL_DUMP_BRIEF] = cbq_qdisc_dump_brief,
+ .qo_dump[NL_DUMP_FULL] = cbq_qdisc_dump_full,
+ .qo_dump[NL_DUMP_STATS] = cbq_qdisc_dump_with_stats,
+};
+
+static struct rtnl_class_ops cbq_class_ops = {
+ .co_kind = "cbq",
+ .co_msg_parser = cbq_class_msg_parser,
+ .co_free_data = cbq_class_free_data,
+ .co_clone = cbq_class_clone,
+ .co_dump[NL_DUMP_BRIEF] = cbq_class_dump_brief,
+ .co_dump[NL_DUMP_FULL] = cbq_class_dump_full,
+ .co_dump[NL_DUMP_STATS] = cbq_class_dump_with_stats,
+};
+
+static void __init cbq_init(void)
+{
+ rtnl_qdisc_register(&cbq_qdisc_ops);
+ rtnl_class_register(&cbq_class_ops);
+}
+
+static void __exit cbq_exit(void)
+{
+ rtnl_qdisc_unregister(&cbq_qdisc_ops);
+ rtnl_class_unregister(&cbq_class_ops);
+}
+
+/** @} */
diff --git a/lib/route/sch/dsmark.c b/lib/route/sch/dsmark.c
new file mode 100644
index 0000000..5ba6b92
--- /dev/null
+++ b/lib/route/sch/dsmark.c
@@ -0,0 +1,459 @@
+/*
+ * lib/route/sch/dsmark.c DSMARK
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup qdisc_api
+ * @ingroup class_api
+ * @defgroup dsmark Differentiated Services Marker (DSMARK)
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/route/qdisc.h>
+#include <netlink/route/qdisc-modules.h>
+#include <netlink/route/class.h>
+#include <netlink/route/class-modules.h>
+#include <netlink/route/sch/dsmark.h>
+
+/** @cond SKIP */
+#define SCH_DSMARK_ATTR_INDICES 0x1
+#define SCH_DSMARK_ATTR_DEFAULT_INDEX 0x2
+#define SCH_DSMARK_ATTR_SET_TC_INDEX 0x4
+
+#define SCH_DSMARK_ATTR_MASK 0x1
+#define SCH_DSMARK_ATTR_VALUE 0x2
+/** @endcond */
+
+static inline struct rtnl_dsmark_qdisc *dsmark_qdisc(struct rtnl_qdisc *qdisc)
+{
+ return (struct rtnl_dsmark_qdisc *) qdisc->q_subdata;
+}
+
+static inline struct rtnl_dsmark_qdisc *
+dsmark_qdisc_alloc(struct rtnl_qdisc *qdisc)
+{
+ if (!qdisc->q_subdata)
+ qdisc->q_subdata = calloc(1, sizeof(struct rtnl_dsmark_qdisc));
+
+ return dsmark_qdisc(qdisc);
+}
+
+static struct nla_policy dsmark_policy[TCA_DSMARK_MAX+1] = {
+ [TCA_DSMARK_INDICES] = { .type = NLA_U16 },
+ [TCA_DSMARK_DEFAULT_INDEX] = { .type = NLA_U16 },
+ [TCA_DSMARK_SET_TC_INDEX] = { .type = NLA_FLAG },
+ [TCA_DSMARK_VALUE] = { .type = NLA_U8 },
+ [TCA_DSMARK_MASK] = { .type = NLA_U8 },
+};
+
+static int dsmark_qdisc_msg_parser(struct rtnl_qdisc *qdisc)
+{
+ int err;
+ struct nlattr *tb[TCA_DSMARK_MAX + 1];
+ struct rtnl_dsmark_qdisc *dsmark;
+
+ err = tca_parse(tb, TCA_DSMARK_MAX, (struct rtnl_tca *) qdisc,
+ dsmark_policy);
+ if (err < 0)
+ return err;
+
+ dsmark = dsmark_qdisc_alloc(qdisc);
+ if (!dsmark)
+ return nl_errno(ENOMEM);
+
+ if (tb[TCA_DSMARK_INDICES]) {
+ dsmark->qdm_indices = nla_get_u16(tb[TCA_DSMARK_INDICES]);
+ dsmark->qdm_mask |= SCH_DSMARK_ATTR_INDICES;
+ }
+
+ if (tb[TCA_DSMARK_DEFAULT_INDEX]) {
+ dsmark->qdm_default_index =
+ nla_get_u16(tb[TCA_DSMARK_DEFAULT_INDEX]);
+ dsmark->qdm_mask |= SCH_DSMARK_ATTR_DEFAULT_INDEX;
+ }
+
+ if (tb[TCA_DSMARK_SET_TC_INDEX]) {
+ dsmark->qdm_set_tc_index = 1;
+ dsmark->qdm_mask |= SCH_DSMARK_ATTR_SET_TC_INDEX;
+ }
+
+ return 0;
+}
+
+static inline struct rtnl_dsmark_class *dsmark_class(struct rtnl_class *class)
+{
+ return (struct rtnl_dsmark_class *) class->c_subdata;
+}
+
+static inline struct rtnl_dsmark_class *
+dsmark_class_alloc(struct rtnl_class *class)
+{
+ if (!class->c_subdata)
+ class->c_subdata = calloc(1, sizeof(struct rtnl_dsmark_class));
+
+ return dsmark_class(class);
+}
+
+static int dsmark_class_msg_parser(struct rtnl_class *class)
+{
+ int err;
+ struct nlattr *tb[TCA_DSMARK_MAX + 1];
+ struct rtnl_dsmark_class *dsmark;
+
+ err = tca_parse(tb, TCA_DSMARK_MAX, (struct rtnl_tca *) class,
+ dsmark_policy);
+ if (err < 0)
+ return err;
+
+ dsmark = dsmark_class_alloc(class);
+ if (!dsmark)
+ return nl_errno(ENOMEM);
+
+ if (tb[TCA_DSMARK_MASK]) {
+ dsmark->cdm_bmask = nla_get_u8(tb[TCA_DSMARK_MASK]);
+ dsmark->cdm_mask |= SCH_DSMARK_ATTR_MASK;
+ }
+
+ if (tb[TCA_DSMARK_VALUE]) {
+ dsmark->cdm_value = nla_get_u8(tb[TCA_DSMARK_VALUE]);
+ dsmark->cdm_mask |= SCH_DSMARK_ATTR_VALUE;
+ }
+
+ return 0;
+}
+
+static int dsmark_qdisc_dump_brief(struct rtnl_qdisc *qdisc,
+ struct nl_dump_params *p, int line)
+{
+ struct rtnl_dsmark_qdisc *dsmark = dsmark_qdisc(qdisc);
+
+ if (dsmark && (dsmark->qdm_mask & SCH_DSMARK_ATTR_INDICES))
+ dp_dump(p, " indices 0x%04x", dsmark->qdm_indices);
+
+ return line;
+}
+
+static int dsmark_qdisc_dump_full(struct rtnl_qdisc *qdisc,
+ struct nl_dump_params *p, int line)
+{
+ struct rtnl_dsmark_qdisc *dsmark = dsmark_qdisc(qdisc);
+
+ if (!dsmark)
+ goto ignore;
+
+ if (dsmark->qdm_mask & SCH_DSMARK_ATTR_DEFAULT_INDEX)
+ dp_dump(p, " default index 0x%04x", dsmark->qdm_default_index);
+
+ if (dsmark->qdm_mask & SCH_DSMARK_ATTR_SET_TC_INDEX)
+ dp_dump(p, " set-tc-index");
+
+ignore:
+ return line;
+}
+
+static int dsmark_class_dump_brief(struct rtnl_class *class,
+ struct nl_dump_params *p, int line)
+{
+ struct rtnl_dsmark_class *dsmark = dsmark_class(class);
+
+ if (!dsmark)
+ goto ignore;
+
+ if (dsmark->cdm_mask & SCH_DSMARK_ATTR_VALUE)
+ dp_dump(p, " value 0x%02x", dsmark->cdm_value);
+
+ if (dsmark->cdm_mask & SCH_DSMARK_ATTR_MASK)
+ dp_dump(p, " mask 0x%02x", dsmark->cdm_bmask);
+
+ignore:
+ return line;
+}
+
+static struct nl_msg *dsmark_qdisc_get_opts(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_dsmark_qdisc *dsmark = dsmark_qdisc(qdisc);
+ struct nl_msg *msg;
+
+ if (!dsmark)
+ return NULL;
+
+ msg = nlmsg_alloc();
+ if (!msg)
+ goto nla_put_failure;
+
+ if (dsmark->qdm_mask & SCH_DSMARK_ATTR_INDICES)
+ NLA_PUT_U16(msg, TCA_DSMARK_INDICES, dsmark->qdm_indices);
+
+ if (dsmark->qdm_mask & SCH_DSMARK_ATTR_DEFAULT_INDEX)
+ NLA_PUT_U16(msg, TCA_DSMARK_DEFAULT_INDEX,
+ dsmark->qdm_default_index);
+
+ if (dsmark->qdm_mask & SCH_DSMARK_ATTR_SET_TC_INDEX)
+ NLA_PUT_FLAG(msg, TCA_DSMARK_SET_TC_INDEX);
+
+ return msg;
+
+nla_put_failure:
+ nlmsg_free(msg);
+ return NULL;
+}
+
+static struct nl_msg *dsmark_class_get_opts(struct rtnl_class *class)
+{
+ struct rtnl_dsmark_class *dsmark = dsmark_class(class);
+ struct nl_msg *msg;
+
+ if (!dsmark)
+ return NULL;
+
+ msg = nlmsg_alloc();
+ if (!msg)
+ goto nla_put_failure;
+
+ if (dsmark->cdm_mask & SCH_DSMARK_ATTR_MASK)
+ NLA_PUT_U8(msg, TCA_DSMARK_MASK, dsmark->cdm_bmask);
+
+ if (dsmark->cdm_mask & SCH_DSMARK_ATTR_VALUE)
+ NLA_PUT_U8(msg, TCA_DSMARK_VALUE, dsmark->cdm_value);
+
+ return msg;
+
+nla_put_failure:
+ nlmsg_free(msg);
+ return NULL;
+}
+
+/**
+ * @name Class Attribute Access
+ * @{
+ */
+
+/**
+ * Set bitmask of DSMARK class.
+ * @arg class DSMARK class to be modified.
+ * @arg mask New bitmask.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_class_dsmark_set_bitmask(struct rtnl_class *class, uint8_t mask)
+{
+ struct rtnl_dsmark_class *dsmark;
+
+ dsmark = dsmark_class(class);
+ if (!dsmark)
+ return nl_errno(ENOMEM);
+
+ dsmark->cdm_bmask = mask;
+ dsmark->cdm_mask |= SCH_DSMARK_ATTR_MASK;
+
+ return 0;
+}
+
+/**
+ * Get bitmask of DSMARK class.
+ * @arg class DSMARK class.
+ * @return Bitmask or a negative error code.
+ */
+int rtnl_class_dsmark_get_bitmask(struct rtnl_class *class)
+{
+ struct rtnl_dsmark_class *dsmark;
+
+ dsmark = dsmark_class(class);
+ if (dsmark && dsmark->cdm_mask & SCH_DSMARK_ATTR_MASK)
+ return dsmark->cdm_bmask;
+ else
+ return nl_errno(ENOENT);
+}
+
+/**
+ * Set value of DSMARK class.
+ * @arg class DSMARK class to be modified.
+ * @arg value New value.
+ * @return 0 on success or a negative errror code.
+ */
+int rtnl_class_dsmark_set_value(struct rtnl_class *class, uint8_t value)
+{
+ struct rtnl_dsmark_class *dsmark;
+
+ dsmark = dsmark_class(class);
+ if (!dsmark)
+ return nl_errno(ENOMEM);
+
+ dsmark->cdm_value = value;
+ dsmark->cdm_mask |= SCH_DSMARK_ATTR_VALUE;
+
+ return 0;
+}
+
+/**
+ * Get value of DSMARK class.
+ * @arg class DSMARK class.
+ * @return Value or a negative error code.
+ */
+int rtnl_class_dsmark_get_value(struct rtnl_class *class)
+{
+ struct rtnl_dsmark_class *dsmark;
+
+ dsmark = dsmark_class(class);
+ if (dsmark && dsmark->cdm_mask & SCH_DSMARK_ATTR_VALUE)
+ return dsmark->cdm_value;
+ else
+ return nl_errno(ENOENT);
+}
+
+/** @} */
+
+/**
+ * @name Qdisc Attribute Access
+ * @{
+ */
+
+/**
+ * Set indices of DSMARK qdisc.
+ * @arg qdisc DSMARK qdisc to be modified.
+ * @arg indices New indices.
+ */
+int rtnl_qdisc_dsmark_set_indices(struct rtnl_qdisc *qdisc, uint16_t indices)
+{
+ struct rtnl_dsmark_qdisc *dsmark;
+
+ dsmark = dsmark_qdisc(qdisc);
+ if (!dsmark)
+ return nl_errno(ENOMEM);
+
+ dsmark->qdm_indices = indices;
+ dsmark->qdm_mask |= SCH_DSMARK_ATTR_INDICES;
+
+ return 0;
+}
+
+/**
+ * Get indices of DSMARK qdisc.
+ * @arg qdisc DSMARK qdisc.
+ * @return Indices or a negative error code.
+ */
+int rtnl_qdisc_dsmark_get_indices(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_dsmark_qdisc *dsmark;
+
+ dsmark = dsmark_qdisc(qdisc);
+ if (dsmark && dsmark->qdm_mask & SCH_DSMARK_ATTR_INDICES)
+ return dsmark->qdm_indices;
+ else
+ return nl_errno(ENOENT);
+}
+
+/**
+ * Set default index of DSMARK qdisc.
+ * @arg qdisc DSMARK qdisc to be modified.
+ * @arg default_index New default index.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_qdisc_dsmark_set_default_index(struct rtnl_qdisc *qdisc,
+ uint16_t default_index)
+{
+ struct rtnl_dsmark_qdisc *dsmark;
+
+ dsmark = dsmark_qdisc(qdisc);
+ if (!dsmark)
+ return nl_errno(ENOMEM);
+
+ dsmark->qdm_default_index = default_index;
+ dsmark->qdm_mask |= SCH_DSMARK_ATTR_DEFAULT_INDEX;
+
+ return 0;
+}
+
+/**
+ * Get default index of DSMARK qdisc.
+ * @arg qdisc DSMARK qdisc.
+ * @return Default index or a negative error code.
+ */
+int rtnl_qdisc_dsmark_get_default_index(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_dsmark_qdisc *dsmark;
+
+ dsmark = dsmark_qdisc(qdisc);
+ if (dsmark && dsmark->qdm_mask & SCH_DSMARK_ATTR_DEFAULT_INDEX)
+ return dsmark->qdm_default_index;
+ else
+ return nl_errno(ENOENT);
+}
+
+/**
+ * Set set-tc-index flag of DSMARK qdisc.
+ * @arg qdisc DSMARK qdisc to be modified.
+ * @arg flag Flag indicating whether to enable or disable.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_qdisc_dsmark_set_set_tc_index(struct rtnl_qdisc *qdisc, int flag)
+{
+ struct rtnl_dsmark_qdisc *dsmark;
+
+ dsmark = dsmark_qdisc(qdisc);
+ if (!dsmark)
+ return nl_errno(ENOMEM);
+
+ dsmark->qdm_set_tc_index = !!flag;
+ dsmark->qdm_mask |= SCH_DSMARK_ATTR_SET_TC_INDEX;
+
+ return 0;
+}
+
+/**
+ * Get set-tc-index flag of DSMARK qdisc.
+ * @arg qdisc DSMARK qdisc to be modified.
+ * @return 1 or 0 to indicate wehther the flag is enabled or a negative
+ * error code.
+ */
+int rtnl_qdisc_dsmark_get_set_tc_index(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_dsmark_qdisc *dsmark;
+
+ dsmark = dsmark_qdisc(qdisc);
+ if (dsmark && dsmark->qdm_mask & SCH_DSMARK_ATTR_SET_TC_INDEX)
+ return dsmark->qdm_set_tc_index;
+ else
+ return nl_errno(ENOENT);
+}
+
+/** @} */
+
+static struct rtnl_qdisc_ops dsmark_qdisc_ops = {
+ .qo_kind = "dsmark",
+ .qo_msg_parser = dsmark_qdisc_msg_parser,
+ .qo_dump[NL_DUMP_BRIEF] = dsmark_qdisc_dump_brief,
+ .qo_dump[NL_DUMP_FULL] = dsmark_qdisc_dump_full,
+ .qo_get_opts = dsmark_qdisc_get_opts,
+};
+
+static struct rtnl_class_ops dsmark_class_ops = {
+ .co_kind = "dsmark",
+ .co_msg_parser = dsmark_class_msg_parser,
+ .co_dump[NL_DUMP_BRIEF] = dsmark_class_dump_brief,
+ .co_get_opts = dsmark_class_get_opts,
+};
+
+static void __init dsmark_init(void)
+{
+ rtnl_qdisc_register(&dsmark_qdisc_ops);
+ rtnl_class_register(&dsmark_class_ops);
+}
+
+static void __exit dsmark_exit(void)
+{
+ rtnl_qdisc_unregister(&dsmark_qdisc_ops);
+ rtnl_class_unregister(&dsmark_class_ops);
+}
+
+/** @} */
diff --git a/lib/route/sch/fifo.c b/lib/route/sch/fifo.c
new file mode 100644
index 0000000..4f8d202
--- /dev/null
+++ b/lib/route/sch/fifo.c
@@ -0,0 +1,205 @@
+/*
+ * lib/route/sch/fifo.c (p|b)fifo
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup qdisc_api
+ * @defgroup fifo Packet/Bytes FIFO (pfifo/bfifo)
+ * @brief
+ *
+ * The FIFO qdisc comes in two flavours:
+ * @par bfifo (Byte FIFO)
+ * Allows enqueuing until the currently queued volume in bytes exceeds
+ * the configured limit.backlog contains currently enqueued volume in bytes.
+ *
+ * @par pfifo (Packet FIFO)
+ * Allows enquueing until the currently queued number of packets
+ * exceeds the configured limit.
+ *
+ * The configuration is exactly the same, the decision which of
+ * the two variations is going to be used is made based on the
+ * kind of the qdisc (rtnl_qdisc_set_kind()).
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/route/qdisc.h>
+#include <netlink/route/qdisc-modules.h>
+#include <netlink/route/sch/fifo.h>
+#include <netlink/utils.h>
+
+/** @cond SKIP */
+#define SCH_FIFO_ATTR_LIMIT 1
+/** @endcond */
+
+static inline struct rtnl_fifo *fifo_qdisc(struct rtnl_qdisc *qdisc)
+{
+ return (struct rtnl_fifo *) qdisc->q_subdata;
+}
+
+static inline struct rtnl_fifo *fifo_alloc(struct rtnl_qdisc *qdisc)
+{
+ if (!qdisc->q_subdata)
+ qdisc->q_subdata = calloc(1, sizeof(struct rtnl_fifo));
+
+ return fifo_qdisc(qdisc);
+}
+
+static int fifo_msg_parser(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_fifo *fifo;
+ struct tc_fifo_qopt *opt;
+
+ if (qdisc->q_opts->d_size < sizeof(struct tc_fifo_qopt))
+ return nl_error(EINVAL, "FIFO options size mismatch");
+
+ fifo = fifo_alloc(qdisc);
+ if (!fifo)
+ return nl_errno(ENOMEM);
+
+ opt = (struct tc_fifo_qopt *) qdisc->q_opts->d_data;
+ fifo->qf_limit = opt->limit;
+ fifo->qf_mask = SCH_FIFO_ATTR_LIMIT;
+
+ return 0;
+}
+
+static void fifo_free_data(struct rtnl_qdisc *qdisc)
+{
+ free(qdisc->q_subdata);
+}
+
+static int pfifo_dump_brief(struct rtnl_qdisc *qdisc,
+ struct nl_dump_params *p, int line)
+{
+ struct rtnl_fifo *fifo = fifo_qdisc(qdisc);
+
+ if (fifo)
+ dp_dump(p, " limit %u packets", fifo->qf_limit);
+
+ return line;
+}
+
+static int bfifo_dump_brief(struct rtnl_qdisc *qdisc,
+ struct nl_dump_params *p, int line)
+{
+ struct rtnl_fifo *fifo = fifo_qdisc(qdisc);
+
+ if (fifo) {
+ char *unit;
+ double r;
+
+ r = nl_cancel_down_bytes(fifo->qf_limit, &unit);
+ dp_dump(p, " limit %.1f%s", r, unit);
+ }
+
+ return line;
+}
+
+static struct nl_msg *fifo_get_opts(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_fifo *fifo;
+ struct tc_fifo_qopt opts;
+ struct nl_msg *msg;
+
+ fifo = fifo_qdisc(qdisc);
+ if (!fifo || !(fifo->qf_mask & SCH_FIFO_ATTR_LIMIT))
+ return NULL;
+
+ msg = nlmsg_alloc();
+ if (!msg)
+ goto errout;
+
+ memset(&opts, 0, sizeof(opts));
+ opts.limit = fifo->qf_limit;
+
+ if (nlmsg_append(msg, &opts, sizeof(opts), NL_DONTPAD) < 0)
+ goto errout;
+
+ return msg;
+errout:
+ nlmsg_free(msg);
+ return NULL;
+}
+
+/**
+ * @name Attribute Modification
+ * @{
+ */
+
+/**
+ * Set limit of FIFO qdisc.
+ * @arg qdisc FIFO qdisc to be modified.
+ * @arg limit New limit.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_qdisc_fifo_set_limit(struct rtnl_qdisc *qdisc, int limit)
+{
+ struct rtnl_fifo *fifo;
+
+ fifo = fifo_alloc(qdisc);
+ if (!fifo)
+ return nl_errno(ENOMEM);
+
+ fifo->qf_limit = limit;
+ fifo->qf_mask |= SCH_FIFO_ATTR_LIMIT;
+
+ return 0;
+}
+
+/**
+ * Get limit of a FIFO qdisc.
+ * @arg qdisc FIFO qdisc.
+ * @return Numeric limit or a negative error code.
+ */
+int rtnl_qdisc_fifo_get_limit(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_fifo *fifo;
+
+ fifo = fifo_qdisc(qdisc);
+ if (fifo && fifo->qf_mask & SCH_FIFO_ATTR_LIMIT)
+ return fifo->qf_limit;
+ else
+ return nl_errno(ENOMEM);
+}
+
+/** @} */
+
+static struct rtnl_qdisc_ops pfifo_ops = {
+ .qo_kind = "pfifo",
+ .qo_msg_parser = fifo_msg_parser,
+ .qo_free_data = fifo_free_data,
+ .qo_dump[NL_DUMP_BRIEF] = pfifo_dump_brief,
+ .qo_get_opts = fifo_get_opts,
+};
+
+static struct rtnl_qdisc_ops bfifo_ops = {
+ .qo_kind = "bfifo",
+ .qo_msg_parser = fifo_msg_parser,
+ .qo_free_data = fifo_free_data,
+ .qo_dump[NL_DUMP_BRIEF] = bfifo_dump_brief,
+ .qo_get_opts = fifo_get_opts,
+};
+
+static void __init fifo_init(void)
+{
+ rtnl_qdisc_register(&pfifo_ops);
+ rtnl_qdisc_register(&bfifo_ops);
+}
+
+static void __exit fifo_exit(void)
+{
+ rtnl_qdisc_unregister(&pfifo_ops);
+ rtnl_qdisc_unregister(&bfifo_ops);
+}
+
+/** @} */
diff --git a/lib/route/sch/htb.c b/lib/route/sch/htb.c
new file mode 100644
index 0000000..6de87b3
--- /dev/null
+++ b/lib/route/sch/htb.c
@@ -0,0 +1,553 @@
+/*
+ * lib/route/sch/htb.c HTB Qdisc
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ * Copyright (c) 2005-2006 Petr Gotthard <petr.gotthard@siemens.com>
+ * Copyright (c) 2005-2006 Siemens AG Oesterreich
+ */
+
+/**
+ * @ingroup qdisc_api
+ * @ingroup class_api
+ * @defgroup htb Hierachical Token Bucket (HTB)
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/cache.h>
+#include <netlink/utils.h>
+#include <netlink/route/tc.h>
+#include <netlink/route/qdisc.h>
+#include <netlink/route/qdisc-modules.h>
+#include <netlink/route/class.h>
+#include <netlink/route/class-modules.h>
+#include <netlink/route/link.h>
+#include <netlink/route/sch/htb.h>
+
+/** @cond SKIP */
+#define SCH_HTB_HAS_RATE2QUANTUM 0x01
+#define SCH_HTB_HAS_DEFCLS 0x02
+
+#define SCH_HTB_HAS_PRIO 0x001
+#define SCH_HTB_HAS_MTU 0x002
+#define SCH_HTB_HAS_RATE 0x004
+#define SCH_HTB_HAS_CEIL 0x008
+#define SCH_HTB_HAS_RBUFFER 0x010
+#define SCH_HTB_HAS_CBUFFER 0x020
+#define SCH_HTB_HAS_QUANTUM 0x040
+#define SCH_HTB_HAS_OVERHEAD 0x080
+#define SCH_HTB_HAS_MPU 0x100
+/** @endcond */
+
+static inline struct rtnl_htb_qdisc *htb_qdisc(struct rtnl_qdisc *qdisc)
+{
+ if (qdisc->q_subdata == NULL)
+ qdisc->q_subdata = calloc(1, sizeof(struct rtnl_htb_qdisc));
+
+ return (struct rtnl_htb_qdisc *) qdisc->q_subdata;
+}
+
+static struct nla_policy htb_policy[TCA_HTB_MAX+1] = {
+ [TCA_HTB_INIT] = { .minlen = sizeof(struct tc_htb_glob) },
+ [TCA_HTB_PARMS] = { .minlen = sizeof(struct tc_htb_opt) },
+};
+
+static int htb_qdisc_msg_parser(struct rtnl_qdisc *qdisc)
+{
+ int err;
+ struct nlattr *tb[TCA_HTB_MAX + 1];
+ struct rtnl_htb_qdisc *d;
+
+ err = tca_parse(tb, TCA_HTB_MAX, (struct rtnl_tca *) qdisc, htb_policy);
+ if (err < 0)
+ return err;
+
+ d = htb_qdisc(qdisc);
+
+ if (tb[TCA_HTB_INIT]) {
+ struct tc_htb_glob opts;
+
+ nla_memcpy(&opts, tb[TCA_HTB_INIT], sizeof(opts));
+ d->qh_rate2quantum = opts.rate2quantum;
+ d->qh_defcls = opts.defcls;
+
+ d->qh_mask = (SCH_HTB_HAS_RATE2QUANTUM | SCH_HTB_HAS_DEFCLS);
+ }
+
+ return 0;
+}
+
+static void htb_qdisc_free_data(struct rtnl_qdisc *qdisc)
+{
+ free(qdisc->q_subdata);
+}
+
+static inline struct rtnl_htb_class *htb_class(struct rtnl_class *class)
+{
+ if (class->c_subdata == NULL)
+ class->c_subdata = calloc(1, sizeof(struct rtnl_htb_class));
+
+ return (struct rtnl_htb_class *) class->c_subdata;
+}
+
+static int htb_class_msg_parser(struct rtnl_class *class)
+{
+ int err;
+ struct nlattr *tb[TCA_HTB_MAX + 1];
+ struct rtnl_htb_class *d;
+
+ err = tca_parse(tb, TCA_HTB_MAX, (struct rtnl_tca *) class, htb_policy);
+ if (err < 0)
+ return err;
+
+ d = htb_class(class);
+
+ if (tb[TCA_HTB_PARMS]) {
+ struct tc_htb_opt opts;
+
+ nla_memcpy(&opts, tb[TCA_HTB_PARMS], sizeof(opts));
+ d->ch_prio = opts.prio;
+ rtnl_copy_ratespec(&d->ch_rate, &opts.rate);
+ rtnl_copy_ratespec(&d->ch_ceil, &opts.ceil);
+ d->ch_rbuffer = rtnl_tc_calc_bufsize(opts.buffer, opts.rate.rate);
+ d->ch_cbuffer = rtnl_tc_calc_bufsize(opts.cbuffer, opts.ceil.rate);
+ d->ch_quantum = opts.quantum;
+ d->ch_overhead = (opts.rate.mpu >> 8) & 0xff;
+ d->ch_mpu = opts.rate.mpu & 0xff;
+
+ d->ch_mask = (SCH_HTB_HAS_PRIO | SCH_HTB_HAS_RATE |
+ SCH_HTB_HAS_CEIL | SCH_HTB_HAS_RBUFFER |
+ SCH_HTB_HAS_CBUFFER | SCH_HTB_HAS_QUANTUM |
+ SCH_HTB_HAS_OVERHEAD | SCH_HTB_HAS_MPU);
+ }
+
+ return 0;
+}
+
+static void htb_class_free_data(struct rtnl_class *class)
+{
+ free(class->c_subdata);
+}
+
+static int htb_qdisc_dump_brief(struct rtnl_qdisc *qdisc,
+ struct nl_dump_params *p, int line)
+{
+ struct rtnl_htb_qdisc *d = (struct rtnl_htb_qdisc *) qdisc->q_subdata;
+
+ if (d == NULL)
+ goto ignore;
+
+ if (d->qh_mask & SCH_HTB_HAS_RATE2QUANTUM)
+ dp_dump(p, " r2q %u", d->qh_rate2quantum);
+
+ if (d->qh_mask & SCH_HTB_HAS_DEFCLS) {
+ char buf[32];
+ dp_dump(p, " default %s",
+ rtnl_tc_handle2str(d->qh_defcls, buf, sizeof(buf)));
+ }
+
+ignore:
+ return line;
+}
+
+static int htb_class_dump_brief(struct rtnl_class *class,
+ struct nl_dump_params *p, int line)
+{
+ struct rtnl_htb_class *d = (struct rtnl_htb_class *) class->c_subdata;
+
+ if (d == NULL)
+ goto ignore;
+
+ if (d->ch_mask & SCH_HTB_HAS_RATE) {
+ double r, rbit;
+ char *ru, *rubit;
+
+ r = nl_cancel_down_bytes(d->ch_rate.rs_rate, &ru);
+ rbit = nl_cancel_down_bits(d->ch_rate.rs_rate*8, &rubit);
+
+ dp_dump(p, " rate %.2f%s/s (%.0f%s) log %u",
+ r, ru, rbit, rubit, 1<<d->ch_rate.rs_cell_log);
+ }
+
+ignore:
+ return line;
+}
+
+static int htb_class_dump_full(struct rtnl_class *class,
+ struct nl_dump_params *p, int line)
+{
+ struct rtnl_htb_class *d = (struct rtnl_htb_class *) class->c_subdata;
+
+ if (d == NULL)
+ goto ignore;
+
+ /* line 1 */
+ if (d->ch_mask & SCH_HTB_HAS_CEIL) {
+ double r, rbit;
+ char *ru, *rubit;
+
+ r = nl_cancel_down_bytes(d->ch_ceil.rs_rate, &ru);
+ rbit = nl_cancel_down_bits(d->ch_ceil.rs_rate*8, &rubit);
+
+ dp_dump(p, " ceil %.2f%s/s (%.0f%s) log %u",
+ r, ru, rbit, rubit, 1<<d->ch_ceil.rs_cell_log);
+ }
+
+ if (d->ch_mask & SCH_HTB_HAS_PRIO)
+ dp_dump(p, " prio %u", d->ch_prio);
+
+ if (d->ch_mask & SCH_HTB_HAS_MTU)
+ dp_dump(p, " mtu %u", d->ch_mtu);
+
+ if (d->ch_mask & SCH_HTB_HAS_RBUFFER) {
+ double b;
+ char *bu;
+
+ b = nl_cancel_down_bytes(d->ch_rbuffer, &bu);
+ dp_dump(p, " rbuffer %.2f%s", b, bu);
+ }
+
+ if (d->ch_mask & SCH_HTB_HAS_CBUFFER) {
+ double b;
+ char *bu;
+
+ b = nl_cancel_down_bytes(d->ch_cbuffer, &bu);
+ dp_dump(p, " cbuffer %.2f%s", b, bu);
+ }
+
+ if (d->ch_mask & SCH_HTB_HAS_QUANTUM)
+ dp_dump(p, " quantum %u", d->ch_quantum);
+
+ if (d->ch_mask & SCH_HTB_HAS_OVERHEAD)
+ dp_dump(p, " overhead %u", d->ch_overhead);
+
+ if (d->ch_mask & SCH_HTB_HAS_MPU)
+ dp_dump(p, " mpu %u", d->ch_mpu);
+
+ignore:
+ return line;
+}
+
+static struct nl_msg *htb_qdisc_get_opts(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_htb_qdisc *d = (struct rtnl_htb_qdisc *) qdisc->q_subdata;
+ struct tc_htb_glob opts;
+ struct nl_msg *msg;
+
+ if (d == NULL)
+ return NULL;
+
+ msg = nlmsg_alloc();
+ if (msg == NULL)
+ return NULL;
+
+ memset(&opts, 0, sizeof(opts));
+ opts.version = TC_HTB_PROTOVER;
+
+ if (d->qh_mask & SCH_HTB_HAS_RATE2QUANTUM)
+ opts.rate2quantum = d->qh_rate2quantum;
+ if (d->qh_mask & SCH_HTB_HAS_DEFCLS)
+ opts.defcls = d->qh_defcls;
+
+ nla_put(msg, TCA_HTB_INIT, sizeof(opts), &opts);
+
+ return msg;
+}
+
+static uint8_t compute_cell(uint32_t rate, uint32_t mtu)
+{
+ uint8_t cell_log = 0;
+ while (mtu > 255) {
+ mtu >>= 1;
+ cell_log++;
+ }
+
+ return cell_log;
+}
+
+static struct nl_msg *htb_class_get_opts(struct rtnl_class *class)
+{
+ struct rtnl_htb_class *d = (struct rtnl_htb_class *) class->c_subdata;
+ uint32_t mtu, rtable[RTNL_TC_RTABLE_SIZE], ctable[RTNL_TC_RTABLE_SIZE];
+ struct tc_htb_opt opts;
+ struct nl_msg *msg;
+ int buffer, cbuffer;
+ uint8_t overhead = 0, mpu = 0;
+
+ if (d == NULL)
+ return NULL;
+
+ msg = nlmsg_alloc();
+ memset(&opts, 0, sizeof(opts));
+
+ /* if not set, zero (0) is used as priority */
+ if (d->ch_mask & SCH_HTB_HAS_PRIO)
+ opts.prio = d->ch_prio;
+
+ if (d->ch_mask & SCH_HTB_HAS_MTU)
+ mtu = d->ch_mtu;
+ else
+ mtu = 1600; /* eth packet len */
+
+ if (!(d->ch_mask & SCH_HTB_HAS_RATE))
+ BUG();
+
+ rtnl_rcopy_ratespec(&opts.rate, &d->ch_rate);
+ /* if cell_log not set, compute default value */
+ if (opts.rate.cell_log == UINT8_MAX)
+ opts.rate.cell_log = compute_cell(opts.rate.rate, mtu);
+
+ /* if not set, configured rate is used as ceil, which implies no borrowing */
+ if (d->ch_mask & SCH_HTB_HAS_CEIL)
+ rtnl_rcopy_ratespec(&opts.ceil, &d->ch_ceil);
+ else
+ memcpy(&opts.ceil, &opts.rate, sizeof(struct tc_ratespec));
+ /* if cell_log not set, compute default value */
+ if (opts.ceil.cell_log == UINT8_MAX)
+ opts.ceil.cell_log = compute_cell(opts.ceil.rate, mtu);
+
+ if (d->ch_mask & SCH_HTB_HAS_RBUFFER)
+ buffer = d->ch_rbuffer;
+ else
+ buffer = opts.rate.rate / nl_get_hz() + mtu;
+
+ opts.buffer = rtnl_tc_calc_txtime(buffer, opts.rate.rate);
+
+ if (d->ch_mask & SCH_HTB_HAS_CBUFFER)
+ cbuffer = d->ch_cbuffer;
+ else
+ cbuffer = opts.ceil.rate / nl_get_hz() + mtu;
+
+ opts.cbuffer = rtnl_tc_calc_txtime(cbuffer, opts.ceil.rate);
+
+ if (d->ch_mask & SCH_HTB_HAS_QUANTUM)
+ opts.quantum = d->ch_quantum;
+
+ if (d->ch_mask & SCH_HTB_HAS_OVERHEAD)
+ overhead = d->ch_overhead;
+
+ if (d->ch_mask & SCH_HTB_HAS_MPU)
+ mpu = d->ch_mpu;
+
+ opts.rate.mpu = mpu | (overhead << 8);
+ opts.ceil.mpu = mpu | (overhead << 8);
+
+ nla_put(msg, TCA_HTB_PARMS, sizeof(opts), &opts);
+
+ rtnl_tc_build_rate_table(rtable, mpu, overhead,
+ 1 << opts.rate.cell_log,
+ opts.rate.rate);
+ nla_put(msg, TCA_HTB_RTAB, sizeof(rtable), &rtable);
+
+ rtnl_tc_build_rate_table(ctable, mpu, overhead,
+ 1 << opts.ceil.cell_log,
+ opts.ceil.rate);
+ nla_put(msg, TCA_HTB_CTAB, sizeof(ctable), &ctable);
+
+ return msg;
+}
+
+/**
+ * @name Attribute Modifications
+ * @{
+ */
+
+void rtnl_htb_set_rate2quantum(struct rtnl_qdisc *qdisc, uint32_t rate2quantum)
+{
+ struct rtnl_htb_qdisc *d = htb_qdisc(qdisc);
+ if (d == NULL)
+ return;
+
+ d->qh_rate2quantum = rate2quantum;
+ d->qh_mask |= SCH_HTB_HAS_RATE2QUANTUM;
+}
+
+/**
+ * Set default class of the htb qdisc to the specified value
+ * @arg qdisc qdisc to change
+ * @arg defcls new default class
+ */
+void rtnl_htb_set_defcls(struct rtnl_qdisc *qdisc, uint32_t defcls)
+{
+ struct rtnl_htb_qdisc *d = htb_qdisc(qdisc);
+ if (d == NULL)
+ return;
+
+ d->qh_defcls = defcls;
+ d->qh_mask |= SCH_HTB_HAS_DEFCLS;
+}
+
+void rtnl_htb_set_prio(struct rtnl_class *class, uint32_t prio)
+{
+ struct rtnl_htb_class *d = htb_class(class);
+ if (d == NULL)
+ return;
+
+ d->ch_prio = prio;
+ d->ch_mask |= SCH_HTB_HAS_PRIO;
+}
+
+/**
+ * Set MTU of the data link.
+ * @arg class HTB class to be modified.
+ * @arg mtu New MTU in bytes.
+ *
+ * Sets MTU of the data link controlled by the HTB class.
+ * If not set, the Ethernet MTU (1600) is used.
+ */
+void rtnl_htb_set_mtu(struct rtnl_class *class, uint32_t mtu)
+{
+ struct rtnl_htb_class *d = htb_class(class);
+ if (d == NULL)
+ return;
+
+ d->ch_mtu = mtu;
+ d->ch_mask |= SCH_HTB_HAS_MTU;
+}
+
+/**
+ * Set rate of HTB class.
+ * @arg class HTB class to be modified.
+ * @arg rate New rate in bytes per second.
+ */
+void rtnl_htb_set_rate(struct rtnl_class *class, uint32_t rate)
+{
+ struct rtnl_htb_class *d = htb_class(class);
+ if (d == NULL)
+ return;
+
+ d->ch_rate.rs_cell_log = UINT8_MAX; /* use default value */
+ d->ch_rate.rs_rate = rate;
+ d->ch_mask |= SCH_HTB_HAS_RATE;
+}
+
+/**
+ * Set ceil of HTB class.
+ * @arg class HTB class to be modified.
+ * @arg ceil New ceil in bytes per second.
+ */
+void rtnl_htb_set_ceil(struct rtnl_class *class, uint32_t ceil)
+{
+ struct rtnl_htb_class *d = htb_class(class);
+ if (d == NULL)
+ return;
+
+ d->ch_ceil.rs_cell_log = UINT8_MAX; /* use default value */
+ d->ch_ceil.rs_rate = ceil;
+ d->ch_mask |= SCH_HTB_HAS_CEIL;
+}
+
+/**
+ * Set size of the rate bucket of HTB class.
+ * @arg class HTB class to be modified.
+ * @arg rbuffer New size in bytes.
+ */
+void rtnl_htb_set_rbuffer(struct rtnl_class *class, uint32_t rbuffer)
+{
+ struct rtnl_htb_class *d = htb_class(class);
+ if (d == NULL)
+ return;
+
+ d->ch_rbuffer = rbuffer;
+ d->ch_mask |= SCH_HTB_HAS_RBUFFER;
+}
+
+/**
+ * Set size of the ceil bucket of HTB class.
+ * @arg class HTB class to be modified.
+ * @arg cbuffer New size in bytes.
+ */
+void rtnl_htb_set_cbuffer(struct rtnl_class *class, uint32_t cbuffer)
+{
+ struct rtnl_htb_class *d = htb_class(class);
+ if (d == NULL)
+ return;
+
+ d->ch_cbuffer = cbuffer;
+ d->ch_mask |= SCH_HTB_HAS_CBUFFER;
+}
+
+/**
+ * Set how much bytes to serve from leaf at once of HTB class {use r2q}.
+ * @arg class HTB class to be modified.
+ * @arg quantum New size in bytes.
+ */
+void rtnl_htb_set_quantum(struct rtnl_class *class, uint32_t quantum)
+{
+ struct rtnl_htb_class *d = htb_class(class);
+ if (d == NULL)
+ return;
+
+ d->ch_quantum = quantum;
+ d->ch_mask |= SCH_HTB_HAS_QUANTUM;
+}
+
+/**
+ * Set per-packet size overhead used in rate computations of HTB class.
+ * @arg class HTB class to be modified.
+ * @arg overhead Size in bytes.
+ */
+void rtnl_htb_set_overhead(struct rtnl_class *class, uint8_t overhead)
+{
+ struct rtnl_htb_class *d = htb_class(class);
+ if (d == NULL)
+ return;
+
+ d->ch_overhead = overhead;
+ d->ch_mask |= SCH_HTB_HAS_OVERHEAD;
+}
+
+/**
+ * Set the minimum packet size used in rate computations of HTB class.
+ * @arg class HTB class to be modified.
+ * @arg mpu Size in bytes.
+ */
+void rtnl_htb_set_mpu(struct rtnl_class *class, uint8_t mpu)
+{
+ struct rtnl_htb_class *d = htb_class(class);
+ if (d == NULL)
+ return;
+
+ d->ch_mpu = mpu;
+ d->ch_mask |= SCH_HTB_HAS_MPU;
+}
+
+/** @} */
+
+static struct rtnl_qdisc_ops htb_qdisc_ops = {
+ .qo_kind = "htb",
+ .qo_msg_parser = htb_qdisc_msg_parser,
+ .qo_free_data = htb_qdisc_free_data,
+ .qo_dump[NL_DUMP_BRIEF] = htb_qdisc_dump_brief,
+ .qo_get_opts = htb_qdisc_get_opts,
+};
+
+static struct rtnl_class_ops htb_class_ops = {
+ .co_kind = "htb",
+ .co_msg_parser = htb_class_msg_parser,
+ .co_free_data = htb_class_free_data,
+ .co_dump[NL_DUMP_BRIEF] = htb_class_dump_brief,
+ .co_dump[NL_DUMP_FULL] = htb_class_dump_full,
+ .co_get_opts = htb_class_get_opts,
+};
+
+static void __init htb_init(void)
+{
+ rtnl_qdisc_register(&htb_qdisc_ops);
+ rtnl_class_register(&htb_class_ops);
+}
+
+static void __exit htb_exit(void)
+{
+ rtnl_qdisc_unregister(&htb_qdisc_ops);
+ rtnl_class_unregister(&htb_class_ops);
+}
+
+/** @} */
diff --git a/lib/route/sch/netem.c b/lib/route/sch/netem.c
new file mode 100644
index 0000000..e8b8913
--- /dev/null
+++ b/lib/route/sch/netem.c
@@ -0,0 +1,603 @@
+/*
+ * lib/route/sch/netem.c Network Emulator Qdisc
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup qdisc_api
+ * @defgroup netem Network Emulator
+ * @brief
+ *
+ * For further documentation see http://linux-net.osdl.org/index.php/Netem
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/route/qdisc.h>
+#include <netlink/route/qdisc-modules.h>
+#include <netlink/route/sch/netem.h>
+
+/** @cond SKIP */
+#define SCH_NETEM_ATTR_LATENCY 0x001
+#define SCH_NETEM_ATTR_LIMIT 0x002
+#define SCH_NETEM_ATTR_LOSS 0x004
+#define SCH_NETEM_ATTR_GAP 0x008
+#define SCH_NETEM_ATTR_DUPLICATE 0x010
+#define SCH_NETEM_ATTR_JITTER 0x020
+#define SCH_NETEM_ATTR_DELAY_CORR 0x040
+#define SCH_NETEM_ATTR_LOSS_CORR 0x080
+#define SCH_NETEM_ATTR_DUP_CORR 0x100
+#define SCH_NETEM_ATTR_RO_PROB 0x200
+#define SCH_NETEM_ATTR_RO_CORR 0x400
+/** @endcond */
+
+static inline struct rtnl_netem *netem_qdisc(struct rtnl_qdisc *qdisc)
+{
+ return (struct rtnl_netem *) qdisc->q_subdata;
+}
+
+static inline struct rtnl_netem *netem_alloc(struct rtnl_qdisc *qdisc)
+{
+ if (!qdisc->q_subdata)
+ qdisc->q_subdata = calloc(1, sizeof(struct rtnl_netem));
+
+ return netem_qdisc(qdisc);
+}
+
+static struct nla_policy netem_policy[TCA_NETEM_MAX+1] = {
+ [TCA_NETEM_CORR] = { .minlen = sizeof(struct tc_netem_corr) },
+ [TCA_NETEM_REORDER] = { .minlen = sizeof(struct tc_netem_reorder) },
+};
+
+static int netem_msg_parser(struct rtnl_qdisc *qdisc)
+{
+ int len, err = 0;
+ struct rtnl_netem *netem;
+ struct tc_netem_qopt *opts;
+
+ if (qdisc->q_opts->d_size < sizeof(*opts))
+ return nl_error(EINVAL, "Netem specific options size mismatch");
+
+ netem = netem_alloc(qdisc);
+ if (!netem)
+ return nl_errno(ENOMEM);
+
+ opts = (struct tc_netem_qopt *) qdisc->q_opts->d_data;
+ netem->qnm_latency = opts->latency;
+ netem->qnm_limit = opts->limit;
+ netem->qnm_loss = opts->loss;
+ netem->qnm_gap = opts->gap;
+ netem->qnm_duplicate = opts->duplicate;
+ netem->qnm_jitter = opts->jitter;
+
+ netem->qnm_mask = (SCH_NETEM_ATTR_LATENCY | SCH_NETEM_ATTR_LIMIT |
+ SCH_NETEM_ATTR_LOSS | SCH_NETEM_ATTR_GAP |
+ SCH_NETEM_ATTR_DUPLICATE | SCH_NETEM_ATTR_JITTER);
+
+ len = qdisc->q_opts->d_size - sizeof(*opts);
+
+ if (len > 0) {
+ struct nlattr *tb[TCA_NETEM_MAX+1];
+
+ err = nla_parse(tb, TCA_NETEM_MAX, (struct nlattr *)
+ qdisc->q_opts->d_data + sizeof(*opts),
+ len, netem_policy);
+ if (err < 0) {
+ free(netem);
+ return err;
+ }
+
+ if (tb[TCA_NETEM_CORR]) {
+ struct tc_netem_corr cor;
+
+ nla_memcpy(&cor, tb[TCA_NETEM_CORR], sizeof(cor));
+ netem->qnm_corr.nmc_delay = cor.delay_corr;
+ netem->qnm_corr.nmc_loss = cor.loss_corr;
+ netem->qnm_corr.nmc_duplicate = cor.dup_corr;
+
+ netem->qnm_mask |= (SCH_NETEM_ATTR_DELAY_CORR |
+ SCH_NETEM_ATTR_LOSS_CORR |
+ SCH_NETEM_ATTR_DELAY_CORR);
+ }
+
+ if (tb[TCA_NETEM_REORDER]) {
+ struct tc_netem_reorder ro;
+
+ nla_memcpy(&ro, tb[TCA_NETEM_REORDER], sizeof(ro));
+ netem->qnm_ro.nmro_probability = ro.probability;
+ netem->qnm_ro.nmro_correlation = ro.correlation;
+
+ netem->qnm_mask |= (SCH_NETEM_ATTR_RO_PROB |
+ SCH_NETEM_ATTR_RO_CORR);
+ }
+ }
+
+ return 0;
+}
+
+static void netem_free_data(struct rtnl_qdisc *qdisc)
+{
+ free(qdisc->q_subdata);
+}
+
+static int netem_dump_brief(struct rtnl_qdisc *qdisc, struct nl_dump_params *p,
+ int line)
+{
+ struct rtnl_netem *netem = netem_qdisc(qdisc);
+
+ if (netem)
+ dp_dump(p, "limit %d", netem->qnm_limit);
+
+ return line;
+}
+
+static int netem_dump_full(struct rtnl_qdisc *qdisc, struct nl_dump_params *p,
+ int line)
+{
+ return line;
+}
+
+static struct nl_msg *netem_get_opts(struct rtnl_qdisc *qdisc)
+{
+ return NULL;
+}
+
+/**
+ * @name Queue Limit
+ * @{
+ */
+
+/**
+ * Set limit of netem qdisc.
+ * @arg qdisc Netem qdisc to be modified.
+ * @arg limit New limit in bytes.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_netem_set_limit(struct rtnl_qdisc *qdisc, int limit)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_alloc(qdisc);
+ if (!netem)
+ return nl_errno(ENOMEM);
+
+ netem->qnm_limit = limit;
+ netem->qnm_mask |= SCH_NETEM_ATTR_LIMIT;
+
+ return 0;
+}
+
+/**
+ * Get limit of netem qdisc.
+ * @arg qdisc Netem qdisc.
+ * @return Limit in bytes or a negative error code.
+ */
+int rtnl_netem_get_limit(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_qdisc(qdisc);
+ if (netem && (netem->qnm_mask & SCH_NETEM_ATTR_LIMIT))
+ return netem->qnm_limit;
+ else
+ return nl_errno(ENOENT);
+}
+
+/** @} */
+
+/**
+ * @name Packet Re-ordering
+ * @{
+ */
+
+/**
+ * Set re-ordering gap of netem qdisc.
+ * @arg qdisc Netem qdisc to be modified.
+ * @arg gap New gap in number of packets.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_netem_set_gap(struct rtnl_qdisc *qdisc, int gap)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_alloc(qdisc);
+ if (!netem)
+ return nl_errno(ENOMEM);
+
+ netem->qnm_gap = gap;
+ netem->qnm_mask |= SCH_NETEM_ATTR_GAP;
+
+ return 0;
+}
+
+/**
+ * Get re-ordering gap of netem qdisc.
+ * @arg qdisc Netem qdisc.
+ * @return Re-ordering gap in packets or a negative error code.
+ */
+int rtnl_netem_get_gap(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_qdisc(qdisc);
+ if (netem && (netem->qnm_mask & SCH_NETEM_ATTR_GAP))
+ return netem->qnm_gap;
+ else
+ return nl_errno(ENOENT);
+}
+
+/**
+ * Set re-ordering probability of netem qdisc.
+ * @arg qdisc Netem qdisc to be modified.
+ * @arg prob New re-ordering probability.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_netem_set_reorder_probability(struct rtnl_qdisc *qdisc, int prob)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_alloc(qdisc);
+ if (!netem)
+ return nl_errno(ENOMEM);
+
+ netem->qnm_ro.nmro_probability = prob;
+ netem->qnm_mask |= SCH_NETEM_ATTR_RO_PROB;
+
+ return 0;
+}
+
+/**
+ * Get re-ordering probability of netem qdisc.
+ * @arg qdisc Netem qdisc.
+ * @return Re-ordering probability or a negative error code.
+ */
+int rtnl_netem_get_reorder_probability(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_qdisc(qdisc);
+ if (netem && (netem->qnm_mask & SCH_NETEM_ATTR_RO_PROB))
+ return netem->qnm_ro.nmro_probability;
+ else
+ return nl_errno(ENOENT);
+}
+
+/**
+ * Set re-order correlation probability of netem qdisc.
+ * @arg qdisc Netem qdisc to be modified.
+ * @arg prob New re-ordering correlation probability.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_netem_set_reorder_correlation(struct rtnl_qdisc *qdisc, int prob)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_alloc(qdisc);
+ if (!netem)
+ return nl_errno(ENOMEM);
+
+ netem->qnm_ro.nmro_correlation = prob;
+ netem->qnm_mask |= SCH_NETEM_ATTR_RO_CORR;
+
+ return 0;
+}
+
+/**
+ * Get re-ordering correlation probability of netem qdisc.
+ * @arg qdisc Netem qdisc.
+ * @return Re-ordering correlation probability or a negative error code.
+ */
+int rtnl_netem_get_reorder_correlation(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_qdisc(qdisc);
+ if (netem && (netem->qnm_mask & SCH_NETEM_ATTR_RO_CORR))
+ return netem->qnm_ro.nmro_correlation;
+ else
+ return nl_errno(ENOENT);
+}
+
+/** @} */
+
+/**
+ * @name Packet Loss
+ * @{
+ */
+
+/**
+ * Set packet loss probability of netem qdisc.
+ * @arg qdisc Netem qdisc to be modified.
+ * @arg prob New packet loss probability.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_netem_set_loss(struct rtnl_qdisc *qdisc, int prob)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_alloc(qdisc);
+ if (!netem)
+ return nl_errno(ENOMEM);
+
+ netem->qnm_loss = prob;
+ netem->qnm_mask |= SCH_NETEM_ATTR_LOSS;
+
+ return 0;
+}
+
+/**
+ * Get packet loss probability of netem qdisc.
+ * @arg qdisc Netem qdisc.
+ * @return Packet loss probability or a negative error code.
+ */
+int rtnl_netem_get_loss(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_qdisc(qdisc);
+ if (netem && (netem->qnm_mask & SCH_NETEM_ATTR_LOSS))
+ return netem->qnm_loss;
+ else
+ return nl_errno(ENOENT);
+}
+
+/**
+ * Set packet loss correlation probability of netem qdisc.
+ * @arg qdisc Netem qdisc to be modified.
+ * @arg prob New packet loss correlation.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_netem_set_loss_correlation(struct rtnl_qdisc *qdisc, int prob)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_alloc(qdisc);
+ if (!netem)
+ return nl_errno(ENOMEM);
+
+ netem->qnm_corr.nmc_loss = prob;
+ netem->qnm_mask |= SCH_NETEM_ATTR_LOSS_CORR;
+
+ return 0;
+}
+
+/**
+ * Get packet loss correlation probability of netem qdisc.
+ * @arg qdisc Netem qdisc.
+ * @return Packet loss correlation probability or a negative error code.
+ */
+int rtnl_netem_get_loss_correlation(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_qdisc(qdisc);
+ if (netem && (netem->qnm_mask & SCH_NETEM_ATTR_LOSS_CORR))
+ return netem->qnm_corr.nmc_loss;
+ else
+ return nl_errno(ENOENT);
+}
+
+/** @} */
+
+/**
+ * @name Packet Duplication
+ * @{
+ */
+
+/**
+ * Set packet duplication probability of netem qdisc.
+ * @arg qdisc Netem qdisc to be modified.
+ * @arg prob New packet duplication probability.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_netem_set_duplicate(struct rtnl_qdisc *qdisc, int prob)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_alloc(qdisc);
+ if (!netem)
+ return nl_errno(ENOMEM);
+
+ netem->qnm_duplicate = prob;
+ netem->qnm_mask |= SCH_NETEM_ATTR_DUPLICATE;
+
+ return 0;
+}
+
+/**
+ * Get packet duplication probability of netem qdisc.
+ * @arg qdisc Netem qdisc.
+ * @return Packet duplication probability or a negative error code.
+ */
+int rtnl_netem_get_duplicate(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_qdisc(qdisc);
+ if (netem && (netem->qnm_mask & SCH_NETEM_ATTR_DUPLICATE))
+ return netem->qnm_duplicate;
+ else
+ return nl_errno(ENOENT);
+}
+
+/**
+ * Set packet duplication correlation probability of netem qdisc.
+ * @arg qdisc Netem qdisc to be modified.
+ * @arg prob New packet duplication correlation probability.
+ * @return 0 on sucess or a negative error code.
+ */
+int rtnl_netem_set_duplicate_correlation(struct rtnl_qdisc *qdisc, int prob)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_alloc(qdisc);
+ if (!netem)
+ return nl_errno(ENOMEM);
+
+ netem->qnm_corr.nmc_duplicate = prob;
+ netem->qnm_mask |= SCH_NETEM_ATTR_DUP_CORR;
+
+ return 0;
+}
+
+/**
+ * Get packet duplication correlation probability of netem qdisc.
+ * @arg qdisc Netem qdisc.
+ * @return Packet duplication correlation probability or a negative error code.
+ */
+int rtnl_netem_get_duplicate_correlation(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_qdisc(qdisc);
+ if (netem && (netem->qnm_mask & SCH_NETEM_ATTR_DUP_CORR))
+ return netem->qnm_corr.nmc_duplicate;
+ else
+ return nl_errno(ENOENT);
+}
+
+/** @} */
+
+/**
+ * @name Packet Delay
+ * @{
+ */
+
+/**
+ * Set packet delay of netem qdisc.
+ * @arg qdisc Netem qdisc to be modified.
+ * @arg delay New packet delay in micro seconds.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_netem_set_delay(struct rtnl_qdisc *qdisc, int delay)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_alloc(qdisc);
+ if (!netem)
+ return nl_errno(ENOMEM);
+
+ netem->qnm_latency = nl_us2ticks(delay);
+ netem->qnm_mask |= SCH_NETEM_ATTR_LATENCY;
+
+ return 0;
+}
+
+/**
+ * Get packet delay of netem qdisc.
+ * @arg qdisc Netem qdisc.
+ * @return Packet delay in micro seconds or a negative error code.
+ */
+int rtnl_netem_get_delay(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_qdisc(qdisc);
+ if (netem && (netem->qnm_mask & SCH_NETEM_ATTR_LATENCY))
+ return nl_ticks2us(netem->qnm_latency);
+ else
+ return nl_errno(ENOENT);
+}
+
+/**
+ * Set packet delay jitter of netem qdisc.
+ * @arg qdisc Netem qdisc to be modified.
+ * @arg jitter New packet delay jitter in micro seconds.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_netem_set_jitter(struct rtnl_qdisc *qdisc, int jitter)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_alloc(qdisc);
+ if (!netem)
+ return nl_errno(ENOMEM);
+
+ netem->qnm_jitter = nl_us2ticks(jitter);
+ netem->qnm_mask |= SCH_NETEM_ATTR_JITTER;
+
+ return 0;
+}
+
+/**
+ * Get packet delay jitter of netem qdisc.
+ * @arg qdisc Netem qdisc.
+ * @return Packet delay jitter in micro seconds or a negative error code.
+ */
+int rtnl_netem_get_jitter(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_qdisc(qdisc);
+ if (netem && (netem->qnm_mask & SCH_NETEM_ATTR_JITTER))
+ return nl_ticks2us(netem->qnm_jitter);
+ else
+ return nl_errno(ENOENT);
+}
+
+/**
+ * Set packet delay correlation probability of netem qdisc.
+ * @arg qdisc Netem qdisc to be modified.
+ * @arg prob New packet delay correlation probability.
+ */
+int rtnl_netem_set_delay_correlation(struct rtnl_qdisc *qdisc, int prob)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_alloc(qdisc);
+ if (!netem)
+ return nl_errno(ENOMEM);
+
+ netem->qnm_corr.nmc_delay = prob;
+ netem->qnm_mask |= SCH_NETEM_ATTR_DELAY_CORR;
+
+ return 0;
+}
+
+/**
+ * Get packet delay correlation probability of netem qdisc.
+ * @arg qdisc Netem qdisc.
+ * @return Packet delay correlation probability or a negative error code.
+ */
+int rtnl_netem_get_delay_correlation(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_netem *netem;
+
+ netem = netem_qdisc(qdisc);
+ if (netem && (netem->qnm_mask & SCH_NETEM_ATTR_DELAY_CORR))
+ return netem->qnm_corr.nmc_delay;
+ else
+ return nl_errno(ENOENT);
+}
+
+/** @} */
+
+static struct rtnl_qdisc_ops netem_ops = {
+ .qo_kind = "netem",
+ .qo_msg_parser = netem_msg_parser,
+ .qo_free_data = netem_free_data,
+ .qo_dump[NL_DUMP_BRIEF] = netem_dump_brief,
+ .qo_dump[NL_DUMP_FULL] = netem_dump_full,
+ .qo_get_opts = netem_get_opts,
+};
+
+static void __init netem_init(void)
+{
+ rtnl_qdisc_register(&netem_ops);
+}
+
+static void __exit netem_exit(void)
+{
+ rtnl_qdisc_unregister(&netem_ops);
+}
+
+/** @} */
diff --git a/lib/route/sch/prio.c b/lib/route/sch/prio.c
new file mode 100644
index 0000000..4e3d624
--- /dev/null
+++ b/lib/route/sch/prio.c
@@ -0,0 +1,332 @@
+/*
+ * lib/route/sch/prio.c PRIO Qdisc/Class
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup qdisc_api
+ * @defgroup prio (Fast) Prio
+ * @brief
+ *
+ * @par 1) Typical PRIO configuration
+ * @code
+ * // Specify the maximal number of bands to be used for this PRIO qdisc.
+ * rtnl_qdisc_prio_set_bands(qdisc, QDISC_PRIO_DEFAULT_BANDS);
+ *
+ * // Provide a map assigning each priority to a band number.
+ * uint8_t map[] = QDISC_PRIO_DEFAULT_PRIOMAP;
+ * rtnl_qdisc_prio_set_priomap(qdisc, map, sizeof(map));
+ * @endcode
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/route/qdisc.h>
+#include <netlink/route/qdisc-modules.h>
+#include <netlink/route/sch/prio.h>
+
+/** @cond SKIP */
+#define SCH_PRIO_ATTR_BANDS 1
+#define SCH_PRIO_ATTR_PRIOMAP 2
+/** @endcond */
+
+static inline struct rtnl_prio *prio_qdisc(struct rtnl_qdisc *qdisc)
+{
+ return (struct rtnl_prio *) qdisc->q_subdata;
+}
+
+static inline struct rtnl_prio *prio_alloc(struct rtnl_qdisc *qdisc)
+{
+ if (!qdisc->q_subdata)
+ qdisc->q_subdata = calloc(1, sizeof(struct rtnl_prio));
+
+ return prio_qdisc(qdisc);
+}
+
+static int prio_msg_parser(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_prio *prio;
+ struct tc_prio_qopt *opt;
+
+ if (qdisc->q_opts->d_size < sizeof(*opt))
+ return nl_error(EINVAL, "prio specific option size mismatch");
+
+ prio = prio_alloc(qdisc);
+ if (!prio)
+ return nl_errno(ENOMEM);
+
+ opt = (struct tc_prio_qopt *) qdisc->q_opts->d_data;
+ prio->qp_bands = opt->bands;
+ memcpy(prio->qp_priomap, opt->priomap, sizeof(prio->qp_priomap));
+ prio->qp_mask = (SCH_PRIO_ATTR_BANDS | SCH_PRIO_ATTR_PRIOMAP);
+
+ return 0;
+}
+
+static void prio_free_data(struct rtnl_qdisc *qdisc)
+{
+ free(qdisc->q_subdata);
+}
+
+static int prio_dump_brief(struct rtnl_qdisc *qdisc,
+ struct nl_dump_params *p, int line)
+{
+ struct rtnl_prio *prio = prio_qdisc(qdisc);
+
+ if (prio)
+ dp_dump(p, " bands %u", prio->qp_bands);
+
+ return line;
+}
+
+static int prio_dump_full(struct rtnl_qdisc *qdisc,
+ struct nl_dump_params *p, int line)
+{
+ struct rtnl_prio *prio = prio_qdisc(qdisc);
+ int i, hp;
+
+ if (!prio)
+ goto ignore;
+
+ dp_dump(p, "priomap [");
+
+ for (i = 0; i <= TC_PRIO_MAX; i++)
+ dp_dump(p, "%u%s", prio->qp_priomap[i],
+ i < TC_PRIO_MAX ? " " : "");
+
+ dp_dump(p, "]\n");
+ dp_new_line(p, line++);
+
+ hp = (((TC_PRIO_MAX/2) + 1) & ~1);
+
+ for (i = 0; i < hp; i++) {
+ char a[32];
+ dp_dump(p, " %18s => %u",
+ rtnl_prio2str(i, a, sizeof(a)),
+ prio->qp_priomap[i]);
+ if (hp+i <= TC_PRIO_MAX) {
+ dp_dump(p, " %18s => %u",
+ rtnl_prio2str(hp+i, a, sizeof(a)),
+ prio->qp_priomap[hp+i]);
+ if (i < (hp - 1)) {
+ dp_dump(p, "\n");
+ dp_new_line(p, line++);
+ }
+ }
+ }
+
+ignore:
+ return line;
+}
+
+static struct nl_msg *prio_get_opts(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_prio *prio;
+ struct tc_prio_qopt opts;
+ struct nl_msg *msg;
+
+ prio = prio_qdisc(qdisc);
+ if (!prio ||
+ !(prio->qp_mask & SCH_PRIO_ATTR_PRIOMAP))
+ goto errout;
+
+ opts.bands = prio->qp_bands;
+ memcpy(opts.priomap, prio->qp_priomap, sizeof(opts.priomap));
+
+ msg = nlmsg_alloc();
+ if (!msg)
+ goto errout;
+
+ if (nlmsg_append(msg, &opts, sizeof(opts), NL_DONTPAD) < 0) {
+ nlmsg_free(msg);
+ goto errout;
+ }
+
+ return msg;
+errout:
+ return NULL;
+}
+
+/**
+ * @name Attribute Modification
+ * @{
+ */
+
+/**
+ * Set number of bands of PRIO qdisc.
+ * @arg qdisc PRIO qdisc to be modified.
+ * @arg bands New number of bands.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_qdisc_prio_set_bands(struct rtnl_qdisc *qdisc, int bands)
+{
+ struct rtnl_prio *prio;
+
+ prio = prio_alloc(qdisc);
+ if (!prio)
+ return nl_errno(ENOMEM);
+
+ prio->qp_bands = bands;
+ prio->qp_mask |= SCH_PRIO_ATTR_BANDS;
+
+ return 0;
+}
+
+/**
+ * Get number of bands of PRIO qdisc.
+ * @arg qdisc PRIO qdisc.
+ * @return Number of bands or a negative error code.
+ */
+int rtnl_qdisc_prio_get_bands(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_prio *prio;
+
+ prio = prio_qdisc(qdisc);
+ if (prio && prio->qp_mask & SCH_PRIO_ATTR_BANDS)
+ return prio->qp_bands;
+ else
+ return nl_errno(ENOMEM);
+}
+
+/**
+ * Set priomap of the PRIO qdisc.
+ * @arg qdisc PRIO qdisc to be modified.
+ * @arg priomap New priority mapping.
+ * @arg len Length of priomap (# of elements).
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_qdisc_prio_set_priomap(struct rtnl_qdisc *qdisc, uint8_t priomap[],
+ int len)
+{
+ struct rtnl_prio *prio;
+ int i;
+
+ prio = prio_alloc(qdisc);
+ if (!prio)
+ return nl_errno(ENOMEM);
+
+ if (!(prio->qp_mask & SCH_PRIO_ATTR_BANDS))
+ return nl_error(EINVAL, "Set number of bands first");
+
+ if ((len / sizeof(uint8_t)) > (TC_PRIO_MAX+1))
+ return nl_error(ERANGE, "priomap length out of bounds");
+
+ for (i = 0; i <= TC_PRIO_MAX; i++) {
+ if (priomap[i] > prio->qp_bands)
+ return nl_error(ERANGE, "priomap element %d " \
+ "out of bounds, increase bands number");
+ }
+
+ memcpy(prio->qp_priomap, priomap, len);
+ prio->qp_mask |= SCH_PRIO_ATTR_PRIOMAP;
+
+ return 0;
+}
+
+/**
+ * Get priomap of a PRIO qdisc.
+ * @arg qdisc PRIO qdisc.
+ * @return Priority mapping as array of size TC_PRIO_MAX+1
+ * or NULL if an error occured.
+ */
+uint8_t *rtnl_qdisc_prio_get_priomap(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_prio *prio;
+
+ prio = prio_qdisc(qdisc);
+ if (prio && prio->qp_mask & SCH_PRIO_ATTR_PRIOMAP)
+ return prio->qp_priomap;
+ else {
+ nl_errno(ENOENT);
+ return NULL;
+ }
+}
+
+/** @} */
+
+/**
+ * @name Priority Band Translations
+ * @{
+ */
+
+static struct trans_tbl prios[] = {
+ __ADD(TC_PRIO_BESTEFFORT,besteffort)
+ __ADD(TC_PRIO_FILLER,filler)
+ __ADD(TC_PRIO_BULK,bulk)
+ __ADD(TC_PRIO_INTERACTIVE_BULK,interactive_bulk)
+ __ADD(TC_PRIO_INTERACTIVE,interactive)
+ __ADD(TC_PRIO_CONTROL,control)
+};
+
+/**
+ * Convert priority to character string.
+ * @arg prio Priority.
+ * @arg buf Destination buffer
+ * @arg size Size of destination buffer.
+ *
+ * Converts a priority to a character string and stores the result in
+ * the specified destination buffer.
+ *
+ * @return Name of priority as character string.
+ */
+char * rtnl_prio2str(int prio, char *buf, size_t size)
+{
+ return __type2str(prio, buf, size, prios, ARRAY_SIZE(prios));
+}
+
+/**
+ * Convert character string to priority.
+ * @arg name Name of priority.
+ *
+ * Converts the provided character string specifying a priority
+ * to the corresponding numeric value.
+ *
+ * @return Numeric priority or a negative value if no match was found.
+ */
+int rtnl_str2prio(const char *name)
+{
+ return __str2type(name, prios, ARRAY_SIZE(prios));
+}
+
+/** @} */
+
+static struct rtnl_qdisc_ops prio_ops = {
+ .qo_kind = "prio",
+ .qo_msg_parser = prio_msg_parser,
+ .qo_free_data = prio_free_data,
+ .qo_dump[NL_DUMP_BRIEF] = prio_dump_brief,
+ .qo_dump[NL_DUMP_FULL] = prio_dump_full,
+ .qo_get_opts = prio_get_opts,
+};
+
+static struct rtnl_qdisc_ops pfifo_fast_ops = {
+ .qo_kind = "pfifo_fast",
+ .qo_msg_parser = prio_msg_parser,
+ .qo_free_data = prio_free_data,
+ .qo_dump[NL_DUMP_BRIEF] = prio_dump_brief,
+ .qo_dump[NL_DUMP_FULL] = prio_dump_full,
+ .qo_get_opts = prio_get_opts,
+};
+
+static void __init prio_init(void)
+{
+ rtnl_qdisc_register(&prio_ops);
+ rtnl_qdisc_register(&pfifo_fast_ops);
+}
+
+static void __exit prio_exit(void)
+{
+ rtnl_qdisc_unregister(&prio_ops);
+ rtnl_qdisc_unregister(&pfifo_fast_ops);
+}
+
+/** @} */
diff --git a/lib/route/sch/red.c b/lib/route/sch/red.c
new file mode 100644
index 0000000..a31c358
--- /dev/null
+++ b/lib/route/sch/red.c
@@ -0,0 +1,219 @@
+/*
+ * lib/route/sch/red.c RED Qdisc
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup qdisc_api
+ * @defgroup red Random Early Detection (RED)
+ * @brief
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/route/qdisc.h>
+#include <netlink/route/qdisc-modules.h>
+#include <netlink/route/sch/red.h>
+
+/** @cond SKIP */
+#define RED_ATTR_LIMIT 0x01
+#define RED_ATTR_QTH_MIN 0x02
+#define RED_ATTR_QTH_MAX 0x04
+#define RED_ATTR_FLAGS 0x08
+#define RED_ATTR_WLOG 0x10
+#define RED_ATTR_PLOG 0x20
+#define RED_ATTR_SCELL_LOG 0x40
+/** @endcond */
+
+static inline struct rtnl_red *red_qdisc(struct rtnl_qdisc *qdisc)
+{
+ return (struct rtnl_red *) qdisc->q_subdata;
+}
+
+static inline struct rtnl_red *red_alloc(struct rtnl_qdisc *qdisc)
+{
+ if (!qdisc->q_subdata)
+ qdisc->q_subdata = calloc(1, sizeof(struct rtnl_red));
+
+ return red_qdisc(qdisc);
+}
+
+static struct nla_policy red_policy[TCA_RED_MAX+1] = {
+ [TCA_RED_PARMS] = { .minlen = sizeof(struct tc_red_qopt) },
+};
+
+static int red_msg_parser(struct rtnl_qdisc *qdisc)
+{
+ struct nlattr *tb[TCA_RED_MAX+1];
+ struct rtnl_red *red;
+ struct tc_red_qopt *opts;
+ int err;
+
+ if (!(qdisc->ce_mask & TCA_ATTR_OPTS))
+ return 0;
+
+ err = tca_parse(tb, TCA_RED_MAX, (struct rtnl_tca *) qdisc, red_policy);
+ if (err < 0)
+ return err;
+
+ if (!tb[TCA_RED_PARMS])
+ return nl_error(EINVAL, "Missing TCA_RED_PARMS");
+
+ red = red_alloc(qdisc);
+ if (!red)
+ return nl_errno(ENOMEM);
+
+ opts = nla_data(tb[TCA_RED_PARMS]);
+
+ red->qr_limit = opts->limit;
+ red->qr_qth_min = opts->qth_min;
+ red->qr_qth_max = opts->qth_max;
+ red->qr_flags = opts->flags;
+ red->qr_wlog = opts->Wlog;
+ red->qr_plog = opts->Plog;
+ red->qr_scell_log = opts->Scell_log;
+
+ red->qr_mask = (RED_ATTR_LIMIT | RED_ATTR_QTH_MIN | RED_ATTR_QTH_MAX |
+ RED_ATTR_FLAGS | RED_ATTR_WLOG | RED_ATTR_PLOG |
+ RED_ATTR_SCELL_LOG);
+
+ return 0;
+}
+
+static int red_dump_brief(struct rtnl_qdisc *qdisc, struct nl_dump_params *p,
+ int line)
+{
+ struct rtnl_red *red = red_qdisc(qdisc);
+
+ if (red) {
+ /* XXX: limit, min, max, flags */
+ }
+
+ return line;
+}
+
+static int red_dump_full(struct rtnl_qdisc *qdisc, struct nl_dump_params *p,
+ int line)
+{
+ struct rtnl_red *red = red_qdisc(qdisc);
+
+ if (red) {
+ /* XXX: wlog, plog, scell_log */
+ }
+
+ return line;
+}
+
+static int red_dump_stats(struct rtnl_qdisc *qdisc, struct nl_dump_params *p,
+ int line)
+{
+ struct rtnl_red *red = red_qdisc(qdisc);
+
+ if (red) {
+ /* XXX: xstats */
+ }
+
+ return line;
+}
+
+static struct nl_msg *red_get_opts(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_red *red;
+ struct nl_msg *msg;
+
+ red = red_qdisc(qdisc);
+ if (!red)
+ return NULL;
+
+ msg = nlmsg_alloc();
+ if (!msg)
+ goto errout;
+
+#if 0
+ memset(&opts, 0, sizeof(opts));
+ opts.quantum = sfq->qs_quantum;
+ opts.perturb_period = sfq->qs_perturb;
+ opts.limit = sfq->qs_limit;
+
+ if (nlmsg_append(msg, &opts, sizeof(opts), NL_DONTPAD) < 0)
+ goto errout;
+#endif
+
+ return msg;
+errout:
+ nlmsg_free(msg);
+ return NULL;
+}
+
+/**
+ * @name Attribute Access
+ * @{
+ */
+
+/**
+ * Set limit of RED qdisc.
+ * @arg qdisc RED qdisc to be modified.
+ * @arg limit New limit in number of packets.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_red_set_limit(struct rtnl_qdisc *qdisc, int limit)
+{
+ struct rtnl_red *red;
+
+ red = red_alloc(qdisc);
+ if (!red)
+ return nl_errno(ENOMEM);
+
+ red->qr_limit = limit;
+ red->qr_mask |= RED_ATTR_LIMIT;
+
+ return 0;
+}
+
+/**
+ * Get limit of RED qdisc.
+ * @arg qdisc RED qdisc.
+ * @return Limit or a negative error code.
+ */
+int rtnl_red_get_limit(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_red *red;
+
+ red = red_qdisc(qdisc);
+ if (red && (red->qr_mask & RED_ATTR_LIMIT))
+ return red->qr_limit;
+ else
+ return nl_errno(ENOENT);
+}
+
+/** @} */
+
+static struct rtnl_qdisc_ops red_ops = {
+ .qo_kind = "red",
+ .qo_msg_parser = red_msg_parser,
+ .qo_dump[NL_DUMP_BRIEF] = red_dump_brief,
+ .qo_dump[NL_DUMP_FULL] = red_dump_full,
+ .qo_dump[NL_DUMP_STATS] = red_dump_stats,
+ .qo_get_opts = red_get_opts,
+};
+
+static void __init red_init(void)
+{
+ rtnl_qdisc_register(&red_ops);
+}
+
+static void __exit red_exit(void)
+{
+ rtnl_qdisc_unregister(&red_ops);
+}
+
+/** @} */
diff --git a/lib/route/sch/sfq.c b/lib/route/sch/sfq.c
new file mode 100644
index 0000000..d530c0f
--- /dev/null
+++ b/lib/route/sch/sfq.c
@@ -0,0 +1,294 @@
+/*
+ * lib/route/sch/sfq.c SFQ Qdisc
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup qdisc_api
+ * @defgroup sfq Stochastic Fairness Queueing (SFQ)
+ * @brief
+ *
+ * @par Parameter Description
+ * - \b Quantum: Number of bytes to send out per slot and round.
+ * - \b Perturbation: Timer period between changing the hash function.
+ * - \b Limit: Upper limit of queue in number of packets before SFQ starts
+ * dropping packets.
+ * - \b Divisor: Hash table divisor, i.e. size of hash table.
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/route/qdisc.h>
+#include <netlink/route/qdisc-modules.h>
+#include <netlink/route/sch/sfq.h>
+
+/** @cond SKIP */
+#define SCH_SFQ_ATTR_QUANTUM 0x01
+#define SCH_SFQ_ATTR_PERTURB 0x02
+#define SCH_SFQ_ATTR_LIMIT 0x04
+#define SCH_SFQ_ATTR_DIVISOR 0x08
+#define SCH_SFQ_ATTR_FLOWS 0x10
+/** @endcond */
+
+static inline struct rtnl_sfq *sfq_qdisc(struct rtnl_qdisc *qdisc)
+{
+ return (struct rtnl_sfq *) qdisc->q_subdata;
+}
+
+static inline struct rtnl_sfq *sfq_alloc(struct rtnl_qdisc *qdisc)
+{
+ if (!qdisc->q_subdata)
+ qdisc->q_subdata = calloc(1, sizeof(struct rtnl_sfq));
+
+ return sfq_qdisc(qdisc);
+}
+
+static int sfq_msg_parser(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_sfq *sfq;
+ struct tc_sfq_qopt *opts;
+
+ if (!(qdisc->ce_mask & TCA_ATTR_OPTS))
+ return 0;
+
+ if (qdisc->q_opts->d_size < sizeof(*opts))
+ return nl_error(EINVAL, "SFQ specific options size mismatch");
+
+ sfq = sfq_alloc(qdisc);
+ if (!sfq)
+ return nl_errno(ENOMEM);
+
+ opts = (struct tc_sfq_qopt *) qdisc->q_opts->d_data;
+
+ sfq->qs_quantum = opts->quantum;
+ sfq->qs_perturb = opts->perturb_period;
+ sfq->qs_limit = opts->limit;
+ sfq->qs_divisor = opts->divisor;
+ sfq->qs_flows = opts->flows;
+
+ sfq->qs_mask = (SCH_SFQ_ATTR_QUANTUM | SCH_SFQ_ATTR_PERTURB |
+ SCH_SFQ_ATTR_LIMIT | SCH_SFQ_ATTR_DIVISOR |
+ SCH_SFQ_ATTR_FLOWS);
+
+ return 0;
+}
+
+static void sfq_free_data(struct rtnl_qdisc *qdisc)
+{
+ free(qdisc->q_subdata);
+}
+
+static int sfq_dump_brief(struct rtnl_qdisc *qdisc, struct nl_dump_params *p,
+ int line)
+{
+ struct rtnl_sfq *sfq = sfq_qdisc(qdisc);
+
+ if (sfq)
+ dp_dump(p, " quantum %u perturb %us",
+ sfq->qs_quantum,
+ nl_ticks2us(sfq->qs_perturb * nl_get_hz()));
+
+ return line;
+}
+
+static int sfq_dump_full(struct rtnl_qdisc *qdisc, struct nl_dump_params *p,
+ int line)
+{
+ struct rtnl_sfq *sfq = sfq_qdisc(qdisc);
+
+ if (sfq)
+ dp_dump(p, "limit %u divisor %u",
+ sfq->qs_limit, sfq->qs_divisor);
+
+ return line;
+}
+
+static struct nl_msg *sfq_get_opts(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_sfq *sfq;
+ struct tc_sfq_qopt opts;
+ struct nl_msg *msg;
+
+ sfq = sfq_qdisc(qdisc);
+ if (!sfq)
+ return NULL;
+
+ msg = nlmsg_alloc();
+ if (!msg)
+ goto errout;
+
+ memset(&opts, 0, sizeof(opts));
+ opts.quantum = sfq->qs_quantum;
+ opts.perturb_period = sfq->qs_perturb;
+ opts.limit = sfq->qs_limit;
+
+ if (nlmsg_append(msg, &opts, sizeof(opts), NL_DONTPAD) < 0)
+ goto errout;
+
+ return msg;
+errout:
+ nlmsg_free(msg);
+ return NULL;
+}
+
+/**
+ * @name Attribute Access
+ * @{
+ */
+
+/**
+ * Set quantum of SFQ qdisc.
+ * @arg qdisc SFQ qdisc to be modified.
+ * @arg quantum New quantum in bytes.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_sfq_set_quantum(struct rtnl_qdisc *qdisc, int quantum)
+{
+ struct rtnl_sfq *sfq;
+
+ sfq = sfq_alloc(qdisc);
+ if (!sfq)
+ return nl_errno(ENOMEM);
+
+ sfq->qs_quantum = quantum;
+ sfq->qs_mask |= SCH_SFQ_ATTR_QUANTUM;
+
+ return 0;
+}
+
+/**
+ * Get quantum of SFQ qdisc.
+ * @arg qdisc SFQ qdisc.
+ * @return Quantum in bytes or a negative error code.
+ */
+int rtnl_sfq_get_quantum(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_sfq *sfq;
+
+ sfq = sfq_qdisc(qdisc);
+ if (sfq && sfq->qs_mask & SCH_SFQ_ATTR_QUANTUM)
+ return sfq->qs_quantum;
+ else
+ return nl_errno(ENOENT);
+}
+
+/**
+ * Set limit of SFQ qdisc.
+ * @arg qdisc SFQ qdisc to be modified.
+ * @arg limit New limit in number of packets.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_sfq_set_limit(struct rtnl_qdisc *qdisc, int limit)
+{
+ struct rtnl_sfq *sfq;
+
+ sfq = sfq_alloc(qdisc);
+ if (!sfq)
+ return nl_errno(ENOMEM);
+
+ sfq->qs_limit = limit;
+ sfq->qs_mask |= SCH_SFQ_ATTR_LIMIT;
+
+ return 0;
+}
+
+/**
+ * Get limit of SFQ qdisc.
+ * @arg qdisc SFQ qdisc.
+ * @return Limit or a negative error code.
+ */
+int rtnl_sfq_get_limit(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_sfq *sfq;
+
+ sfq = sfq_qdisc(qdisc);
+ if (sfq && sfq->qs_mask & SCH_SFQ_ATTR_LIMIT)
+ return sfq->qs_limit;
+ else
+ return nl_errno(ENOENT);
+}
+
+/**
+ * Set perturbation interval of SFQ qdisc.
+ * @arg qdisc SFQ qdisc to be modified.
+ * @arg perturb New perturbation interval in seconds.
+ * @note A value of 0 disables perturbation altogether.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_sfq_set_perturb(struct rtnl_qdisc *qdisc, int perturb)
+{
+ struct rtnl_sfq *sfq;
+
+ sfq = sfq_alloc(qdisc);
+ if (!sfq)
+ return nl_errno(ENOMEM);
+
+ sfq->qs_perturb = perturb;
+ sfq->qs_mask |= SCH_SFQ_ATTR_PERTURB;
+
+ return 0;
+}
+
+/**
+ * Get perturbation interval of SFQ qdisc.
+ * @arg qdisc SFQ qdisc.
+ * @return Perturbation interval in seconds or a negative error code.
+ */
+int rtnl_sfq_get_perturb(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_sfq *sfq;
+
+ sfq = sfq_qdisc(qdisc);
+ if (sfq && sfq->qs_mask & SCH_SFQ_ATTR_PERTURB)
+ return sfq->qs_perturb;
+ else
+ return nl_errno(ENOENT);
+}
+
+/**
+ * Get divisor of SFQ qdisc.
+ * @arg qdisc SFQ qdisc.
+ * @return Divisor in number of entries or a negative error code.
+ */
+int rtnl_sfq_get_divisor(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_sfq *sfq;
+
+ sfq = sfq_qdisc(qdisc);
+ if (sfq && sfq->qs_mask & SCH_SFQ_ATTR_DIVISOR)
+ return sfq->qs_divisor;
+ else
+ return nl_errno(ENOENT);
+}
+
+/** @} */
+
+static struct rtnl_qdisc_ops sfq_ops = {
+ .qo_kind = "sfq",
+ .qo_msg_parser = sfq_msg_parser,
+ .qo_free_data = sfq_free_data,
+ .qo_dump[NL_DUMP_BRIEF] = sfq_dump_brief,
+ .qo_dump[NL_DUMP_FULL] = sfq_dump_full,
+ .qo_get_opts = sfq_get_opts,
+};
+
+static void __init sfq_init(void)
+{
+ rtnl_qdisc_register(&sfq_ops);
+}
+
+static void __exit sfq_exit(void)
+{
+ rtnl_qdisc_unregister(&sfq_ops);
+}
+
+/** @} */
diff --git a/lib/route/sch/tbf.c b/lib/route/sch/tbf.c
new file mode 100644
index 0000000..04d1689
--- /dev/null
+++ b/lib/route/sch/tbf.c
@@ -0,0 +1,540 @@
+/*
+ * lib/route/sch/tbf.c TBF Qdisc
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup qdisc_api
+ * @defgroup tbf Token Bucket Filter (TBF)
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/cache.h>
+#include <netlink/utils.h>
+#include <netlink/route/tc.h>
+#include <netlink/route/qdisc.h>
+#include <netlink/route/qdisc-modules.h>
+#include <netlink/route/class.h>
+#include <netlink/route/class-modules.h>
+#include <netlink/route/link.h>
+#include <netlink/route/sch/tbf.h>
+
+/** @cond SKIP */
+#define TBF_ATTR_LIMIT 0x01
+#define TBF_ATTR_RATE 0x02
+#define TBF_ATTR_PEAKRATE 0x10
+#define TBF_ATTR_MPU 0x80
+/** @endcond */
+
+static inline struct rtnl_tbf *tbf_qdisc(struct rtnl_qdisc *qdisc)
+{
+ return (struct rtnl_tbf *) qdisc->q_subdata;
+}
+
+static inline struct rtnl_tbf *tbf_alloc(struct rtnl_qdisc *qdisc)
+{
+ if (!qdisc->q_subdata)
+ qdisc->q_subdata = calloc(1, sizeof(struct rtnl_tbf));
+
+ return tbf_qdisc(qdisc);
+}
+
+static struct nla_policy tbf_policy[TCA_TBF_MAX+1] = {
+ [TCA_TBF_PARMS] = { .minlen = sizeof(struct tc_tbf_qopt) },
+};
+
+static int tbf_msg_parser(struct rtnl_qdisc *q)
+{
+ int err;
+ struct nlattr *tb[TCA_TBF_MAX + 1];
+ struct rtnl_tbf *tbf;
+
+ err = tca_parse(tb, TCA_TBF_MAX, (struct rtnl_tca *) q, tbf_policy);
+ if (err < 0)
+ return err;
+
+ tbf = tbf_qdisc(q);
+ if (!tbf)
+ return nl_errno(ENOMEM);
+
+ if (tb[TCA_TBF_PARMS]) {
+ struct tc_tbf_qopt opts;
+ int bufsize;
+
+ nla_memcpy(&opts, tb[TCA_TBF_PARMS], sizeof(opts));
+ tbf->qt_limit = opts.limit;
+ tbf->qt_mpu = opts.rate.mpu;
+
+ rtnl_copy_ratespec(&tbf->qt_rate, &opts.rate);
+ tbf->qt_rate_txtime = opts.buffer;
+ bufsize = rtnl_tc_calc_bufsize(nl_ticks2us(opts.buffer),
+ opts.rate.rate);
+ tbf->qt_rate_bucket = bufsize;
+
+ rtnl_copy_ratespec(&tbf->qt_peakrate, &opts.peakrate);
+ tbf->qt_peakrate_txtime = opts.mtu;
+ bufsize = rtnl_tc_calc_bufsize(nl_ticks2us(opts.mtu),
+ opts.peakrate.rate);
+ tbf->qt_peakrate_bucket = bufsize;
+
+ tbf->qt_mask = (TBF_ATTR_LIMIT | TBF_ATTR_MPU | TBF_ATTR_RATE |
+ TBF_ATTR_PEAKRATE);
+ }
+
+ return 0;
+}
+
+static int tbf_dump_brief(struct rtnl_qdisc *qdisc, struct nl_dump_params *p,
+ int line)
+{
+ double r, rbit, lim;
+ char *ru, *rubit, *limu;
+ struct rtnl_tbf *tbf = tbf_qdisc(qdisc);
+
+ if (!tbf)
+ goto ignore;
+
+ r = nl_cancel_down_bytes(tbf->qt_rate.rs_rate, &ru);
+ rbit = nl_cancel_down_bits(tbf->qt_rate.rs_rate*8, &rubit);
+ lim = nl_cancel_down_bytes(tbf->qt_limit, &limu);
+
+ dp_dump(p, " rate %.2f%s/s (%.0f%s) limit %.2f%s",
+ r, ru, rbit, rubit, lim, limu);
+
+ignore:
+ return line;
+}
+
+static int tbf_dump_full(struct rtnl_qdisc *qdisc, struct nl_dump_params *p,
+ int line)
+{
+ struct rtnl_tbf *tbf = tbf_qdisc(qdisc);
+
+ if (!tbf)
+ goto ignore;
+
+ if (1) {
+ char *bu, *cu;
+ double bs = nl_cancel_down_bytes(tbf->qt_rate_bucket, &bu);
+ double cl = nl_cancel_down_bytes(1 << tbf->qt_rate.rs_cell_log,
+ &cu);
+
+ dp_dump(p, "mpu %u rate-bucket-size %1.f%s "
+ "rate-cell-size %.1f%s\n",
+ tbf->qt_mpu, bs, bu, cl, cu);
+
+ }
+
+ if (tbf->qt_mask & TBF_ATTR_PEAKRATE) {
+ char *pru, *prbu, *bsu, *clu;
+ double pr, prb, bs, cl;
+
+ pr = nl_cancel_down_bytes(tbf->qt_peakrate.rs_rate, &pru);
+ prb = nl_cancel_down_bits(tbf->qt_peakrate.rs_rate * 8, &prbu);
+ bs = nl_cancel_down_bits(tbf->qt_peakrate_bucket, &bsu);
+ cl = nl_cancel_down_bits(1 << tbf->qt_peakrate.rs_cell_log,
+ &clu);
+
+ dp_dump_line(p, line++, " peak-rate %.2f%s/s (%.0f%s) "
+ "bucket-size %.1f%s cell-size %.1f%s",
+ "latency %.1f%s",
+ pr, pru, prb, prbu, bs, bsu, cl, clu);
+ }
+
+ignore:
+ return line;
+}
+
+static struct nl_msg *tbf_get_opts(struct rtnl_qdisc *qdisc)
+{
+ struct tc_tbf_qopt opts;
+ struct rtnl_tbf *tbf;
+ struct nl_msg *msg;
+ uint32_t rtab[RTNL_TC_RTABLE_SIZE];
+ uint32_t ptab[RTNL_TC_RTABLE_SIZE];
+ int required = TBF_ATTR_RATE | TBF_ATTR_LIMIT;
+
+ memset(&opts, 0, sizeof(opts));
+
+ tbf = tbf_qdisc(qdisc);
+ if (!tbf)
+ return NULL;
+
+ if (!(tbf->qt_mask & required) != required)
+ return NULL;
+
+ opts.limit = tbf->qt_limit;
+ opts.buffer = tbf->qt_rate_txtime;
+ tbf->qt_rate.rs_mpu = tbf->qt_mpu;
+ rtnl_rcopy_ratespec(&opts.rate, &tbf->qt_rate);
+
+ rtnl_tc_build_rate_table(rtab, tbf->qt_mpu & 0xff, tbf->qt_mpu >> 8,
+ 1 << tbf->qt_rate.rs_cell_log,
+ tbf->qt_rate.rs_rate);
+
+ if (tbf->qt_mask & TBF_ATTR_PEAKRATE) {
+ opts.mtu = tbf->qt_peakrate_txtime;
+ tbf->qt_peakrate.rs_mpu = tbf->qt_mpu;
+ rtnl_rcopy_ratespec(&opts.peakrate, &tbf->qt_peakrate);
+
+ rtnl_tc_build_rate_table(ptab, tbf->qt_mpu & 0xff,
+ tbf->qt_mpu >> 8,
+ 1 << tbf->qt_peakrate.rs_cell_log,
+ tbf->qt_peakrate.rs_rate);
+ }
+
+ msg = nlmsg_alloc();
+ if (!msg)
+ goto nla_put_failure;
+
+ NLA_PUT(msg, TCA_TBF_PARMS, sizeof(opts), &opts);
+ NLA_PUT(msg, TCA_TBF_RTAB, sizeof(rtab), rtab);
+
+ if (tbf->qt_mask & TBF_ATTR_PEAKRATE)
+ NLA_PUT(msg, TCA_TBF_PTAB, sizeof(ptab), ptab);
+
+ return msg;
+
+nla_put_failure:
+ nlmsg_free(msg);
+ return NULL;
+}
+
+/**
+ * @name Attribute Access
+ * @{
+ */
+
+/**
+ * Set limit of TBF qdisc.
+ * @arg qdisc TBF qdisc to be modified.
+ * @arg limit New limit in bytes.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_qdisc_tbf_set_limit(struct rtnl_qdisc *qdisc, int limit)
+{
+ struct rtnl_tbf *tbf;
+
+ tbf = tbf_alloc(qdisc);
+ if (!tbf)
+ return nl_errno(ENOMEM);
+
+ tbf->qt_limit = limit;
+ tbf->qt_mask |= TBF_ATTR_LIMIT;
+
+ return 0;
+}
+
+static inline double calc_limit(struct rtnl_ratespec *spec, int latency,
+ int bucket)
+{
+ double limit;
+
+ limit = (double) spec->rs_rate * ((double) latency / 1000000.);
+ limit += bucket;
+
+ return limit;
+}
+
+/**
+ * Set limit of TBF qdisc by latency.
+ * @arg qdisc TBF qdisc to be modified.
+ * @arg latency Latency in micro seconds.
+ *
+ * Calculates and sets the limit based on the desired latency and the
+ * configured rate and peak rate. In order for this operation to succeed,
+ * the rate and if required the peak rate must have been set in advance.
+ *
+ * @f[
+ * limit_n = \frac{{rate_n} \times {latency}}{10^6}+{bucketsize}_n
+ * @f]
+ * @f[
+ * limit = min(limit_{rate},limit_{peak})
+ * @f]
+ *
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_qdisc_tbf_set_limit_by_latency(struct rtnl_qdisc *qdisc, int latency)
+{
+ struct rtnl_tbf *tbf;
+ double limit, limit2;
+
+ tbf = tbf_alloc(qdisc);
+ if (!tbf)
+ return nl_errno(ENOMEM);
+
+ if (!(tbf->qt_mask & TBF_ATTR_RATE))
+ return nl_error(EINVAL, "The rate must be specified before "
+ "limit can be calculated based on latency.");
+
+ limit = calc_limit(&tbf->qt_rate, latency, tbf->qt_rate_bucket);
+
+ if (tbf->qt_mask & TBF_ATTR_PEAKRATE) {
+ limit2 = calc_limit(&tbf->qt_peakrate, latency,
+ tbf->qt_peakrate_bucket);
+
+ if (limit2 < limit)
+ limit = limit2;
+ }
+
+ return rtnl_qdisc_tbf_set_limit(qdisc, (int) limit);
+}
+
+/**
+ * Get limit of TBF qdisc.
+ * @arg qdisc TBF qdisc.
+ * @return Limit in bytes or a negative error code.
+ */
+int rtnl_qdisc_tbf_get_limit(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_tbf *tbf;
+
+ tbf = tbf_qdisc(qdisc);
+ if (tbf && (tbf->qt_mask & TBF_ATTR_LIMIT))
+ return tbf->qt_limit;
+ return
+ nl_errno(ENOENT);
+}
+
+/**
+ * Set MPU of TBF qdisc.
+ * @arg qdisc TBF qdisc to be modified.
+ * @arg mpu New MPU in bytes.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_qdisc_tbf_set_mpu(struct rtnl_qdisc *qdisc, int mpu)
+{
+ struct rtnl_tbf *tbf;
+
+ tbf = tbf_alloc(qdisc);
+ if (!tbf)
+ return nl_errno(ENOMEM);
+
+ tbf->qt_mpu = mpu;
+ tbf->qt_mask |= TBF_ATTR_MPU;
+
+ return 0;
+}
+
+/**
+ * Get MPU of TBF qdisc.
+ * @arg qdisc TBF qdisc.
+ * @return MPU in bytes or a negative error code.
+ */
+int rtnl_qdisc_tbf_get_mpu(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_tbf *tbf;
+
+ tbf = tbf_qdisc(qdisc);
+ if (tbf && (tbf->qt_mask & TBF_ATTR_MPU))
+ return tbf->qt_mpu;
+ return
+ nl_errno(ENOENT);
+}
+
+static inline int calc_cell_log(int cell, int bucket)
+{
+ if (cell > 0)
+ cell = rtnl_tc_calc_cell_log(cell);
+ else {
+ cell = 0;
+
+ if (!bucket)
+ bucket = 2047; /* defaults to cell_log=3 */
+
+ while ((bucket >> cell) > 255)
+ cell++;
+ }
+
+ return cell;
+}
+
+/**
+ * Set rate of TBF qdisc.
+ * @arg qdisc TBF qdisc to be modified.
+ * @arg rate New rate in bytes per second.
+ * @arg bucket Size of bucket in bytes.
+ * @arg cell Size of a rate cell or 0 to get default value.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_qdisc_tbf_set_rate(struct rtnl_qdisc *qdisc, int rate, int bucket,
+ int cell)
+{
+ struct rtnl_tbf *tbf;
+ int cell_log;
+
+ tbf = tbf_alloc(qdisc);
+ if (!tbf)
+ return nl_errno(ENOMEM);
+
+ cell_log = calc_cell_log(cell, bucket);
+ if (cell_log < 0)
+ return cell_log;
+
+ tbf->qt_rate.rs_rate = rate;
+ tbf->qt_rate_bucket = bucket;
+ tbf->qt_rate.rs_cell_log = cell_log;
+ tbf->qt_rate_txtime = rtnl_tc_calc_txtime(bucket, rate);
+ tbf->qt_mask |= TBF_ATTR_RATE;
+
+ return 0;
+}
+
+/**
+ * Get rate of TBF qdisc.
+ * @arg qdisc TBF qdisc.
+ * @return Rate in bytes per seconds or a negative error code.
+ */
+int rtnl_qdisc_tbf_get_rate(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_tbf *tbf;
+
+ tbf = tbf_qdisc(qdisc);
+ if (tbf && (tbf->qt_mask & TBF_ATTR_RATE))
+ return tbf->qt_rate.rs_rate;
+ else
+ return -1;
+}
+
+/**
+ * Get rate bucket size of TBF qdisc.
+ * @arg qdisc TBF qdisc.
+ * @return Size of rate bucket or a negative error code.
+ */
+int rtnl_qdisc_tbf_get_rate_bucket(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_tbf *tbf;
+
+ tbf = tbf_qdisc(qdisc);
+ if (tbf && (tbf->qt_mask & TBF_ATTR_RATE))
+ return tbf->qt_rate_bucket;
+ else
+ return -1;
+}
+
+/**
+ * Get rate cell size of TBF qdisc.
+ * @arg qdisc TBF qdisc.
+ * @return Size of rate cell in bytes or a negative error code.
+ */
+int rtnl_qdisc_tbf_get_rate_cell(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_tbf *tbf;
+
+ tbf = tbf_qdisc(qdisc);
+ if (tbf && (tbf->qt_mask & TBF_ATTR_RATE))
+ return (1 << tbf->qt_rate.rs_cell_log);
+ else
+ return -1;
+}
+
+/**
+ * Set peak rate of TBF qdisc.
+ * @arg qdisc TBF qdisc to be modified.
+ * @arg rate New peak rate in bytes per second.
+ * @arg bucket Size of peakrate bucket.
+ * @arg cell Size of a peakrate cell or 0 to get default value.
+ * @return 0 on success or a negative error code.
+ */
+int rtnl_qdisc_tbf_set_peakrate(struct rtnl_qdisc *qdisc, int rate, int bucket,
+ int cell)
+{
+ struct rtnl_tbf *tbf;
+ int cell_log;
+
+ tbf = tbf_alloc(qdisc);
+ if (!tbf)
+ return nl_errno(ENOMEM);
+
+ cell_log = calc_cell_log(cell, bucket);
+ if (cell_log < 0)
+ return cell_log;
+
+ tbf->qt_peakrate.rs_rate = rate;
+ tbf->qt_peakrate_bucket = bucket;
+ tbf->qt_peakrate.rs_cell_log = cell_log;
+ tbf->qt_peakrate_txtime = rtnl_tc_calc_txtime(bucket, rate);
+
+ tbf->qt_mask |= TBF_ATTR_PEAKRATE;
+
+ return 0;
+}
+
+/**
+ * Get peak rate of TBF qdisc.
+ * @arg qdisc TBF qdisc.
+ * @return Peak rate in bytes per seconds or a negative error code.
+ */
+int rtnl_qdisc_tbf_get_peakrate(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_tbf *tbf;
+
+ tbf = tbf_qdisc(qdisc);
+ if (tbf && (tbf->qt_mask & TBF_ATTR_PEAKRATE))
+ return tbf->qt_peakrate.rs_rate;
+ else
+ return -1;
+}
+
+/**
+ * Get peak rate bucket size of TBF qdisc.
+ * @arg qdisc TBF qdisc.
+ * @return Size of peak rate bucket or a negative error code.
+ */
+int rtnl_qdisc_tbf_get_peakrate_bucket(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_tbf *tbf;
+
+ tbf = tbf_qdisc(qdisc);
+ if (tbf && (tbf->qt_mask & TBF_ATTR_PEAKRATE))
+ return tbf->qt_peakrate_bucket;
+ else
+ return -1;
+}
+
+/**
+ * Get peak rate cell size of TBF qdisc.
+ * @arg qdisc TBF qdisc.
+ * @return Size of peak rate cell in bytes or a negative error code.
+ */
+int rtnl_qdisc_tbf_get_peakrate_cell(struct rtnl_qdisc *qdisc)
+{
+ struct rtnl_tbf *tbf;
+
+ tbf = tbf_qdisc(qdisc);
+ if (tbf && (tbf->qt_mask & TBF_ATTR_PEAKRATE))
+ return (1 << tbf->qt_peakrate.rs_cell_log);
+ else
+ return -1;
+}
+
+/** @} */
+
+static struct rtnl_qdisc_ops tbf_qdisc_ops = {
+ .qo_kind = "tbf",
+ .qo_msg_parser = tbf_msg_parser,
+ .qo_dump[NL_DUMP_BRIEF] = tbf_dump_brief,
+ .qo_dump[NL_DUMP_FULL] = tbf_dump_full,
+ .qo_get_opts = tbf_get_opts,
+};
+
+static void __init tbf_init(void)
+{
+ rtnl_qdisc_register(&tbf_qdisc_ops);
+}
+
+static void __exit tbf_exit(void)
+{
+ rtnl_qdisc_unregister(&tbf_qdisc_ops);
+}
+
+/** @} */
diff --git a/lib/route/tc.c b/lib/route/tc.c
new file mode 100644
index 0000000..1351fa2
--- /dev/null
+++ b/lib/route/tc.c
@@ -0,0 +1,585 @@
+/*
+ * lib/route/tc.c Traffic Control
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup rtnl
+ * @defgroup tc Traffic Control
+ * @brief
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink-tc.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/route/rtnl.h>
+#include <netlink/route/link.h>
+#include <netlink/route/tc.h>
+
+/** @cond SKIP */
+
+static struct nla_policy tc_policy[TCA_MAX+1] = {
+ [TCA_KIND] = { .type = NLA_STRING,
+ .maxlen = TCKINDSIZ },
+ [TCA_STATS] = { .minlen = sizeof(struct tc_stats) },
+ [TCA_STATS2] = { .type = NLA_NESTED },
+};
+
+int tca_parse(struct nlattr **tb, int maxattr, struct rtnl_tca *g,
+ struct nla_policy *policy)
+{
+
+ if (g->ce_mask & TCA_ATTR_OPTS)
+ return nla_parse(tb, maxattr,
+ (struct nlattr *) g->tc_opts->d_data,
+ g->tc_opts->d_size, policy);
+ else {
+ /* Ugly but tb[] must be in a defined state even if no
+ * attributes can be found. */
+ memset(tb, 0, sizeof(struct nlattr *) * (maxattr + 1));
+ return 0;
+ }
+}
+
+static struct nla_policy tc_stats2_policy[TCA_STATS_MAX+1] = {
+ [TCA_STATS_BASIC] = { .minlen = sizeof(struct gnet_stats_basic) },
+ [TCA_STATS_RATE_EST] = { .minlen = sizeof(struct gnet_stats_rate_est) },
+ [TCA_STATS_QUEUE] = { .minlen = sizeof(struct gnet_stats_queue) },
+};
+
+int tca_msg_parser(struct nlmsghdr *n, struct rtnl_tca *g)
+{
+ struct nlattr *tb[TCA_MAX + 1];
+ struct tcmsg *tm;
+ int err;
+
+ err = nlmsg_parse(n, sizeof(*tm), tb, TCA_MAX, tc_policy);
+ if (err < 0)
+ return err;
+
+ if (tb[TCA_KIND] == NULL)
+ return nl_error(EINVAL, "Missing tca kind TLV");
+
+ nla_strlcpy(g->tc_kind, tb[TCA_KIND], TCKINDSIZ);
+
+ tm = nlmsg_data(n);
+ g->tc_family = tm->tcm_family;
+ g->tc_ifindex = tm->tcm_ifindex;
+ g->tc_handle = tm->tcm_handle;
+ g->tc_parent = tm->tcm_parent;
+ g->tc_info = tm->tcm_info;
+
+ g->ce_mask = (TCA_ATTR_FAMILY | TCA_ATTR_IFINDEX | TCA_ATTR_HANDLE |
+ TCA_ATTR_PARENT | TCA_ATTR_INFO | TCA_ATTR_KIND);
+
+ if (tb[TCA_OPTIONS]) {
+ g->tc_opts = nla_get_data(tb[TCA_OPTIONS]);
+ if (!g->tc_opts)
+ return nl_errno(ENOMEM);
+ g->ce_mask |= TCA_ATTR_OPTS;
+ }
+
+
+ if (tb[TCA_STATS2]) {
+ struct nlattr *tbs[TCA_STATS_MAX + 1];
+
+ err = nla_parse_nested(tbs, TCA_STATS_MAX, tb[TCA_STATS2],
+ tc_stats2_policy);
+ if (err < 0)
+ return err;
+
+ if (tbs[TCA_STATS_BASIC]) {
+ struct gnet_stats_basic *bs;
+
+ bs = nla_data(tbs[TCA_STATS_BASIC]);
+ g->tc_stats[RTNL_TC_BYTES] = bs->bytes;
+ g->tc_stats[RTNL_TC_PACKETS] = bs->packets;
+ }
+
+ if (tbs[TCA_STATS_RATE_EST]) {
+ struct gnet_stats_rate_est *re;
+
+ re = nla_data(tbs[TCA_STATS_RATE_EST]);
+ g->tc_stats[RTNL_TC_RATE_BPS] = re->bps;
+ g->tc_stats[RTNL_TC_RATE_PPS] = re->pps;
+ }
+
+ if (tbs[TCA_STATS_QUEUE]) {
+ struct gnet_stats_queue *q;
+
+ q = nla_data(tbs[TCA_STATS_QUEUE]);
+ g->tc_stats[RTNL_TC_QLEN] = q->qlen;
+ g->tc_stats[RTNL_TC_BACKLOG] = q->backlog;
+ g->tc_stats[RTNL_TC_DROPS] = q->drops;
+ g->tc_stats[RTNL_TC_REQUEUES] = q->requeues;
+ g->tc_stats[RTNL_TC_OVERLIMITS] = q->overlimits;
+ }
+
+ g->ce_mask |= TCA_ATTR_STATS;
+
+ if (tbs[TCA_STATS_APP]) {
+ g->tc_xstats = nla_get_data(tbs[TCA_STATS_APP]);
+ if (g->tc_xstats == NULL)
+ return -ENOMEM;
+ } else
+ goto compat_xstats;
+ } else {
+ if (tb[TCA_STATS]) {
+ struct tc_stats *st = nla_data(tb[TCA_STATS]);
+
+ g->tc_stats[RTNL_TC_BYTES] = st->bytes;
+ g->tc_stats[RTNL_TC_PACKETS] = st->packets;
+ g->tc_stats[RTNL_TC_RATE_BPS] = st->bps;
+ g->tc_stats[RTNL_TC_RATE_PPS] = st->pps;
+ g->tc_stats[RTNL_TC_QLEN] = st->qlen;
+ g->tc_stats[RTNL_TC_BACKLOG] = st->backlog;
+ g->tc_stats[RTNL_TC_DROPS] = st->drops;
+ g->tc_stats[RTNL_TC_OVERLIMITS] = st->overlimits;
+
+ g->ce_mask |= TCA_ATTR_STATS;
+ }
+
+compat_xstats:
+ if (tb[TCA_XSTATS]) {
+ g->tc_xstats = nla_get_data(tb[TCA_XSTATS]);
+ if (g->tc_xstats == NULL)
+ return -ENOMEM;
+ g->ce_mask |= TCA_ATTR_XSTATS;
+ }
+ }
+
+
+ return 0;
+}
+
+void tca_free_data(struct rtnl_tca *tca)
+{
+ nl_data_free(tca->tc_opts);
+ nl_data_free(tca->tc_xstats);
+}
+
+int tca_clone(struct rtnl_tca *dst, struct rtnl_tca *src)
+{
+ if (src->tc_opts) {
+ dst->tc_opts = nl_data_clone(src->tc_opts);
+ if (!dst->tc_opts)
+ goto errout;
+ }
+
+ if (src->tc_xstats) {
+ dst->tc_xstats = nl_data_clone(src->tc_xstats);
+ if (!dst->tc_xstats)
+ goto errout;
+ }
+
+ return 0;
+errout:
+ return nl_get_errno();
+}
+
+int tca_dump_brief(struct rtnl_tca *g, const char *type,
+ struct nl_dump_params *p, int line)
+{
+ char handle[32], parent[32];
+ struct nl_cache *link_cache;
+
+ link_cache = nl_cache_mngt_require("route/link");
+
+ dp_dump(p, "%s %s ", g->tc_kind, type);
+
+ if (link_cache) {
+ char buf[32];
+ dp_dump(p, "dev %s ",
+ rtnl_link_i2name(link_cache, g->tc_ifindex,
+ buf, sizeof(buf)));
+ } else
+ dp_dump(p, "dev %u ", g->tc_ifindex);
+
+ dp_dump(p, "handle %s parent %s",
+ rtnl_tc_handle2str(g->tc_handle, handle, sizeof(handle)),
+ rtnl_tc_handle2str(g->tc_parent, parent, sizeof(parent)));
+
+ return 1;
+}
+
+int tca_dump_full(struct rtnl_tca *g, struct nl_dump_params *p, int line)
+{
+ dp_dump_line(p, line++, " ");
+ return line;
+}
+
+int tca_dump_stats(struct rtnl_tca *g, struct nl_dump_params *p, int line)
+{
+ char *unit, fmt[64];
+ float res;
+ strcpy(fmt, " %7.2f %s %10u %10u %10u %10u %10u\n");
+
+ dp_dump_line(p, line++,
+ " Stats: bytes packets drops overlimits" \
+ " qlen backlog\n");
+
+ res = nl_cancel_down_bytes(g->tc_stats[RTNL_TC_BYTES], &unit);
+ if (*unit == 'B')
+ fmt[11] = '9';
+
+ dp_dump_line(p, line++, fmt, res, unit,
+ g->tc_stats[RTNL_TC_PACKETS],
+ g->tc_stats[RTNL_TC_DROPS],
+ g->tc_stats[RTNL_TC_OVERLIMITS],
+ g->tc_stats[RTNL_TC_QLEN],
+ g->tc_stats[RTNL_TC_BACKLOG]);
+
+ res = nl_cancel_down_bytes(g->tc_stats[RTNL_TC_RATE_BPS], &unit);
+
+ strcpy(fmt, " %7.2f %s/s%9u pps");
+
+ if (*unit == 'B')
+ fmt[11] = '9';
+
+ dp_dump_line(p, line++, fmt, res, unit, g->tc_stats[RTNL_TC_RATE_PPS]);
+
+ return line;
+}
+
+int tca_compare(struct nl_object *_a, struct nl_object *_b,
+ uint32_t attrs, int flags)
+{
+ struct rtnl_tca *a = (struct rtnl_tca *) _a;
+ struct rtnl_tca *b = (struct rtnl_tca *) _b;
+ int diff = 0;
+
+#define TC_DIFF(ATTR, EXPR) ATTR_DIFF(attrs, TCA_ATTR_##ATTR, a, b, EXPR)
+
+ diff |= TC_DIFF(HANDLE, a->tc_handle != b->tc_handle);
+ diff |= TC_DIFF(PARENT, a->tc_parent != b->tc_parent);
+ diff |= TC_DIFF(IFINDEX, a->tc_ifindex != b->tc_ifindex);
+ diff |= TC_DIFF(KIND, strcmp(a->tc_kind, b->tc_kind));
+
+#undef TC_DIFF
+
+ return diff;
+}
+
+void tca_set_ifindex(struct rtnl_tca *t, int ifindex)
+{
+ t->tc_ifindex = ifindex;
+ t->ce_mask |= TCA_ATTR_IFINDEX;
+}
+
+int tca_get_ifindex(struct rtnl_tca *t)
+{
+ if (t->ce_mask & TCA_ATTR_IFINDEX)
+ return t->tc_ifindex;
+ else
+ return RTNL_LINK_NOT_FOUND;
+}
+
+void tca_set_handle(struct rtnl_tca *t, uint32_t handle)
+{
+ t->tc_handle = handle;
+ t->ce_mask |= TCA_ATTR_HANDLE;
+}
+
+uint32_t tca_get_handle(struct rtnl_tca *t)
+{
+ if (t->ce_mask & TCA_ATTR_HANDLE)
+ return t->tc_handle;
+ else
+ return 0;
+}
+
+void tca_set_parent(struct rtnl_tca *t, uint32_t parent)
+{
+ t->tc_parent = parent;
+ t->ce_mask |= TCA_ATTR_PARENT;
+}
+
+uint32_t tca_get_parent(struct rtnl_tca *t)
+{
+ if (t->ce_mask & TCA_ATTR_PARENT)
+ return t->tc_parent;
+ else
+ return 0;
+}
+
+void tca_set_kind(struct rtnl_tca *t, const char *kind)
+{
+ strncpy(t->tc_kind, kind, sizeof(t->tc_kind) - 1);
+ t->ce_mask |= TCA_ATTR_KIND;
+}
+
+char *tca_get_kind(struct rtnl_tca *t)
+{
+ if (t->ce_mask & TCA_ATTR_KIND)
+ return t->tc_kind;
+ else
+ return NULL;
+}
+
+uint64_t tca_get_stat(struct rtnl_tca *t, int id)
+{
+ if (id < 0 || id > RTNL_TC_STATS_MAX)
+ return 0;
+
+ return t->tc_stats[id];
+}
+
+struct nl_msg *tca_build_msg(struct rtnl_tca *tca, int type, int flags)
+{
+ struct nl_msg *msg;
+ struct tcmsg tchdr = {
+ .tcm_family = AF_UNSPEC,
+ .tcm_ifindex = tca->tc_ifindex,
+ .tcm_handle = tca->tc_handle,
+ .tcm_parent = tca->tc_parent,
+ };
+
+ msg = nlmsg_alloc_simple(type, flags);
+ if (!msg)
+ goto nla_put_failure;
+
+ if (nlmsg_append(msg, &tchdr, sizeof(tchdr), NLMSG_ALIGNTO) < 0)
+ goto nla_put_failure;
+
+ if (tca->ce_mask & TCA_ATTR_KIND)
+ NLA_PUT_STRING(msg, TCA_KIND, tca->tc_kind);
+
+ return msg;
+
+nla_put_failure:
+ nlmsg_free(msg);
+ return NULL;
+}
+
+/** @endcond */
+
+/**
+ * @name Utilities
+ * @{
+ */
+
+/**
+ * Calculate time required to transmit buffer at a specific rate
+ * @arg bufsize Size of buffer to be transmited in bytes.
+ * @arg rate Transmit rate in bytes per second.
+ *
+ * Calculates the number of micro seconds required to transmit a
+ * specific buffer at a specific transmit rate.
+ *
+ * @f[
+ * txtime=\frac{bufsize}{rate}10^6
+ * @f]
+ *
+ * @return Required transmit time in micro seconds.
+ */
+int rtnl_tc_calc_txtime(int bufsize, int rate)
+{
+ double tx_time_secs;
+
+ tx_time_secs = (double) bufsize / (double) rate;
+
+ return tx_time_secs * 1000000.;
+}
+
+/**
+ * Calculate buffer size able to transmit in a specific time and rate.
+ * @arg txtime Available transmit time in micro seconds.
+ * @arg rate Transmit rate in bytes per second.
+ *
+ * Calculates the size of the buffer that can be transmitted in a
+ * specific time period at a specific transmit rate.
+ *
+ * @f[
+ * bufsize=\frac{{txtime} \times {rate}}{10^6}
+ * @f]
+ *
+ * @return Size of buffer in bytes.
+ */
+int rtnl_tc_calc_bufsize(int txtime, int rate)
+{
+ double bufsize;
+
+ bufsize = (double) txtime * (double) rate;
+
+ return bufsize / 1000000.;
+}
+
+/**
+ * Calculate the binary logarithm for a specific cell size
+ * @arg cell_size Size of cell, must be a power of two.
+ * @return Binary logirhtm of cell size or a negative error code.
+ */
+int rtnl_tc_calc_cell_log(int cell_size)
+{
+ int i;
+
+ for (i = 0; i < 32; i++)
+ if ((1 << i) == cell_size)
+ return i;
+
+ return nl_errno(EINVAL);
+}
+
+
+/** @} */
+
+/**
+ * @name Rate Tables
+ * @{
+ */
+
+/**
+ * Compute a transmission time lookup table
+ * @arg dst Destination buffer of RTNL_TC_RTABLE_SIZE uint32_t[].
+ * @arg mpu Minimal size of a packet at all times.
+ * @arg overhead Overhead to be added to each packet.
+ * @arg cell Size of cell, i.e. size of step between entries in bytes.
+ * @arg rate Rate in bytes per second.
+ *
+ * Computes a table of RTNL_TC_RTABLE_SIZE entries specyfing the
+ * transmission times for various packet sizes, e.g. the transmission
+ * time for a packet of size \c pktsize could be looked up:
+ * @code
+ * txtime = table[pktsize >> log2(cell)];
+ * @endcode
+ */
+int rtnl_tc_build_rate_table(uint32_t *dst, uint8_t mpu, uint8_t overhead,
+ int cell, int rate)
+{
+ int i, size, cell_log;
+
+ cell_log = rtnl_tc_calc_cell_log(cell);
+ if (cell_log < 0)
+ return cell_log;
+
+ for (i = 0; i < RTNL_TC_RTABLE_SIZE; i++) {
+ size = (i << cell_log) + overhead;
+ if (size < mpu)
+ size = mpu;
+
+ dst[i] = rtnl_tc_calc_txtime(size, rate);
+ }
+
+ return 0;
+}
+
+/** @} */
+
+/**
+ * @name Traffic Control Handle Translations
+ * @{
+ */
+
+/**
+ * Convert a traffic control handle to a character string (Reentrant).
+ * @arg handle traffic control handle
+ * @arg buf destination buffer
+ * @arg len buffer length
+ *
+ * Converts a tarffic control handle to a character string in the
+ * form of \c MAJ:MIN and stores it in the specified destination buffer.
+ *
+ * @return The destination buffer or the type encoded in hexidecimal
+ * form if no match was found.
+ */
+char * rtnl_tc_handle2str(uint32_t handle, char *buf, size_t len)
+{
+ if (TC_H_ROOT == handle)
+ snprintf(buf, len, "root");
+ else if (TC_H_UNSPEC == handle)
+ snprintf(buf, len, "none");
+ else if (0 == TC_H_MAJ(handle))
+ snprintf(buf, len, ":%02x", TC_H_MIN(handle));
+ else if (0 == TC_H_MIN(handle))
+ snprintf(buf, len, "%02x:", TC_H_MAJ(handle) >> 16);
+ else
+ snprintf(buf, len, "%02x:%02x",
+ TC_H_MAJ(handle) >> 16, TC_H_MIN(handle));
+
+ return buf;
+}
+
+/**
+ * Convert a charactering strint to a traffic control handle
+ * @arg name traffic control handle as character string
+ * @arg res destination buffer
+ *
+ * Converts the provided character string specifying a traffic
+ * control handle to the corresponding numeric value.
+ *
+ * The handle must be provided in one of the following formats:
+ * - root
+ * - none
+ * - XXXX:
+ * - :YYYY
+ * - XXXX:YYYY
+ * - XXXXYYYY
+ *
+ * @return 0 on success or a negative error code
+ */
+int rtnl_tc_str2handle(const char *name, uint32_t *res)
+{
+ char *colon, *end;
+ uint32_t h;
+
+ if (!strcasecmp(name, "root")) {
+ *res = TC_H_ROOT;
+ return 0;
+ }
+
+ if (!strcasecmp(name, "none")) {
+ *res = TC_H_UNSPEC;
+ return 0;
+ }
+
+ h = strtoul(name, &colon, 16);
+
+ if (colon == name) {
+ /* :YYYY */
+ h = 0;
+ if (':' != *colon)
+ return -EINVAL;
+ }
+
+ if (':' == *colon) {
+ /* check if we would lose bits */
+ if (TC_H_MAJ(h))
+ return -ERANGE;
+ h <<= 16;
+
+ if ('\0' == colon[1]) {
+ /* XXXX: */
+ *res = h;
+ } else {
+ /* XXXX:YYYY */
+ uint32_t l = strtoul(colon+1, &end, 16);
+
+ /* check if we overlap with major part */
+ if (TC_H_MAJ(l))
+ return -ERANGE;
+
+ if ('\0' != *end)
+ return -EINVAL;
+
+ *res = (h | l);
+ }
+ } else if ('\0' == *colon) {
+ /* XXXXYYYY */
+ *res = h;
+ } else
+ return -EINVAL;
+
+ return 0;
+}
+
+/** @} */
+
+/** @} */
diff --git a/lib/socket.c b/lib/socket.c
new file mode 100644
index 0000000..f68e8cf
--- /dev/null
+++ b/lib/socket.c
@@ -0,0 +1,548 @@
+/*
+ * lib/socket.c Netlink Socket Handle
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @ingroup nl
+ * @defgroup socket Socket
+ * @brief Handle representing a netlink socket.
+ *
+ * The socket is represented in a structure called the netlink handle,
+ * besides the socket, it stores various settings and values related
+ * to the socket. Every socket handle has a mandatory association with
+ * a set of callbacks which can be used to modify the behaviour when
+ * sending/receiving data from the socket.
+ *
+ * @par Socket Attributes
+ * - \b Local \b Port: The local port is a netlink port identifying the
+ * local endpoint. It is used as source address for outgoing messages
+ * and will be addressed in replies. It must therefore be unique among
+ * all userspace applications. When the socket handle is allocated, a
+ * unique port number is generated automatically in the form of 22 bits
+ * Process Identifier + 10 bits Arbitary Number. Therefore the library
+ * is capable of generating 1024 unique local port numbers for every
+ * process. If more sockets are required, the application has to manage
+ * port numbers itself using nl_socket_set_local_port().
+ * - \b Group \b Subscriptions: A socket can subscribe to any number of
+ * multicast groups. It will then receive a copy of all messages sent
+ * to one of the groups. This method is mainly used for event notification.
+ * Prior to kernel 2.6.14, the group subscription was done via bitmask
+ * which limited to a total number of groups of 32. With 2.6.14 a new
+ * method was added based on continous identifiers which supports an
+ * arbitary number of groups. Both methods are supported, see
+ * nl_join_groups() respectively nl_socket_add_membership() and
+ * nl_socket_drop_membership().
+ * - \b Peer \b Port: The peer port is a netlink port identifying the
+ * peer's endpoint. If no peer port is specified, the kernel will try to
+ * autobind to a socket of the specified netlink family automatically.
+ * This is very common as typically only one listening socket exists
+ * on the kernel side. The peer port can be modified using
+ * nl_socket_set_peer_port().
+ * - \b Peer \b Groups:
+ * - \b File \b Descriptor: The file descriptor of the socket, it can be
+ * accessed via nl_socket_get_fd() to change socket options or monitor
+ * activity using poll()/select().
+ * - \b Protocol: Once connected, the socket is bound to stick to one
+ * netlink family. This field is invisible, it is maintained automatically.
+ * (See nl_connect())
+ * - \b Next \b Sequence \b Number: Next available sequence number to be used
+ * for the next message being sent out. (Initial value: UNIX time when the
+ * socket was allocated.) Sequence numbers can be used via
+ * nl_socket_use_seq().
+ * - \b Expected \b Sequence \b Number: Expected sequence number in the next
+ * message received from the socket. (Initial value: Equal to next sequence
+ * number.)
+ * - \b Callbacks \b Configuration:
+ *
+ * @par 1) Creating the netlink handle
+ * @code
+ * struct nl_handle *handle;
+ *
+ * // Allocate and initialize a new netlink handle
+ * handle = nl_handle_alloc();
+ *
+ * // Use nl_socket_get_fd() to fetch the file description, for example to
+ * // put a socket into non-blocking i/o mode.
+ * fcntl(nl_socket_get_fd(handle), F_SETFL, O_NONBLOCK);
+ * @endcode
+ *
+ * @par 2) Group Subscriptions
+ * @code
+ * // Event notifications are typically sent to multicast addresses which
+ * // represented by groups. Join a group to f.e. receive link notifications.
+ * nl_socket_add_membership(handle, RTNLGRP_LINK);
+ * @endcode
+ *
+ * @par 6) Cleaning up
+ * @code
+ * // Finally destroy the netlink handle
+ * nl_handle_destroy(handle);
+ * @endcode
+ *
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <netlink/handlers.h>
+#include <netlink/msg.h>
+#include <netlink/attr.h>
+
+static uint32_t used_ports_map[32];
+
+static uint32_t generate_local_port(void)
+{
+ int i, n;
+ uint32_t pid = getpid() & 0x3FFFFF;
+
+ for (i = 0; i < 32; i++) {
+ if (used_ports_map[i] == 0xFFFFFFFF)
+ continue;
+
+ for (n = 0; n < 32; n++) {
+ if (1UL & (used_ports_map[i] >> n))
+ continue;
+
+ used_ports_map[i] |= (1UL << n);
+ n += (i * 32);
+
+ /* PID_MAX_LIMIT is currently at 2^22, leaving 10 bit
+ * to, i.e. 1024 unique ports per application. */
+ return pid + (n << 22);
+
+ }
+ }
+
+ /* Out of sockets in our own PID namespace, what to do? FIXME */
+ return UINT_MAX;
+}
+
+static void release_local_port(uint32_t port)
+{
+ int nr = port >> 22;
+
+ used_ports_map[nr / 32] &= ~(nr % 32);
+}
+
+/**
+ * @name Allocation
+ * @{
+ */
+
+static struct nl_handle *__alloc_handle(struct nl_cb *cb)
+{
+ struct nl_handle *handle;
+
+ handle = calloc(1, sizeof(*handle));
+ if (!handle) {
+ nl_errno(ENOMEM);
+ return NULL;
+ }
+
+ handle->h_cb = cb;
+ handle->h_local.nl_family = AF_NETLINK;
+ handle->h_local.nl_pid = generate_local_port();
+ handle->h_peer.nl_family = AF_NETLINK;
+ handle->h_seq_expect = handle->h_seq_next = time(0);
+
+ return handle;
+}
+
+/**
+ * Allocate new netlink socket handle.
+ *
+ * @return Newly allocated netlink socket handle or NULL.
+ */
+struct nl_handle *nl_handle_alloc(void)
+{
+ struct nl_cb *cb;
+
+ cb = nl_cb_alloc(NL_CB_DEFAULT);
+ if (!cb) {
+ nl_errno(ENOMEM);
+ return NULL;
+ }
+
+ return __alloc_handle(cb);
+}
+
+/**
+ * Allocate new socket handle with custom callbacks
+ * @arg cb Callback handler
+ *
+ * The reference to the callback handler is taken into account
+ * automatically, it is released again upon calling nl_handle_destroy().
+ *
+ *@return Newly allocted socket handle or NULL.
+ */
+struct nl_handle *nl_handle_alloc_cb(struct nl_cb *cb)
+{
+ if (cb == NULL)
+ BUG();
+
+ return __alloc_handle(nl_cb_get(cb));
+}
+
+/**
+ * Destroy netlink handle.
+ * @arg handle Netlink handle.
+ */
+void nl_handle_destroy(struct nl_handle *handle)
+{
+ if (!handle)
+ return;
+
+ if (!(handle->h_flags & NL_OWN_PORT))
+ release_local_port(handle->h_local.nl_pid);
+
+ nl_cb_put(handle->h_cb);
+ free(handle);
+}
+
+/** @} */
+
+/**
+ * @name Sequence Numbers
+ * @{
+ */
+
+static int noop_seq_check(struct nl_msg *msg, void *arg)
+{
+ return NL_OK;
+}
+
+
+/**
+ * Disable sequence number checking.
+ * @arg handle Netlink handle.
+ *
+ * Disables checking of sequence numbers on the netlink handle. This is
+ * required to allow messages to be processed which were not requested by
+ * a preceding request message, e.g. netlink events.
+ *
+ * @note This function modifies the NL_CB_SEQ_CHECK configuration in
+ * the callback handle associated with the socket.
+ */
+void nl_disable_sequence_check(struct nl_handle *handle)
+{
+ nl_cb_set(handle->h_cb, NL_CB_SEQ_CHECK,
+ NL_CB_CUSTOM, noop_seq_check, NULL);
+}
+
+/**
+ * Use next sequence number
+ * @arg handle Netlink handle
+ *
+ * Uses the next available sequence number and increases the counter
+ * by one for subsequent calls.
+ *
+ * @return Unique serial sequence number
+ */
+unsigned int nl_socket_use_seq(struct nl_handle *handle)
+{
+ return handle->h_seq_next++;
+}
+
+/** @} */
+
+/**
+ * @name Source Idenficiation
+ * @{
+ */
+
+uint32_t nl_socket_get_local_port(struct nl_handle *handle)
+{
+ return handle->h_local.nl_pid;
+}
+
+/**
+ * Set local port of socket
+ * @arg handle Netlink handle
+ * @arg port Local port identifier
+ *
+ * Assigns a local port identifier to the socket. If port is 0
+ * a unique port identifier will be generated automatically.
+ */
+void nl_socket_set_local_port(struct nl_handle *handle, uint32_t port)
+{
+ if (port == 0) {
+ port = generate_local_port();
+ handle->h_flags &= ~NL_OWN_PORT;
+ } else {
+ if (!(handle->h_flags & NL_OWN_PORT))
+ release_local_port(handle->h_local.nl_pid);
+ handle->h_flags |= NL_OWN_PORT;
+ }
+
+ handle->h_local.nl_pid = port;
+}
+
+/** @} */
+
+/**
+ * @name Group Subscriptions
+ * @{
+ */
+
+/**
+ * Join a group
+ * @arg handle Netlink handle
+ * @arg group Group identifier
+ *
+ * Joins the specified group using the modern socket option which
+ * is available since kernel version 2.6.14. It allows joining an
+ * almost arbitary number of groups without limitation.
+ *
+ * Make sure to use the correct group definitions as the older
+ * bitmask definitions for nl_join_groups() are likely to still
+ * be present for backward compatibility reasons.
+ *
+ * @return 0 on sucess or a negative error code.
+ */
+int nl_socket_add_membership(struct nl_handle *handle, int group)
+{
+ int err;
+
+ err = setsockopt(handle->h_fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
+ &group, sizeof(group));
+ if (err < 0)
+ return nl_error(errno, "setsockopt(NETLINK_ADD_MEMBERSHIP) "
+ "failed");
+
+ return 0;
+}
+
+/**
+ * Leave a group
+ * @arg handle Netlink handle
+ * @arg group Group identifier
+ *
+ * Leaves the specified group using the modern socket option
+ * which is available since kernel version 2.6.14.
+ *
+ * @see nl_socket_add_membership
+ * @return 0 on success or a negative error code.
+ */
+int nl_socket_drop_membership(struct nl_handle *handle, int group)
+{
+ int err;
+
+ err = setsockopt(handle->h_fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
+ &group, sizeof(group));
+ if (err < 0)
+ return nl_error(errno, "setsockopt(NETLINK_DROP_MEMBERSHIP) "
+ "failed");
+
+ return 0;
+}
+
+/**
+ * Join multicast groups (deprecated)
+ * @arg handle Netlink handle.
+ * @arg groups Bitmask of groups to join.
+ *
+ * This function defines the old way of joining multicast group which
+ * has to be done prior to calling nl_connect(). It works on any kernel
+ * version but is very limited as only 32 groups can be joined.
+ */
+void nl_join_groups(struct nl_handle *handle, int groups)
+{
+ handle->h_local.nl_groups |= groups;
+}
+
+
+/** @} */
+
+/**
+ * @name Peer Identfication
+ * @{
+ */
+
+uint32_t nl_socket_get_peer_port(struct nl_handle *handle)
+{
+ return handle->h_peer.nl_pid;
+}
+
+void nl_socket_set_peer_port(struct nl_handle *handle, uint32_t port)
+{
+ handle->h_peer.nl_pid = port;
+}
+
+/** @} */
+
+/**
+ * @name File Descriptor
+ * @{
+ */
+
+int nl_socket_get_fd(struct nl_handle *handle)
+{
+ return handle->h_fd;
+}
+
+/**
+ * Set file descriptor of socket handle to non-blocking state
+ * @arg handle Netlink socket
+ *
+ * @return 0 on success or a negative error code.
+ */
+int nl_socket_set_nonblocking(struct nl_handle *handle)
+{
+ if (fcntl(handle->h_fd, F_SETFL, O_NONBLOCK) < 0)
+ return nl_error(errno, "fcntl(F_SETFL, O_NONBLOCK) failed");
+
+ return 0;
+}
+
+/**
+ * Enable use of MSG_PEEK when reading from socket
+ * @arg handle Netlink socket
+ */
+void nl_socket_enable_msg_peek(struct nl_handle *handle)
+{
+ handle->h_flags |= NL_MSG_PEEK;
+}
+
+/**
+ * Disable use of MSG_PEEK when reading from socket
+ * @arg handle Netlink socket
+ */
+void nl_socket_disable_msg_peek(struct nl_handle *handle)
+{
+ handle->h_flags &= ~NL_MSG_PEEK;
+}
+
+/** @} */
+
+/**
+ * @name Callback Handler
+ * @{
+ */
+
+struct nl_cb *nl_socket_get_cb(struct nl_handle *handle)
+{
+ return nl_cb_get(handle->h_cb);
+}
+
+void nl_socket_set_cb(struct nl_handle *handle, struct nl_cb *cb)
+{
+ nl_cb_put(handle->h_cb);
+ handle->h_cb = nl_cb_get(cb);
+}
+
+/**
+ * Modify the callback handler associated to the socket
+ * @arg handle netlink handle
+ * @arg type which type callback to set
+ * @arg kind kind of callback
+ * @arg func callback function
+ * @arg arg argument to be passwd to callback function
+ *
+ * @see nl_cb_set
+ */
+int nl_socket_modify_cb(struct nl_handle *handle, enum nl_cb_type type,
+ enum nl_cb_kind kind, nl_recvmsg_msg_cb_t func,
+ void *arg)
+{
+ return nl_cb_set(handle->h_cb, type, kind, func, arg);
+}
+
+/** @} */
+
+/**
+ * @name Utilities
+ * @{
+ */
+
+/**
+ * Set socket buffer size of netlink handle.
+ * @arg handle Netlink handle.
+ * @arg rxbuf New receive socket buffer size in bytes.
+ * @arg txbuf New transmit socket buffer size in bytes.
+ *
+ * Sets the socket buffer size of a netlink handle to the specified
+ * values \c rxbuf and \c txbuf. Providing a value of \c 0 assumes a
+ * good default value.
+ *
+ * @note It is not required to call this function prior to nl_connect().
+ * @return 0 on sucess or a negative error code.
+ */
+int nl_set_buffer_size(struct nl_handle *handle, int rxbuf, int txbuf)
+{
+ int err;
+
+ if (rxbuf <= 0)
+ rxbuf = 32768;
+
+ if (txbuf <= 0)
+ txbuf = 32768;
+
+ err = setsockopt(handle->h_fd, SOL_SOCKET, SO_SNDBUF,
+ &txbuf, sizeof(txbuf));
+ if (err < 0)
+ return nl_error(errno, "setsockopt(SO_SNDBUF) failed");
+
+ err = setsockopt(handle->h_fd, SOL_SOCKET, SO_RCVBUF,
+ &rxbuf, sizeof(rxbuf));
+ if (err < 0)
+ return nl_error(errno, "setsockopt(SO_RCVBUF) failed");
+
+ handle->h_flags |= NL_SOCK_BUFSIZE_SET;
+
+ return 0;
+}
+
+/**
+ * Enable/disable credential passing on netlink handle.
+ * @arg handle Netlink handle
+ * @arg state New state (0 - disabled, 1 - enabled)
+ *
+ * @return 0 on success or a negative error code
+ */
+int nl_set_passcred(struct nl_handle *handle, int state)
+{
+ int err;
+
+ err = setsockopt(handle->h_fd, SOL_SOCKET, SO_PASSCRED,
+ &state, sizeof(state));
+ if (err < 0)
+ return nl_error(errno, "setsockopt(SO_PASSCRED) failed");
+
+ if (state)
+ handle->h_flags |= NL_SOCK_PASSCRED;
+ else
+ handle->h_flags &= ~NL_SOCK_PASSCRED;
+
+ return 0;
+}
+
+/**
+ * Enable/disable receival of additional packet information
+ * @arg handle Netlink handle
+ * @arg state New state (0 - disabled, 1 - enabled)
+ *
+ * @return 0 on success or a negative error code
+ */
+int nl_socket_recv_pktinfo(struct nl_handle *handle, int state)
+{
+ int err;
+
+ err = setsockopt(handle->h_fd, SOL_NETLINK, NETLINK_PKTINFO,
+ &state, sizeof(state));
+ if (err < 0)
+ return nl_error(errno, "setsockopt(NETLINK_PKTINFO) failed");
+
+ return 0;
+}
+
+/** @} */
+
+/** @} */
diff --git a/lib/utils.c b/lib/utils.c
new file mode 100644
index 0000000..8b86921
--- /dev/null
+++ b/lib/utils.c
@@ -0,0 +1,701 @@
+/*
+ * lib/utils.c Utility Functions
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation version 2.1
+ * of the License.
+ *
+ * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
+ */
+
+/**
+ * @defgroup utils Utilities
+ * @{
+ */
+
+#include <netlink-local.h>
+#include <netlink/netlink.h>
+#include <netlink/utils.h>
+#include <linux/socket.h>
+
+/**
+ * Debug level
+ */
+int nl_debug = 0;
+
+struct nl_dump_params nl_debug_dp = {
+ .dp_type = NL_DUMP_FULL,
+};
+
+static void __init nl_debug_dp_init(void)
+{
+ nl_debug_dp.dp_fd = stderr;
+}
+
+/**
+ * @name Error Code Helpers
+ * @{
+ */
+
+static char *errbuf;
+static int nlerrno;
+
+/** @cond SKIP */
+int __nl_error(int err, const char *file, unsigned int line, const char *func,
+ const char *fmt, ...)
+{
+ char *user_err;
+ va_list args;
+
+ if (errbuf) {
+ free(errbuf);
+ errbuf = NULL;
+ }
+
+ nlerrno = err;
+
+ if (fmt) {
+ va_start(args, fmt);
+ vasprintf(&user_err, fmt, args);
+ va_end(args);
+ }
+
+#ifdef VERBOSE_ERRORS
+ asprintf(&errbuf, "%s:%u:%s: %s (errno = %s)",
+ file, line, func, fmt ? user_err : "", strerror(err));
+#else
+ asprintf(&errbuf, "%s (errno = %s)",
+ fmt ? user_err : "", strerror(err));
+#endif
+
+ if (fmt)
+ free(user_err);
+
+ return -err;
+}
+
+int __nl_read_num_str_file(const char *path, int (*cb)(long, const char *))
+{
+ FILE *fd;
+ char buf[128];
+
+ fd = fopen(path, "r");
+ if (fd == NULL)
+ return nl_error(errno, "Unable to open file %s for reading",
+ path);
+
+ while (fgets(buf, sizeof(buf), fd)) {
+ int goodlen, err;
+ long num;
+ char *end;
+
+ if (*buf == '#' || *buf == '\n' || *buf == '\r')
+ continue;
+
+ num = strtol(buf, &end, 0);
+ if (end == buf)
+ return nl_error(EINVAL, "Parsing error");
+
+ if (num == LONG_MIN || num == LONG_MAX)
+ return nl_error(errno, "Number of out range");
+
+ while (*end == ' ' || *end == '\t')
+ end++;
+
+ goodlen = strcspn(end, "#\r\n\t ");
+ if (goodlen == 0)
+ return nl_error(EINVAL, "Empty string");
+
+ end[goodlen] = '\0';
+
+ err = cb(num, end);
+ if (err < 0)
+ return err;
+ }
+
+ fclose(fd);
+
+ return 0;
+}
+
+/** @endcond */
+
+int nl_get_errno(void)
+{
+ return nlerrno;
+}
+
+
+/**
+ * Return error message for an error code
+ * @return error message
+ */
+char *nl_geterror(void)
+{
+ if (errbuf)
+ return errbuf;
+
+ if (nlerrno)
+ return strerror(nlerrno);
+
+ return "Sucess\n";
+}
+
+/**
+ * Print a libnl error message
+ * @arg s error message prefix
+ *
+ * Prints the error message of the call that failed last.
+ *
+ * If s is not NULL and *s is not a null byte the argument
+ * string is printed, followed by a colon and a blank. Then
+ * the error message and a new-line.
+ */
+void nl_perror(const char *s)
+{
+ if (s && *s)
+ fprintf(stderr, "%s: %s\n", s, nl_geterror());
+ else
+ fprintf(stderr, "%s\n", nl_geterror());
+}
+
+/** @} */
+
+/**
+ * @name Unit Pretty-Printing
+ * @{
+ */
+
+/**
+ * Cancel down a byte counter
+ * @arg l byte counter
+ * @arg unit destination unit pointer
+ *
+ * Cancels down a byte counter until it reaches a reasonable
+ * unit. The chosen unit is assigned to \a unit.
+ *
+ * @return The cancelled down byte counter in the new unit.
+ */
+double nl_cancel_down_bytes(unsigned long long l, char **unit)
+{
+ if (l >= 1099511627776LL) {
+ *unit = "TiB";
+ return ((double) l) / 1099511627776LL;
+ } else if (l >= 1073741824) {
+ *unit = "GiB";
+ return ((double) l) / 1073741824;
+ } else if (l >= 1048576) {
+ *unit = "MiB";
+ return ((double) l) / 1048576;
+ } else if (l >= 1024) {
+ *unit = "KiB";
+ return ((double) l) / 1024;
+ } else {
+ *unit = "B";
+ return (double) l;
+ }
+}
+
+/**
+ * Cancel down a bit counter
+ * @arg l bit counter
+ * @arg unit destination unit pointer
+ *
+ * Cancels downa bit counter until it reaches a reasonable
+ * unit. The chosen unit is assigned to \a unit.
+ *
+ * @return The cancelled down bit counter in the new unit.
+ */
+double nl_cancel_down_bits(unsigned long long l, char **unit)
+{
+ if (l >= 1099511627776ULL) {
+ *unit = "Tbit";
+ return ((double) l) / 1099511627776ULL;
+ } else if (l >= 1073741824) {
+ *unit = "Gbit";
+ return ((double) l) / 1073741824;
+ } else if (l >= 1048576) {
+ *unit = "Mbit";
+ return ((double) l) / 1048576;
+ } else if (l >= 1024) {
+ *unit = "Kbit";
+ return ((double) l) / 1024;
+ } else {
+ *unit = "bit";
+ return (double) l;
+ }
+
+}
+
+/**
+ * Cancel down a micro second value
+ * @arg l micro seconds
+ * @arg unit destination unit pointer
+ *
+ * Cancels down a microsecond counter until it reaches a
+ * reasonable unit. The chosen unit is assigned to \a unit.
+ *
+ * @return The cancelled down microsecond in the new unit
+ */
+double nl_cancel_down_us(uint32_t l, char **unit)
+{
+ if (l >= 1000000) {
+ *unit = "s";
+ return ((double) l) / 1000000;
+ } else if (l >= 1000) {
+ *unit = "ms";
+ return ((double) l) / 1000;
+ } else {
+ *unit = "us";
+ return (double) l;
+ }
+}
+
+/** @} */
+
+/**
+ * @name Generic Unit Translations
+ * @{
+ */
+
+/**
+ * Convert a character string to a size
+ * @arg str size encoded as character string
+ *
+ * Converts the specified size as character to the corresponding
+ * number of bytes.
+ *
+ * Supported formats are:
+ * - b,kb/k,m/mb,gb/g for bytes
+ * - bit,kbit/mbit/gbit
+ *
+ * @return The number of bytes or -1 if the string is unparseable
+ */
+long nl_size2int(const char *str)
+{
+ char *p;
+ long l = strtol(str, &p, 0);
+ if (p == str)
+ return -1;
+
+ if (*p) {
+ if (!strcasecmp(p, "kb") || !strcasecmp(p, "k"))
+ l *= 1024;
+ else if (!strcasecmp(p, "gb") || !strcasecmp(p, "g"))
+ l *= 1024*1024*1024;
+ else if (!strcasecmp(p, "gbit"))
+ l *= 1024*1024*1024/8;
+ else if (!strcasecmp(p, "mb") || !strcasecmp(p, "m"))
+ l *= 1024*1024;
+ else if (!strcasecmp(p, "mbit"))
+ l *= 1024*1024/8;
+ else if (!strcasecmp(p, "kbit"))
+ l *= 1024/8;
+ else if (!strcasecmp(p, "bit"))
+ l /= 8;
+ else if (strcasecmp(p, "b") != 0)
+ return -1;
+ }
+
+ return l;
+}
+
+/**
+ * Convert a character string to a probability
+ * @arg str probability encoded as character string
+ *
+ * Converts the specified probability as character to the
+ * corresponding probability number.
+ *
+ * Supported formats are:
+ * - 0.0-1.0
+ * - 0%-100%
+ *
+ * @return The probability relative to NL_PROB_MIN and NL_PROB_MAX
+ */
+long nl_prob2int(const char *str)
+{
+ char *p;
+ double d = strtod(str, &p);
+
+ if (p == str)
+ return -1;
+
+ if (d > 1.0)
+ d /= 100.0f;
+
+ if (d > 1.0f || d < 0.0f)
+ return -1;
+
+ if (*p && strcmp(p, "%") != 0)
+ return -1;
+
+ return rint(d * NL_PROB_MAX);
+}
+
+/** @} */
+
+/**
+ * @name Time Translations
+ * @{
+ */
+
+#ifdef USER_HZ
+static uint32_t user_hz = USER_HZ;
+#else
+static uint32_t user_hz = 100;
+#endif
+
+static double ticks_per_usec = 1.0f;
+
+/* Retrieves the configured HZ and ticks/us value in the kernel.
+ * The value is cached. Supported ways of getting it:
+ *
+ * 1) environment variable
+ * 2) /proc/net/psched and sysconf
+ *
+ * Supports the environment variables:
+ * PROC_NET_PSCHED - may point to psched file in /proc
+ * PROC_ROOT - may point to /proc fs */
+static void __init get_psched_settings(void)
+{
+ char name[FILENAME_MAX];
+ FILE *fd;
+ int got_hz = 0, got_tick = 0;
+
+ if (getenv("HZ")) {
+ long hz = strtol(getenv("HZ"), NULL, 0);
+
+ if (LONG_MIN != hz && LONG_MAX != hz) {
+ user_hz = hz;
+ got_hz = 1;
+ }
+ }
+
+ if (!got_hz)
+ user_hz = sysconf(_SC_CLK_TCK);
+
+ if (getenv("TICKS_PER_USEC")) {
+ double t = strtod(getenv("TICKS_PER_USEC"), NULL);
+
+ ticks_per_usec = t;
+ got_tick = 1;
+ }
+
+
+ if (getenv("PROC_NET_PSCHED"))
+ snprintf(name, sizeof(name), "%s", getenv("PROC_NET_PSCHED"));
+ else if (getenv("PROC_ROOT"))
+ snprintf(name, sizeof(name), "%s/net/psched",
+ getenv("PROC_ROOT"));
+ else
+ strncpy(name, "/proc/net/psched", sizeof(name) - 1);
+
+ if ((fd = fopen(name, "r"))) {
+ uint32_t tick, us, nom;
+ int r = fscanf(fd, "%08x%08x%08x%*08x", &tick, &us, &nom);
+
+ if (4 == r && nom == 1000000 && !got_tick)
+ ticks_per_usec = (double)tick/(double)us;
+
+ fclose(fd);
+ }
+}
+
+
+/**
+ * Return the value of HZ
+ */
+int nl_get_hz(void)
+{
+ return user_hz;
+}
+
+
+/**
+ * Convert micro seconds to ticks
+ * @arg us micro seconds
+ * @return number of ticks
+ */
+uint32_t nl_us2ticks(uint32_t us)
+{
+ return us * ticks_per_usec;
+}
+
+
+/**
+ * Convert ticks to micro seconds
+ * @arg ticks number of ticks
+ * @return microseconds
+ */
+uint32_t nl_ticks2us(uint32_t ticks)
+{
+ return ticks / ticks_per_usec;
+}
+
+long nl_time2int(const char *str)
+{
+ char *p;
+ long l = strtol(str, &p, 0);
+ if (p == str)
+ return -1;
+
+ if (*p) {
+ if (!strcasecmp(p, "min") == 0 || !strcasecmp(p, "m"))
+ l *= 60;
+ else if (!strcasecmp(p, "hour") || !strcasecmp(p, "h"))
+ l *= 60*60;
+ else if (!strcasecmp(p, "day") || !strcasecmp(p, "d"))
+ l *= 60*60*24;
+ else if (strcasecmp(p, "s") != 0)
+ return -1;
+ }
+
+ return l;
+}
+
+/**
+ * Convert milliseconds to a character string
+ * @arg msec number of milliseconds
+ * @arg buf destination buffer
+ * @arg len buffer length
+ *
+ * Converts milliseconds to a character string split up in days, hours,
+ * minutes, seconds, and milliseconds and stores it in the specified
+ * destination buffer.
+ *
+ * @return The destination buffer.
+ */
+char * nl_msec2str(uint64_t msec, char *buf, size_t len)
+{
+ int i, split[5];
+ char *units[] = {"d", "h", "m", "s", "msec"};
+
+#define _SPLIT(idx, unit) if ((split[idx] = msec / unit) > 0) msec %= unit
+ _SPLIT(0, 86400000); /* days */
+ _SPLIT(1, 3600000); /* hours */
+ _SPLIT(2, 60000); /* minutes */
+ _SPLIT(3, 1000); /* seconds */
+#undef _SPLIT
+ split[4] = msec;
+
+ memset(buf, 0, len);
+
+ for (i = 0; i < ARRAY_SIZE(split); i++) {
+ if (split[i] > 0) {
+ char t[64];
+ snprintf(t, sizeof(t), "%s%d%s",
+ strlen(buf) ? " " : "", split[i], units[i]);
+ strncat(buf, t, len - strlen(buf) - 1);
+ }
+ }
+
+ return buf;
+}
+
+/** @} */
+
+/**
+ * @name Link Layer Protocol Translations
+ * @{
+ */
+
+static struct trans_tbl llprotos[] = {
+ {0, "generic"},
+ __ADD(ARPHRD_ETHER,ether)
+ __ADD(ARPHRD_EETHER,eether)
+ __ADD(ARPHRD_AX25,ax25)
+ __ADD(ARPHRD_PRONET,pronet)
+ __ADD(ARPHRD_CHAOS,chaos)
+ __ADD(ARPHRD_IEEE802,ieee802)
+ __ADD(ARPHRD_ARCNET,arcnet)
+ __ADD(ARPHRD_APPLETLK,atalk)
+ __ADD(ARPHRD_DLCI,dlci)
+ __ADD(ARPHRD_ATM,atm)
+ __ADD(ARPHRD_METRICOM,metricom)
+ __ADD(ARPHRD_IEEE1394,ieee1394)
+#ifdef ARPHRD_EUI64
+ __ADD(ARPHRD_EUI64,eui64)
+#endif
+ __ADD(ARPHRD_INFINIBAND,infiniband)
+ __ADD(ARPHRD_SLIP,slip)
+ __ADD(ARPHRD_CSLIP,cslip)
+ __ADD(ARPHRD_SLIP6,slip6)
+ __ADD(ARPHRD_CSLIP6,cslip6)
+ __ADD(ARPHRD_RSRVD,rsrvd)
+ __ADD(ARPHRD_ADAPT,adapt)
+ __ADD(ARPHRD_ROSE,rose)
+ __ADD(ARPHRD_X25,x25)
+#ifdef ARPHRD_HWX25
+ __ADD(ARPHRD_HWX25,hwx25)
+#endif
+ __ADD(ARPHRD_PPP,ppp)
+ __ADD(ARPHRD_HDLC,hdlc)
+ __ADD(ARPHRD_LAPB,lapb)
+ __ADD(ARPHRD_DDCMP,ddcmp)
+ __ADD(ARPHRD_RAWHDLC,rawhdlc)
+ __ADD(ARPHRD_TUNNEL,ipip)
+ __ADD(ARPHRD_TUNNEL6,tunnel6)
+ __ADD(ARPHRD_FRAD,frad)
+ __ADD(ARPHRD_SKIP,skip)
+ __ADD(ARPHRD_LOOPBACK,loopback)
+ __ADD(ARPHRD_LOCALTLK,localtlk)
+ __ADD(ARPHRD_FDDI,fddi)
+ __ADD(ARPHRD_BIF,bif)
+ __ADD(ARPHRD_SIT,sit)
+ __ADD(ARPHRD_IPDDP,ip/ddp)
+ __ADD(ARPHRD_IPGRE,gre)
+ __ADD(ARPHRD_PIMREG,pimreg)
+ __ADD(ARPHRD_HIPPI,hippi)
+ __ADD(ARPHRD_ASH,ash)
+ __ADD(ARPHRD_ECONET,econet)
+ __ADD(ARPHRD_IRDA,irda)
+ __ADD(ARPHRD_FCPP,fcpp)
+ __ADD(ARPHRD_FCAL,fcal)
+ __ADD(ARPHRD_FCPL,fcpl)
+ __ADD(ARPHRD_FCFABRIC,fcfb_0)
+ __ADD(ARPHRD_FCFABRIC+1,fcfb_1)
+ __ADD(ARPHRD_FCFABRIC+2,fcfb_2)
+ __ADD(ARPHRD_FCFABRIC+3,fcfb_3)
+ __ADD(ARPHRD_FCFABRIC+4,fcfb_4)
+ __ADD(ARPHRD_FCFABRIC+5,fcfb_5)
+ __ADD(ARPHRD_FCFABRIC+6,fcfb_6)
+ __ADD(ARPHRD_FCFABRIC+7,fcfb_7)
+ __ADD(ARPHRD_FCFABRIC+8,fcfb_8)
+ __ADD(ARPHRD_FCFABRIC+9,fcfb_9)
+ __ADD(ARPHRD_FCFABRIC+10,fcfb_10)
+ __ADD(ARPHRD_FCFABRIC+11,fcfb_11)
+ __ADD(ARPHRD_FCFABRIC+12,fcfb_12)
+ __ADD(ARPHRD_IEEE802_TR,tr)
+ __ADD(ARPHRD_IEEE80211,ieee802.11)
+#ifdef ARPHRD_IEEE80211_PRISM
+ __ADD(ARPHRD_IEEE80211_PRISM, ieee802.11_prism)
+#endif
+#ifdef ARPHRD_VOID
+ __ADD(ARPHRD_VOID,void)
+#endif
+};
+
+char * nl_llproto2str(int llproto, char *buf, size_t len)
+{
+ return __type2str(llproto, buf, len, llprotos, ARRAY_SIZE(llprotos));
+}
+
+int nl_str2llproto(const char *name)
+{
+ return __str2type(name, llprotos, ARRAY_SIZE(llprotos));
+}
+
+/** @} */
+
+
+/**
+ * @name Ethernet Protocol Translations
+ * @{
+ */
+
+static struct trans_tbl ether_protos[] = {
+ __ADD(ETH_P_LOOP,loop)
+ __ADD(ETH_P_PUP,pup)
+ __ADD(ETH_P_PUPAT,pupat)
+ __ADD(ETH_P_IP,ip)
+ __ADD(ETH_P_X25,x25)
+ __ADD(ETH_P_ARP,arp)
+ __ADD(ETH_P_BPQ,bpq)
+ __ADD(ETH_P_IEEEPUP,ieeepup)
+ __ADD(ETH_P_IEEEPUPAT,ieeepupat)
+ __ADD(ETH_P_DEC,dec)
+ __ADD(ETH_P_DNA_DL,dna_dl)
+ __ADD(ETH_P_DNA_RC,dna_rc)
+ __ADD(ETH_P_DNA_RT,dna_rt)
+ __ADD(ETH_P_LAT,lat)
+ __ADD(ETH_P_DIAG,diag)
+ __ADD(ETH_P_CUST,cust)
+ __ADD(ETH_P_SCA,sca)
+ __ADD(ETH_P_RARP,rarp)
+ __ADD(ETH_P_ATALK,atalk)
+ __ADD(ETH_P_AARP,aarp)
+#ifdef ETH_P_8021Q
+ __ADD(ETH_P_8021Q,802.1q)
+#endif
+ __ADD(ETH_P_IPX,ipx)
+ __ADD(ETH_P_IPV6,ipv6)
+#ifdef ETH_P_WCCP
+ __ADD(ETH_P_WCCP,wccp)
+#endif
+ __ADD(ETH_P_PPP_DISC,ppp_disc)
+ __ADD(ETH_P_PPP_SES,ppp_ses)
+ __ADD(ETH_P_MPLS_UC,mpls_uc)
+ __ADD(ETH_P_MPLS_MC,mpls_mc)
+ __ADD(ETH_P_ATMMPOA,atmmpoa)
+ __ADD(ETH_P_ATMFATE,atmfate)
+ __ADD(ETH_P_EDP2,edp2)
+ __ADD(ETH_P_802_3,802.3)
+ __ADD(ETH_P_AX25,ax25)
+ __ADD(ETH_P_ALL,all)
+ __ADD(ETH_P_802_2,802.2)
+ __ADD(ETH_P_SNAP,snap)
+ __ADD(ETH_P_DDCMP,ddcmp)
+ __ADD(ETH_P_WAN_PPP,wan_ppp)
+ __ADD(ETH_P_PPP_MP,ppp_mp)
+ __ADD(ETH_P_LOCALTALK,localtalk)
+ __ADD(ETH_P_PPPTALK,ppptalk)
+ __ADD(ETH_P_TR_802_2,tr_802.2)
+ __ADD(ETH_P_MOBITEX,mobitex)
+ __ADD(ETH_P_CONTROL,control)
+ __ADD(ETH_P_IRDA,irda)
+ __ADD(ETH_P_ECONET,econet)
+ __ADD(ETH_P_HDLC,hdlc)
+};
+
+char *nl_ether_proto2str(int eproto, char *buf, size_t len)
+{
+ return __type2str(eproto, buf, len, ether_protos,
+ ARRAY_SIZE(ether_protos));
+}
+
+int nl_str2ether_proto(const char *name)
+{
+ return __str2type(name, ether_protos, ARRAY_SIZE(ether_protos));
+}
+
+/** @} */
+
+/**
+ * @name IP Protocol Translations
+ * @{
+ */
+
+char *nl_ip_proto2str(int proto, char *buf, size_t len)
+{
+ struct protoent *p = getprotobynumber(proto);
+
+ if (p) {
+ snprintf(buf, len, "%s", p->p_name);
+ return buf;
+ }
+
+ snprintf(buf, len, "0x%x", proto);
+ return buf;
+}
+
+int nl_str2ip_proto(const char *name)
+{
+ struct protoent *p = getprotobyname(name);
+ unsigned long l;
+ char *end;
+
+ if (p)
+ return p->p_proto;
+
+ l = strtoul(name, &end, 0);
+ if (l == ULONG_MAX || *end != '\0')
+ return -1;
+
+ return (int) l;
+}
+
+/** @} */
+
+/** @} */