attr.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  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. [NLA_S8] = sizeof(int8_t),
  431. [NLA_S16] = sizeof(int16_t),
  432. [NLA_S32] = sizeof(int32_t),
  433. [NLA_S64] = sizeof(int64_t),
  434. };
  435. static int validate_nla(const struct nlattr *nla, int maxtype,
  436. const struct nla_policy *policy)
  437. {
  438. const struct nla_policy *pt;
  439. int minlen = 0, type = nla_type(nla);
  440. if (type <= 0 || type > maxtype)
  441. return 0;
  442. pt = &policy[type];
  443. if (pt->type > NLA_TYPE_MAX)
  444. BUG();
  445. if (pt->minlen)
  446. minlen = pt->minlen;
  447. else if (pt->type != NLA_UNSPEC)
  448. minlen = nla_attr_minlen[pt->type];
  449. if (pt->type == NLA_FLAG && nla_len(nla) > 0)
  450. return -NLE_RANGE;
  451. if (nla_len(nla) < minlen)
  452. return -NLE_RANGE;
  453. if (pt->maxlen && nla_len(nla) > pt->maxlen)
  454. return -NLE_RANGE;
  455. if (pt->type == NLA_STRING) {
  456. char *data = nla_data(nla);
  457. if (data[nla_len(nla) - 1] != '\0')
  458. return -NLE_INVAL;
  459. }
  460. return 0;
  461. }
  462. /**
  463. * Create attribute index based on a stream of attributes.
  464. * @arg tb Index array to be filled (maxtype+1 elements).
  465. * @arg maxtype Maximum attribute type expected and accepted.
  466. * @arg head Head of attribute stream.
  467. * @arg len Length of attribute stream.
  468. * @arg policy Attribute validation policy.
  469. *
  470. * Iterates over the stream of attributes and stores a pointer to each
  471. * attribute in the index array using the attribute type as index to
  472. * the array. Attribute with a type greater than the maximum type
  473. * specified will be silently ignored in order to maintain backwards
  474. * compatibility. If \a policy is not NULL, the attribute will be
  475. * validated using the specified policy.
  476. *
  477. * @see nla_validate
  478. * @return 0 on success or a negative error code.
  479. */
  480. int nla_parse(struct nlattr *tb[], int maxtype, struct nlattr *head, int len,
  481. const struct nla_policy *policy)
  482. {
  483. struct nlattr *nla;
  484. int rem, err;
  485. memset(tb, 0, sizeof(struct nlattr *) * (maxtype + 1));
  486. nla_for_each_attr(nla, head, len, rem) {
  487. int type = nla_type(nla);
  488. if (type == 0) {
  489. fprintf(stderr, "Illegal nla->nla_type == 0\n");
  490. continue;
  491. }
  492. if (type <= maxtype) {
  493. if (policy) {
  494. err = validate_nla(nla, maxtype, policy);
  495. if (err < 0)
  496. goto errout;
  497. }
  498. tb[type] = nla;
  499. }
  500. }
  501. if (rem > 0)
  502. fprintf(stderr, "netlink: %d bytes leftover after parsing "
  503. "attributes.\n", rem);
  504. err = 0;
  505. errout:
  506. return err;
  507. }
  508. /**
  509. * Validate a stream of attributes.
  510. * @arg head Head of attributes stream.
  511. * @arg len Length of attributes stream.
  512. * @arg maxtype Maximum attribute type expected and accepted.
  513. * @arg policy Validation policy.
  514. *
  515. * Iterates over the stream of attributes and validates each attribute
  516. * one by one using the specified policy. Attributes with a type greater
  517. * than the maximum type specified will be silently ignored in order to
  518. * maintain backwards compatibility.
  519. *
  520. * See \ref attr_datatypes for more details on what kind of validation
  521. * checks are performed on each attribute data type.
  522. *
  523. * @return 0 on success or a negative error code.
  524. */
  525. int nla_validate(const struct nlattr *head, int len, int maxtype,
  526. const struct nla_policy *policy)
  527. {
  528. const struct nlattr *nla;
  529. int rem, err;
  530. nla_for_each_attr(nla, head, len, rem) {
  531. err = validate_nla(nla, maxtype, policy);
  532. if (err < 0)
  533. goto errout;
  534. }
  535. err = 0;
  536. errout:
  537. return err;
  538. }
  539. /**
  540. * Find a single attribute in a stream of attributes.
  541. * @arg head Head of attributes stream.
  542. * @arg len Length of attributes stream.
  543. * @arg attrtype Attribute type to look for.
  544. *
  545. * Iterates over the stream of attributes and compares each type with
  546. * the type specified. Returns the first attribute which matches the
  547. * type.
  548. *
  549. * @return Pointer to attribute found or NULL.
  550. */
  551. struct nlattr *nla_find(struct nlattr *head, int len, int attrtype)
  552. {
  553. struct nlattr *nla;
  554. int rem;
  555. nla_for_each_attr(nla, head, len, rem)
  556. if (nla_type(nla) == attrtype)
  557. return nla;
  558. return NULL;
  559. }
  560. /** @} */
  561. /**
  562. * @name Unspecific Attribute
  563. * @{
  564. */
  565. /**
  566. * Reserve space for a attribute.
  567. * @arg msg Netlink Message.
  568. * @arg attrtype Attribute Type.
  569. * @arg attrlen Length of payload.
  570. *
  571. * Reserves room for a attribute in the specified netlink message and
  572. * fills in the attribute header (type, length). Returns NULL if there
  573. * is unsuficient space for the attribute.
  574. *
  575. * Any padding between payload and the start of the next attribute is
  576. * zeroed out.
  577. *
  578. * @return Pointer to start of attribute or NULL on failure.
  579. */
  580. struct nlattr *nla_reserve(struct nl_msg *msg, int attrtype, int attrlen)
  581. {
  582. struct nlattr *nla;
  583. int tlen;
  584. tlen = NLMSG_ALIGN(msg->nm_nlh->nlmsg_len) + nla_total_size(attrlen);
  585. if ((tlen + msg->nm_nlh->nlmsg_len) > msg->nm_size)
  586. return NULL;
  587. nla = (struct nlattr *) nlmsg_tail(msg->nm_nlh);
  588. nla->nla_type = attrtype;
  589. nla->nla_len = nla_attr_size(attrlen);
  590. memset((unsigned char *) nla + nla->nla_len, 0, nla_padlen(attrlen));
  591. msg->nm_nlh->nlmsg_len = tlen;
  592. NL_DBG(2, "msg %p: Reserved %d bytes at offset +%td for attr %d "
  593. "nlmsg_len=%d\n", msg, attrlen,
  594. (void *) nla - nlmsg_data(msg->nm_nlh),
  595. attrtype, msg->nm_nlh->nlmsg_len);
  596. return nla;
  597. }
  598. /**
  599. * Add a unspecific attribute to netlink message.
  600. * @arg msg Netlink message.
  601. * @arg attrtype Attribute type.
  602. * @arg datalen Length of data to be used as payload.
  603. * @arg data Pointer to data to be used as attribute payload.
  604. *
  605. * Reserves room for a unspecific attribute and copies the provided data
  606. * into the message as payload of the attribute. Returns an error if there
  607. * is insufficient space for the attribute.
  608. *
  609. * @see nla_reserve
  610. * @return 0 on success or a negative error code.
  611. */
  612. int nla_put(struct nl_msg *msg, int attrtype, int datalen, const void *data)
  613. {
  614. struct nlattr *nla;
  615. nla = nla_reserve(msg, attrtype, datalen);
  616. if (!nla)
  617. return -NLE_NOMEM;
  618. memcpy(nla_data(nla), data, datalen);
  619. NL_DBG(2, "msg %p: Wrote %d bytes at offset +%td for attr %d\n",
  620. msg, datalen, (void *) nla - nlmsg_data(msg->nm_nlh), attrtype);
  621. return 0;
  622. }
  623. /** @} */