libnl  3.2.24-rc1
nl.c
1 /*
2  * lib/nl.c Core Netlink Interface
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation version 2.1
7  * of the License.
8  *
9  * Copyright (c) 2003-2012 Thomas Graf <tgraf@suug.ch>
10  */
11 
12 /**
13  * @defgroup core Core Library (libnl)
14  *
15  * Socket handling, connection management, sending and receiving of data,
16  * message construction and parsing, object caching system, ...
17  *
18  * This is the API reference of the core library. It is not meant as a guide
19  * but as a reference. Please refer to the core library guide for detailed
20  * documentation on the library architecture and examples:
21  *
22  * * @ref_asciidoc{core,_,Netlink Core Library Development Guide}
23  *
24  *
25  * @{
26  */
27 
28 #include <netlink-private/netlink.h>
29 #include <netlink/netlink.h>
30 #include <netlink/utils.h>
31 #include <netlink/handlers.h>
32 #include <netlink/msg.h>
33 #include <netlink/attr.h>
34 
35 /**
36  * @defgroup core_types Data Types
37  *
38  * Core library data types
39  * @{
40  * @}
41  *
42  * @defgroup send_recv Send & Receive Data
43  *
44  * Connection management, sending & receiving of data
45  *
46  * Related sections in the development guide:
47  * - @core_doc{core_send_recv, Sending & Receiving}
48  * - @core_doc{core_sockets, Sockets}
49  *
50  * @{
51  *
52  * Header
53  * ------
54  * ~~~~{.c}
55  * #include <netlink/netlink.h>
56  * ~~~~
57  */
58 
59 /**
60  * @name Connection Management
61  * @{
62  */
63 
64 /**
65  * Create file descriptor and bind socket.
66  * @arg sk Netlink socket (required)
67  * @arg protocol Netlink protocol to use (required)
68  *
69  * Creates a new Netlink socket using `socket()` and binds the socket to the
70  * protocol and local port specified in the `sk` socket object. Fails if
71  * the socket is already connected.
72  *
73  * @note If available, the `close-on-exec` (`SOCK_CLOEXEC`) feature is enabled
74  * automatically on the new file descriptor. This causes the socket to
75  * be closed automatically if any of the `exec` family functions succeed.
76  * This is essential for multi threaded programs.
77  *
78  * @see nl_socket_alloc()
79  * @see nl_close()
80  *
81  * @return 0 on success or a negative error code.
82  *
83  * @retval -NLE_BAD_SOCK Socket is already connected
84  */
85 int nl_connect(struct nl_sock *sk, int protocol)
86 {
87  int err, flags = 0;
88  socklen_t addrlen;
89 
90 #ifdef SOCK_CLOEXEC
91  flags |= SOCK_CLOEXEC;
92 #endif
93 
94  if (sk->s_fd != -1)
95  return -NLE_BAD_SOCK;
96 
97  sk->s_fd = socket(AF_NETLINK, SOCK_RAW | flags, protocol);
98  if (sk->s_fd < 0) {
99  err = -nl_syserr2nlerr(errno);
100  goto errout;
101  }
102 
103  if (!(sk->s_flags & NL_SOCK_BUFSIZE_SET)) {
104  err = nl_socket_set_buffer_size(sk, 0, 0);
105  if (err < 0)
106  goto errout;
107  }
108 
109  err = bind(sk->s_fd, (struct sockaddr*) &sk->s_local,
110  sizeof(sk->s_local));
111  if (err < 0) {
112  err = -nl_syserr2nlerr(errno);
113  goto errout;
114  }
115 
116  addrlen = sizeof(sk->s_local);
117  err = getsockname(sk->s_fd, (struct sockaddr *) &sk->s_local,
118  &addrlen);
119  if (err < 0) {
120  err = -nl_syserr2nlerr(errno);
121  goto errout;
122  }
123 
124  if (addrlen != sizeof(sk->s_local)) {
125  err = -NLE_NOADDR;
126  goto errout;
127  }
128 
129  if (sk->s_local.nl_family != AF_NETLINK) {
130  err = -NLE_AF_NOSUPPORT;
131  goto errout;
132  }
133 
134  sk->s_proto = protocol;
135 
136  return 0;
137 errout:
138  if (sk->s_fd != -1) {
139  close(sk->s_fd);
140  sk->s_fd = -1;
141  }
142 
143  return err;
144 }
145 
146 /**
147  * Close Netlink socket
148  * @arg sk Netlink socket (required)
149  *
150  * Closes the Netlink socket using `close()`.
151  *
152  * @note The socket is closed automatically if a `struct nl_sock` object is
153  * freed using `nl_socket_free()`.
154  *
155  * @see nl_connect()
156  */
157 void nl_close(struct nl_sock *sk)
158 {
159  if (sk->s_fd >= 0) {
160  close(sk->s_fd);
161  sk->s_fd = -1;
162  }
163 
164  sk->s_proto = 0;
165 }
166 
167 /** @} */
168 
169 /**
170  * @name Send
171  * @{
172  */
173 
174 /**
175  * Transmit raw data over Netlink socket.
176  * @arg sk Netlink socket (required)
177  * @arg buf Buffer carrying data to send (required)
178  * @arg size Size of buffer (required)
179  *
180  * Transmits "raw" data over the specified Netlink socket. Unlike the other
181  * transmit functions it does not modify the data in any way. It directly
182  * passes the buffer \c buf of \c size to sendto().
183  *
184  * The message is addressed to the peer as specified in the socket by either
185  * the nl_socket_set_peer_port() or nl_socket_set_peer_groups() function.
186  *
187  * @note Because there is no indication on the message boundaries of the data
188  * being sent, the \c NL_CB_MSG_OUT callback handler will not be invoked
189  * for data that is being sent using this function.
190  *
191  * @see nl_socket_set_peer_port()
192  * @see nl_socket_set_peer_groups()
193  * @see nl_sendmsg()
194  *
195  * @return Number of bytes sent or a negative error code.
196  */
197 int nl_sendto(struct nl_sock *sk, void *buf, size_t size)
198 {
199  int ret;
200 
201  if (!buf)
202  return -NLE_INVAL;
203 
204  if (sk->s_fd < 0)
205  return -NLE_BAD_SOCK;
206 
207  ret = sendto(sk->s_fd, buf, size, 0, (struct sockaddr *)
208  &sk->s_peer, sizeof(sk->s_peer));
209  if (ret < 0)
210  return -nl_syserr2nlerr(errno);
211 
212  return ret;
213 }
214 
215 /**
216  * Transmit Netlink message using sendmsg()
217  * @arg sk Netlink socket (required)
218  * @arg msg Netlink message to be sent (required)
219  * @arg hdr sendmsg() message header (required)
220  *
221  * Transmits the message specified in \c hdr over the Netlink socket using the
222  * sendmsg() system call.
223  *
224  * @attention
225  * The `msg` argument will *not* be used to derive the message payload that
226  * is being sent out. The `msg` argument is *only* passed on to the
227  * `NL_CB_MSG_OUT` callback. The caller is responsible to initialize the
228  * `hdr` struct properly and have it point to the message payload and
229  * socket address.
230  *
231  * @note
232  * This function uses `nlmsg_set_src()` to modify the `msg` argument prior to
233  * invoking the `NL_CB_MSG_OUT` callback to provide the local port number.
234  *
235  * @callback This function triggers the `NL_CB_MSG_OUT` callback.
236  *
237  * @attention
238  * Think twice before using this function. It provides a low level access to
239  * the Netlink socket. Among other limitations, it does not add credentials
240  * even if enabled or respect the destination address specified in the `msg`
241  * object.
242  *
243  * @see nl_socket_set_local_port()
244  * @see nl_send_auto()
245  * @see nl_send_iovec()
246  *
247  * @return Number of bytes sent on success or a negative error code.
248  *
249  * @lowlevel
250  */
251 int nl_sendmsg(struct nl_sock *sk, struct nl_msg *msg, struct msghdr *hdr)
252 {
253  struct nl_cb *cb;
254  int ret;
255 
256  if (sk->s_fd < 0)
257  return -NLE_BAD_SOCK;
258 
259  nlmsg_set_src(msg, &sk->s_local);
260 
261  cb = sk->s_cb;
262  if (cb->cb_set[NL_CB_MSG_OUT])
263  if ((ret = nl_cb_call(cb, NL_CB_MSG_OUT, msg)) != NL_OK)
264  return ret;
265 
266  ret = sendmsg(sk->s_fd, hdr, 0);
267  if (ret < 0)
268  return -nl_syserr2nlerr(errno);
269 
270  NL_DBG(4, "sent %d bytes\n", ret);
271  return ret;
272 }
273 
274 
275 /**
276  * Transmit Netlink message (taking IO vector)
277  * @arg sk Netlink socket (required)
278  * @arg msg Netlink message to be sent (required)
279  * @arg iov IO vector to be sent (required)
280  * @arg iovlen Number of struct iovec to be sent (required)
281  *
282  * This function is identical to nl_send() except that instead of taking a
283  * `struct nl_msg` object it takes an IO vector. Please see the description
284  * of `nl_send()`.
285  *
286  * @callback This function triggers the `NL_CB_MSG_OUT` callback.
287  *
288  * @see nl_send()
289  *
290  * @return Number of bytes sent on success or a negative error code.
291  *
292  * @lowlevel
293  */
294 int nl_send_iovec(struct nl_sock *sk, struct nl_msg *msg, struct iovec *iov, unsigned iovlen)
295 {
296  struct sockaddr_nl *dst;
297  struct ucred *creds;
298  struct msghdr hdr = {
299  .msg_name = (void *) &sk->s_peer,
300  .msg_namelen = sizeof(struct sockaddr_nl),
301  .msg_iov = iov,
302  .msg_iovlen = iovlen,
303  };
304 
305  /* Overwrite destination if specified in the message itself, defaults
306  * to the peer address of the socket.
307  */
308  dst = nlmsg_get_dst(msg);
309  if (dst->nl_family == AF_NETLINK)
310  hdr.msg_name = dst;
311 
312  /* Add credentials if present. */
313  creds = nlmsg_get_creds(msg);
314  if (creds != NULL) {
315  char buf[CMSG_SPACE(sizeof(struct ucred))];
316  struct cmsghdr *cmsg;
317 
318  hdr.msg_control = buf;
319  hdr.msg_controllen = sizeof(buf);
320 
321  cmsg = CMSG_FIRSTHDR(&hdr);
322  cmsg->cmsg_level = SOL_SOCKET;
323  cmsg->cmsg_type = SCM_CREDENTIALS;
324  cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
325  memcpy(CMSG_DATA(cmsg), creds, sizeof(struct ucred));
326  }
327 
328  return nl_sendmsg(sk, msg, &hdr);
329 }
330 
331 /**
332  * Transmit Netlink message
333  * @arg sk Netlink socket (required)
334  * @arg msg Netlink message (required)
335  *
336  * Transmits the Netlink message `msg` over the Netlink socket using the
337  * `sendmsg()` system call. This function is based on `nl_send_iovec()` but
338  * takes care of initializing a `struct iovec` based on the `msg` object.
339  *
340  * The message is addressed to the peer as specified in the socket by either
341  * the nl_socket_set_peer_port() or nl_socket_set_peer_groups() function.
342  * The peer address can be overwritten by specifying an address in the `msg`
343  * object using nlmsg_set_dst().
344  *
345  * If present in the `msg`, credentials set by the nlmsg_set_creds() function
346  * are added to the control buffer of the message.
347  *
348  * @par Overwriting Capability:
349  * Calls to this function can be overwritten by providing an alternative using
350  * the nl_cb_overwrite_send() function.
351  *
352  * @callback This function triggers the `NL_CB_MSG_OUT` callback.
353  *
354  * @attention
355  * Unlike `nl_send_auto()`, this function does *not* finalize the message in
356  * terms of automatically adding needed flags or filling out port numbers.
357  *
358  * @see nl_send_auto()
359  * @see nl_send_iovec()
360  * @see nl_socket_set_peer_port()
361  * @see nl_socket_set_peer_groups()
362  * @see nlmsg_set_dst()
363  * @see nlmsg_set_creds()
364  * @see nl_cb_overwrite_send()
365  *
366  * @return Number of bytes sent on success or a negative error code.
367 */
368 int nl_send(struct nl_sock *sk, struct nl_msg *msg)
369 {
370  struct nl_cb *cb = sk->s_cb;
371 
372  if (cb->cb_send_ow)
373  return cb->cb_send_ow(sk, msg);
374  else {
375  struct iovec iov = {
376  .iov_base = (void *) nlmsg_hdr(msg),
377  .iov_len = nlmsg_hdr(msg)->nlmsg_len,
378  };
379 
380  return nl_send_iovec(sk, msg, &iov, 1);
381  }
382 }
383 
384 /**
385  * Finalize Netlink message
386  * @arg sk Netlink socket (required)
387  * @arg msg Netlink message (required)
388  *
389  * This function finalizes a Netlink message by completing the message with
390  * desirable flags and values depending on the socket configuration.
391  *
392  * - If not yet filled out, the source address of the message (`nlmsg_pid`)
393  * will be set to the local port number of the socket.
394  * - If not yet specified, the next available sequence number is assigned
395  * to the message (`nlmsg_seq`).
396  * - If not yet specified, the protocol field of the message will be set to
397  * the protocol field of the socket.
398  * - The `NLM_F_REQUEST` Netlink message flag will be set.
399  * - The `NLM_F_ACK` flag will be set if Auto-ACK mode is enabled on the
400  * socket.
401  */
402 void nl_complete_msg(struct nl_sock *sk, struct nl_msg *msg)
403 {
404  struct nlmsghdr *nlh;
405 
406  nlh = nlmsg_hdr(msg);
407  if (nlh->nlmsg_pid == NL_AUTO_PORT)
408  nlh->nlmsg_pid = sk->s_local.nl_pid;
409 
410  if (nlh->nlmsg_seq == NL_AUTO_SEQ)
411  nlh->nlmsg_seq = sk->s_seq_next++;
412 
413  if (msg->nm_protocol == -1)
414  msg->nm_protocol = sk->s_proto;
415 
416  nlh->nlmsg_flags |= NLM_F_REQUEST;
417 
418  if (!(sk->s_flags & NL_NO_AUTO_ACK))
419  nlh->nlmsg_flags |= NLM_F_ACK;
420 }
421 
422 /**
423  * Finalize and transmit Netlink message
424  * @arg sk Netlink socket (required)
425  * @arg msg Netlink message (required)
426  *
427  * Finalizes the message by passing it to `nl_complete_msg()` and transmits it
428  * by passing it to `nl_send()`.
429  *
430  * @callback This function triggers the `NL_CB_MSG_OUT` callback.
431  *
432  * @see nl_complete_msg()
433  * @see nl_send()
434  *
435  * @return Number of bytes sent or a negative error code.
436  */
437 int nl_send_auto(struct nl_sock *sk, struct nl_msg *msg)
438 {
439  nl_complete_msg(sk, msg);
440 
441  return nl_send(sk, msg);
442 }
443 
444 /**
445  * Finalize and transmit Netlink message and wait for ACK or error message
446  * @arg sk Netlink socket (required)
447  * @arg msg Netlink message (required)
448  *
449  * Passes the `msg` to `nl_send_auto()` to finalize and transmit it. Frees the
450  * message and waits (sleeps) for the ACK or error message to be received.
451  *
452  * @attention
453  * Disabling Auto-ACK (nl_socket_disable_auto_ack()) will cause this function
454  * to return immediately after transmitting the message. However, the peer may
455  * still be returning an error message in response to the request. It is the
456  * responsibility of the caller to handle such messages.
457  *
458  * @callback This function triggers the `NL_CB_MSG_OUT` callback.
459  *
460  * @attention
461  * This function frees the `msg` object after transmitting it by calling
462  * `nlmsg_free()`.
463  *
464  * @see nl_send_auto().
465  * @see nl_wait_for_ack()
466  *
467  * @return 0 on success or a negative error code.
468  */
469 int nl_send_sync(struct nl_sock *sk, struct nl_msg *msg)
470 {
471  int err;
472 
473  err = nl_send_auto(sk, msg);
474  nlmsg_free(msg);
475  if (err < 0)
476  return err;
477 
478  return wait_for_ack(sk);
479 }
480 
481 /**
482  * Construct and transmit a Netlink message
483  * @arg sk Netlink socket (required)
484  * @arg type Netlink message type (required)
485  * @arg flags Netlink message flags (optional)
486  * @arg buf Data buffer (optional)
487  * @arg size Size of data buffer (optional)
488  *
489  * Allocates a new Netlink message based on `type` and `flags`. If `buf`
490  * points to payload of length `size` that payload will be appended to the
491  * message.
492  *
493  * Sends out the message using `nl_send_auto()` and frees the message
494  * afterwards.
495  *
496  * @see nl_send_auto()
497  *
498  * @return Number of characters sent on success or a negative error code.
499  * @retval -NLE_NOMEM Unable to allocate Netlink message
500  */
501 int nl_send_simple(struct nl_sock *sk, int type, int flags, void *buf,
502  size_t size)
503 {
504  int err;
505  struct nl_msg *msg;
506 
507  msg = nlmsg_alloc_simple(type, flags);
508  if (!msg)
509  return -NLE_NOMEM;
510 
511  if (buf && size) {
512  err = nlmsg_append(msg, buf, size, NLMSG_ALIGNTO);
513  if (err < 0)
514  goto errout;
515  }
516 
517  err = nl_send_auto(sk, msg);
518 errout:
519  nlmsg_free(msg);
520 
521  return err;
522 }
523 
524 /** @} */
525 
526 /**
527  * @name Receive
528  * @{
529  */
530 
531 /**
532  * Receive data from netlink socket
533  * @arg sk Netlink socket (required)
534  * @arg nla Netlink socket structure to hold address of peer (required)
535  * @arg buf Destination pointer for message content (required)
536  * @arg creds Destination pointer for credentials (optional)
537  *
538  * Receives data from a connected netlink socket using recvmsg() and returns
539  * the number of bytes read. The read data is stored in a newly allocated
540  * buffer that is assigned to \c *buf. The peer's netlink address will be
541  * stored in \c *nla.
542  *
543  * This function blocks until data is available to be read unless the socket
544  * has been put into non-blocking mode using nl_socket_set_nonblocking() in
545  * which case this function will return immediately with a return value of 0.
546  *
547  * The buffer size used when reading from the netlink socket and thus limiting
548  * the maximum size of a netlink message that can be read defaults to the size
549  * of a memory page (getpagesize()). The buffer size can be modified on a per
550  * socket level using the function nl_socket_set_msg_buf_size().
551  *
552  * If message peeking is enabled using nl_socket_enable_msg_peek() the size of
553  * the message to be read will be determined using the MSG_PEEK flag prior to
554  * performing the actual read. This leads to an additional recvmsg() call for
555  * every read operation which has performance implications and is not
556  * recommended for high throughput protocols.
557  *
558  * An eventual interruption of the recvmsg() system call is automatically
559  * handled by retrying the operation.
560  *
561  * If receiving of credentials has been enabled using the function
562  * nl_socket_set_passcred(), this function will allocate a new struct ucred
563  * filled with the received credentials and assign it to \c *creds. The caller
564  * is responsible for freeing the buffer.
565  *
566  * @note The caller is responsible to free the returned data buffer and if
567  * enabled, the credentials buffer.
568  *
569  * @see nl_socket_set_nonblocking()
570  * @see nl_socket_set_msg_buf_size()
571  * @see nl_socket_enable_msg_peek()
572  * @see nl_socket_set_passcred()
573  *
574  * @return Number of bytes read, 0 on EOF, 0 on no data event (non-blocking
575  * mode), or a negative error code.
576  */
577 int nl_recv(struct nl_sock *sk, struct sockaddr_nl *nla,
578  unsigned char **buf, struct ucred **creds)
579 {
580  ssize_t n;
581  int flags = 0;
582  static int page_size = 0;
583  struct iovec iov;
584  struct msghdr msg = {
585  .msg_name = (void *) nla,
586  .msg_namelen = sizeof(struct sockaddr_nl),
587  .msg_iov = &iov,
588  .msg_iovlen = 1,
589  };
590  struct ucred* tmpcreds = NULL;
591  int retval = 0;
592 
593  if (!buf || !nla)
594  return -NLE_INVAL;
595 
596  if (sk->s_flags & NL_MSG_PEEK)
597  flags |= MSG_PEEK | MSG_TRUNC;
598 
599  if (page_size == 0)
600  page_size = getpagesize() * 4;
601 
602  iov.iov_len = sk->s_bufsize ? : page_size;
603  iov.iov_base = malloc(iov.iov_len);
604 
605  if (!iov.iov_base) {
606  retval = -NLE_NOMEM;
607  goto abort;
608  }
609 
610  if (creds && (sk->s_flags & NL_SOCK_PASSCRED)) {
611  msg.msg_controllen = CMSG_SPACE(sizeof(struct ucred));
612  msg.msg_control = malloc(msg.msg_controllen);
613  if (!msg.msg_control) {
614  retval = -NLE_NOMEM;
615  goto abort;
616  }
617  }
618 retry:
619 
620  n = recvmsg(sk->s_fd, &msg, flags);
621  if (!n) {
622  retval = 0;
623  goto abort;
624  }
625  if (n < 0) {
626  if (errno == EINTR) {
627  NL_DBG(3, "recvmsg() returned EINTR, retrying\n");
628  goto retry;
629  }
630  retval = -nl_syserr2nlerr(errno);
631  goto abort;
632  }
633 
634  if (msg.msg_flags & MSG_CTRUNC) {
635  void *tmp;
636  msg.msg_controllen *= 2;
637  tmp = realloc(msg.msg_control, msg.msg_controllen);
638  if (!tmp) {
639  retval = -NLE_NOMEM;
640  goto abort;
641  }
642  msg.msg_control = tmp;
643  goto retry;
644  }
645 
646  if (iov.iov_len < n || (msg.msg_flags & MSG_TRUNC)) {
647  void *tmp;
648  /* Provided buffer is not long enough, enlarge it
649  * to size of n (which should be total length of the message)
650  * and try again. */
651  iov.iov_len = n;
652  tmp = realloc(iov.iov_base, iov.iov_len);
653  if (!tmp) {
654  retval = -NLE_NOMEM;
655  goto abort;
656  }
657  iov.iov_base = tmp;
658  flags = 0;
659  goto retry;
660  }
661 
662  if (flags != 0) {
663  /* Buffer is big enough, do the actual reading */
664  flags = 0;
665  goto retry;
666  }
667 
668  if (msg.msg_namelen != sizeof(struct sockaddr_nl)) {
669  retval = -NLE_NOADDR;
670  goto abort;
671  }
672 
673  if (creds && (sk->s_flags & NL_SOCK_PASSCRED)) {
674  struct cmsghdr *cmsg;
675 
676  for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
677  if (cmsg->cmsg_level != SOL_SOCKET)
678  continue;
679  if (cmsg->cmsg_type != SCM_CREDENTIALS)
680  continue;
681  tmpcreds = malloc(sizeof(*tmpcreds));
682  if (!tmpcreds) {
683  retval = -NLE_NOMEM;
684  goto abort;
685  }
686  memcpy(tmpcreds, CMSG_DATA(cmsg), sizeof(*tmpcreds));
687  break;
688  }
689  }
690 
691  retval = n;
692 abort:
693  free(msg.msg_control);
694 
695  if (retval <= 0) {
696  free(iov.iov_base);
697  iov.iov_base = NULL;
698  free(tmpcreds);
699  tmpcreds = NULL;
700  } else
701  *buf = iov.iov_base;
702 
703  if (creds)
704  *creds = tmpcreds;
705 
706  return retval;
707 }
708 
709 /** @cond SKIP */
710 #define NL_CB_CALL(cb, type, msg) \
711 do { \
712  err = nl_cb_call(cb, type, msg); \
713  switch (err) { \
714  case NL_OK: \
715  err = 0; \
716  break; \
717  case NL_SKIP: \
718  goto skip; \
719  case NL_STOP: \
720  goto stop; \
721  default: \
722  goto out; \
723  } \
724 } while (0)
725 /** @endcond */
726 
727 static int recvmsgs(struct nl_sock *sk, struct nl_cb *cb)
728 {
729  int n, err = 0, multipart = 0, interrupted = 0, nrecv = 0;
730  unsigned char *buf = NULL;
731  struct nlmsghdr *hdr;
732 
733  /*
734  nla is passed on to not only to nl_recv() but may also be passed
735  to a function pointer provided by the caller which may or may not
736  initialize the variable. Thomas Graf.
737  */
738  struct sockaddr_nl nla = {0};
739  struct nl_msg *msg = NULL;
740  struct ucred *creds = NULL;
741 
742 continue_reading:
743  NL_DBG(3, "Attempting to read from %p\n", sk);
744  if (cb->cb_recv_ow)
745  n = cb->cb_recv_ow(sk, &nla, &buf, &creds);
746  else
747  n = nl_recv(sk, &nla, &buf, &creds);
748 
749  if (n <= 0)
750  return n;
751 
752  NL_DBG(3, "recvmsgs(%p): Read %d bytes\n", sk, n);
753 
754  hdr = (struct nlmsghdr *) buf;
755  while (nlmsg_ok(hdr, n)) {
756  NL_DBG(3, "recvmsgs(%p): Processing valid message...\n", sk);
757 
758  nlmsg_free(msg);
759  msg = nlmsg_convert(hdr);
760  if (!msg) {
761  err = -NLE_NOMEM;
762  goto out;
763  }
764 
765  nlmsg_set_proto(msg, sk->s_proto);
766  nlmsg_set_src(msg, &nla);
767  if (creds)
768  nlmsg_set_creds(msg, creds);
769 
770  nrecv++;
771 
772  /* Raw callback is the first, it gives the most control
773  * to the user and he can do his very own parsing. */
774  if (cb->cb_set[NL_CB_MSG_IN])
775  NL_CB_CALL(cb, NL_CB_MSG_IN, msg);
776 
777  /* Sequence number checking. The check may be done by
778  * the user, otherwise a very simple check is applied
779  * enforcing strict ordering */
780  if (cb->cb_set[NL_CB_SEQ_CHECK]) {
781  NL_CB_CALL(cb, NL_CB_SEQ_CHECK, msg);
782 
783  /* Only do sequence checking if auto-ack mode is enabled */
784  } else if (!(sk->s_flags & NL_NO_AUTO_ACK)) {
785  if (hdr->nlmsg_seq != sk->s_seq_expect) {
786  if (cb->cb_set[NL_CB_INVALID])
787  NL_CB_CALL(cb, NL_CB_INVALID, msg);
788  else {
789  err = -NLE_SEQ_MISMATCH;
790  goto out;
791  }
792  }
793  }
794 
795  if (hdr->nlmsg_type == NLMSG_DONE ||
796  hdr->nlmsg_type == NLMSG_ERROR ||
797  hdr->nlmsg_type == NLMSG_NOOP ||
798  hdr->nlmsg_type == NLMSG_OVERRUN) {
799  /* We can't check for !NLM_F_MULTI since some netlink
800  * users in the kernel are broken. */
801  sk->s_seq_expect++;
802  NL_DBG(3, "recvmsgs(%p): Increased expected " \
803  "sequence number to %d\n",
804  sk, sk->s_seq_expect);
805  }
806 
807  if (hdr->nlmsg_flags & NLM_F_MULTI)
808  multipart = 1;
809 
810  if (hdr->nlmsg_flags & NLM_F_DUMP_INTR) {
811  if (cb->cb_set[NL_CB_DUMP_INTR])
812  NL_CB_CALL(cb, NL_CB_DUMP_INTR, msg);
813  else {
814  /*
815  * We have to continue reading to clear
816  * all messages until a NLMSG_DONE is
817  * received and report the inconsistency.
818  */
819  interrupted = 1;
820  }
821  }
822 
823  /* Other side wishes to see an ack for this message */
824  if (hdr->nlmsg_flags & NLM_F_ACK) {
825  if (cb->cb_set[NL_CB_SEND_ACK])
826  NL_CB_CALL(cb, NL_CB_SEND_ACK, msg);
827  else {
828  /* FIXME: implement */
829  }
830  }
831 
832  /* messages terminates a multipart message, this is
833  * usually the end of a message and therefore we slip
834  * out of the loop by default. the user may overrule
835  * this action by skipping this packet. */
836  if (hdr->nlmsg_type == NLMSG_DONE) {
837  multipart = 0;
838  if (cb->cb_set[NL_CB_FINISH])
839  NL_CB_CALL(cb, NL_CB_FINISH, msg);
840  }
841 
842  /* Message to be ignored, the default action is to
843  * skip this message if no callback is specified. The
844  * user may overrule this action by returning
845  * NL_PROCEED. */
846  else if (hdr->nlmsg_type == NLMSG_NOOP) {
847  if (cb->cb_set[NL_CB_SKIPPED])
848  NL_CB_CALL(cb, NL_CB_SKIPPED, msg);
849  else
850  goto skip;
851  }
852 
853  /* Data got lost, report back to user. The default action is to
854  * quit parsing. The user may overrule this action by retuning
855  * NL_SKIP or NL_PROCEED (dangerous) */
856  else if (hdr->nlmsg_type == NLMSG_OVERRUN) {
857  if (cb->cb_set[NL_CB_OVERRUN])
858  NL_CB_CALL(cb, NL_CB_OVERRUN, msg);
859  else {
860  err = -NLE_MSG_OVERFLOW;
861  goto out;
862  }
863  }
864 
865  /* Message carries a nlmsgerr */
866  else if (hdr->nlmsg_type == NLMSG_ERROR) {
867  struct nlmsgerr *e = nlmsg_data(hdr);
868 
869  if (hdr->nlmsg_len < nlmsg_size(sizeof(*e))) {
870  /* Truncated error message, the default action
871  * is to stop parsing. The user may overrule
872  * this action by returning NL_SKIP or
873  * NL_PROCEED (dangerous) */
874  if (cb->cb_set[NL_CB_INVALID])
875  NL_CB_CALL(cb, NL_CB_INVALID, msg);
876  else {
877  err = -NLE_MSG_TRUNC;
878  goto out;
879  }
880  } else if (e->error) {
881  /* Error message reported back from kernel. */
882  if (cb->cb_err) {
883  err = cb->cb_err(&nla, e,
884  cb->cb_err_arg);
885  if (err < 0)
886  goto out;
887  else if (err == NL_SKIP)
888  goto skip;
889  else if (err == NL_STOP) {
890  err = -nl_syserr2nlerr(e->error);
891  goto out;
892  }
893  } else {
894  err = -nl_syserr2nlerr(e->error);
895  goto out;
896  }
897  } else if (cb->cb_set[NL_CB_ACK])
898  NL_CB_CALL(cb, NL_CB_ACK, msg);
899  } else {
900  /* Valid message (not checking for MULTIPART bit to
901  * get along with broken kernels. NL_SKIP has no
902  * effect on this. */
903  if (cb->cb_set[NL_CB_VALID])
904  NL_CB_CALL(cb, NL_CB_VALID, msg);
905  }
906 skip:
907  err = 0;
908  hdr = nlmsg_next(hdr, &n);
909  }
910 
911  nlmsg_free(msg);
912  free(buf);
913  free(creds);
914  buf = NULL;
915  msg = NULL;
916  creds = NULL;
917 
918  if (multipart) {
919  /* Multipart message not yet complete, continue reading */
920  goto continue_reading;
921  }
922 stop:
923  err = 0;
924 out:
925  nlmsg_free(msg);
926  free(buf);
927  free(creds);
928 
929  if (interrupted)
930  err = -NLE_DUMP_INTR;
931 
932  if (!err)
933  err = nrecv;
934 
935  return err;
936 }
937 
938 /**
939  * Receive a set of messages from a netlink socket and report parsed messages
940  * @arg sk Netlink socket.
941  * @arg cb set of callbacks to control behaviour.
942  *
943  * This function is identical to nl_recvmsgs() to the point that it will
944  * return the number of parsed messages instead of 0 on success.
945  *
946  * @see nl_recvmsgs()
947  *
948  * @return Number of received messages or a negative error code from nl_recv().
949  */
950 int nl_recvmsgs_report(struct nl_sock *sk, struct nl_cb *cb)
951 {
952  if (cb->cb_recvmsgs_ow)
953  return cb->cb_recvmsgs_ow(sk, cb);
954  else
955  return recvmsgs(sk, cb);
956 }
957 
958 /**
959  * Receive a set of messages from a netlink socket.
960  * @arg sk Netlink socket.
961  * @arg cb set of callbacks to control behaviour.
962  *
963  * Repeatedly calls nl_recv() or the respective replacement if provided
964  * by the application (see nl_cb_overwrite_recv()) and parses the
965  * received data as netlink messages. Stops reading if one of the
966  * callbacks returns NL_STOP or nl_recv returns either 0 or a negative error code.
967  *
968  * A non-blocking sockets causes the function to return immediately if
969  * no data is available.
970  *
971  * @see nl_recvmsgs_report()
972  *
973  * @return 0 on success or a negative error code from nl_recv().
974  */
975 int nl_recvmsgs(struct nl_sock *sk, struct nl_cb *cb)
976 {
977  int err;
978 
979  if ((err = nl_recvmsgs_report(sk, cb)) > 0)
980  err = 0;
981 
982  return err;
983 }
984 
985 /**
986  * Receive a set of message from a netlink socket using handlers in nl_sock.
987  * @arg sk Netlink socket.
988  *
989  * Calls nl_recvmsgs() with the handlers configured in the netlink socket.
990  */
991 int nl_recvmsgs_default(struct nl_sock *sk)
992 {
993  return nl_recvmsgs(sk, sk->s_cb);
994 
995 }
996 
997 static int ack_wait_handler(struct nl_msg *msg, void *arg)
998 {
999  return NL_STOP;
1000 }
1001 
1002 /**
1003  * Wait for ACK.
1004  * @arg sk Netlink socket.
1005  * @pre The netlink socket must be in blocking state.
1006  *
1007  * Waits until an ACK is received for the latest not yet acknowledged
1008  * netlink message.
1009  */
1010 int nl_wait_for_ack(struct nl_sock *sk)
1011 {
1012  int err;
1013  struct nl_cb *cb;
1014 
1015  cb = nl_cb_clone(sk->s_cb);
1016  if (cb == NULL)
1017  return -NLE_NOMEM;
1018 
1019  nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ack_wait_handler, NULL);
1020  err = nl_recvmsgs(sk, cb);
1021  nl_cb_put(cb);
1022 
1023  return err;
1024 }
1025 
1026 /** @cond SKIP */
1027 struct pickup_param
1028 {
1029  int (*parser)(struct nl_cache_ops *, struct sockaddr_nl *,
1030  struct nlmsghdr *, struct nl_parser_param *);
1031  struct nl_object *result;
1032 };
1033 
1034 static int __store_answer(struct nl_object *obj, struct nl_parser_param *p)
1035 {
1036  struct pickup_param *pp = p->pp_arg;
1037  /*
1038  * the parser will put() the object at the end, expecting the cache
1039  * to take the reference.
1040  */
1041  nl_object_get(obj);
1042  pp->result = obj;
1043 
1044  return 0;
1045 }
1046 
1047 static int __pickup_answer(struct nl_msg *msg, void *arg)
1048 {
1049  struct pickup_param *pp = arg;
1050  struct nl_parser_param parse_arg = {
1051  .pp_cb = __store_answer,
1052  .pp_arg = pp,
1053  };
1054 
1055  return pp->parser(NULL, &msg->nm_src, msg->nm_nlh, &parse_arg);
1056 }
1057 
1058 /** @endcond */
1059 
1060 /**
1061  * Pickup netlink answer, parse is and return object
1062  * @arg sk Netlink socket
1063  * @arg parser Parser function to parse answer
1064  * @arg result Result pointer to return parsed object
1065  *
1066  * @return 0 on success or a negative error code.
1067  */
1068 int nl_pickup(struct nl_sock *sk,
1069  int (*parser)(struct nl_cache_ops *, struct sockaddr_nl *,
1070  struct nlmsghdr *, struct nl_parser_param *),
1071  struct nl_object **result)
1072 {
1073  struct nl_cb *cb;
1074  int err;
1075  struct pickup_param pp = {
1076  .parser = parser,
1077  };
1078 
1079  cb = nl_cb_clone(sk->s_cb);
1080  if (cb == NULL)
1081  return -NLE_NOMEM;
1082 
1083  nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, __pickup_answer, &pp);
1084 
1085  err = nl_recvmsgs(sk, cb);
1086  if (err < 0)
1087  goto errout;
1088 
1089  *result = pp.result;
1090 errout:
1091  nl_cb_put(cb);
1092 
1093  return err;
1094 }
1095 
1096 /** @} */
1097 
1098 /**
1099  * @name Deprecated
1100  * @{
1101  */
1102 
1103 /**
1104  * @deprecated Please use nl_complete_msg()
1105  */
1106 void nl_auto_complete(struct nl_sock *sk, struct nl_msg *msg)
1107 {
1108  nl_complete_msg(sk, msg);
1109 }
1110 
1111 /**
1112  * @deprecated Please use nl_send_auto()
1113  */
1114 int nl_send_auto_complete(struct nl_sock *sk, struct nl_msg *msg)
1115 {
1116  return nl_send_auto(sk, msg);
1117 }
1118 
1119 
1120 /** @} */
1121 
1122 /** @} */
1123 
1124 /** @} */