Update copyright on all non-GPL files
[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     /* This method of joining multicast groups is only supported by newish
154      * kernels, but it allows for an arbitrary number of multicast groups. */
155     if (multicast_group > 32
156         && setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
157                       &multicast_group, sizeof multicast_group) < 0) {
158         VLOG_ERR("setsockopt(NETLINK_ADD_MEMBERSHIP,%d): %s",
159                  multicast_group, strerror(errno));
160         goto error_free_pid;
161     }
162
163     *sockp = sock;
164     return 0;
165
166 error_free_pid:
167     free_pid(sock->pid);
168 error:
169     if (retval == 0) {
170         retval = errno;
171         if (retval == 0) {
172             retval = EINVAL;
173         }
174     }
175     if (sock->fd >= 0) {
176         close(sock->fd);
177     }
178     free(sock);
179     return retval;
180 }
181
182 /* Destroys netlink socket 'sock'. */
183 void
184 nl_sock_destroy(struct nl_sock *sock) 
185 {
186     if (sock) {
187         close(sock->fd);
188         free_pid(sock->pid);
189         free(sock);
190     }
191 }
192
193 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
194  * 'sock'.  nlmsg_len in 'msg' will be finalized to match msg->size before the
195  * message is sent.
196  *
197  * Returns 0 if successful, otherwise a positive errno value.  If
198  * 'wait' is true, then the send will wait until buffer space is ready;
199  * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
200 int
201 nl_sock_send(struct nl_sock *sock, const struct buffer *msg, bool wait) 
202 {
203     int retval;
204
205     nl_msg_nlmsghdr(msg)->nlmsg_len = msg->size;
206     do {
207         retval = send(sock->fd, msg->data, msg->size, wait ? 0 : MSG_DONTWAIT);
208     } while (retval < 0 && errno == EINTR);
209     return retval < 0 ? errno : 0;
210 }
211
212 /* Tries to send the 'n_iov' chunks of data in 'iov' to the kernel on 'sock' as
213  * a single Netlink message.  (The message must be fully formed and not require
214  * finalization of its nlmsg_len field.)
215  *
216  * Returns 0 if successful, otherwise a positive errno value.  If 'wait' is
217  * true, then the send will wait until buffer space is ready; otherwise,
218  * returns EAGAIN if the 'sock' send buffer is full. */
219 int
220 nl_sock_sendv(struct nl_sock *sock, const struct iovec iov[], size_t n_iov,
221               bool wait) 
222 {
223     struct msghdr msg;
224     int retval;
225
226     memset(&msg, 0, sizeof msg);
227     msg.msg_iov = (struct iovec *) iov;
228     msg.msg_iovlen = n_iov;
229     do {
230         retval = sendmsg(sock->fd, &msg, MSG_DONTWAIT);
231     } while (retval < 0 && errno == EINTR);
232     return retval < 0 ? errno : 0;
233 }
234
235 /* Tries to receive a netlink message from the kernel on 'sock'.  If
236  * successful, stores the received message into '*bufp' and returns 0.  The
237  * caller is responsible for destroying the message with buffer_delete().  On
238  * failure, returns a positive errno value and stores a null pointer into
239  * '*bufp'.
240  *
241  * If 'wait' is true, nl_sock_recv waits for a message to be ready; otherwise,
242  * returns EAGAIN if the 'sock' receive buffer is empty. */
243 int
244 nl_sock_recv(struct nl_sock *sock, struct buffer **bufp, bool wait) 
245 {
246     uint8_t tmp;
247     ssize_t bufsize = 2048;
248     ssize_t nbytes, nbytes2;
249     struct buffer *buf;
250     struct nlmsghdr *nlmsghdr;
251     struct iovec iov;
252     struct msghdr msg = {
253         .msg_name = NULL,
254         .msg_namelen = 0,
255         .msg_iov = &iov,
256         .msg_iovlen = 1,
257         .msg_control = NULL,
258         .msg_controllen = 0,
259         .msg_flags = 0
260     };
261
262     buf = buffer_new(bufsize);
263     *bufp = NULL;
264
265 try_again:
266     /* Attempt to read the message.  We don't know the size of the data
267      * yet, so we take a guess at 2048.  If we're wrong, we keep trying
268      * and doubling the buffer size each time. 
269      */
270     nlmsghdr = buffer_put_uninit(buf, bufsize);
271     iov.iov_base = nlmsghdr;
272     iov.iov_len = bufsize;
273     do {
274         nbytes = recvmsg(sock->fd, &msg, (wait ? 0 : MSG_DONTWAIT) | MSG_PEEK); 
275     } while (nbytes < 0 && errno == EINTR);
276     if (nbytes < 0) {
277         buffer_delete(buf);
278         return errno;
279     }
280     if (msg.msg_flags & MSG_TRUNC) {
281         bufsize *= 2;
282         buffer_reinit(buf, bufsize);
283         goto try_again;
284     }
285     buf->size = nbytes;
286
287     /* We successfully read the message, so recv again to clear the queue */
288     iov.iov_base = &tmp;
289     iov.iov_len = 1;
290     do {
291         nbytes2 = recvmsg(sock->fd, &msg, MSG_DONTWAIT);
292         if (nbytes2 < 0) {
293             VLOG_ERR("failed to remove nlmsg from socket: %d\n", errno);
294         }
295     } while (nbytes2 < 0 && errno == EINTR);
296
297     if (!NLMSG_OK(nlmsghdr, nbytes)) {
298         VLOG_ERR("received invalid nlmsg (%zd bytes < %d)",
299                  bufsize, NLMSG_HDRLEN);
300         buffer_delete(buf);
301         return EPROTO;
302     }
303     *bufp = buf;
304     return 0;
305 }
306
307 /* Sends 'request' to the kernel via 'sock' and waits for a response.  If
308  * successful, stores the reply into '*replyp' and returns 0.  The caller is
309  * responsible for destroying the reply with buffer_delete().  On failure,
310  * returns a positive errno value and stores a null pointer into '*replyp'.
311  *
312  * Bare Netlink is an unreliable transport protocol.  This function layers
313  * reliable delivery and reply semantics on top of bare Netlink.
314  * 
315  * In Netlink, sending a request to the kernel is reliable enough, because the
316  * kernel will tell us if the message cannot be queued (and we will in that
317  * case put it on the transmit queue and wait until it can be delivered).
318  * 
319  * Receiving the reply is the real problem: if the socket buffer is full when
320  * the kernel tries to send the reply, the reply will be dropped.  However, the
321  * kernel sets a flag that a reply has been dropped.  The next call to recv
322  * then returns ENOBUFS.  We can then re-send the request.
323  *
324  * Caveats:
325  *
326  *      1. Netlink depends on sequence numbers to match up requests and
327  *         replies.  The sender of a request supplies a sequence number, and
328  *         the reply echos back that sequence number.
329  *
330  *         This is fine, but (1) some kernel netlink implementations are
331  *         broken, in that they fail to echo sequence numbers and (2) this
332  *         function will drop packets with non-matching sequence numbers, so
333  *         that only a single request can be usefully transacted at a time.
334  *
335  *      2. Resending the request causes it to be re-executed, so the request
336  *         needs to be idempotent.
337  */
338 int
339 nl_sock_transact(struct nl_sock *sock,
340                  const struct buffer *request, struct buffer **replyp) 
341 {
342     uint32_t seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
343     struct nlmsghdr *nlmsghdr;
344     struct buffer *reply;
345     int retval;
346
347     *replyp = NULL;
348
349     /* Ensure that we get a reply even if this message doesn't ordinarily call
350      * for one. */
351     nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_ACK;
352     
353 send:
354     retval = nl_sock_send(sock, request, true);
355     if (retval) {
356         return retval;
357     }
358
359 recv:
360     retval = nl_sock_recv(sock, &reply, true);
361     if (retval) {
362         if (retval == ENOBUFS) {
363             VLOG_DBG("receive buffer overflow, resending request");
364             goto send;
365         } else {
366             return retval;
367         }
368     }
369     nlmsghdr = nl_msg_nlmsghdr(reply);
370     if (seq != nlmsghdr->nlmsg_seq) {
371         VLOG_DBG("ignoring seq %"PRIu32" != expected %"PRIu32,
372                  nl_msg_nlmsghdr(reply)->nlmsg_seq, seq);
373         buffer_delete(reply);
374         goto recv;
375     }
376     if (nl_msg_nlmsgerr(reply, &retval)) {
377         if (retval) {
378             VLOG_DBG("received NAK error=%d (%s)", retval, strerror(retval));
379         }
380         return retval != EAGAIN ? retval : EPROTO;
381     }
382
383     *replyp = reply;
384     return 0;
385 }
386
387 /* Returns 'sock''s underlying file descriptor. */
388 int
389 nl_sock_fd(const struct nl_sock *sock) 
390 {
391     return sock->fd;
392 }
393 \f
394 /* Netlink messages. */
395
396 /* Returns the nlmsghdr at the head of 'msg'.
397  *
398  * 'msg' must be at least as large as a nlmsghdr. */
399 struct nlmsghdr *
400 nl_msg_nlmsghdr(const struct buffer *msg) 
401 {
402     return buffer_at_assert(msg, 0, NLMSG_HDRLEN);
403 }
404
405 /* Returns the genlmsghdr just past 'msg''s nlmsghdr.
406  *
407  * Returns a null pointer if 'msg' is not large enough to contain an nlmsghdr
408  * and a genlmsghdr. */
409 struct genlmsghdr *
410 nl_msg_genlmsghdr(const struct buffer *msg) 
411 {
412     return buffer_at(msg, NLMSG_HDRLEN, GENL_HDRLEN);
413 }
414
415 /* If 'buffer' is a NLMSG_ERROR message, stores 0 in '*errorp' if it is an ACK
416  * message, otherwise a positive errno value, and returns true.  If 'buffer' is
417  * not an NLMSG_ERROR message, returns false.
418  *
419  * 'msg' must be at least as large as a nlmsghdr. */
420 bool
421 nl_msg_nlmsgerr(const struct buffer *msg, int *errorp) 
422 {
423     if (nl_msg_nlmsghdr(msg)->nlmsg_type == NLMSG_ERROR) {
424         struct nlmsgerr *err = buffer_at(msg, NLMSG_HDRLEN, sizeof *err);
425         int code = EPROTO;
426         if (!err) {
427             VLOG_ERR("received invalid nlmsgerr (%zd bytes < %zd)",
428                      msg->size, NLMSG_HDRLEN + sizeof *err);
429         } else if (err->error <= 0 && err->error > INT_MIN) {
430             code = -err->error;
431         }
432         if (errorp) {
433             *errorp = code;
434         }
435         return true;
436     } else {
437         return false;
438     }
439 }
440
441 /* Ensures that 'b' has room for at least 'size' bytes plus netlink pading at
442  * its tail end, reallocating and copying its data if necessary. */
443 void
444 nl_msg_reserve(struct buffer *msg, size_t size) 
445 {
446     buffer_reserve_tailroom(msg, NLMSG_ALIGN(size));
447 }
448
449 /* Puts a nlmsghdr at the beginning of 'msg', which must be initially empty.
450  * Uses the given 'type' and 'flags'.  'sock' is used to obtain a PID and
451  * sequence number for proper routing of replies.  'expected_payload' should be
452  * an estimate of the number of payload bytes to be supplied; if the size of
453  * the payload is unknown a value of 0 is acceptable.
454  *
455  * 'type' is ordinarily an enumerated value specific to the Netlink protocol
456  * (e.g. RTM_NEWLINK, for NETLINK_ROUTE protocol).  For Generic Netlink, 'type'
457  * is the family number obtained via nl_lookup_genl_family().
458  *
459  * 'flags' is a bit-mask that indicates what kind of request is being made.  It
460  * is often NLM_F_REQUEST indicating that a request is being made, commonly
461  * or'd with NLM_F_ACK to request an acknowledgement.
462  *
463  * nl_msg_put_genlmsghdr is more convenient for composing a Generic Netlink
464  * message. */
465 void
466 nl_msg_put_nlmsghdr(struct buffer *msg, struct nl_sock *sock,
467                     size_t expected_payload, uint32_t type, uint32_t flags) 
468 {
469     struct nlmsghdr *nlmsghdr;
470
471     assert(msg->size == 0);
472
473     nl_msg_reserve(msg, NLMSG_HDRLEN + expected_payload);
474     nlmsghdr = nl_msg_put_uninit(msg, NLMSG_HDRLEN);
475     nlmsghdr->nlmsg_len = 0;
476     nlmsghdr->nlmsg_type = type;
477     nlmsghdr->nlmsg_flags = flags;
478     nlmsghdr->nlmsg_seq = ++next_seq;
479     nlmsghdr->nlmsg_pid = sock->pid;
480 }
481
482 /* Puts a nlmsghdr and genlmsghdr at the beginning of 'msg', which must be
483  * initially empty.  'sock' is used to obtain a PID and sequence number for
484  * proper routing of replies.  'expected_payload' should be an estimate of the
485  * number of payload bytes to be supplied; if the size of the payload is
486  * unknown a value of 0 is acceptable.
487  *
488  * 'family' is the family number obtained via nl_lookup_genl_family().
489  *
490  * 'flags' is a bit-mask that indicates what kind of request is being made.  It
491  * is often NLM_F_REQUEST indicating that a request is being made, commonly
492  * or'd with NLM_F_ACK to request an acknowledgement.
493  *
494  * 'cmd' is an enumerated value specific to the Generic Netlink family
495  * (e.g. CTRL_CMD_NEWFAMILY for the GENL_ID_CTRL family).
496  *
497  * 'version' is a version number specific to the family and command (often 1).
498  *
499  * nl_msg_put_nlmsghdr should be used to compose Netlink messages that are not
500  * Generic Netlink messages. */
501 void
502 nl_msg_put_genlmsghdr(struct buffer *msg, struct nl_sock *sock,
503                       size_t expected_payload, int family, uint32_t flags,
504                       uint8_t cmd, uint8_t version)
505 {
506     struct genlmsghdr *genlmsghdr;
507
508     nl_msg_put_nlmsghdr(msg, sock, GENL_HDRLEN + expected_payload,
509                         family, flags);
510     assert(msg->size == NLMSG_HDRLEN);
511     genlmsghdr = nl_msg_put_uninit(msg, GENL_HDRLEN);
512     genlmsghdr->cmd = cmd;
513     genlmsghdr->version = version;
514     genlmsghdr->reserved = 0;
515 }
516
517 /* Appends the 'size' bytes of data in 'p', plus Netlink padding if needed, to
518  * the tail end of 'msg'.  Data in 'msg' is reallocated and copied if
519  * necessary. */
520 void
521 nl_msg_put(struct buffer *msg, const void *data, size_t size) 
522 {
523     memcpy(nl_msg_put_uninit(msg, size), data, size);
524 }
525
526 /* Appends 'size' bytes of data, plus Netlink padding if needed, to the tail
527  * end of 'msg', reallocating and copying its data if necessary.  Returns a
528  * pointer to the first byte of the new data, which is left uninitialized. */
529 void *
530 nl_msg_put_uninit(struct buffer *msg, size_t size) 
531 {
532     size_t pad = NLMSG_ALIGN(size) - size;
533     char *p = buffer_put_uninit(msg, size + pad);
534     if (pad) {
535         memset(p + size, 0, pad); 
536     }
537     return p;
538 }
539
540 /* Appends a Netlink attribute of the given 'type' and room for 'size' bytes of
541  * data as its payload, plus Netlink padding if needed, to the tail end of
542  * 'msg', reallocating and copying its data if necessary.  Returns a pointer to
543  * the first byte of data in the attribute, which is left uninitialized. */
544 void *
545 nl_msg_put_unspec_uninit(struct buffer *msg, uint16_t type, size_t size) 
546 {
547     size_t total_size = NLA_HDRLEN + size;
548     struct nlattr* nla = nl_msg_put_uninit(msg, total_size);
549     assert(NLA_ALIGN(total_size) <= UINT16_MAX);
550     nla->nla_len = total_size;
551     nla->nla_type = type;
552     return nla + 1;
553 }
554
555 /* Appends a Netlink attribute of the given 'type' and the 'size' bytes of
556  * 'data' as its payload, to the tail end of 'msg', reallocating and copying
557  * its data if necessary.  Returns a pointer to the first byte of data in the
558  * attribute, which is left uninitialized. */
559 void
560 nl_msg_put_unspec(struct buffer *msg, uint16_t type,
561                   const void *data, size_t size) 
562 {
563     memcpy(nl_msg_put_unspec_uninit(msg, type, size), data, size);
564 }
565
566 /* Appends a Netlink attribute of the given 'type' and no payload to 'msg'.
567  * (Some Netlink protocols use the presence or absence of an attribute as a
568  * Boolean flag.) */
569 void
570 nl_msg_put_flag(struct buffer *msg, uint16_t type) 
571 {
572     nl_msg_put_unspec(msg, type, NULL, 0);
573 }
574
575 /* Appends a Netlink attribute of the given 'type' and the given 8-bit 'value'
576  * to 'msg'. */
577 void
578 nl_msg_put_u8(struct buffer *msg, uint16_t type, uint8_t value) 
579 {
580     nl_msg_put_unspec(msg, type, &value, sizeof value);
581 }
582
583 /* Appends a Netlink attribute of the given 'type' and the given 16-bit 'value'
584  * to 'msg'. */
585 void
586 nl_msg_put_u16(struct buffer *msg, uint16_t type, uint16_t value)
587 {
588     nl_msg_put_unspec(msg, type, &value, sizeof value);
589 }
590
591 /* Appends a Netlink attribute of the given 'type' and the given 32-bit 'value'
592  * to 'msg'. */
593 void
594 nl_msg_put_u32(struct buffer *msg, uint16_t type, uint32_t value)
595 {
596     nl_msg_put_unspec(msg, type, &value, sizeof value);
597 }
598
599 /* Appends a Netlink attribute of the given 'type' and the given 64-bit 'value'
600  * to 'msg'. */
601 void
602 nl_msg_put_u64(struct buffer *msg, uint16_t type, uint64_t value)
603 {
604     nl_msg_put_unspec(msg, type, &value, sizeof value);
605 }
606
607 /* Appends a Netlink attribute of the given 'type' and the given
608  * null-terminated string 'value' to 'msg'. */
609 void
610 nl_msg_put_string(struct buffer *msg, uint16_t type, const char *value)
611 {
612     nl_msg_put_unspec(msg, type, value, strlen(value) + 1);
613 }
614
615 /* Appends a Netlink attribute of the given 'type' and the given buffered
616  * netlink message in 'nested_msg' to 'msg'.  The nlmsg_len field in
617  * 'nested_msg' is finalized to match 'nested_msg->size'. */
618 void
619 nl_msg_put_nested(struct buffer *msg,
620                   uint16_t type, struct buffer *nested_msg)
621 {
622     nl_msg_nlmsghdr(nested_msg)->nlmsg_len = nested_msg->size;
623     nl_msg_put_unspec(msg, type, nested_msg->data, nested_msg->size);
624 }
625
626 /* Returns the first byte in the payload of attribute 'nla'. */
627 const void *
628 nl_attr_get(const struct nlattr *nla) 
629 {
630     assert(nla->nla_len >= NLA_HDRLEN);
631     return nla + 1;
632 }
633
634 /* Returns the number of bytes in the payload of attribute 'nla'. */
635 size_t
636 nl_attr_get_size(const struct nlattr *nla) 
637 {
638     assert(nla->nla_len >= NLA_HDRLEN);
639     return nla->nla_len - NLA_HDRLEN;
640 }
641
642 /* Asserts that 'nla''s payload is at least 'size' bytes long, and returns the
643  * first byte of the payload. */
644 const void *
645 nl_attr_get_unspec(const struct nlattr *nla, size_t size) 
646 {
647     assert(nla->nla_len >= NLA_HDRLEN + size);
648     return nla + 1;
649 }
650
651 /* Returns true if 'nla' is nonnull.  (Some Netlink protocols use the presence
652  * or absence of an attribute as a Boolean flag.) */
653 bool
654 nl_attr_get_flag(const struct nlattr *nla) 
655 {
656     return nla != NULL;
657 }
658
659 #define NL_ATTR_GET_AS(NLA, TYPE) \
660         (*(TYPE*) nl_attr_get_unspec(nla, sizeof(TYPE)))
661
662 /* Returns the 8-bit value in 'nla''s payload.
663  *
664  * Asserts that 'nla''s payload is at least 1 byte long. */
665 uint8_t
666 nl_attr_get_u8(const struct nlattr *nla) 
667 {
668     return NL_ATTR_GET_AS(nla, uint8_t);
669 }
670
671 /* Returns the 16-bit value in 'nla''s payload.
672  *
673  * Asserts that 'nla''s payload is at least 2 bytes long. */
674 uint16_t
675 nl_attr_get_u16(const struct nlattr *nla) 
676 {
677     return NL_ATTR_GET_AS(nla, uint16_t);
678 }
679
680 /* Returns the 32-bit value in 'nla''s payload.
681  *
682  * Asserts that 'nla''s payload is at least 4 bytes long. */
683 uint32_t
684 nl_attr_get_u32(const struct nlattr *nla) 
685 {
686     return NL_ATTR_GET_AS(nla, uint32_t);
687 }
688
689 /* Returns the 64-bit value in 'nla''s payload.
690  *
691  * Asserts that 'nla''s payload is at least 8 bytes long. */
692 uint64_t
693 nl_attr_get_u64(const struct nlattr *nla) 
694 {
695     return NL_ATTR_GET_AS(nla, uint64_t);
696 }
697
698 /* Returns the null-terminated string value in 'nla''s payload.
699  *
700  * Asserts that 'nla''s payload contains a null-terminated string. */
701 const char *
702 nl_attr_get_string(const struct nlattr *nla) 
703 {
704     assert(nla->nla_len > NLA_HDRLEN);
705     assert(memchr(nl_attr_get(nla), '\0', nla->nla_len - NLA_HDRLEN) != NULL);
706     return nl_attr_get(nla);
707 }
708
709 /* Default minimum and maximum payload sizes for each type of attribute. */
710 static const size_t attr_len_range[][2] = {
711     [0 ... N_NL_ATTR_TYPES - 1] = { 0, SIZE_MAX },
712     [NL_A_U8] = { 1, 1 },
713     [NL_A_U16] = { 2, 2 },
714     [NL_A_U32] = { 4, 4 },
715     [NL_A_U64] = { 8, 8 },
716     [NL_A_STRING] = { 1, SIZE_MAX },
717     [NL_A_FLAG] = { 0, SIZE_MAX },
718     [NL_A_NESTED] = { NLMSG_HDRLEN, SIZE_MAX },
719 };
720
721 /* Parses the Generic Netlink payload of 'msg' as a sequence of Netlink
722  * attributes.  'policy[i]', for 0 <= i < n_attrs, specifies how the attribute
723  * with nla_type == i is parsed; a pointer to attribute i is stored in
724  * attrs[i].  Returns true if successful, false on failure. */
725 bool
726 nl_policy_parse(const struct buffer *msg, const struct nl_policy policy[],
727                 struct nlattr *attrs[], size_t n_attrs)
728 {
729     void *p, *tail;
730     size_t n_required;
731     size_t i;
732
733     n_required = 0;
734     for (i = 0; i < n_attrs; i++) {
735         attrs[i] = NULL;
736
737         assert(policy[i].type < N_NL_ATTR_TYPES);
738         if (policy[i].type != NL_A_NO_ATTR
739             && policy[i].type != NL_A_FLAG
740             && !policy[i].optional) {
741             n_required++;
742         }
743     }
744
745     p = buffer_at(msg, NLMSG_HDRLEN + GENL_HDRLEN, 0);
746     if (p == NULL) {
747         VLOG_DBG("missing headers in nl_policy_parse");
748         return false;
749     }
750     tail = buffer_tail(msg);
751
752     while (p < tail) {
753         size_t offset = p - msg->data;
754         struct nlattr *nla = p;
755         size_t len, aligned_len;
756         uint16_t type;
757
758         /* Make sure its claimed length is plausible. */
759         if (nla->nla_len < NLA_HDRLEN) {
760             VLOG_DBG("%zu: attr shorter than NLA_HDRLEN (%"PRIu16")",
761                      offset, nla->nla_len);
762             return false;
763         }
764         len = nla->nla_len - NLA_HDRLEN;
765         aligned_len = NLA_ALIGN(len);
766         if (aligned_len > tail - p) {
767             VLOG_DBG("%zu: attr %"PRIu16" aligned data len (%zu) "
768                      "> bytes left (%tu)",
769                      offset, nla->nla_type, aligned_len, tail - p);
770             return false;
771         }
772
773         type = nla->nla_type;
774         if (type < n_attrs && policy[type].type != NL_A_NO_ATTR) {
775             const struct nl_policy *p = &policy[type];
776             size_t min_len, max_len;
777
778             /* Validate length and content. */
779             min_len = p->min_len ? p->min_len : attr_len_range[p->type][0];
780             max_len = p->max_len ? p->max_len : attr_len_range[p->type][1];
781             if (len < min_len || len > max_len) {
782                 VLOG_DBG("%zu: attr %"PRIu16" length %zu not in allowed range "
783                          "%zu...%zu", offset, type, len, min_len, max_len);
784                 return false;
785             }
786             if (p->type == NL_A_STRING) {
787                 if (((char *) nla)[nla->nla_len - 1]) {
788                     VLOG_DBG("%zu: attr %"PRIu16" lacks null terminator",
789                              offset, type);
790                     return false;
791                 }
792                 if (memchr(nla + 1, '\0', len - 1) != NULL) {
793                     VLOG_DBG("%zu: attr %"PRIu16" lies about string length",
794                              offset, type);
795                     return false;
796                 }
797             }
798             if (!p->optional && attrs[type] == NULL) {
799                 assert(n_required > 0);
800                 --n_required;
801             }
802             attrs[type] = nla;
803         } else {
804             /* Skip attribute type that we don't care about. */
805         }
806         p += NLA_ALIGN(nla->nla_len);
807     }
808     if (n_required) {
809         VLOG_DBG("%zu required attrs missing", n_required);
810         return false;
811     }
812     return true;
813 }
814 \f
815 /* Miscellaneous.  */
816
817 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = { 
818     [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
819 };
820
821 static int do_lookup_genl_family(const char *name) 
822 {
823     struct nl_sock *sock;
824     struct buffer request, *reply;
825     struct nlattr *attrs[ARRAY_SIZE(family_policy)];
826     int retval;
827
828     retval = nl_sock_create(NETLINK_GENERIC, 0, 0, 0, &sock);
829     if (retval) {
830         return -retval;
831     }
832
833     buffer_init(&request, 0);
834     nl_msg_put_genlmsghdr(&request, sock, 0, GENL_ID_CTRL, NLM_F_REQUEST,
835                           CTRL_CMD_GETFAMILY, 1);
836     nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
837     retval = nl_sock_transact(sock, &request, &reply);
838     buffer_uninit(&request);
839     if (retval) {
840         nl_sock_destroy(sock);
841         return -retval;
842     }
843
844     if (!nl_policy_parse(reply, family_policy, attrs,
845                          ARRAY_SIZE(family_policy))) {
846         nl_sock_destroy(sock);
847         buffer_delete(reply);
848         return -EPROTO;
849     }
850
851     retval = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
852     if (retval == 0) {
853         retval = -EPROTO;
854     }
855     nl_sock_destroy(sock);
856     buffer_delete(reply);
857     return retval;
858 }
859
860 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
861  * number and stores it in '*number'.  If successful, returns 0 and the caller
862  * may use '*number' as the family number.  On failure, returns a positive
863  * errno value and '*number' caches the errno value. */
864 int
865 nl_lookup_genl_family(const char *name, int *number) 
866 {
867     if (*number == 0) {
868         *number = do_lookup_genl_family(name);
869         assert(*number != 0);
870     }
871     return *number > 0 ? 0 : -*number;
872 }
873 \f
874 /* Netlink PID.
875  *
876  * Every Netlink socket must be bound to a unique 32-bit PID.  By convention,
877  * programs that have a single Netlink socket use their Unix process ID as PID,
878  * and programs with multiple Netlink sockets add a unique per-socket
879  * identifier in the bits above the Unix process ID.
880  *
881  * The kernel has Netlink PID 0.
882  */
883
884 /* Parameters for how many bits in the PID should come from the Unix process ID
885  * and how many unique per-socket. */
886 #define SOCKET_BITS 10
887 #define MAX_SOCKETS (1u << SOCKET_BITS)
888
889 #define PROCESS_BITS (32 - SOCKET_BITS)
890 #define MAX_PROCESSES (1u << PROCESS_BITS)
891 #define PROCESS_MASK ((uint32_t) (MAX_PROCESSES - 1))
892
893 /* Bit vector of unused socket identifiers. */
894 static uint32_t avail_sockets[ROUND_UP(MAX_SOCKETS, 32)];
895
896 /* Allocates and returns a new Netlink PID. */
897 static int
898 alloc_pid(uint32_t *pid)
899 {
900     int i;
901
902     for (i = 0; i < MAX_SOCKETS; i++) {
903         if ((avail_sockets[i / 32] & (1u << (i % 32))) == 0) {
904             avail_sockets[i / 32] |= 1u << (i % 32);
905             *pid = (getpid() & PROCESS_MASK) | (i << PROCESS_BITS);
906             return 0;
907         }
908     }
909     VLOG_ERR("netlink pid space exhausted");
910     return ENOBUFS;
911 }
912
913 /* Makes the specified 'pid' available for reuse. */
914 static void
915 free_pid(uint32_t pid)
916 {
917     int sock = pid >> PROCESS_BITS;
918     assert(avail_sockets[sock / 32] & (1u << (sock % 32)));
919     avail_sockets[sock / 32] &= ~(1u << (sock % 32));
920 }