netlink: New functions for putting attributes at the beginning of a buffer.
[sliver-openvswitch.git] / lib / netlink.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "netlink.h"
19 #include <assert.h>
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <sys/types.h>
23 #include <unistd.h>
24 #include "coverage.h"
25 #include "netlink-protocol.h"
26 #include "ofpbuf.h"
27 #include "timeval.h"
28 #include "unaligned.h"
29 #include "vlog.h"
30
31 VLOG_DEFINE_THIS_MODULE(netlink);
32
33 /* A single (bad) Netlink message can in theory dump out many, many log
34  * messages, so the burst size is set quite high here to avoid missing useful
35  * information.  Also, at high logging levels we log *all* Netlink messages. */
36 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 600);
37
38 /* Returns the nlmsghdr at the head of 'msg'.
39  *
40  * 'msg' must be at least as large as a nlmsghdr. */
41 struct nlmsghdr *
42 nl_msg_nlmsghdr(const struct ofpbuf *msg)
43 {
44     return ofpbuf_at_assert(msg, 0, NLMSG_HDRLEN);
45 }
46
47 /* Returns the genlmsghdr just past 'msg''s nlmsghdr.
48  *
49  * Returns a null pointer if 'msg' is not large enough to contain an nlmsghdr
50  * and a genlmsghdr. */
51 struct genlmsghdr *
52 nl_msg_genlmsghdr(const struct ofpbuf *msg)
53 {
54     return ofpbuf_at(msg, NLMSG_HDRLEN, GENL_HDRLEN);
55 }
56
57 /* If 'buffer' is a NLMSG_ERROR message, stores 0 in '*errorp' if it is an ACK
58  * message, otherwise a positive errno value, and returns true.  If 'buffer' is
59  * not an NLMSG_ERROR message, returns false.
60  *
61  * 'msg' must be at least as large as a nlmsghdr. */
62 bool
63 nl_msg_nlmsgerr(const struct ofpbuf *msg, int *errorp)
64 {
65     if (nl_msg_nlmsghdr(msg)->nlmsg_type == NLMSG_ERROR) {
66         struct nlmsgerr *err = ofpbuf_at(msg, NLMSG_HDRLEN, sizeof *err);
67         int code = EPROTO;
68         if (!err) {
69             VLOG_ERR_RL(&rl, "received invalid nlmsgerr (%zd bytes < %zd)",
70                         msg->size, NLMSG_HDRLEN + sizeof *err);
71         } else if (err->error <= 0 && err->error > INT_MIN) {
72             code = -err->error;
73         }
74         if (errorp) {
75             *errorp = code;
76         }
77         return true;
78     } else {
79         return false;
80     }
81 }
82
83 /* Ensures that 'b' has room for at least 'size' bytes plus netlink padding at
84  * its tail end, reallocating and copying its data if necessary. */
85 void
86 nl_msg_reserve(struct ofpbuf *msg, size_t size)
87 {
88     ofpbuf_prealloc_tailroom(msg, NLMSG_ALIGN(size));
89 }
90
91 static uint32_t
92 get_nlmsg_seq(void)
93 {
94     /* Next nlmsghdr sequence number.
95      *
96      * This implementation uses sequence numbers that are unique process-wide,
97      * to avoid a hypothetical race: send request, close socket, open new
98      * socket that reuses the old socket's PID value, send request on new
99      * socket, receive reply from kernel to old socket but with same PID and
100      * sequence number.  (This race could be avoided other ways, e.g. by
101      * preventing PIDs from being quickly reused). */
102     static uint32_t next_seq;
103
104     if (next_seq == 0) {
105         /* Pick initial sequence number. */
106         next_seq = getpid() ^ time_wall();
107     }
108     return next_seq++;
109 }
110
111 /* Puts a nlmsghdr at the beginning of 'msg', which must be initially empty.
112  * Uses the given 'type' and 'flags'.  'expected_payload' should be
113  * an estimate of the number of payload bytes to be supplied; if the size of
114  * the payload is unknown a value of 0 is acceptable.
115  *
116  * 'type' is ordinarily an enumerated value specific to the Netlink protocol
117  * (e.g. RTM_NEWLINK, for NETLINK_ROUTE protocol).  For Generic Netlink, 'type'
118  * is the family number obtained via nl_lookup_genl_family().
119  *
120  * 'flags' is a bit-mask that indicates what kind of request is being made.  It
121  * is often NLM_F_REQUEST indicating that a request is being made, commonly
122  * or'd with NLM_F_ACK to request an acknowledgement.
123  *
124  * Sets the new nlmsghdr's nlmsg_pid field to 0 for now.  nl_sock_send() will
125  * fill it in just before sending the message.
126  *
127  * nl_msg_put_genlmsghdr() is more convenient for composing a Generic Netlink
128  * message. */
129 void
130 nl_msg_put_nlmsghdr(struct ofpbuf *msg,
131                     size_t expected_payload, uint32_t type, uint32_t flags)
132 {
133     struct nlmsghdr *nlmsghdr;
134
135     assert(msg->size == 0);
136
137     nl_msg_reserve(msg, NLMSG_HDRLEN + expected_payload);
138     nlmsghdr = nl_msg_put_uninit(msg, NLMSG_HDRLEN);
139     nlmsghdr->nlmsg_len = 0;
140     nlmsghdr->nlmsg_type = type;
141     nlmsghdr->nlmsg_flags = flags;
142     nlmsghdr->nlmsg_seq = get_nlmsg_seq();
143     nlmsghdr->nlmsg_pid = 0;
144 }
145
146 /* Puts a nlmsghdr and genlmsghdr at the beginning of 'msg', which must be
147  * initially empty.  'expected_payload' should be an estimate of the number of
148  * payload bytes to be supplied; if the size of the payload is unknown a value
149  * of 0 is acceptable.
150  *
151  * 'family' is the family number obtained via nl_lookup_genl_family().
152  *
153  * 'flags' is a bit-mask that indicates what kind of request is being made.  It
154  * is often NLM_F_REQUEST indicating that a request is being made, commonly
155  * or'd with NLM_F_ACK to request an acknowledgement.
156  *
157  * 'cmd' is an enumerated value specific to the Generic Netlink family
158  * (e.g. CTRL_CMD_NEWFAMILY for the GENL_ID_CTRL family).
159  *
160  * 'version' is a version number specific to the family and command (often 1).
161  *
162  * Sets the new nlmsghdr's nlmsg_pid field to 0 for now.  nl_sock_send() will
163  * fill it in just before sending the message.
164  *
165  * nl_msg_put_nlmsghdr() should be used to compose Netlink messages that are
166  * not Generic Netlink messages. */
167 void
168 nl_msg_put_genlmsghdr(struct ofpbuf *msg, size_t expected_payload,
169                       int family, uint32_t flags, uint8_t cmd, uint8_t version)
170 {
171     struct genlmsghdr *genlmsghdr;
172
173     nl_msg_put_nlmsghdr(msg, GENL_HDRLEN + expected_payload, family, flags);
174     assert(msg->size == NLMSG_HDRLEN);
175     genlmsghdr = nl_msg_put_uninit(msg, GENL_HDRLEN);
176     genlmsghdr->cmd = cmd;
177     genlmsghdr->version = version;
178     genlmsghdr->reserved = 0;
179 }
180
181 /* Appends the 'size' bytes of data in 'p', plus Netlink padding if needed, to
182  * the tail end of 'msg'.  Data in 'msg' is reallocated and copied if
183  * necessary. */
184 void
185 nl_msg_put(struct ofpbuf *msg, const void *data, size_t size)
186 {
187     memcpy(nl_msg_put_uninit(msg, size), data, size);
188 }
189
190 /* Appends 'size' bytes of data, plus Netlink padding if needed, to the tail
191  * end of 'msg', reallocating and copying its data if necessary.  Returns a
192  * pointer to the first byte of the new data, which is left uninitialized. */
193 void *
194 nl_msg_put_uninit(struct ofpbuf *msg, size_t size)
195 {
196     size_t pad = NLMSG_ALIGN(size) - size;
197     char *p = ofpbuf_put_uninit(msg, size + pad);
198     if (pad) {
199         memset(p + size, 0, pad);
200     }
201     return p;
202 }
203
204 /* Prepends the 'size' bytes of data in 'p', plus Netlink padding if needed, to
205  * the head end of 'msg'.  Data in 'msg' is reallocated and copied if
206  * necessary. */
207 void
208 nl_msg_push(struct ofpbuf *msg, const void *data, size_t size)
209 {
210     memcpy(nl_msg_push_uninit(msg, size), data, size);
211 }
212
213 /* Prepends 'size' bytes of data, plus Netlink padding if needed, to the head
214  * end of 'msg', reallocating and copying its data if necessary.  Returns a
215  * pointer to the first byte of the new data, which is left uninitialized. */
216 void *
217 nl_msg_push_uninit(struct ofpbuf *msg, size_t size)
218 {
219     size_t pad = NLMSG_ALIGN(size) - size;
220     char *p = ofpbuf_push_uninit(msg, size + pad);
221     if (pad) {
222         memset(p + size, 0, pad);
223     }
224     return p;
225 }
226
227 /* Appends a Netlink attribute of the given 'type' and room for 'size' bytes of
228  * data as its payload, plus Netlink padding if needed, to the tail end of
229  * 'msg', reallocating and copying its data if necessary.  Returns a pointer to
230  * the first byte of data in the attribute, which is left uninitialized. */
231 void *
232 nl_msg_put_unspec_uninit(struct ofpbuf *msg, uint16_t type, size_t size)
233 {
234     size_t total_size = NLA_HDRLEN + size;
235     struct nlattr* nla = nl_msg_put_uninit(msg, total_size);
236     assert(NLA_ALIGN(total_size) <= UINT16_MAX);
237     nla->nla_len = total_size;
238     nla->nla_type = type;
239     return nla + 1;
240 }
241
242 /* Appends a Netlink attribute of the given 'type' and the 'size' bytes of
243  * 'data' as its payload, to the tail end of 'msg', reallocating and copying
244  * its data if necessary.  Returns a pointer to the first byte of data in the
245  * attribute, which is left uninitialized. */
246 void
247 nl_msg_put_unspec(struct ofpbuf *msg, uint16_t type,
248                   const void *data, size_t size)
249 {
250     memcpy(nl_msg_put_unspec_uninit(msg, type, size), data, size);
251 }
252
253 /* Appends a Netlink attribute of the given 'type' and no payload to 'msg'.
254  * (Some Netlink protocols use the presence or absence of an attribute as a
255  * Boolean flag.) */
256 void
257 nl_msg_put_flag(struct ofpbuf *msg, uint16_t type)
258 {
259     nl_msg_put_unspec(msg, type, NULL, 0);
260 }
261
262 /* Appends a Netlink attribute of the given 'type' and the given 8-bit 'value'
263  * to 'msg'. */
264 void
265 nl_msg_put_u8(struct ofpbuf *msg, uint16_t type, uint8_t value)
266 {
267     nl_msg_put_unspec(msg, type, &value, sizeof value);
268 }
269
270 /* Appends a Netlink attribute of the given 'type' and the given 16-bit host
271  * byte order 'value' to 'msg'. */
272 void
273 nl_msg_put_u16(struct ofpbuf *msg, uint16_t type, uint16_t value)
274 {
275     nl_msg_put_unspec(msg, type, &value, sizeof value);
276 }
277
278 /* Appends a Netlink attribute of the given 'type' and the given 32-bit host
279  * byte order 'value' to 'msg'. */
280 void
281 nl_msg_put_u32(struct ofpbuf *msg, uint16_t type, uint32_t value)
282 {
283     nl_msg_put_unspec(msg, type, &value, sizeof value);
284 }
285
286 /* Appends a Netlink attribute of the given 'type' and the given 64-bit host
287  * byte order 'value' to 'msg'. */
288 void
289 nl_msg_put_u64(struct ofpbuf *msg, uint16_t type, uint64_t value)
290 {
291     nl_msg_put_unspec(msg, type, &value, sizeof value);
292 }
293
294 /* Appends a Netlink attribute of the given 'type' and the given 16-bit network
295  * byte order 'value' to 'msg'. */
296 void
297 nl_msg_put_be16(struct ofpbuf *msg, uint16_t type, ovs_be16 value)
298 {
299     nl_msg_put_unspec(msg, type, &value, sizeof value);
300 }
301
302 /* Appends a Netlink attribute of the given 'type' and the given 32-bit network
303  * byte order 'value' to 'msg'. */
304 void
305 nl_msg_put_be32(struct ofpbuf *msg, uint16_t type, ovs_be32 value)
306 {
307     nl_msg_put_unspec(msg, type, &value, sizeof value);
308 }
309
310 /* Appends a Netlink attribute of the given 'type' and the given 64-bit network
311  * byte order 'value' to 'msg'. */
312 void
313 nl_msg_put_be64(struct ofpbuf *msg, uint16_t type, ovs_be64 value)
314 {
315     nl_msg_put_unspec(msg, type, &value, sizeof value);
316 }
317
318 /* Appends a Netlink attribute of the given 'type' and the given
319  * null-terminated string 'value' to 'msg'. */
320 void
321 nl_msg_put_string(struct ofpbuf *msg, uint16_t type, const char *value)
322 {
323     nl_msg_put_unspec(msg, type, value, strlen(value) + 1);
324 }
325
326 /* Prepends a Netlink attribute of the given 'type' and room for 'size' bytes
327  * of data as its payload, plus Netlink padding if needed, to the head end of
328  * 'msg', reallocating and copying its data if necessary.  Returns a pointer to
329  * the first byte of data in the attribute, which is left uninitialized. */
330 void *
331 nl_msg_push_unspec_uninit(struct ofpbuf *msg, uint16_t type, size_t size)
332 {
333     size_t total_size = NLA_HDRLEN + size;
334     struct nlattr* nla = nl_msg_push_uninit(msg, total_size);
335     assert(NLA_ALIGN(total_size) <= UINT16_MAX);
336     nla->nla_len = total_size;
337     nla->nla_type = type;
338     return nla + 1;
339 }
340
341 /* Prepends a Netlink attribute of the given 'type' and the 'size' bytes of
342  * 'data' as its payload, to the head end of 'msg', reallocating and copying
343  * its data if necessary.  Returns a pointer to the first byte of data in the
344  * attribute, which is left uninitialized. */
345 void
346 nl_msg_push_unspec(struct ofpbuf *msg, uint16_t type,
347                   const void *data, size_t size)
348 {
349     memcpy(nl_msg_push_unspec_uninit(msg, type, size), data, size);
350 }
351
352 /* Prepends a Netlink attribute of the given 'type' and no payload to 'msg'.
353  * (Some Netlink protocols use the presence or absence of an attribute as a
354  * Boolean flag.) */
355 void
356 nl_msg_push_flag(struct ofpbuf *msg, uint16_t type)
357 {
358     nl_msg_push_unspec(msg, type, NULL, 0);
359 }
360
361 /* Prepends a Netlink attribute of the given 'type' and the given 8-bit 'value'
362  * to 'msg'. */
363 void
364 nl_msg_push_u8(struct ofpbuf *msg, uint16_t type, uint8_t value)
365 {
366     nl_msg_push_unspec(msg, type, &value, sizeof value);
367 }
368
369 /* Prepends a Netlink attribute of the given 'type' and the given 16-bit host
370  * byte order 'value' to 'msg'. */
371 void
372 nl_msg_push_u16(struct ofpbuf *msg, uint16_t type, uint16_t value)
373 {
374     nl_msg_push_unspec(msg, type, &value, sizeof value);
375 }
376
377 /* Prepends a Netlink attribute of the given 'type' and the given 32-bit host
378  * byte order 'value' to 'msg'. */
379 void
380 nl_msg_push_u32(struct ofpbuf *msg, uint16_t type, uint32_t value)
381 {
382     nl_msg_push_unspec(msg, type, &value, sizeof value);
383 }
384
385 /* Prepends a Netlink attribute of the given 'type' and the given 64-bit host
386  * byte order 'value' to 'msg'. */
387 void
388 nl_msg_push_u64(struct ofpbuf *msg, uint16_t type, uint64_t value)
389 {
390     nl_msg_push_unspec(msg, type, &value, sizeof value);
391 }
392
393 /* Prepends a Netlink attribute of the given 'type' and the given 16-bit
394  * network byte order 'value' to 'msg'. */
395 void
396 nl_msg_push_be16(struct ofpbuf *msg, uint16_t type, ovs_be16 value)
397 {
398     nl_msg_push_unspec(msg, type, &value, sizeof value);
399 }
400
401 /* Prepends a Netlink attribute of the given 'type' and the given 32-bit
402  * network byte order 'value' to 'msg'. */
403 void
404 nl_msg_push_be32(struct ofpbuf *msg, uint16_t type, ovs_be32 value)
405 {
406     nl_msg_push_unspec(msg, type, &value, sizeof value);
407 }
408
409 /* Prepends a Netlink attribute of the given 'type' and the given 64-bit
410  * network byte order 'value' to 'msg'. */
411 void
412 nl_msg_push_be64(struct ofpbuf *msg, uint16_t type, ovs_be64 value)
413 {
414     nl_msg_push_unspec(msg, type, &value, sizeof value);
415 }
416
417 /* Prepends a Netlink attribute of the given 'type' and the given
418  * null-terminated string 'value' to 'msg'. */
419 void
420 nl_msg_push_string(struct ofpbuf *msg, uint16_t type, const char *value)
421 {
422     nl_msg_push_unspec(msg, type, value, strlen(value) + 1);
423 }
424
425 /* Adds the header for nested Netlink attributes to 'msg', with the specified
426  * 'type', and returns the header's offset within 'msg'.  The caller should add
427  * the content for the nested Netlink attribute to 'msg' (e.g. using the other
428  * nl_msg_*() functions), and then pass the returned offset to
429  * nl_msg_end_nested() to finish up the nested attributes. */
430 size_t
431 nl_msg_start_nested(struct ofpbuf *msg, uint16_t type)
432 {
433     size_t offset = msg->size;
434     nl_msg_put_unspec(msg, type, NULL, 0);
435     return offset;
436 }
437
438 /* Finalizes a nested Netlink attribute in 'msg'.  'offset' should be the value
439  * returned by nl_msg_start_nested(). */
440 void
441 nl_msg_end_nested(struct ofpbuf *msg, size_t offset)
442 {
443     struct nlattr *attr = ofpbuf_at_assert(msg, offset, sizeof *attr);
444     attr->nla_len = msg->size - offset;
445 }
446
447 /* Appends a nested Netlink attribute of the given 'type', with the 'size'
448  * bytes of content starting at 'data', to 'msg'. */
449 void
450 nl_msg_put_nested(struct ofpbuf *msg,
451                   uint16_t type, const void *data, size_t size)
452 {
453     size_t offset = nl_msg_start_nested(msg, type);
454     nl_msg_put(msg, data, size);
455     nl_msg_end_nested(msg, offset);
456 }
457
458 /* If 'buffer' begins with a valid "struct nlmsghdr", pulls the header and its
459  * payload off 'buffer', stores header and payload in 'msg->data' and
460  * 'msg->size', and returns a pointer to the header.
461  *
462  * If 'buffer' does not begin with a "struct nlmsghdr" or begins with one that
463  * is invalid, returns NULL without modifying 'buffer'. */
464 struct nlmsghdr *
465 nl_msg_next(struct ofpbuf *buffer, struct ofpbuf *msg)
466 {
467     if (buffer->size >= sizeof(struct nlmsghdr)) {
468         struct nlmsghdr *nlmsghdr = nl_msg_nlmsghdr(buffer);
469         size_t len = nlmsghdr->nlmsg_len;
470         if (len >= sizeof *nlmsghdr && len <= buffer->size) {
471             ofpbuf_use_const(msg, nlmsghdr, len);
472             ofpbuf_pull(buffer, len);
473             return nlmsghdr;
474         }
475     }
476
477     msg->data = NULL;
478     msg->size = 0;
479     return NULL;
480 }
481 \f
482 /* Attributes. */
483
484 /* Returns the bits of 'nla->nla_type' that are significant for determining its
485  * type. */
486 int
487 nl_attr_type(const struct nlattr *nla)
488 {
489     return nla->nla_type & NLA_TYPE_MASK;
490 }
491
492 /* Returns the first byte in the payload of attribute 'nla'. */
493 const void *
494 nl_attr_get(const struct nlattr *nla)
495 {
496     assert(nla->nla_len >= NLA_HDRLEN);
497     return nla + 1;
498 }
499
500 /* Returns the number of bytes in the payload of attribute 'nla'. */
501 size_t
502 nl_attr_get_size(const struct nlattr *nla)
503 {
504     assert(nla->nla_len >= NLA_HDRLEN);
505     return nla->nla_len - NLA_HDRLEN;
506 }
507
508 /* Asserts that 'nla''s payload is at least 'size' bytes long, and returns the
509  * first byte of the payload. */
510 const void *
511 nl_attr_get_unspec(const struct nlattr *nla, size_t size)
512 {
513     assert(nla->nla_len >= NLA_HDRLEN + size);
514     return nla + 1;
515 }
516
517 /* Returns true if 'nla' is nonnull.  (Some Netlink protocols use the presence
518  * or absence of an attribute as a Boolean flag.) */
519 bool
520 nl_attr_get_flag(const struct nlattr *nla)
521 {
522     return nla != NULL;
523 }
524
525 #define NL_ATTR_GET_AS(NLA, TYPE) \
526         (*(TYPE*) nl_attr_get_unspec(nla, sizeof(TYPE)))
527
528 /* Returns the 8-bit value in 'nla''s payload.
529  *
530  * Asserts that 'nla''s payload is at least 1 byte long. */
531 uint8_t
532 nl_attr_get_u8(const struct nlattr *nla)
533 {
534     return NL_ATTR_GET_AS(nla, uint8_t);
535 }
536
537 /* Returns the 16-bit host byte order value in 'nla''s payload.
538  *
539  * Asserts that 'nla''s payload is at least 2 bytes long. */
540 uint16_t
541 nl_attr_get_u16(const struct nlattr *nla)
542 {
543     return NL_ATTR_GET_AS(nla, uint16_t);
544 }
545
546 /* Returns the 32-bit host byte order value in 'nla''s payload.
547  *
548  * Asserts that 'nla''s payload is at least 4 bytes long. */
549 uint32_t
550 nl_attr_get_u32(const struct nlattr *nla)
551 {
552     return NL_ATTR_GET_AS(nla, uint32_t);
553 }
554
555 /* Returns the 64-bit host byte order value in 'nla''s payload.
556  *
557  * Asserts that 'nla''s payload is at least 8 bytes long. */
558 uint64_t
559 nl_attr_get_u64(const struct nlattr *nla)
560 {
561     const ovs_32aligned_u64 *x = nl_attr_get_unspec(nla, sizeof *x);
562     return get_32aligned_u64(x);
563 }
564
565 /* Returns the 16-bit network byte order value in 'nla''s payload.
566  *
567  * Asserts that 'nla''s payload is at least 2 bytes long. */
568 ovs_be16
569 nl_attr_get_be16(const struct nlattr *nla)
570 {
571     return NL_ATTR_GET_AS(nla, ovs_be16);
572 }
573
574 /* Returns the 32-bit network byte order value in 'nla''s payload.
575  *
576  * Asserts that 'nla''s payload is at least 4 bytes long. */
577 ovs_be32
578 nl_attr_get_be32(const struct nlattr *nla)
579 {
580     return NL_ATTR_GET_AS(nla, ovs_be32);
581 }
582
583 /* Returns the 64-bit network byte order value in 'nla''s payload.
584  *
585  * Asserts that 'nla''s payload is at least 8 bytes long. */
586 ovs_be64
587 nl_attr_get_be64(const struct nlattr *nla)
588 {
589     const ovs_32aligned_be64 *x = nl_attr_get_unspec(nla, sizeof *x);
590     return get_32aligned_be64(x);
591 }
592
593 /* Returns the null-terminated string value in 'nla''s payload.
594  *
595  * Asserts that 'nla''s payload contains a null-terminated string. */
596 const char *
597 nl_attr_get_string(const struct nlattr *nla)
598 {
599     assert(nla->nla_len > NLA_HDRLEN);
600     assert(memchr(nl_attr_get(nla), '\0', nla->nla_len - NLA_HDRLEN) != NULL);
601     return nl_attr_get(nla);
602 }
603
604 /* Initializes 'nested' to the payload of 'nla'. */
605 void
606 nl_attr_get_nested(const struct nlattr *nla, struct ofpbuf *nested)
607 {
608     ofpbuf_use_const(nested, nl_attr_get(nla), nl_attr_get_size(nla));
609 }
610
611 /* Default minimum and maximum payload sizes for each type of attribute. */
612 static const size_t attr_len_range[][2] = {
613     [0 ... N_NL_ATTR_TYPES - 1] = { 0, SIZE_MAX },
614     [NL_A_U8] = { 1, 1 },
615     [NL_A_U16] = { 2, 2 },
616     [NL_A_U32] = { 4, 4 },
617     [NL_A_U64] = { 8, 8 },
618     [NL_A_STRING] = { 1, SIZE_MAX },
619     [NL_A_FLAG] = { 0, SIZE_MAX },
620     [NL_A_NESTED] = { 0, SIZE_MAX },
621 };
622
623 /* Parses the 'msg' starting at the given 'nla_offset' as a sequence of Netlink
624  * attributes.  'policy[i]', for 0 <= i < n_attrs, specifies how the attribute
625  * with nla_type == i is parsed; a pointer to attribute i is stored in
626  * attrs[i].  Returns true if successful, false on failure.
627  *
628  * If the Netlink attributes in 'msg' follow a Netlink header and a Generic
629  * Netlink header, then 'nla_offset' should be NLMSG_HDRLEN + GENL_HDRLEN. */
630 bool
631 nl_policy_parse(const struct ofpbuf *msg, size_t nla_offset,
632                 const struct nl_policy policy[],
633                 struct nlattr *attrs[], size_t n_attrs)
634 {
635     void *p, *tail;
636     size_t n_required;
637     size_t i;
638
639     n_required = 0;
640     for (i = 0; i < n_attrs; i++) {
641         attrs[i] = NULL;
642
643         assert(policy[i].type < N_NL_ATTR_TYPES);
644         if (policy[i].type != NL_A_NO_ATTR
645             && policy[i].type != NL_A_FLAG
646             && !policy[i].optional) {
647             n_required++;
648         }
649     }
650
651     p = ofpbuf_at(msg, nla_offset, 0);
652     if (p == NULL) {
653         VLOG_DBG_RL(&rl, "missing headers in nl_policy_parse");
654         return false;
655     }
656     tail = ofpbuf_tail(msg);
657
658     while (p < tail) {
659         size_t offset = (char*)p - (char*)msg->data;
660         struct nlattr *nla = p;
661         size_t len, aligned_len;
662         uint16_t type;
663
664         /* Make sure its claimed length is plausible. */
665         if (nla->nla_len < NLA_HDRLEN) {
666             VLOG_DBG_RL(&rl, "%zu: attr shorter than NLA_HDRLEN (%"PRIu16")",
667                         offset, nla->nla_len);
668             return false;
669         }
670         len = nla->nla_len - NLA_HDRLEN;
671         aligned_len = NLA_ALIGN(len);
672         if (aligned_len > (char*)tail - (char*)p) {
673             VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" aligned data len (%zu) "
674                         "> bytes left (%tu)",
675                         offset, nl_attr_type(nla), aligned_len,
676                         (char*)tail - (char*)p);
677             return false;
678         }
679
680         type = nl_attr_type(nla);
681         if (type < n_attrs && policy[type].type != NL_A_NO_ATTR) {
682             const struct nl_policy *e = &policy[type];
683             size_t min_len, max_len;
684
685             /* Validate length and content. */
686             min_len = e->min_len ? e->min_len : attr_len_range[e->type][0];
687             max_len = e->max_len ? e->max_len : attr_len_range[e->type][1];
688             if (len < min_len || len > max_len) {
689                 VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" length %zu not in "
690                             "allowed range %zu...%zu",
691                             offset, type, len, min_len, max_len);
692                 return false;
693             }
694             if (e->type == NL_A_STRING) {
695                 if (((char *) nla)[nla->nla_len - 1]) {
696                     VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" lacks null at end",
697                                 offset, type);
698                     return false;
699                 }
700                 if (memchr(nla + 1, '\0', len - 1) != NULL) {
701                     VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" has bad length",
702                                 offset, type);
703                     return false;
704                 }
705             }
706             if (!e->optional && attrs[type] == NULL) {
707                 assert(n_required > 0);
708                 --n_required;
709             }
710             if (attrs[type]) {
711                 VLOG_DBG_RL(&rl, "%zu: duplicate attr %"PRIu16, offset, type);
712             }
713             attrs[type] = nla;
714         } else {
715             /* Skip attribute type that we don't care about. */
716         }
717         p = (char*)p + NLA_ALIGN(nla->nla_len);
718     }
719     if (n_required) {
720         VLOG_DBG_RL(&rl, "%zu required attrs missing", n_required);
721         return false;
722     }
723     return true;
724 }
725
726 /* Parses the Netlink attributes within 'nla'.  'policy[i]', for 0 <= i <
727  * n_attrs, specifies how the attribute with nla_type == i is parsed; a pointer
728  * to attribute i is stored in attrs[i].  Returns true if successful, false on
729  * failure. */
730 bool
731 nl_parse_nested(const struct nlattr *nla, const struct nl_policy policy[],
732                 struct nlattr *attrs[], size_t n_attrs)
733 {
734     struct ofpbuf buf;
735
736     nl_attr_get_nested(nla, &buf);
737     return nl_policy_parse(&buf, 0, policy, attrs, n_attrs);
738 }
739
740 const struct nlattr *
741 nl_attr_find__(const struct nlattr *attrs, size_t size, uint16_t type)
742 {
743     const struct nlattr *nla;
744     size_t left;
745
746     NL_ATTR_FOR_EACH (nla, left, attrs, size) {
747         if (nl_attr_type (nla) == type) {
748             return nla;
749         }
750     }
751     return NULL;
752 }
753
754 /* Returns the first Netlink attribute within 'buf' with the specified 'type',
755  * skipping a header of 'hdr_len' bytes at the beginning of 'buf'.
756  *
757  * This function does not validate the attribute's length. */
758 const struct nlattr *
759 nl_attr_find(const struct ofpbuf *buf, size_t hdr_len, uint16_t type)
760 {
761     const uint8_t *start = (const uint8_t *) buf->data + hdr_len;
762     return nl_attr_find__((const struct nlattr *) start, buf->size - hdr_len,
763                           type);
764 }
765
766 /* Returns the first Netlink attribute within 'nla' with the specified
767  * 'type'.
768  *
769  * This function does not validate the attribute's length. */
770 const struct nlattr *
771 nl_attr_find_nested(const struct nlattr *nla, uint16_t type)
772 {
773     return nl_attr_find__(nl_attr_get(nla), nl_attr_get_size(nla), type);
774 }