Changes based on feedback from GigaFin.
[openvswitch] / lib / netlink.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  * 
4  * We are making the OpenFlow specification and associated documentation
5  * (Software) available for public use and benefit with the expectation
6  * that others will use, modify and enhance the Software and contribute
7  * those enhancements back to the community. However, since we would
8  * like to make the Software available for broadest use, with as few
9  * restrictions as possible permission is hereby granted, free of
10  * charge, to any person obtaining a copy of this Software to deal in
11  * the Software under the copyrights without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE.
28  * 
29  * The name and trademarks of copyright holder(s) may NOT be used in
30  * advertising or publicity pertaining to the Software or any
31  * derivatives without specific, written prior permission.
32  */
33
34 #include "netlink.h"
35 #include <assert.h>
36 #include <errno.h>
37 #include <inttypes.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <time.h>
42 #include <unistd.h>
43 #include "buffer.h"
44 #include "util.h"
45
46 #include "vlog.h"
47 #define THIS_MODULE VLM_netlink
48
49 /* Linux header file confusion causes this to be undefined. */
50 #ifndef SOL_NETLINK
51 #define SOL_NETLINK 270
52 #endif
53 \f
54 /* Netlink sockets. */
55
56 struct nl_sock
57 {
58     int fd;
59     uint32_t pid;
60 };
61
62 /* Next nlmsghdr sequence number.
63  * 
64  * This implementation uses sequence numbers that are unique process-wide, to
65  * avoid a hypothetical race: send request, close socket, open new socket that
66  * reuses the old socket's PID value, send request on new socket, receive reply
67  * from kernel to old socket but with same PID and sequence number.  (This race
68  * could be avoided other ways, e.g. by preventing PIDs from being quickly
69  * reused). */
70 static uint32_t next_seq;
71
72 static int alloc_pid(uint32_t *);
73 static void free_pid(uint32_t);
74
75 /* Creates a new netlink socket for the given netlink 'protocol'
76  * (NETLINK_ROUTE, NETLINK_GENERIC, ...).  Returns 0 and sets '*sockp' to the
77  * new socket if successful, otherwise returns a positive errno value.
78  *
79  * If 'multicast_group' is nonzero, the new socket subscribes to the specified
80  * netlink multicast group.  (A netlink socket may listen to an arbitrary
81  * number of multicast groups, but so far we only need one at a time.)
82  *
83  * Nonzero 'so_sndbuf' or 'so_rcvbuf' override the kernel default send or
84  * receive buffer size, respectively.
85  */
86 int
87 nl_sock_create(int protocol, int multicast_group,
88                size_t so_sndbuf, size_t so_rcvbuf, struct nl_sock **sockp)
89 {
90     struct nl_sock *sock;
91     struct sockaddr_nl local, remote;
92     int retval = 0;
93
94     if (next_seq == 0) {
95         /* Pick initial sequence number. */
96         next_seq = getpid() ^ time(0);
97     }
98
99     *sockp = NULL;
100     sock = malloc(sizeof *sock);
101     if (sock == NULL) {
102         return ENOMEM;
103     }
104
105     sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
106     if (sock->fd < 0) {
107         VLOG_ERR("fcntl: %s", strerror(errno));
108         goto error;
109     }
110
111     retval = alloc_pid(&sock->pid);
112     if (retval) {
113         goto error;
114     }
115
116     if (so_sndbuf != 0
117         && setsockopt(sock->fd, SOL_SOCKET, SO_SNDBUF,
118                       &so_sndbuf, sizeof so_sndbuf) < 0) {
119         VLOG_ERR("setsockopt(SO_SNDBUF,%zu): %s", so_sndbuf, strerror(errno));
120         goto error_free_pid;
121     }
122
123     if (so_rcvbuf != 0
124         && setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUF,
125                       &so_rcvbuf, sizeof so_rcvbuf) < 0) {
126         VLOG_ERR("setsockopt(SO_RCVBUF,%zu): %s", so_rcvbuf, strerror(errno));
127         goto error_free_pid;
128     }
129
130     /* Bind local address as our selected pid. */
131     memset(&local, 0, sizeof local);
132     local.nl_family = AF_NETLINK;
133     local.nl_pid = sock->pid;
134     if (multicast_group > 0 && multicast_group <= 32) {
135         /* This method of joining multicast groups is supported by old kernels,
136          * but it only allows 32 multicast groups per protocol. */
137         local.nl_groups |= 1ul << (multicast_group - 1);
138     }
139     if (bind(sock->fd, (struct sockaddr *) &local, sizeof local) < 0) {
140         VLOG_ERR("bind(%"PRIu32"): %s", sock->pid, strerror(errno));
141         goto error_free_pid;
142     }
143
144     /* Bind remote address as the kernel (pid 0). */
145     memset(&remote, 0, sizeof remote);
146     remote.nl_family = AF_NETLINK;
147     remote.nl_pid = 0;
148     if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
149         VLOG_ERR("connect(0): %s", strerror(errno));
150         goto error_free_pid;
151     }
152
153 #ifdef NETLINK_ADD_MEMBERSHIP
154     /* This method of joining multicast groups is only supported by newish
155      * kernels, but it allows for an arbitrary number of multicast groups. */
156     if (multicast_group > 32
157         && setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
158                       &multicast_group, sizeof multicast_group) < 0) {
159         VLOG_ERR("setsockopt(NETLINK_ADD_MEMBERSHIP,%d): %s",
160                  multicast_group, strerror(errno));
161         goto error_free_pid;
162     }
163 #endif
164
165     *sockp = sock;
166     return 0;
167
168 error_free_pid:
169     free_pid(sock->pid);
170 error:
171     if (retval == 0) {
172         retval = errno;
173         if (retval == 0) {
174             retval = EINVAL;
175         }
176     }
177     if (sock->fd >= 0) {
178         close(sock->fd);
179     }
180     free(sock);
181     return retval;
182 }
183
184 /* Destroys netlink socket 'sock'. */
185 void
186 nl_sock_destroy(struct nl_sock *sock) 
187 {
188     if (sock) {
189         close(sock->fd);
190         free_pid(sock->pid);
191         free(sock);
192     }
193 }
194
195 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
196  * 'sock'.  nlmsg_len in 'msg' will be finalized to match msg->size before the
197  * message is sent.
198  *
199  * Returns 0 if successful, otherwise a positive errno value.  If
200  * 'wait' is true, then the send will wait until buffer space is ready;
201  * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
202 int
203 nl_sock_send(struct nl_sock *sock, const struct buffer *msg, bool wait) 
204 {
205     int retval;
206
207     nl_msg_nlmsghdr(msg)->nlmsg_len = msg->size;
208     do {
209         retval = send(sock->fd, msg->data, msg->size, wait ? 0 : MSG_DONTWAIT);
210     } while (retval < 0 && errno == EINTR);
211     return retval < 0 ? errno : 0;
212 }
213
214 /* Tries to send the 'n_iov' chunks of data in 'iov' to the kernel on 'sock' as
215  * a single Netlink message.  (The message must be fully formed and not require
216  * finalization of its nlmsg_len field.)
217  *
218  * Returns 0 if successful, otherwise a positive errno value.  If 'wait' is
219  * true, then the send will wait until buffer space is ready; otherwise,
220  * returns EAGAIN if the 'sock' send buffer is full. */
221 int
222 nl_sock_sendv(struct nl_sock *sock, const struct iovec iov[], size_t n_iov,
223               bool wait) 
224 {
225     struct msghdr msg;
226     int retval;
227
228     memset(&msg, 0, sizeof msg);
229     msg.msg_iov = (struct iovec *) iov;
230     msg.msg_iovlen = n_iov;
231     do {
232         retval = sendmsg(sock->fd, &msg, MSG_DONTWAIT);
233     } while (retval < 0 && errno == EINTR);
234     return retval < 0 ? errno : 0;
235 }
236
237 /* Tries to receive a netlink message from the kernel on 'sock'.  If
238  * successful, stores the received message into '*bufp' and returns 0.  The
239  * caller is responsible for destroying the message with buffer_delete().  On
240  * failure, returns a positive errno value and stores a null pointer into
241  * '*bufp'.
242  *
243  * If 'wait' is true, nl_sock_recv waits for a message to be ready; otherwise,
244  * returns EAGAIN if the 'sock' receive buffer is empty. */
245 int
246 nl_sock_recv(struct nl_sock *sock, struct buffer **bufp, bool wait) 
247 {
248     uint8_t tmp;
249     ssize_t bufsize = 2048;
250     ssize_t nbytes, nbytes2;
251     struct buffer *buf;
252     struct nlmsghdr *nlmsghdr;
253     struct iovec iov;
254     struct msghdr msg = {
255         .msg_name = NULL,
256         .msg_namelen = 0,
257         .msg_iov = &iov,
258         .msg_iovlen = 1,
259         .msg_control = NULL,
260         .msg_controllen = 0,
261         .msg_flags = 0
262     };
263
264     buf = buffer_new(bufsize);
265     *bufp = NULL;
266
267 try_again:
268     /* Attempt to read the message.  We don't know the size of the data
269      * yet, so we take a guess at 2048.  If we're wrong, we keep trying
270      * and doubling the buffer size each time. 
271      */
272     nlmsghdr = buffer_put_uninit(buf, bufsize);
273     iov.iov_base = nlmsghdr;
274     iov.iov_len = bufsize;
275     do {
276         nbytes = recvmsg(sock->fd, &msg, (wait ? 0 : MSG_DONTWAIT) | MSG_PEEK); 
277     } while (nbytes < 0 && errno == EINTR);
278     if (nbytes < 0) {
279         buffer_delete(buf);
280         return errno;
281     }
282     if (msg.msg_flags & MSG_TRUNC) {
283         bufsize *= 2;
284         buffer_reinit(buf, bufsize);
285         goto try_again;
286     }
287     buf->size = nbytes;
288
289     /* We successfully read the message, so recv again to clear the queue */
290     iov.iov_base = &tmp;
291     iov.iov_len = 1;
292     do {
293         nbytes2 = recvmsg(sock->fd, &msg, MSG_DONTWAIT);
294         if (nbytes2 < 0) {
295             VLOG_ERR("failed to remove nlmsg from socket: %d\n", errno);
296         }
297     } while (nbytes2 < 0 && errno == EINTR);
298
299     if (!NLMSG_OK(nlmsghdr, nbytes)) {
300         VLOG_ERR("received invalid nlmsg (%zd bytes < %d)",
301                  bufsize, NLMSG_HDRLEN);
302         buffer_delete(buf);
303         return EPROTO;
304     }
305     *bufp = buf;
306     return 0;
307 }
308
309 /* Sends 'request' to the kernel via 'sock' and waits for a response.  If
310  * successful, stores the reply into '*replyp' and returns 0.  The caller is
311  * responsible for destroying the reply with buffer_delete().  On failure,
312  * returns a positive errno value and stores a null pointer into '*replyp'.
313  *
314  * Bare Netlink is an unreliable transport protocol.  This function layers
315  * reliable delivery and reply semantics on top of bare Netlink.
316  * 
317  * In Netlink, sending a request to the kernel is reliable enough, because the
318  * kernel will tell us if the message cannot be queued (and we will in that
319  * case put it on the transmit queue and wait until it can be delivered).
320  * 
321  * Receiving the reply is the real problem: if the socket buffer is full when
322  * the kernel tries to send the reply, the reply will be dropped.  However, the
323  * kernel sets a flag that a reply has been dropped.  The next call to recv
324  * then returns ENOBUFS.  We can then re-send the request.
325  *
326  * Caveats:
327  *
328  *      1. Netlink depends on sequence numbers to match up requests and
329  *         replies.  The sender of a request supplies a sequence number, and
330  *         the reply echos back that sequence number.
331  *
332  *         This is fine, but (1) some kernel netlink implementations are
333  *         broken, in that they fail to echo sequence numbers and (2) this
334  *         function will drop packets with non-matching sequence numbers, so
335  *         that only a single request can be usefully transacted at a time.
336  *
337  *      2. Resending the request causes it to be re-executed, so the request
338  *         needs to be idempotent.
339  */
340 int
341 nl_sock_transact(struct nl_sock *sock,
342                  const struct buffer *request, struct buffer **replyp) 
343 {
344     uint32_t seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
345     struct nlmsghdr *nlmsghdr;
346     struct buffer *reply;
347     int retval;
348
349     *replyp = NULL;
350
351     /* Ensure that we get a reply even if this message doesn't ordinarily call
352      * for one. */
353     nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_ACK;
354     
355 send:
356     retval = nl_sock_send(sock, request, true);
357     if (retval) {
358         return retval;
359     }
360
361 recv:
362     retval = nl_sock_recv(sock, &reply, true);
363     if (retval) {
364         if (retval == ENOBUFS) {
365             VLOG_DBG("receive buffer overflow, resending request");
366             goto send;
367         } else {
368             return retval;
369         }
370     }
371     nlmsghdr = nl_msg_nlmsghdr(reply);
372     if (seq != nlmsghdr->nlmsg_seq) {
373         VLOG_DBG("ignoring seq %"PRIu32" != expected %"PRIu32,
374                  nl_msg_nlmsghdr(reply)->nlmsg_seq, seq);
375         buffer_delete(reply);
376         goto recv;
377     }
378     if (nl_msg_nlmsgerr(reply, &retval)) {
379         if (retval) {
380             VLOG_DBG("received NAK error=%d (%s)", retval, strerror(retval));
381         }
382         return retval != EAGAIN ? retval : EPROTO;
383     }
384
385     *replyp = reply;
386     return 0;
387 }
388
389 /* Returns 'sock''s underlying file descriptor. */
390 int
391 nl_sock_fd(const struct nl_sock *sock) 
392 {
393     return sock->fd;
394 }
395 \f
396 /* Netlink messages. */
397
398 /* Returns the nlmsghdr at the head of 'msg'.
399  *
400  * 'msg' must be at least as large as a nlmsghdr. */
401 struct nlmsghdr *
402 nl_msg_nlmsghdr(const struct buffer *msg) 
403 {
404     return buffer_at_assert(msg, 0, NLMSG_HDRLEN);
405 }
406
407 /* Returns the genlmsghdr just past 'msg''s nlmsghdr.
408  *
409  * Returns a null pointer if 'msg' is not large enough to contain an nlmsghdr
410  * and a genlmsghdr. */
411 struct genlmsghdr *
412 nl_msg_genlmsghdr(const struct buffer *msg) 
413 {
414     return buffer_at(msg, NLMSG_HDRLEN, GENL_HDRLEN);
415 }
416
417 /* If 'buffer' is a NLMSG_ERROR message, stores 0 in '*errorp' if it is an ACK
418  * message, otherwise a positive errno value, and returns true.  If 'buffer' is
419  * not an NLMSG_ERROR message, returns false.
420  *
421  * 'msg' must be at least as large as a nlmsghdr. */
422 bool
423 nl_msg_nlmsgerr(const struct buffer *msg, int *errorp) 
424 {
425     if (nl_msg_nlmsghdr(msg)->nlmsg_type == NLMSG_ERROR) {
426         struct nlmsgerr *err = buffer_at(msg, NLMSG_HDRLEN, sizeof *err);
427         int code = EPROTO;
428         if (!err) {
429             VLOG_ERR("received invalid nlmsgerr (%zd bytes < %zd)",
430                      msg->size, NLMSG_HDRLEN + sizeof *err);
431         } else if (err->error <= 0 && err->error > INT_MIN) {
432             code = -err->error;
433         }
434         if (errorp) {
435             *errorp = code;
436         }
437         return true;
438     } else {
439         return false;
440     }
441 }
442
443 /* Ensures that 'b' has room for at least 'size' bytes plus netlink pading at
444  * its tail end, reallocating and copying its data if necessary. */
445 void
446 nl_msg_reserve(struct buffer *msg, size_t size) 
447 {
448     buffer_reserve_tailroom(msg, NLMSG_ALIGN(size));
449 }
450
451 /* Puts a nlmsghdr at the beginning of 'msg', which must be initially empty.
452  * Uses the given 'type' and 'flags'.  'sock' is used to obtain a PID and
453  * sequence number for proper routing of replies.  'expected_payload' should be
454  * an estimate of the number of payload bytes to be supplied; if the size of
455  * the payload is unknown a value of 0 is acceptable.
456  *
457  * 'type' is ordinarily an enumerated value specific to the Netlink protocol
458  * (e.g. RTM_NEWLINK, for NETLINK_ROUTE protocol).  For Generic Netlink, 'type'
459  * is the family number obtained via nl_lookup_genl_family().
460  *
461  * 'flags' is a bit-mask that indicates what kind of request is being made.  It
462  * is often NLM_F_REQUEST indicating that a request is being made, commonly
463  * or'd with NLM_F_ACK to request an acknowledgement.
464  *
465  * nl_msg_put_genlmsghdr is more convenient for composing a Generic Netlink
466  * message. */
467 void
468 nl_msg_put_nlmsghdr(struct buffer *msg, struct nl_sock *sock,
469                     size_t expected_payload, uint32_t type, uint32_t flags) 
470 {
471     struct nlmsghdr *nlmsghdr;
472
473     assert(msg->size == 0);
474
475     nl_msg_reserve(msg, NLMSG_HDRLEN + expected_payload);
476     nlmsghdr = nl_msg_put_uninit(msg, NLMSG_HDRLEN);
477     nlmsghdr->nlmsg_len = 0;
478     nlmsghdr->nlmsg_type = type;
479     nlmsghdr->nlmsg_flags = flags;
480     nlmsghdr->nlmsg_seq = ++next_seq;
481     nlmsghdr->nlmsg_pid = sock->pid;
482 }
483
484 /* Puts a nlmsghdr and genlmsghdr at the beginning of 'msg', which must be
485  * initially empty.  'sock' is used to obtain a PID and sequence number for
486  * proper routing of replies.  'expected_payload' should be an estimate of the
487  * number of payload bytes to be supplied; if the size of the payload is
488  * unknown a value of 0 is acceptable.
489  *
490  * 'family' is the family number obtained via nl_lookup_genl_family().
491  *
492  * 'flags' is a bit-mask that indicates what kind of request is being made.  It
493  * is often NLM_F_REQUEST indicating that a request is being made, commonly
494  * or'd with NLM_F_ACK to request an acknowledgement.
495  *
496  * 'cmd' is an enumerated value specific to the Generic Netlink family
497  * (e.g. CTRL_CMD_NEWFAMILY for the GENL_ID_CTRL family).
498  *
499  * 'version' is a version number specific to the family and command (often 1).
500  *
501  * nl_msg_put_nlmsghdr should be used to compose Netlink messages that are not
502  * Generic Netlink messages. */
503 void
504 nl_msg_put_genlmsghdr(struct buffer *msg, struct nl_sock *sock,
505                       size_t expected_payload, int family, uint32_t flags,
506                       uint8_t cmd, uint8_t version)
507 {
508     struct genlmsghdr *genlmsghdr;
509
510     nl_msg_put_nlmsghdr(msg, sock, GENL_HDRLEN + expected_payload,
511                         family, flags);
512     assert(msg->size == NLMSG_HDRLEN);
513     genlmsghdr = nl_msg_put_uninit(msg, GENL_HDRLEN);
514     genlmsghdr->cmd = cmd;
515     genlmsghdr->version = version;
516     genlmsghdr->reserved = 0;
517 }
518
519 /* Appends the 'size' bytes of data in 'p', plus Netlink padding if needed, to
520  * the tail end of 'msg'.  Data in 'msg' is reallocated and copied if
521  * necessary. */
522 void
523 nl_msg_put(struct buffer *msg, const void *data, size_t size) 
524 {
525     memcpy(nl_msg_put_uninit(msg, size), data, size);
526 }
527
528 /* Appends 'size' bytes of data, plus Netlink padding if needed, to the tail
529  * end of 'msg', reallocating and copying its data if necessary.  Returns a
530  * pointer to the first byte of the new data, which is left uninitialized. */
531 void *
532 nl_msg_put_uninit(struct buffer *msg, size_t size) 
533 {
534     size_t pad = NLMSG_ALIGN(size) - size;
535     char *p = buffer_put_uninit(msg, size + pad);
536     if (pad) {
537         memset(p + size, 0, pad); 
538     }
539     return p;
540 }
541
542 /* Appends a Netlink attribute of the given 'type' and room for 'size' bytes of
543  * data as its payload, plus Netlink padding if needed, to the tail end of
544  * 'msg', reallocating and copying its data if necessary.  Returns a pointer to
545  * the first byte of data in the attribute, which is left uninitialized. */
546 void *
547 nl_msg_put_unspec_uninit(struct buffer *msg, uint16_t type, size_t size) 
548 {
549     size_t total_size = NLA_HDRLEN + size;
550     struct nlattr* nla = nl_msg_put_uninit(msg, total_size);
551     assert(NLA_ALIGN(total_size) <= UINT16_MAX);
552     nla->nla_len = total_size;
553     nla->nla_type = type;
554     return nla + 1;
555 }
556
557 /* Appends a Netlink attribute of the given 'type' and the 'size' bytes of
558  * 'data' as its payload, to the tail end of 'msg', reallocating and copying
559  * its data if necessary.  Returns a pointer to the first byte of data in the
560  * attribute, which is left uninitialized. */
561 void
562 nl_msg_put_unspec(struct buffer *msg, uint16_t type,
563                   const void *data, size_t size) 
564 {
565     memcpy(nl_msg_put_unspec_uninit(msg, type, size), data, size);
566 }
567
568 /* Appends a Netlink attribute of the given 'type' and no payload to 'msg'.
569  * (Some Netlink protocols use the presence or absence of an attribute as a
570  * Boolean flag.) */
571 void
572 nl_msg_put_flag(struct buffer *msg, uint16_t type) 
573 {
574     nl_msg_put_unspec(msg, type, NULL, 0);
575 }
576
577 /* Appends a Netlink attribute of the given 'type' and the given 8-bit 'value'
578  * to 'msg'. */
579 void
580 nl_msg_put_u8(struct buffer *msg, uint16_t type, uint8_t value) 
581 {
582     nl_msg_put_unspec(msg, type, &value, sizeof value);
583 }
584
585 /* Appends a Netlink attribute of the given 'type' and the given 16-bit 'value'
586  * to 'msg'. */
587 void
588 nl_msg_put_u16(struct buffer *msg, uint16_t type, uint16_t value)
589 {
590     nl_msg_put_unspec(msg, type, &value, sizeof value);
591 }
592
593 /* Appends a Netlink attribute of the given 'type' and the given 32-bit 'value'
594  * to 'msg'. */
595 void
596 nl_msg_put_u32(struct buffer *msg, uint16_t type, uint32_t value)
597 {
598     nl_msg_put_unspec(msg, type, &value, sizeof value);
599 }
600
601 /* Appends a Netlink attribute of the given 'type' and the given 64-bit 'value'
602  * to 'msg'. */
603 void
604 nl_msg_put_u64(struct buffer *msg, uint16_t type, uint64_t value)
605 {
606     nl_msg_put_unspec(msg, type, &value, sizeof value);
607 }
608
609 /* Appends a Netlink attribute of the given 'type' and the given
610  * null-terminated string 'value' to 'msg'. */
611 void
612 nl_msg_put_string(struct buffer *msg, uint16_t type, const char *value)
613 {
614     nl_msg_put_unspec(msg, type, value, strlen(value) + 1);
615 }
616
617 /* Appends a Netlink attribute of the given 'type' and the given buffered
618  * netlink message in 'nested_msg' to 'msg'.  The nlmsg_len field in
619  * 'nested_msg' is finalized to match 'nested_msg->size'. */
620 void
621 nl_msg_put_nested(struct buffer *msg,
622                   uint16_t type, struct buffer *nested_msg)
623 {
624     nl_msg_nlmsghdr(nested_msg)->nlmsg_len = nested_msg->size;
625     nl_msg_put_unspec(msg, type, nested_msg->data, nested_msg->size);
626 }
627
628 /* Returns the first byte in the payload of attribute 'nla'. */
629 const void *
630 nl_attr_get(const struct nlattr *nla) 
631 {
632     assert(nla->nla_len >= NLA_HDRLEN);
633     return nla + 1;
634 }
635
636 /* Returns the number of bytes in the payload of attribute 'nla'. */
637 size_t
638 nl_attr_get_size(const struct nlattr *nla) 
639 {
640     assert(nla->nla_len >= NLA_HDRLEN);
641     return nla->nla_len - NLA_HDRLEN;
642 }
643
644 /* Asserts that 'nla''s payload is at least 'size' bytes long, and returns the
645  * first byte of the payload. */
646 const void *
647 nl_attr_get_unspec(const struct nlattr *nla, size_t size) 
648 {
649     assert(nla->nla_len >= NLA_HDRLEN + size);
650     return nla + 1;
651 }
652
653 /* Returns true if 'nla' is nonnull.  (Some Netlink protocols use the presence
654  * or absence of an attribute as a Boolean flag.) */
655 bool
656 nl_attr_get_flag(const struct nlattr *nla) 
657 {
658     return nla != NULL;
659 }
660
661 #define NL_ATTR_GET_AS(NLA, TYPE) \
662         (*(TYPE*) nl_attr_get_unspec(nla, sizeof(TYPE)))
663
664 /* Returns the 8-bit value in 'nla''s payload.
665  *
666  * Asserts that 'nla''s payload is at least 1 byte long. */
667 uint8_t
668 nl_attr_get_u8(const struct nlattr *nla) 
669 {
670     return NL_ATTR_GET_AS(nla, uint8_t);
671 }
672
673 /* Returns the 16-bit value in 'nla''s payload.
674  *
675  * Asserts that 'nla''s payload is at least 2 bytes long. */
676 uint16_t
677 nl_attr_get_u16(const struct nlattr *nla) 
678 {
679     return NL_ATTR_GET_AS(nla, uint16_t);
680 }
681
682 /* Returns the 32-bit value in 'nla''s payload.
683  *
684  * Asserts that 'nla''s payload is at least 4 bytes long. */
685 uint32_t
686 nl_attr_get_u32(const struct nlattr *nla) 
687 {
688     return NL_ATTR_GET_AS(nla, uint32_t);
689 }
690
691 /* Returns the 64-bit value in 'nla''s payload.
692  *
693  * Asserts that 'nla''s payload is at least 8 bytes long. */
694 uint64_t
695 nl_attr_get_u64(const struct nlattr *nla) 
696 {
697     return NL_ATTR_GET_AS(nla, uint64_t);
698 }
699
700 /* Returns the null-terminated string value in 'nla''s payload.
701  *
702  * Asserts that 'nla''s payload contains a null-terminated string. */
703 const char *
704 nl_attr_get_string(const struct nlattr *nla) 
705 {
706     assert(nla->nla_len > NLA_HDRLEN);
707     assert(memchr(nl_attr_get(nla), '\0', nla->nla_len - NLA_HDRLEN) != NULL);
708     return nl_attr_get(nla);
709 }
710
711 /* Default minimum and maximum payload sizes for each type of attribute. */
712 static const size_t attr_len_range[][2] = {
713     [0 ... N_NL_ATTR_TYPES - 1] = { 0, SIZE_MAX },
714     [NL_A_U8] = { 1, 1 },
715     [NL_A_U16] = { 2, 2 },
716     [NL_A_U32] = { 4, 4 },
717     [NL_A_U64] = { 8, 8 },
718     [NL_A_STRING] = { 1, SIZE_MAX },
719     [NL_A_FLAG] = { 0, SIZE_MAX },
720     [NL_A_NESTED] = { NLMSG_HDRLEN, SIZE_MAX },
721 };
722
723 /* Parses the Generic Netlink payload of 'msg' as a sequence of Netlink
724  * attributes.  'policy[i]', for 0 <= i < n_attrs, specifies how the attribute
725  * with nla_type == i is parsed; a pointer to attribute i is stored in
726  * attrs[i].  Returns true if successful, false on failure. */
727 bool
728 nl_policy_parse(const struct buffer *msg, const struct nl_policy policy[],
729                 struct nlattr *attrs[], size_t n_attrs)
730 {
731     void *p, *tail;
732     size_t n_required;
733     size_t i;
734
735     n_required = 0;
736     for (i = 0; i < n_attrs; i++) {
737         attrs[i] = NULL;
738
739         assert(policy[i].type < N_NL_ATTR_TYPES);
740         if (policy[i].type != NL_A_NO_ATTR
741             && policy[i].type != NL_A_FLAG
742             && !policy[i].optional) {
743             n_required++;
744         }
745     }
746
747     p = buffer_at(msg, NLMSG_HDRLEN + GENL_HDRLEN, 0);
748     if (p == NULL) {
749         VLOG_DBG("missing headers in nl_policy_parse");
750         return false;
751     }
752     tail = buffer_tail(msg);
753
754     while (p < tail) {
755         size_t offset = p - msg->data;
756         struct nlattr *nla = p;
757         size_t len, aligned_len;
758         uint16_t type;
759
760         /* Make sure its claimed length is plausible. */
761         if (nla->nla_len < NLA_HDRLEN) {
762             VLOG_DBG("%zu: attr shorter than NLA_HDRLEN (%"PRIu16")",
763                      offset, nla->nla_len);
764             return false;
765         }
766         len = nla->nla_len - NLA_HDRLEN;
767         aligned_len = NLA_ALIGN(len);
768         if (aligned_len > tail - p) {
769             VLOG_DBG("%zu: attr %"PRIu16" aligned data len (%zu) "
770                      "> bytes left (%tu)",
771                      offset, nla->nla_type, aligned_len, tail - p);
772             return false;
773         }
774
775         type = nla->nla_type;
776         if (type < n_attrs && policy[type].type != NL_A_NO_ATTR) {
777             const struct nl_policy *p = &policy[type];
778             size_t min_len, max_len;
779
780             /* Validate length and content. */
781             min_len = p->min_len ? p->min_len : attr_len_range[p->type][0];
782             max_len = p->max_len ? p->max_len : attr_len_range[p->type][1];
783             if (len < min_len || len > max_len) {
784                 VLOG_DBG("%zu: attr %"PRIu16" length %zu not in allowed range "
785                          "%zu...%zu", offset, type, len, min_len, max_len);
786                 return false;
787             }
788             if (p->type == NL_A_STRING) {
789                 if (((char *) nla)[nla->nla_len - 1]) {
790                     VLOG_DBG("%zu: attr %"PRIu16" lacks null terminator",
791                              offset, type);
792                     return false;
793                 }
794                 if (memchr(nla + 1, '\0', len - 1) != NULL) {
795                     VLOG_DBG("%zu: attr %"PRIu16" lies about string length",
796                              offset, type);
797                     return false;
798                 }
799             }
800             if (!p->optional && attrs[type] == NULL) {
801                 assert(n_required > 0);
802                 --n_required;
803             }
804             attrs[type] = nla;
805         } else {
806             /* Skip attribute type that we don't care about. */
807         }
808         p += NLA_ALIGN(nla->nla_len);
809     }
810     if (n_required) {
811         VLOG_DBG("%zu required attrs missing", n_required);
812         return false;
813     }
814     return true;
815 }
816 \f
817 /* Miscellaneous.  */
818
819 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = { 
820     [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
821 };
822
823 static int do_lookup_genl_family(const char *name) 
824 {
825     struct nl_sock *sock;
826     struct buffer request, *reply;
827     struct nlattr *attrs[ARRAY_SIZE(family_policy)];
828     int retval;
829
830     retval = nl_sock_create(NETLINK_GENERIC, 0, 0, 0, &sock);
831     if (retval) {
832         return -retval;
833     }
834
835     buffer_init(&request, 0);
836     nl_msg_put_genlmsghdr(&request, sock, 0, GENL_ID_CTRL, NLM_F_REQUEST,
837                           CTRL_CMD_GETFAMILY, 1);
838     nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
839     retval = nl_sock_transact(sock, &request, &reply);
840     buffer_uninit(&request);
841     if (retval) {
842         nl_sock_destroy(sock);
843         return -retval;
844     }
845
846     if (!nl_policy_parse(reply, family_policy, attrs,
847                          ARRAY_SIZE(family_policy))) {
848         nl_sock_destroy(sock);
849         buffer_delete(reply);
850         return -EPROTO;
851     }
852
853     retval = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
854     if (retval == 0) {
855         retval = -EPROTO;
856     }
857     nl_sock_destroy(sock);
858     buffer_delete(reply);
859     return retval;
860 }
861
862 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
863  * number and stores it in '*number'.  If successful, returns 0 and the caller
864  * may use '*number' as the family number.  On failure, returns a positive
865  * errno value and '*number' caches the errno value. */
866 int
867 nl_lookup_genl_family(const char *name, int *number) 
868 {
869     if (*number == 0) {
870         *number = do_lookup_genl_family(name);
871         assert(*number != 0);
872     }
873     return *number > 0 ? 0 : -*number;
874 }
875 \f
876 /* Netlink PID.
877  *
878  * Every Netlink socket must be bound to a unique 32-bit PID.  By convention,
879  * programs that have a single Netlink socket use their Unix process ID as PID,
880  * and programs with multiple Netlink sockets add a unique per-socket
881  * identifier in the bits above the Unix process ID.
882  *
883  * The kernel has Netlink PID 0.
884  */
885
886 /* Parameters for how many bits in the PID should come from the Unix process ID
887  * and how many unique per-socket. */
888 #define SOCKET_BITS 10
889 #define MAX_SOCKETS (1u << SOCKET_BITS)
890
891 #define PROCESS_BITS (32 - SOCKET_BITS)
892 #define MAX_PROCESSES (1u << PROCESS_BITS)
893 #define PROCESS_MASK ((uint32_t) (MAX_PROCESSES - 1))
894
895 /* Bit vector of unused socket identifiers. */
896 static uint32_t avail_sockets[ROUND_UP(MAX_SOCKETS, 32)];
897
898 /* Allocates and returns a new Netlink PID. */
899 static int
900 alloc_pid(uint32_t *pid)
901 {
902     int i;
903
904     for (i = 0; i < MAX_SOCKETS; i++) {
905         if ((avail_sockets[i / 32] & (1u << (i % 32))) == 0) {
906             avail_sockets[i / 32] |= 1u << (i % 32);
907             *pid = (getpid() & PROCESS_MASK) | (i << PROCESS_BITS);
908             return 0;
909         }
910     }
911     VLOG_ERR("netlink pid space exhausted");
912     return ENOBUFS;
913 }
914
915 /* Makes the specified 'pid' available for reuse. */
916 static void
917 free_pid(uint32_t pid)
918 {
919     int sock = pid >> PROCESS_BITS;
920     assert(avail_sockets[sock / 32] & (1u << (sock % 32)));
921     avail_sockets[sock / 32] &= ~(1u << (sock % 32));
922 }