oops
[libnl.git] / lib / attr.c
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-2006 Thomas Graf <tgraf@suug.ch>
10  */
11
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>
19
20 /**
21  * @ingroup nl
22  * @defgroup attr Attributes
23  * Netlink Attributes Construction/Parsing Interface
24  * @par 0) Introduction
25  * Netlink attributes are chained together following each other:
26  * @code
27  *    <------- nla_total_size(payload) ------->
28  *    <---- nla_attr_size(payload) ----->
29  *   +----------+- - -+- - - - - - - - - +- - -+-------- - -
30  *   |  Header  | Pad |     Payload      | Pad |  Header
31  *   +----------+- - -+- - - - - - - - - +- - -+-------- - -
32  *                     <- nla_len(nla) ->      ^
33  *   nla_data(nla)----^                        |
34  *   nla_next(nla)-----------------------------'
35  * @endcode
36  *
37  * @par
38  * The attribute header and payload must be aligned properly:
39  * @code
40  *  <------- NLA_HDRLEN ------> <-- NLA_ALIGN(payload)-->
41  * +---------------------+- - -+- - - - - - - - - -+- - -+
42  * |        Header       | Pad |     Payload       | Pad |
43  * |   (struct nlattr)   | ing |                   | ing |
44  * +---------------------+- - -+- - - - - - - - - -+- - -+
45  *  <-------------- nlattr->nla_len -------------->
46  * @endcode
47  *
48  * @par Nested TLVs:
49  * Nested TLVs are an array of TLVs nested into another TLV. This can be useful
50  * to allow subsystems to have their own formatting rules without the need to
51  * make the underlying layer be aware of it. It can also be useful to transfer
52  * arrays, lists and flattened trees.
53  * \code
54  *  <-------------------- NLA_ALIGN(...) ------------------->
55  * +---------------+- - - - - - - - - - - - - - - - - -+- - -+
56  * |               |+---------+---------+- - -+-------+|     |
57  * |  TLV Header   ||  TLV 1  |  TLV 2  |     | TLV n || Pad |
58  * |               |+---------+---------+- - -+-------+|     |
59  * +---------------+- - - - - - - - - - - - - - - - - -+- - -+
60  *                  <--------- nla_data(nla) --------->
61  * \endcode
62  *
63  * @par 1) Constructing a message with attributes
64  * @code
65  * int param1 = 10;
66  * char *param2 = "parameter text";
67  * struct nlmsghdr hdr = {
68  *      .nlmsg_type = MY_ACTION,
69  * };
70  * struct nl_msg *m = nlmsg_build(&hdr);
71  * nla_put_u32(m, 1, param1);
72  * nla_put_string(m, 2, param2);
73  * 
74  * nl_send_auto_complete(handle, nl_msg_get(m));
75  * nlmsg_free(m);
76  * @endcode
77  *
78  * @par 2) Constructing nested attributes
79  * @code
80  * struct nl_msg * nested_config(void)
81  * {
82  *      int a = 5, int b = 10;
83  *      struct nl_msg *n = nlmsg_build(NULL);
84  *      nla_put_u32(n, 10, a);
85  *      nla_put_u32(n, 20, b);
86  *      return n;
87  * }
88  *
89  * ...
90  * struct nl_msg *m = nlmsg_build(&hdr);
91  * struct nl_msg *nest = nested_config();
92  * nla_put_nested(m, 1, nest);
93  *
94  * nl_send_auto_complete(handle, nl_msg_get(m));
95  * nlmsg_free(nest);
96  * nlmsg_free(m);
97  * @endcode
98  * @{
99  */
100
101 /**
102  * @name Size Calculations
103  * @{
104  */
105
106 /**
107  * length of attribute not including padding
108  * @arg payload         length of payload
109  */
110 int nla_attr_size(int payload)
111 {
112         return NLA_HDRLEN + payload;
113 }
114
115 /**
116  * total length of attribute including padding
117  * @arg payload         length of payload
118  */
119 int nla_total_size(int payload)
120 {
121         return NLA_ALIGN(nla_attr_size(payload));
122 }
123
124 /**
125  * length of padding at the tail of the attribute
126  * @arg payload         length of payload
127  */
128 int nla_padlen(int payload)
129 {
130         return nla_total_size(payload) - nla_attr_size(payload);
131 }
132
133 /** @} */
134
135 /**
136  * @name Payload Access
137  * @{
138  */
139
140 /**
141  * head of payload
142  * @arg nla             netlink attribute
143  */
144 void *nla_data(const struct nlattr *nla)
145 {
146         return (char *) nla + NLA_HDRLEN;
147 }
148
149 /**
150  * length of payload
151  * @arg nla             netlink attribute
152  */
153 int nla_len(const struct nlattr *nla)
154 {
155         return nla->nla_len - NLA_HDRLEN;
156 }
157
158 /** @} */
159
160 /**
161  * @name Attribute Parsing
162  * @{
163  */
164
165 /**
166  * check if the netlink attribute fits into the remaining bytes
167  * @arg nla             netlink attribute
168  * @arg remaining       number of bytes remaining in attribute stream
169  */
170 int nla_ok(const struct nlattr *nla, int remaining)
171 {
172         return remaining >= sizeof(*nla) &&
173                nla->nla_len >= sizeof(*nla) &&
174                nla->nla_len <= remaining;
175 }
176
177 /**
178  * next netlink attribte in attribute stream
179  * @arg nla             netlink attribute
180  * @arg remaining       number of bytes remaining in attribute stream
181  *
182  * @return the next netlink attribute in the attribute stream and
183  * decrements remaining by the size of the current attribute.
184  */
185 struct nlattr *nla_next(const struct nlattr *nla, int *remaining)
186 {
187         int totlen = NLA_ALIGN(nla->nla_len);
188
189         *remaining -= totlen;
190         return (struct nlattr *) ((char *) nla + totlen);
191 }
192
193 static uint16_t nla_attr_minlen[NLA_TYPE_MAX+1] = {
194         [NLA_U8]        = sizeof(uint8_t),
195         [NLA_U16]       = sizeof(uint16_t),
196         [NLA_U32]       = sizeof(uint32_t),
197         [NLA_U64]       = sizeof(uint64_t),
198         [NLA_STRING]    = 1,
199         [NLA_NESTED]    = NLA_HDRLEN,
200 };
201
202 static int validate_nla(struct nlattr *nla, int maxtype,
203                         struct nla_policy *policy)
204 {
205         struct nla_policy *pt;
206         int minlen = 0;
207
208         if (nla->nla_type <= 0 || nla->nla_type > maxtype)
209                 return 0;
210
211         pt = &policy[nla->nla_type];
212
213         if (pt->type > NLA_TYPE_MAX)
214                 BUG();
215
216         if (pt->minlen)
217                 minlen = pt->minlen;
218         else if (pt->type != NLA_UNSPEC)
219                 minlen = nla_attr_minlen[pt->type];
220
221         if (pt->type == NLA_FLAG && nla_len(nla) > 0)
222                 return -ERANGE;
223
224         if (nla_len(nla) < minlen)
225                 return -ERANGE;
226
227         if (pt->maxlen && nla_len(nla) > pt->maxlen)
228                 return -ERANGE;
229
230         if (pt->type == NLA_STRING) {
231                 char *data = nla_data(nla);
232                 if (data[nla_len(nla) - 1] != '\0')
233                         return -EINVAL;
234         }
235
236         return 0;
237 }
238
239
240 /**
241  * Parse a stream of attributes into a tb buffer
242  * @arg tb              destination array with maxtype+1 elements
243  * @arg maxtype         maximum attribute type to be expected
244  * @arg head            head of attribute stream
245  * @arg len             length of attribute stream
246  * @arg policy          validation policy
247  *
248  * Parses a stream of attributes and stores a pointer to each attribute in
249  * the tb array accessable via the attribute type. Attributes with a type
250  * exceeding maxtype will be silently ignored for backwards compatibility
251  * reasons. policy may be set to NULL if no validation is required.
252  *
253  * @return 0 on success or a negative error code.
254  */
255 int nla_parse(struct nlattr *tb[], int maxtype, struct nlattr *head, int len,
256               struct nla_policy *policy)
257 {
258         struct nlattr *nla;
259         int rem, err;
260
261         memset(tb, 0, sizeof(struct nlattr *) * (maxtype + 1));
262
263         nla_for_each_attr(nla, head, len, rem) {
264                 uint16_t type = nla->nla_type;
265
266                 if (type == 0) {
267                         fprintf(stderr, "Illegal nla->nla_type == 0\n");
268                         continue;
269                 }
270
271                 if (type <= maxtype) {
272                         if (policy) {
273                                 err = validate_nla(nla, maxtype, policy);
274                                 if (err < 0)
275                                         goto errout;
276                         }
277
278                         tb[type] = nla;
279                 }
280         }
281
282         if (rem > 0)
283                 fprintf(stderr, "netlink: %d bytes leftover after parsing "
284                        "attributes.\n", rem);
285
286         err = 0;
287 errout:
288         return err;
289 }
290
291
292 /**
293  * parse nested attributes
294  * @arg tb              destination array with maxtype+1 elements
295  * @arg maxtype         maximum attribute type to be expected
296  * @arg nla             attribute containing the nested attributes
297  * @arg policy          validation policy
298  *
299  * @see nla_parse()
300  */
301 int nla_parse_nested(struct nlattr *tb[], int maxtype, struct nlattr *nla,
302                      struct nla_policy *policy)
303 {
304         return nla_parse(tb, maxtype, nla_data(nla), nla_len(nla), policy);
305 }
306
307 /**
308  * Validate a stream of attributes
309  * @arg head            head of attribute stream
310  * @arg len             length of attribute stream
311  * @arg maxtype         maximum attribute type to be expected
312  * @arg policy          validation policy
313  *
314  * Validates all attributes in the specified attribute stream
315  * against the specified policy. Attributes with a type exceeding
316  * maxtype will be ignored. See documenation of struct nla_policy
317  * for more details.
318  *
319  * @return 0 on success or a negative error code.
320  */
321 int nla_validate(struct nlattr *head, int len, int maxtype,
322                  struct nla_policy *policy)
323 {
324         struct nlattr *nla;
325         int rem, err;
326
327         nla_for_each_attr(nla, head, len, rem) {
328                 err = validate_nla(nla, maxtype, policy);
329                 if (err < 0)
330                         goto errout;
331         }
332
333         err = 0;
334 errout:
335         return err;
336 }
337
338 /**
339  * Find a specific attribute in a stream of attributes
340  * @arg head            head of attribute stream
341  * @arg len             length of attribute stream
342  * @arg attrtype        type of attribute to look for
343  *
344  * @return the first attribute in the stream matching the specified type.
345  */
346 struct nlattr *nla_find(struct nlattr *head, int len, int attrtype)
347 {
348         struct nlattr *nla;
349         int rem;
350
351         nla_for_each_attr(nla, head, len, rem)
352                 if (nla->nla_type == attrtype)
353                         return nla;
354
355         return NULL;
356 }
357
358 /** @} */
359
360 /**
361  * @name Utilities
362  * @{
363  */
364
365 /**
366  * Copy a netlink attribute into another memory area
367  * @arg dest            where to copy to memcpy
368  * @arg src             netlink attribute to copy from
369  * @arg count           size of the destination area
370  *
371  * Note: The number of bytes copied is limited by the length of
372  *       attribute's payload. memcpy
373  *
374  * @return the number of bytes copied.
375  */
376 int nla_memcpy(void *dest, struct nlattr *src, int count)
377 {
378         int minlen;
379
380         if (!src)
381                 return 0;
382         
383         minlen = min_t(int, count, nla_len(src));
384         memcpy(dest, nla_data(src), minlen);
385
386         return minlen;
387 }
388
389 /**
390  * Copy string attribute payload into a sized buffer
391  * @arg dst             where to copy the string to
392  * @arg nla             attribute to copy the string from
393  * @arg dstsize         size of destination buffer
394  *
395  * Copies at most dstsize - 1 bytes into the destination buffer.
396  * The result is always a valid NUL-terminated string. Unlike
397  * strlcpy the destination buffer is always padded out.
398  *
399  * @return the length of the source buffer.
400  */
401 size_t nla_strlcpy(char *dst, const struct nlattr *nla, size_t dstsize)
402 {
403         size_t srclen = nla_len(nla);
404         char *src = nla_data(nla);
405
406         if (srclen > 0 && src[srclen - 1] == '\0')
407                 srclen--;
408
409         if (dstsize > 0) {
410                 size_t len = (srclen >= dstsize) ? dstsize - 1 : srclen;
411
412                 memset(dst, 0, dstsize);
413                 memcpy(dst, src, len);
414         }
415
416         return srclen;
417 }
418
419 /**
420  * Compare an attribute with sized memory area
421  * @arg nla             netlink attribute
422  * @arg data            memory area
423  * @arg size            size of memory area
424  */
425 int nla_memcmp(const struct nlattr *nla, const void *data,
426                              size_t size)
427 {
428         int d = nla_len(nla) - size;
429
430         if (d == 0)
431                 d = memcmp(nla_data(nla), data, size);
432
433         return d;
434 }
435
436 /**
437  * Compare a string attribute against a string
438  * @arg nla             netlink string attribute
439  * @arg str             another string
440  */
441 int nla_strcmp(const struct nlattr *nla, const char *str)
442 {
443         int len = strlen(str) + 1;
444         int d = nla_len(nla) - len;
445
446         if (d == 0)
447                 d = memcmp(nla_data(nla), str, len);
448
449         return d;
450 }
451
452 /** @} */
453
454 /**
455  * @name Attribute Construction
456  * @{
457  */
458
459 /**
460  * reserve room for attribute on the skb
461  * @arg n               netlink message
462  * @arg attrtype        attribute type
463  * @arg attrlen         length of attribute payload
464  *
465  * Adds a netlink attribute header to a netlink message and reserves
466  * room for the payload but does not copy it.
467  */
468 struct nlattr *nla_reserve(struct nl_msg *n, int attrtype, int attrlen)
469 {
470         struct nlattr *nla;
471         int tlen;
472         
473         tlen = NLMSG_ALIGN(n->nm_nlh->nlmsg_len) + nla_total_size(attrlen);
474
475         n->nm_nlh = realloc(n->nm_nlh, tlen);
476         if (!n->nm_nlh) {
477                 nl_errno(ENOMEM);
478                 return NULL;
479         }
480
481         nla = (struct nlattr *) nlmsg_tail(n->nm_nlh);
482         nla->nla_type = attrtype;
483         nla->nla_len = nla_attr_size(attrlen);
484
485         memset((unsigned char *) nla + nla->nla_len, 0, nla_padlen(attrlen));
486         n->nm_nlh->nlmsg_len = tlen;
487
488         return nla;
489 }
490
491 /**
492  * Add a netlink attribute to a netlink message
493  * @arg n               netlink message
494  * @arg attrtype        attribute type
495  * @arg attrlen         length of attribute payload
496  * @arg data            head of attribute payload
497  *
498  * @return -1 if the tailroom of the skb is insufficient to store
499  * the attribute header and payload.
500  */
501 int nla_put(struct nl_msg *n, int attrtype, int attrlen, const void *data)
502 {
503         struct nlattr *nla;
504
505         nla = nla_reserve(n, attrtype, attrlen);
506         if (!nla)
507                 return nl_errno(ENOMEM);
508
509         memcpy(nla_data(nla), data, attrlen);
510
511         return 0;
512 }
513
514 /**
515  * Add a nested netlink attribute to a netlink message
516  * @arg n               netlink message
517  * @arg attrtype        attribute type
518  * @arg nested          netlink attribute to nest
519  *
520  * @return -1 if the tailroom of the skb is insufficient to store
521  * the attribute header and payload.
522  */
523 int nla_put_nested(struct nl_msg *n, int attrtype, struct nl_msg *nested)
524 {
525         return nla_put(n, attrtype, nlmsg_len(nested->nm_nlh),
526                        nlmsg_data(nested->nm_nlh));
527 }
528
529 /**
530  * Add a u16 netlink attribute to a netlink message
531  * @arg n               netlink message
532  * @arg attrtype        attribute type
533  * @arg value           numeric value
534  */
535 int nla_put_u8(struct nl_msg *n, int attrtype, uint8_t value)
536 {
537         return nla_put(n, attrtype, sizeof(uint8_t), &value);
538 }
539
540 /**
541  * Add a u16 netlink attribute to a netlink message
542  * @arg n               netlink message
543  * @arg attrtype        attribute type
544  * @arg value           numeric value
545  */
546 int nla_put_u16(struct nl_msg *n, int attrtype, uint16_t value)
547 {
548         return nla_put(n, attrtype, sizeof(uint16_t), &value);
549 }
550
551 /**
552  * Add a u32 netlink attribute to a netlink message
553  * @arg n               netlink message
554  * @arg attrtype        attribute type
555  * @arg value           numeric value
556  */
557 int nla_put_u32(struct nl_msg *n, int attrtype, uint32_t value)
558 {
559         return nla_put(n, attrtype, sizeof(uint32_t), &value);
560 }
561
562 /**
563  * Add a u64 netlink attribute to a netlink message
564  * @arg n               netlink message
565  * @arg attrtype        attribute type
566  * @arg value           numeric value
567  */
568 int nla_put_u64(struct nl_msg *n, int attrtype, uint64_t value)
569 {
570         return nla_put(n, attrtype, sizeof(uint64_t), &value);
571 }
572
573 /**
574  * Add a string netlink attribute to a netlink message
575  * @arg n               netlink message
576  * @arg attrtype        attribute type
577  * @arg str             NUL terminated string
578  */
579 int nla_put_string(struct nl_msg *n, int attrtype, const char *str)
580 {
581         return nla_put(n, attrtype, strlen(str) + 1, str);
582 }
583
584 /**
585  * Add a flag netlink attribute to a netlink message
586  * @arg n               netlink message
587  * @arg attrtype        attribute type
588  */
589 int nla_put_flag(struct nl_msg *n, int attrtype)
590 {
591         return nla_put(n, attrtype, 0, NULL);
592 }
593
594 /**
595  * Add a msecs netlink attribute to a netlink message
596  * @arg n               netlink message
597  * @arg attrtype        attribute type
598  * @arg msecs           number of msecs
599  */
600 int nla_put_msecs(struct nl_msg *n, int attrtype, unsigned long msecs)
601 {
602         return nla_put_u64(n, attrtype, msecs);
603 }
604
605 /**
606  * Add an abstract data netlink attribute to a netlink message
607  * @arg n               netlink message
608  * @arg attrtype        attribute type
609  * @arg data            abstract data
610  */
611 int nla_put_data(struct nl_msg *n, int attrtype, struct nl_data *data)
612 {
613         return nla_put(n, attrtype, nl_data_get_size(data),
614                        nl_data_get(data));
615 }
616
617 /**
618  * Add an abstract address netlink attribute to a netlink message
619  * @arg n               netlink message
620  * @arg attrtype        attribute type
621  * @arg addr            abstract address
622  */
623 int nla_put_addr(struct nl_msg *n, int attrtype, struct nl_addr *addr)
624 {
625         return nla_put(n, attrtype, nl_addr_get_len(addr),
626                        nl_addr_get_binary_addr(addr));
627 }
628
629 /** @} */
630
631 /**
632  * @name Attribute Nesting
633  * @{
634  */
635
636 /**
637  * Start a new level of nested attributes
638  * @arg n               netlink message
639  * @arg attrtype        attribute type of container
640  *
641  * @return the container attribute
642  */
643 struct nlattr *nla_nest_start(struct nl_msg *n, int attrtype)
644 {
645         struct nlattr *start = (struct nlattr *) nlmsg_tail(n->nm_nlh);
646
647         if (nla_put(n, attrtype, 0, NULL) < 0)
648                 return NULL;
649
650         return start;
651 }
652
653 /**
654  * Finalize nesting of attributes
655  * @arg n               netlink message
656  * @arg start           container attribute
657  *
658  * Corrects the container attribute header to include the all
659  * appeneded attributes.
660  *
661  * @return the total data length of the skb.
662  */
663 int nla_nest_end(struct nl_msg *n, struct nlattr *start)
664 {
665         start->nla_len = (unsigned char *) nlmsg_tail(n->nm_nlh) -
666                                 (unsigned char *) start;
667         return 0;
668 }
669
670 /** @} */
671
672 /**
673  * @name Attribute Reading
674  * @{
675  */
676
677 /**
678  * Return payload of u32 attribute
679  * @arg nla             u32 netlink attribute
680  */
681 uint32_t nla_get_u32(struct nlattr *nla)
682 {
683         return *(uint32_t *) nla_data(nla);
684 }
685
686 /**
687  * Return payload of u16 attribute
688  * @arg nla             u16 netlink attribute
689  */
690 uint16_t nla_get_u16(struct nlattr *nla)
691 {
692         return *(uint16_t *) nla_data(nla);
693 }
694
695 /**
696  * Return payload of u8 attribute
697  * @arg nla             u8 netlink attribute
698  */
699 uint8_t nla_get_u8(struct nlattr *nla)
700 {
701         return *(uint8_t *) nla_data(nla);
702 }
703
704 /**
705  * Return payload of u64 attribute
706  * @arg nla             u64 netlink attribute
707  */
708 uint64_t nla_get_u64(struct nlattr *nla)
709 {
710         uint64_t tmp;
711
712         nla_memcpy(&tmp, nla, sizeof(tmp));
713
714         return tmp;
715 }
716
717 /**
718  * Return payload of flag attribute
719  * @arg nla             flag netlink attribute
720  */
721 int nla_get_flag(struct nlattr *nla)
722 {
723         return !!nla;
724 }
725
726 /**
727  * Return payload of msecs attribute
728  * @arg nla             msecs netlink attribute
729  *
730  * @return the number of milliseconds.
731  */
732 unsigned long nla_get_msecs(struct nlattr *nla)
733 {
734         return nla_get_u64(nla);
735 }
736
737 /**
738  * Return payload of address attribute
739  * @arg nla             address netlink attribute
740  * @arg family          address family
741  *
742  * @return Newly allocated address handle or NULL
743  */
744 struct nl_addr *nla_get_addr(struct nlattr *nla, int family)
745 {
746         return nl_addr_build(family, nla_data(nla), nla_len(nla));
747 }
748
749 /**
750  * Return payload of abstract data attribute
751  * @arg nla             abstract data netlink attribute
752  *
753  * @return Newly allocated abstract data handle or NULL
754  */
755 struct nl_data *nla_get_data(struct nlattr *nla)
756 {
757         return nl_data_alloc(nla_data(nla), nla_len(nla));
758 }
759
760 /** @} */
761
762 /** @} */