2 * lib/attr.c Netlink Attributes
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation version 2.1
9 * Copyright (c) 2003-2008 Thomas Graf <tgraf@suug.ch>
12 #include <netlink-local.h>
13 #include <netlink/netlink.h>
14 #include <netlink/utils.h>
15 #include <netlink/addr.h>
16 #include <netlink/attr.h>
17 #include <netlink/msg.h>
18 #include <linux/socket.h>
22 * @defgroup attr Attributes
23 * Netlink Attributes Construction/Parsing Interface
25 * \section attr_sec Netlink Attributes
26 * Netlink attributes allow for data chunks of arbitary length to be
27 * attached to a netlink message. Each attribute is encoded with a
28 * type and length field, both 16 bits, stored in the attribute header
29 * preceding the attribute data. The main advantage of using attributes
30 * over packing everything into the family header is that the interface
31 * stays extendable as new attributes can supersede old attributes while
32 * remaining backwards compatible. Also attributes can be defined optional
33 * thus avoiding the transmission of unnecessary empty data blocks.
34 * Special nested attributes allow for more complex data structures to
35 * be transmitted, e.g. trees, lists, etc.
37 * While not required, netlink attributes typically follow the family
38 * header of a netlink message and must be properly aligned to NLA_ALIGNTO:
40 * +----------------+- - -+---------------+- - -+------------+- - -+
41 * | Netlink Header | Pad | Family Header | Pad | Attributes | Pad |
42 * +----------------+- - -+---------------+- - -+------------+- - -+
45 * The actual attributes are chained together each separately aligned to
46 * NLA_ALIGNTO. The position of an attribute is defined based on the
47 * length field of the preceding attributes:
49 * +-------------+- - -+-------------+- - -+------
50 * | Attribute 1 | Pad | Attribute 2 | Pad | ...
51 * +-------------+- - -+-------------+- - -+------
52 * nla_next(attr1)------^
55 * The attribute itself consists of the attribute header followed by
56 * the actual payload also aligned to NLA_ALIGNTO. The function nla_data()
57 * returns a pointer to the start of the payload while nla_len() returns
58 * the length of the payload in bytes.
60 * \b Note: Be aware, NLA_ALIGNTO equals to 4 bytes, therefore it is not
61 * safe to dereference any 64 bit data types directly.
64 * <----------- nla_total_size(payload) ----------->
65 * <-------- nla_attr_size(payload) --------->
66 * +------------------+- - -+- - - - - - - - - +- - -+
67 * | Attribute Header | Pad | Payload | Pad |
68 * +------------------+- - -+- - - - - - - - - +- - -+
69 * nla_data(nla)-------------^
73 * @subsection attr_datatypes Attribute Data Types
74 * A number of basic data types are supported to simplify access and
75 * validation of netlink attributes. This data type information is
76 * not encoded in the attribute, both the kernel and userspace part
77 * are required to share this information on their own.
79 * One of the major advantages of these basic types is the automatic
80 * validation of each attribute based on an attribute policy. The
81 * validation covers most of the checks required to safely use
82 * attributes and thus keeps the individual sanity check to a minimum.
84 * Never access attribute payload without ensuring basic validation
85 * first, attributes may:
86 * - not be present even though required
87 * - contain less actual payload than expected
88 * - fake a attribute length which exceeds the end of the message
89 * - contain unterminated character strings
91 * Policies are defined as array of the struct nla_policy. The array is
92 * indexed with the attribute type, therefore the array must be sized
95 * static struct nla_policy my_policy[ATTR_MAX+1] = {
96 * [ATTR_FOO] = { .type = ..., .minlen = ..., .maxlen = ... },
99 * err = nla_validate(attrs, attrlen, ATTR_MAX, &my_policy);
102 * Some basic validations are performed on every attribute, regardless of type.
103 * - If the attribute type exceeds the maximum attribute type specified or
104 * the attribute type is lesser-or-equal than zero, the attribute will
105 * be silently ignored.
106 * - If the payload length falls below the \a minlen value the attribute
108 * - If \a maxlen is non-zero and the payload length exceeds the \a maxlen
109 * value the attribute will be rejected.
112 * @par Unspecific Attribute (NLA_UNSPEC)
113 * This is the standard type if no type is specified. It is used for
114 * binary data of arbitary length. Typically this attribute carries
115 * a binary structure or a stream of bytes.
118 * // In this example, we will assume a binary structure requires to
119 * // be transmitted. The definition of the structure will typically
120 * // go into a header file available to both the kernel and userspace
123 * // Note: Be careful when putting 64 bit data types into a structure.
124 * // The attribute payload is only aligned to 4 bytes, dereferencing
125 * // the member may fail.
131 * // The validation function will not enforce an exact length match to
132 * // allow structures to grow as required. Note: While it is allowed
133 * // to add members to the end of the structure, changing the order or
134 * // inserting members in the middle of the structure will break your
135 * // binary interface.
136 * static struct nla_policy my_policy[ATTR_MAX+1] = {
137 * [ATTR_MY_STRICT] = { .type = NLA_UNSPEC,
138 * .minlen = sizeof(struct my_struct) },
140 * // The binary structure is appened to the message using nla_put()
141 * struct my_struct foo = { .a = 1, .b = 2 };
142 * nla_put(msg, ATTR_MY_STRUCT, sizeof(foo), &foo);
144 * // On the receiving side, a pointer to the structure pointing inside
145 * // the message payload is returned by nla_get().
146 * if (attrs[ATTR_MY_STRUCT])
147 * struct my_struct *foo = nla_get(attrs[ATTR_MY_STRUCT]);
150 * @par Integers (NLA_U8, NLA_U16, NLA_U32, NLA_U64)
151 * Integers come in different sizes from 8 bit to 64 bit. However, since the
152 * payload length is aligned to 4 bytes, integers smaller than 32 bit are
153 * only useful to enforce the maximum range of values.
155 * \b Note: There is no difference made between signed and unsigned integers.
156 * The validation only enforces the minimal payload length required to store
157 * an integer of specified type.
160 * // Even though possible, it does not make sense to specify .minlen or
161 * // .maxlen for integer types. The data types implies the corresponding
162 * // minimal payload length.
163 * static struct nla_policy my_policy[ATTR_MAX+1] = {
164 * [ATTR_FOO] = { .type = NLA_U32 },
166 * // Numeric values can be appended directly using the respective
167 * // nla_put_uxxx() function
168 * nla_put_u32(msg, ATTR_FOO, 123);
170 * // Same for the receiving side.
171 * if (attrs[ATTR_FOO])
172 * uint32_t foo = nla_get_u32(attrs[ATTR_FOO]);
175 * @par Character string (NLA_STRING)
176 * This data type represents a NUL terminated character string of variable
177 * length. For binary data streams the type NLA_UNSPEC is recommended.
180 * // Enforce a NUL terminated character string of at most 4 characters
181 * // including the NUL termination.
182 * static struct nla_policy my_policy[ATTR_MAX+1] = {
183 * [ATTR_BAR] = { .type = NLA_STRING, maxlen = 4 },
185 * // nla_put_string() creates a string attribute of the necessary length
186 * // and appends it to the message including the NUL termination.
187 * nla_put_string(msg, ATTR_BAR, "some text");
189 * // It is safe to use the returned character string directly if the
190 * // attribute has been validated as the validation enforces the proper
191 * // termination of the string.
192 * if (attrs[ATTR_BAR])
193 * char *text = nla_get_string(attrs[ATTR_BAR]);
196 * @par Flag (NLA_FLAG)
197 * This attribute type may be used to indicate the presence of a flag. The
198 * attribute is only valid if the payload length is zero. The presence of
199 * the attribute header indicates the presence of the flag.
202 * // This attribute type is special as .minlen and .maxlen have no effect.
203 * static struct nla_policy my_policy[ATTR_MAX+1] = {
204 * [ATTR_FLAG] = { .type = NLA_FLAG },
206 * // nla_put_flag() appends a zero sized attribute to the message.
207 * nla_put_flag(msg, ATTR_FLAG);
209 * // There is no need for a receival function, the presence is the value.
210 * if (attrs[ATTR_FLAG])
214 * @par Micro Seconds (NLA_MSECS)
216 * @par Nested Attribute (NLA_NESTED)
217 * Attributes can be nested and put into a container to create groups, lists
218 * or to construct trees of attributes. Nested attributes are often used to
219 * pass attributes to a subsystem where the top layer has no knowledge of the
220 * configuration possibilities of each subsystem.
222 * \b Note: When validating the attributes using nlmsg_validate() or
223 * nlmsg_parse() it will only affect the top level attributes. Each
224 * level of nested attributes must be validated seperately using
225 * nla_parse_nested() or nla_validate().
228 * // The minimal length policy may be used to enforce the presence of at
229 * // least one attribute.
230 * static struct nla_policy my_policy[ATTR_MAX+1] = {
231 * [ATTR_OPTS] = { .type = NLA_NESTED, minlen = NLA_HDRLEN },
233 * // Nested attributes are constructed by enclosing the attributes
234 * // to be nested with calls to nla_nest_start() respetively nla_nest_end().
235 * struct nlattr *opts = nla_nest_start(msg, ATTR_OPTS);
236 * nla_put_u32(msg, ATTR_FOO, 123);
237 * nla_put_string(msg, ATTR_BAR, "some text");
238 * nla_nest_end(msg, opts);
240 * // Various methods exist to parse nested attributes, the easiest being
241 * // nla_parse_nested() which also allows validation in the same step.
242 * if (attrs[ATTR_OPTS]) {
243 * struct nlattr *nested[ATTR_MAX+1];
245 * nla_parse_nested(nested, ATTR_MAX, attrs[ATTR_OPTS], &policy);
247 * if (nested[ATTR_FOO])
248 * uint32_t foo = nla_get_u32(nested[ATTR_FOO]);
252 * @subsection attr_exceptions Exception Based Attribute Construction
253 * Often a large number of attributes are added to a message in a single
254 * function. In order to simplify error handling, a second set of
255 * construction functions exist which jump to a error label when they
256 * fail instead of returning an error code. This second set consists
257 * of macros which are named after their error code based counterpart
258 * except that the name is written all uppercase.
260 * All of the macros jump to the target \c nla_put_failure if they fail.
262 * void my_func(struct nl_msg *msg)
264 * NLA_PUT_U32(msg, ATTR_FOO, 10);
265 * NLA_PUT_STRING(msg, ATTR_BAR, "bar");
274 * @subsection attr_examples Examples
275 * @par Example 1.1 Constructing a netlink message with attributes.
277 * struct nl_msg *build_msg(int ifindex, struct nl_addr *lladdr, int mtu)
279 * struct nl_msg *msg;
280 * struct nlattr *info, *vlan;
281 * struct ifinfomsg ifi = {
282 * .ifi_family = AF_INET,
283 * .ifi_index = ifindex,
286 * // Allocate a new netlink message, type=RTM_SETLINK, flags=NLM_F_ECHO
287 * if (!(msg = nlmsg_alloc_simple(RTM_SETLINK, NLM_F_ECHO)))
290 * // Append the family specific header (struct ifinfomsg)
291 * if (nlmsg_append(msg, &ifi, sizeof(ifi), NLMSG_ALIGNTO) < 0)
292 * goto nla_put_failure
294 * // Append a 32 bit integer attribute to carry the MTU
295 * NLA_PUT_U32(msg, IFLA_MTU, mtu);
297 * // Append a unspecific attribute to carry the link layer address
298 * NLA_PUT_ADDR(msg, IFLA_ADDRESS, lladdr);
300 * // Append a container for nested attributes to carry link information
301 * if (!(info = nla_nest_start(msg, IFLA_LINKINFO)))
302 * goto nla_put_failure;
304 * // Put a string attribute into the container
305 * NLA_PUT_STRING(msg, IFLA_INFO_KIND, "vlan");
307 * // Append another container inside the open container to carry
308 * // vlan specific attributes
309 * if (!(vlan = nla_nest_start(msg, IFLA_INFO_DATA)))
310 * goto nla_put_failure;
312 * // add vlan specific info attributes here...
314 * // Finish nesting the vlan attributes and close the second container.
315 * nla_nest_end(msg, vlan);
317 * // Finish nesting the link info attribute and close the first container.
318 * nla_nest_end(msg, info);
322 * // If any of the construction macros fails, we end up here.
329 * @par Example 2.1 Parsing a netlink message with attributes.
331 * int parse_message(struct nl_msg *msg)
333 * // The policy defines two attributes: a 32 bit integer and a container
334 * // for nested attributes.
335 * struct nla_policy attr_policy[ATTR_MAX+1] = {
336 * [ATTR_FOO] = { .type = NLA_U32 },
337 * [ATTR_BAR] = { .type = NLA_NESTED },
339 * struct nlattr *attrs[ATTR_MAX+1];
342 * // The nlmsg_parse() function will make sure that the message contains
343 * // enough payload to hold the header (struct my_hdr), validates any
344 * // attributes attached to the messages and stores a pointer to each
345 * // attribute in the attrs[] array accessable by attribute type.
346 * if ((err = nlmsg_parse(nlmsg_hdr(msg), sizeof(struct my_hdr), attrs,
347 * ATTR_MAX, attr_policy)) < 0)
350 * if (attrs[ATTR_FOO]) {
351 * // It is safe to directly access the attribute payload without
352 * // any further checks since nlmsg_parse() enforced the policy.
353 * uint32_t foo = nla_get_u32(attrs[ATTR_FOO]);
356 * if (attrs[ATTR_BAR]) {
357 * struct nlattr *nested[NESTED_MAX+1];
359 * // Attributes nested in a container can be parsed the same way
360 * // as top level attributes.
361 * if ((err = nla_parse_nested(nested, NESTED_MAX, attrs[ATTR_BAR],
362 * nested_policy)) < 0)
365 * // Process nested attributes here.
378 * @name Attribute Size Calculation
385 * @name Parsing Attributes
390 * Check if the attribute header and payload can be accessed safely.
391 * @arg nla Attribute of any kind.
392 * @arg remaining Number of bytes remaining in attribute stream.
394 * Verifies that the header and payload do not exceed the number of
395 * bytes left in the attribute stream. This function must be called
396 * before access the attribute header or payload when iterating over
397 * the attribute stream using nla_next().
399 * @return True if the attribute can be accessed safely, false otherwise.
401 int nla_ok(const struct nlattr
*nla
, int remaining
)
403 return remaining
>= sizeof(*nla
) &&
404 nla
->nla_len
>= sizeof(*nla
) &&
405 nla
->nla_len
<= remaining
;
409 * Return next attribute in a stream of attributes.
410 * @arg nla Attribute of any kind.
411 * @arg remaining Variable to count remaining bytes in stream.
413 * Calculates the offset to the next attribute based on the attribute
414 * given. The attribute provided is assumed to be accessible, the
415 * caller is responsible to use nla_ok() beforehand. The offset (length
416 * of specified attribute including padding) is then subtracted from
417 * the remaining bytes variable and a pointer to the next attribute is
420 * nla_next() can be called as long as remainig is >0.
422 * @return Pointer to next attribute.
424 struct nlattr
*nla_next(const struct nlattr
*nla
, int *remaining
)
426 int totlen
= NLA_ALIGN(nla
->nla_len
);
428 *remaining
-= totlen
;
429 return (struct nlattr
*) ((char *) nla
+ totlen
);
432 static uint16_t nla_attr_minlen
[NLA_TYPE_MAX
+1] = {
433 [NLA_U8
] = sizeof(uint8_t),
434 [NLA_U16
] = sizeof(uint16_t),
435 [NLA_U32
] = sizeof(uint32_t),
436 [NLA_U64
] = sizeof(uint64_t),
440 static int validate_nla(struct nlattr
*nla
, int maxtype
,
441 struct nla_policy
*policy
)
443 struct nla_policy
*pt
;
444 int minlen
= 0, type
= nla_type(nla
);
446 if (type
<= 0 || type
> maxtype
)
451 if (pt
->type
> NLA_TYPE_MAX
)
456 else if (pt
->type
!= NLA_UNSPEC
)
457 minlen
= nla_attr_minlen
[pt
->type
];
459 if (pt
->type
== NLA_FLAG
&& nla_len(nla
) > 0)
462 if (nla_len(nla
) < minlen
)
465 if (pt
->maxlen
&& nla_len(nla
) > pt
->maxlen
)
468 if (pt
->type
== NLA_STRING
) {
469 char *data
= nla_data(nla
);
470 if (data
[nla_len(nla
) - 1] != '\0')
479 * Create attribute index based on a stream of attributes.
480 * @arg tb Index array to be filled (maxtype+1 elements).
481 * @arg maxtype Maximum attribute type expected and accepted.
482 * @arg head Head of attribute stream.
483 * @arg len Length of attribute stream.
484 * @arg policy Attribute validation policy.
486 * Iterates over the stream of attributes and stores a pointer to each
487 * attribute in the index array using the attribute type as index to
488 * the array. Attribute with a type greater than the maximum type
489 * specified will be silently ignored in order to maintain backwards
490 * compatibility. If \a policy is not NULL, the attribute will be
491 * validated using the specified policy.
494 * @return 0 on success or a negative error code.
496 int nla_parse(struct nlattr
*tb
[], int maxtype
, struct nlattr
*head
, int len
,
497 struct nla_policy
*policy
)
502 memset(tb
, 0, sizeof(struct nlattr
*) * (maxtype
+ 1));
504 nla_for_each_attr(nla
, head
, len
, rem
) {
505 int type
= nla_type(nla
);
508 fprintf(stderr
, "Illegal nla->nla_type == 0\n");
512 if (type
<= maxtype
) {
514 err
= validate_nla(nla
, maxtype
, policy
);
524 fprintf(stderr
, "netlink: %d bytes leftover after parsing "
525 "attributes.\n", rem
);
533 * Validate a stream of attributes.
534 * @arg head Head of attributes stream.
535 * @arg len Length of attributes stream.
536 * @arg maxtype Maximum attribute type expected and accepted.
537 * @arg policy Validation policy.
539 * Iterates over the stream of attributes and validates each attribute
540 * one by one using the specified policy. Attributes with a type greater
541 * than the maximum type specified will be silently ignored in order to
542 * maintain backwards compatibility.
544 * See \ref attr_datatypes for more details on what kind of validation
545 * checks are performed on each attribute data type.
547 * @return 0 on success or a negative error code.
549 int nla_validate(struct nlattr
*head
, int len
, int maxtype
,
550 struct nla_policy
*policy
)
555 nla_for_each_attr(nla
, head
, len
, rem
) {
556 err
= validate_nla(nla
, maxtype
, policy
);
567 * Find a single attribute in a stream of attributes.
568 * @arg head Head of attributes stream.
569 * @arg len Length of attributes stream.
570 * @arg attrtype Attribute type to look for.
572 * Iterates over the stream of attributes and compares each type with
573 * the type specified. Returns the first attribute which matches the
576 * @return Pointer to attribute found or NULL.
578 struct nlattr
*nla_find(struct nlattr
*head
, int len
, int attrtype
)
583 nla_for_each_attr(nla
, head
, len
, rem
)
584 if (nla_type(nla
) == attrtype
)
593 * @name Unspecific Attribute
598 * Reserve space for a attribute.
599 * @arg msg Netlink Message.
600 * @arg attrtype Attribute Type.
601 * @arg attrlen Length of payload.
603 * Reserves room for a attribute in the specified netlink message and
604 * fills in the attribute header (type, length). Returns NULL if there
605 * is unsuficient space for the attribute.
607 * Any padding between payload and the start of the next attribute is
610 * @return Pointer to start of attribute or NULL on failure.
612 struct nlattr
*nla_reserve(struct nl_msg
*msg
, int attrtype
, int attrlen
)
617 tlen
= NLMSG_ALIGN(msg
->nm_nlh
->nlmsg_len
) + nla_total_size(attrlen
);
619 if ((tlen
+ msg
->nm_nlh
->nlmsg_len
) > msg
->nm_size
)
622 nla
= (struct nlattr
*) nlmsg_tail(msg
->nm_nlh
);
623 nla
->nla_type
= attrtype
;
624 nla
->nla_len
= nla_attr_size(attrlen
);
626 memset((unsigned char *) nla
+ nla
->nla_len
, 0, nla_padlen(attrlen
));
627 msg
->nm_nlh
->nlmsg_len
= tlen
;
629 NL_DBG(2, "msg %p: Reserved %d bytes at offset +%td for attr %d "
630 "nlmsg_len=%d\n", msg
, attrlen
,
631 (void *) nla
- nlmsg_data(msg
->nm_nlh
),
632 attrtype
, msg
->nm_nlh
->nlmsg_len
);
638 * Add a unspecific attribute to netlink message.
639 * @arg msg Netlink message.
640 * @arg attrtype Attribute type.
641 * @arg datalen Length of data to be used as payload.
642 * @arg data Pointer to data to be used as attribute payload.
644 * Reserves room for a unspecific attribute and copies the provided data
645 * into the message as payload of the attribute. Returns an error if there
646 * is insufficient space for the attribute.
649 * @return 0 on success or a negative error code.
651 int nla_put(struct nl_msg
*msg
, int attrtype
, int datalen
, const void *data
)
655 nla
= nla_reserve(msg
, attrtype
, datalen
);
659 memcpy(nla_data(nla
), data
, datalen
);
660 NL_DBG(2, "msg %p: Wrote %d bytes at offset +%td for attr %d\n",
661 msg
, datalen
, (void *) nla
- nlmsg_data(msg
->nm_nlh
), attrtype
);
This page took 0.096721 seconds and 5 git commands to generate.