attr.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. /*
  2. * lib/attr.c Netlink Attributes
  3. *
  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
  7. * of the License.
  8. *
  9. * Copyright (c) 2003-2008 Thomas Graf <tgraf@suug.ch>
  10. */
  11. #include <netlink-local.h>
  12. #include <netlink/netlink.h>
  13. #include <netlink/utils.h>
  14. #include <netlink/addr.h>
  15. #include <netlink/attr.h>
  16. #include <netlink/msg.h>
  17. #include <linux/socket.h>
  18. /**
  19. * @ingroup msg
  20. * @defgroup attr Attributes
  21. * Netlink Attributes Construction/Parsing Interface
  22. *
  23. * \section attr_sec Netlink Attributes
  24. * Netlink attributes allow for data chunks of arbitary length to be
  25. * attached to a netlink message. Each attribute is encoded with a
  26. * type and length field, both 16 bits, stored in the attribute header
  27. * preceding the attribute data. The main advantage of using attributes
  28. * over packing everything into the family header is that the interface
  29. * stays extendable as new attributes can supersede old attributes while
  30. * remaining backwards compatible. Also attributes can be defined optional
  31. * thus avoiding the transmission of unnecessary empty data blocks.
  32. * Special nested attributes allow for more complex data structures to
  33. * be transmitted, e.g. trees, lists, etc.
  34. *
  35. * While not required, netlink attributes typically follow the family
  36. * header of a netlink message and must be properly aligned to NLA_ALIGNTO:
  37. * @code
  38. * +----------------+- - -+---------------+- - -+------------+- - -+
  39. * | Netlink Header | Pad | Family Header | Pad | Attributes | Pad |
  40. * +----------------+- - -+---------------+- - -+------------+- - -+
  41. * @endcode
  42. *
  43. * The actual attributes are chained together each separately aligned to
  44. * NLA_ALIGNTO. The position of an attribute is defined based on the
  45. * length field of the preceding attributes:
  46. * @code
  47. * +-------------+- - -+-------------+- - -+------
  48. * | Attribute 1 | Pad | Attribute 2 | Pad | ...
  49. * +-------------+- - -+-------------+- - -+------
  50. * nla_next(attr1)------^
  51. * @endcode
  52. *
  53. * The attribute itself consists of the attribute header followed by
  54. * the actual payload also aligned to NLA_ALIGNTO. The function nla_data()
  55. * returns a pointer to the start of the payload while nla_len() returns
  56. * the length of the payload in bytes.
  57. *
  58. * \b Note: Be aware, NLA_ALIGNTO equals to 4 bytes, therefore it is not
  59. * safe to dereference any 64 bit data types directly.
  60. *
  61. * @code
  62. * <----------- nla_total_size(payload) ----------->
  63. * <-------- nla_attr_size(payload) --------->
  64. * +------------------+- - -+- - - - - - - - - +- - -+
  65. * | Attribute Header | Pad | Payload | Pad |
  66. * +------------------+- - -+- - - - - - - - - +- - -+
  67. * nla_data(nla)-------------^
  68. * <- nla_len(nla) ->
  69. * @endcode
  70. *
  71. * @subsection attr_datatypes Attribute Data Types
  72. * A number of basic data types are supported to simplify access and
  73. * validation of netlink attributes. This data type information is
  74. * not encoded in the attribute, both the kernel and userspace part
  75. * are required to share this information on their own.
  76. *
  77. * One of the major advantages of these basic types is the automatic
  78. * validation of each attribute based on an attribute policy. The
  79. * validation covers most of the checks required to safely use
  80. * attributes and thus keeps the individual sanity check to a minimum.
  81. *
  82. * Never access attribute payload without ensuring basic validation
  83. * first, attributes may:
  84. * - not be present even though required
  85. * - contain less actual payload than expected
  86. * - fake a attribute length which exceeds the end of the message
  87. * - contain unterminated character strings
  88. *
  89. * Policies are defined as array of the struct nla_policy. The array is
  90. * indexed with the attribute type, therefore the array must be sized
  91. * accordingly.
  92. * @code
  93. * static struct nla_policy my_policy[ATTR_MAX+1] = {
  94. * [ATTR_FOO] = { .type = ..., .minlen = ..., .maxlen = ... },
  95. * };
  96. *
  97. * err = nla_validate(attrs, attrlen, ATTR_MAX, &my_policy);
  98. * @endcode
  99. *
  100. * Some basic validations are performed on every attribute, regardless of type.
  101. * - If the attribute type exceeds the maximum attribute type specified or
  102. * the attribute type is lesser-or-equal than zero, the attribute will
  103. * be silently ignored.
  104. * - If the payload length falls below the \a minlen value the attribute
  105. * will be rejected.
  106. * - If \a maxlen is non-zero and the payload length exceeds the \a maxlen
  107. * value the attribute will be rejected.
  108. *
  109. *
  110. * @par Unspecific Attribute (NLA_UNSPEC)
  111. * This is the standard type if no type is specified. It is used for
  112. * binary data of arbitary length. Typically this attribute carries
  113. * a binary structure or a stream of bytes.
  114. * @par
  115. * @code
  116. * // In this example, we will assume a binary structure requires to
  117. * // be transmitted. The definition of the structure will typically
  118. * // go into a header file available to both the kernel and userspace
  119. * // side.
  120. * //
  121. * // Note: Be careful when putting 64 bit data types into a structure.
  122. * // The attribute payload is only aligned to 4 bytes, dereferencing
  123. * // the member may fail.
  124. * struct my_struct {
  125. * int a;
  126. * int b;
  127. * };
  128. *
  129. * // The validation function will not enforce an exact length match to
  130. * // allow structures to grow as required. Note: While it is allowed
  131. * // to add members to the end of the structure, changing the order or
  132. * // inserting members in the middle of the structure will break your
  133. * // binary interface.
  134. * static struct nla_policy my_policy[ATTR_MAX+1] = {
  135. * [ATTR_MY_STRICT] = { .type = NLA_UNSPEC,
  136. * .minlen = sizeof(struct my_struct) },
  137. *
  138. * // The binary structure is appened to the message using nla_put()
  139. * struct my_struct foo = { .a = 1, .b = 2 };
  140. * nla_put(msg, ATTR_MY_STRUCT, sizeof(foo), &foo);
  141. *
  142. * // On the receiving side, a pointer to the structure pointing inside
  143. * // the message payload is returned by nla_get().
  144. * if (attrs[ATTR_MY_STRUCT])
  145. * struct my_struct *foo = nla_get(attrs[ATTR_MY_STRUCT]);
  146. * @endcode
  147. *
  148. * @par Integers (NLA_U8, NLA_U16, NLA_U32, NLA_U64)
  149. * Integers come in different sizes from 8 bit to 64 bit. However, since the
  150. * payload length is aligned to 4 bytes, integers smaller than 32 bit are
  151. * only useful to enforce the maximum range of values.
  152. * @par
  153. * \b Note: There is no difference made between signed and unsigned integers.
  154. * The validation only enforces the minimal payload length required to store
  155. * an integer of specified type.
  156. * @par
  157. * @code
  158. * // Even though possible, it does not make sense to specify .minlen or
  159. * // .maxlen for integer types. The data types implies the corresponding
  160. * // minimal payload length.
  161. * static struct nla_policy my_policy[ATTR_MAX+1] = {
  162. * [ATTR_FOO] = { .type = NLA_U32 },
  163. *
  164. * // Numeric values can be appended directly using the respective
  165. * // nla_put_uxxx() function
  166. * nla_put_u32(msg, ATTR_FOO, 123);
  167. *
  168. * // Same for the receiving side.
  169. * if (attrs[ATTR_FOO])
  170. * uint32_t foo = nla_get_u32(attrs[ATTR_FOO]);
  171. * @endcode
  172. *
  173. * @par Character string (NLA_STRING)
  174. * This data type represents a NUL terminated character string of variable
  175. * length. For binary data streams the type NLA_UNSPEC is recommended.
  176. * @par
  177. * @code
  178. * // Enforce a NUL terminated character string of at most 4 characters
  179. * // including the NUL termination.
  180. * static struct nla_policy my_policy[ATTR_MAX+1] = {
  181. * [ATTR_BAR] = { .type = NLA_STRING, maxlen = 4 },
  182. *
  183. * // nla_put_string() creates a string attribute of the necessary length
  184. * // and appends it to the message including the NUL termination.
  185. * nla_put_string(msg, ATTR_BAR, "some text");
  186. *
  187. * // It is safe to use the returned character string directly if the
  188. * // attribute has been validated as the validation enforces the proper
  189. * // termination of the string.
  190. * if (attrs[ATTR_BAR])
  191. * char *text = nla_get_string(attrs[ATTR_BAR]);
  192. * @endcode
  193. *
  194. * @par Flag (NLA_FLAG)
  195. * This attribute type may be used to indicate the presence of a flag. The
  196. * attribute is only valid if the payload length is zero. The presence of
  197. * the attribute header indicates the presence of the flag.
  198. * @par
  199. * @code
  200. * // This attribute type is special as .minlen and .maxlen have no effect.
  201. * static struct nla_policy my_policy[ATTR_MAX+1] = {
  202. * [ATTR_FLAG] = { .type = NLA_FLAG },
  203. *
  204. * // nla_put_flag() appends a zero sized attribute to the message.
  205. * nla_put_flag(msg, ATTR_FLAG);
  206. *
  207. * // There is no need for a receival function, the presence is the value.
  208. * if (attrs[ATTR_FLAG])
  209. * // flag is present
  210. * @endcode
  211. *
  212. * @par Micro Seconds (NLA_MSECS)
  213. *
  214. * @par Nested Attribute (NLA_NESTED)
  215. * Attributes can be nested and put into a container to create groups, lists
  216. * or to construct trees of attributes. Nested attributes are often used to
  217. * pass attributes to a subsystem where the top layer has no knowledge of the
  218. * configuration possibilities of each subsystem.
  219. * @par
  220. * \b Note: When validating the attributes using nlmsg_validate() or
  221. * nlmsg_parse() it will only affect the top level attributes. Each
  222. * level of nested attributes must be validated seperately using
  223. * nla_parse_nested() or nla_validate().
  224. * @par
  225. * @code
  226. * // The minimal length policy may be used to enforce the presence of at
  227. * // least one attribute.
  228. * static struct nla_policy my_policy[ATTR_MAX+1] = {
  229. * [ATTR_OPTS] = { .type = NLA_NESTED, minlen = NLA_HDRLEN },
  230. *
  231. * // Nested attributes are constructed by enclosing the attributes
  232. * // to be nested with calls to nla_nest_start() respetively nla_nest_end().
  233. * struct nlattr *opts = nla_nest_start(msg, ATTR_OPTS);
  234. * nla_put_u32(msg, ATTR_FOO, 123);
  235. * nla_put_string(msg, ATTR_BAR, "some text");
  236. * nla_nest_end(msg, opts);
  237. *
  238. * // Various methods exist to parse nested attributes, the easiest being
  239. * // nla_parse_nested() which also allows validation in the same step.
  240. * if (attrs[ATTR_OPTS]) {
  241. * struct nlattr *nested[ATTR_MAX+1];
  242. *
  243. * nla_parse_nested(nested, ATTR_MAX, attrs[ATTR_OPTS], &policy);
  244. *
  245. * if (nested[ATTR_FOO])
  246. * uint32_t foo = nla_get_u32(nested[ATTR_FOO]);
  247. * }
  248. * @endcode
  249. *
  250. * @subsection attr_exceptions Exception Based Attribute Construction
  251. * Often a large number of attributes are added to a message in a single
  252. * function. In order to simplify error handling, a second set of
  253. * construction functions exist which jump to a error label when they
  254. * fail instead of returning an error code. This second set consists
  255. * of macros which are named after their error code based counterpart
  256. * except that the name is written all uppercase.
  257. *
  258. * All of the macros jump to the target \c nla_put_failure if they fail.
  259. * @code
  260. * void my_func(struct nl_msg *msg)
  261. * {
  262. * NLA_PUT_U32(msg, ATTR_FOO, 10);
  263. * NLA_PUT_STRING(msg, ATTR_BAR, "bar");
  264. *
  265. * return 0;
  266. *
  267. * nla_put_failure:
  268. * return -NLE_NOMEM;
  269. * }
  270. * @endcode
  271. *
  272. * @subsection attr_examples Examples
  273. * @par Example 1.1 Constructing a netlink message with attributes.
  274. * @code
  275. * struct nl_msg *build_msg(int ifindex, struct nl_addr *lladdr, int mtu)
  276. * {
  277. * struct nl_msg *msg;
  278. * struct nlattr *info, *vlan;
  279. * struct ifinfomsg ifi = {
  280. * .ifi_family = AF_INET,
  281. * .ifi_index = ifindex,
  282. * };
  283. *
  284. * // Allocate a new netlink message, type=RTM_SETLINK, flags=NLM_F_ECHO
  285. * if (!(msg = nlmsg_alloc_simple(RTM_SETLINK, NLM_F_ECHO)))
  286. * return NULL;
  287. *
  288. * // Append the family specific header (struct ifinfomsg)
  289. * if (nlmsg_append(msg, &ifi, sizeof(ifi), NLMSG_ALIGNTO) < 0)
  290. * goto nla_put_failure
  291. *
  292. * // Append a 32 bit integer attribute to carry the MTU
  293. * NLA_PUT_U32(msg, IFLA_MTU, mtu);
  294. *
  295. * // Append a unspecific attribute to carry the link layer address
  296. * NLA_PUT_ADDR(msg, IFLA_ADDRESS, lladdr);
  297. *
  298. * // Append a container for nested attributes to carry link information
  299. * if (!(info = nla_nest_start(msg, IFLA_LINKINFO)))
  300. * goto nla_put_failure;
  301. *
  302. * // Put a string attribute into the container
  303. * NLA_PUT_STRING(msg, IFLA_INFO_KIND, "vlan");
  304. *
  305. * // Append another container inside the open container to carry
  306. * // vlan specific attributes
  307. * if (!(vlan = nla_nest_start(msg, IFLA_INFO_DATA)))
  308. * goto nla_put_failure;
  309. *
  310. * // add vlan specific info attributes here...
  311. *
  312. * // Finish nesting the vlan attributes and close the second container.
  313. * nla_nest_end(msg, vlan);
  314. *
  315. * // Finish nesting the link info attribute and close the first container.
  316. * nla_nest_end(msg, info);
  317. *
  318. * return msg;
  319. *
  320. * // If any of the construction macros fails, we end up here.
  321. * nla_put_failure:
  322. * nlmsg_free(msg);
  323. * return NULL;
  324. * }
  325. * @endcode
  326. *
  327. * @par Example 2.1 Parsing a netlink message with attributes.
  328. * @code
  329. * int parse_message(struct nl_msg *msg)
  330. * {
  331. * // The policy defines two attributes: a 32 bit integer and a container
  332. * // for nested attributes.
  333. * struct nla_policy attr_policy[ATTR_MAX+1] = {
  334. * [ATTR_FOO] = { .type = NLA_U32 },
  335. * [ATTR_BAR] = { .type = NLA_NESTED },
  336. * };
  337. * struct nlattr *attrs[ATTR_MAX+1];
  338. * int err;
  339. *
  340. * // The nlmsg_parse() function will make sure that the message contains
  341. * // enough payload to hold the header (struct my_hdr), validates any
  342. * // attributes attached to the messages and stores a pointer to each
  343. * // attribute in the attrs[] array accessable by attribute type.
  344. * if ((err = nlmsg_parse(nlmsg_hdr(msg), sizeof(struct my_hdr), attrs,
  345. * ATTR_MAX, attr_policy)) < 0)
  346. * goto errout;
  347. *
  348. * if (attrs[ATTR_FOO]) {
  349. * // It is safe to directly access the attribute payload without
  350. * // any further checks since nlmsg_parse() enforced the policy.
  351. * uint32_t foo = nla_get_u32(attrs[ATTR_FOO]);
  352. * }
  353. *
  354. * if (attrs[ATTR_BAR]) {
  355. * struct nlattr *nested[NESTED_MAX+1];
  356. *
  357. * // Attributes nested in a container can be parsed the same way
  358. * // as top level attributes.
  359. * if ((err = nla_parse_nested(nested, NESTED_MAX, attrs[ATTR_BAR],
  360. * nested_policy)) < 0)
  361. * goto errout;
  362. *
  363. * // Process nested attributes here.
  364. * }
  365. *
  366. * err = 0;
  367. * errout:
  368. * return err;
  369. * }
  370. * @endcode
  371. *
  372. * @{
  373. */
  374. /**
  375. * @name Attribute Size Calculation
  376. * @{
  377. */
  378. /** @} */
  379. /**
  380. * @name Parsing Attributes
  381. * @{
  382. */
  383. /**
  384. * Check if the attribute header and payload can be accessed safely.
  385. * @arg nla Attribute of any kind.
  386. * @arg remaining Number of bytes remaining in attribute stream.
  387. *
  388. * Verifies that the header and payload do not exceed the number of
  389. * bytes left in the attribute stream. This function must be called
  390. * before access the attribute header or payload when iterating over
  391. * the attribute stream using nla_next().
  392. *
  393. * @return True if the attribute can be accessed safely, false otherwise.
  394. */
  395. int nla_ok(const struct nlattr *nla, int remaining)
  396. {
  397. size_t r = remaining;
  398. return r >= sizeof(*nla) &&
  399. nla->nla_len >= sizeof(*nla) &&
  400. nla->nla_len <= r;
  401. }
  402. /**
  403. * Return next attribute in a stream of attributes.
  404. * @arg nla Attribute of any kind.
  405. * @arg remaining Variable to count remaining bytes in stream.
  406. *
  407. * Calculates the offset to the next attribute based on the attribute
  408. * given. The attribute provided is assumed to be accessible, the
  409. * caller is responsible to use nla_ok() beforehand. The offset (length
  410. * of specified attribute including padding) is then subtracted from
  411. * the remaining bytes variable and a pointer to the next attribute is
  412. * returned.
  413. *
  414. * nla_next() can be called as long as remainig is >0.
  415. *
  416. * @return Pointer to next attribute.
  417. */
  418. struct nlattr *nla_next(const struct nlattr *nla, int *remaining)
  419. {
  420. int totlen = NLA_ALIGN(nla->nla_len);
  421. *remaining -= totlen;
  422. return (struct nlattr *) ((char *) nla + totlen);
  423. }
  424. static uint16_t nla_attr_minlen[NLA_TYPE_MAX+1] = {
  425. [NLA_U8] = sizeof(uint8_t),
  426. [NLA_U16] = sizeof(uint16_t),
  427. [NLA_U32] = sizeof(uint32_t),
  428. [NLA_U64] = sizeof(uint64_t),
  429. [NLA_STRING] = 1,
  430. };
  431. static int validate_nla(struct nlattr *nla, int maxtype,
  432. struct nla_policy *policy)
  433. {
  434. struct nla_policy *pt;
  435. int minlen = 0, type = nla_type(nla);
  436. if (type <= 0 || type > maxtype)
  437. return 0;
  438. pt = &policy[type];
  439. if (pt->type > NLA_TYPE_MAX)
  440. BUG();
  441. if (pt->minlen)
  442. minlen = pt->minlen;
  443. else if (pt->type != NLA_UNSPEC)
  444. minlen = nla_attr_minlen[pt->type];
  445. if (pt->type == NLA_FLAG && nla_len(nla) > 0)
  446. return -NLE_RANGE;
  447. if (nla_len(nla) < minlen)
  448. return -NLE_RANGE;
  449. if (pt->maxlen && nla_len(nla) > pt->maxlen)
  450. return -NLE_RANGE;
  451. if (pt->type == NLA_STRING) {
  452. char *data = nla_data(nla);
  453. if (data[nla_len(nla) - 1] != '\0')
  454. return -NLE_INVAL;
  455. }
  456. return 0;
  457. }
  458. /**
  459. * Create attribute index based on a stream of attributes.
  460. * @arg tb Index array to be filled (maxtype+1 elements).
  461. * @arg maxtype Maximum attribute type expected and accepted.
  462. * @arg head Head of attribute stream.
  463. * @arg len Length of attribute stream.
  464. * @arg policy Attribute validation policy.
  465. *
  466. * Iterates over the stream of attributes and stores a pointer to each
  467. * attribute in the index array using the attribute type as index to
  468. * the array. Attribute with a type greater than the maximum type
  469. * specified will be silently ignored in order to maintain backwards
  470. * compatibility. If \a policy is not NULL, the attribute will be
  471. * validated using the specified policy.
  472. *
  473. * @see nla_validate
  474. * @return 0 on success or a negative error code.
  475. */
  476. int nla_parse(struct nlattr *tb[], int maxtype, struct nlattr *head, int len,
  477. struct nla_policy *policy)
  478. {
  479. struct nlattr *nla;
  480. int rem, err;
  481. memset(tb, 0, sizeof(struct nlattr *) * (maxtype + 1));
  482. nla_for_each_attr(nla, head, len, rem) {
  483. int type = nla_type(nla);
  484. if (type == 0) {
  485. fprintf(stderr, "Illegal nla->nla_type == 0\n");
  486. continue;
  487. }
  488. if (type <= maxtype) {
  489. if (policy) {
  490. err = validate_nla(nla, maxtype, policy);
  491. if (err < 0)
  492. goto errout;
  493. }
  494. tb[type] = nla;
  495. }
  496. }
  497. if (rem > 0)
  498. fprintf(stderr, "netlink: %d bytes leftover after parsing "
  499. "attributes.\n", rem);
  500. err = 0;
  501. errout:
  502. return err;
  503. }
  504. /**
  505. * Validate a stream of attributes.
  506. * @arg head Head of attributes stream.
  507. * @arg len Length of attributes stream.
  508. * @arg maxtype Maximum attribute type expected and accepted.
  509. * @arg policy Validation policy.
  510. *
  511. * Iterates over the stream of attributes and validates each attribute
  512. * one by one using the specified policy. Attributes with a type greater
  513. * than the maximum type specified will be silently ignored in order to
  514. * maintain backwards compatibility.
  515. *
  516. * See \ref attr_datatypes for more details on what kind of validation
  517. * checks are performed on each attribute data type.
  518. *
  519. * @return 0 on success or a negative error code.
  520. */
  521. int nla_validate(struct nlattr *head, int len, int maxtype,
  522. struct nla_policy *policy)
  523. {
  524. struct nlattr *nla;
  525. int rem, err;
  526. nla_for_each_attr(nla, head, len, rem) {
  527. err = validate_nla(nla, maxtype, policy);
  528. if (err < 0)
  529. goto errout;
  530. }
  531. err = 0;
  532. errout:
  533. return err;
  534. }
  535. /**
  536. * Find a single attribute in a stream of attributes.
  537. * @arg head Head of attributes stream.
  538. * @arg len Length of attributes stream.
  539. * @arg attrtype Attribute type to look for.
  540. *
  541. * Iterates over the stream of attributes and compares each type with
  542. * the type specified. Returns the first attribute which matches the
  543. * type.
  544. *
  545. * @return Pointer to attribute found or NULL.
  546. */
  547. struct nlattr *nla_find(struct nlattr *head, int len, int attrtype)
  548. {
  549. struct nlattr *nla;
  550. int rem;
  551. nla_for_each_attr(nla, head, len, rem)
  552. if (nla_type(nla) == attrtype)
  553. return nla;
  554. return NULL;
  555. }
  556. /** @} */
  557. /**
  558. * @name Unspecific Attribute
  559. * @{
  560. */
  561. /**
  562. * Reserve space for a attribute.
  563. * @arg msg Netlink Message.
  564. * @arg attrtype Attribute Type.
  565. * @arg attrlen Length of payload.
  566. *
  567. * Reserves room for a attribute in the specified netlink message and
  568. * fills in the attribute header (type, length). Returns NULL if there
  569. * is unsuficient space for the attribute.
  570. *
  571. * Any padding between payload and the start of the next attribute is
  572. * zeroed out.
  573. *
  574. * @return Pointer to start of attribute or NULL on failure.
  575. */
  576. struct nlattr *nla_reserve(struct nl_msg *msg, int attrtype, int attrlen)
  577. {
  578. struct nlattr *nla;
  579. int tlen;
  580. tlen = NLMSG_ALIGN(msg->nm_nlh->nlmsg_len) + nla_total_size(attrlen);
  581. if ((tlen + msg->nm_nlh->nlmsg_len) > msg->nm_size)
  582. return NULL;
  583. nla = (struct nlattr *) nlmsg_tail(msg->nm_nlh);
  584. nla->nla_type = attrtype;
  585. nla->nla_len = nla_attr_size(attrlen);
  586. memset((unsigned char *) nla + nla->nla_len, 0, nla_padlen(attrlen));
  587. msg->nm_nlh->nlmsg_len = tlen;
  588. NL_DBG(2, "msg %p: Reserved %d bytes at offset +%td for attr %d "
  589. "nlmsg_len=%d\n", msg, attrlen,
  590. (void *) nla - nlmsg_data(msg->nm_nlh),
  591. attrtype, msg->nm_nlh->nlmsg_len);
  592. return nla;
  593. }
  594. /**
  595. * Add a unspecific attribute to netlink message.
  596. * @arg msg Netlink message.
  597. * @arg attrtype Attribute type.
  598. * @arg datalen Length of data to be used as payload.
  599. * @arg data Pointer to data to be used as attribute payload.
  600. *
  601. * Reserves room for a unspecific attribute and copies the provided data
  602. * into the message as payload of the attribute. Returns an error if there
  603. * is insufficient space for the attribute.
  604. *
  605. * @see nla_reserve
  606. * @return 0 on success or a negative error code.
  607. */
  608. int nla_put(struct nl_msg *msg, int attrtype, int datalen, const void *data)
  609. {
  610. struct nlattr *nla;
  611. nla = nla_reserve(msg, attrtype, datalen);
  612. if (!nla)
  613. return -NLE_NOMEM;
  614. memcpy(nla_data(nla), data, datalen);
  615. NL_DBG(2, "msg %p: Wrote %d bytes at offset +%td for attr %d\n",
  616. msg, datalen, (void *) nla - nlmsg_data(msg->nm_nlh), attrtype);
  617. return 0;
  618. }
  619. /** @} */