libnl  3.2.21
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();
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  if (errno == EAGAIN || errno == EWOULDBLOCK) {
631  NL_DBG(3, "recvmsg() returned EAGAIN||EWOULDBLOCK, aborting\n");
632  retval = 0;
633  goto abort;
634  }
635  retval = -nl_syserr2nlerr(errno);
636  goto abort;
637  }
638 
639  if (msg.msg_flags & MSG_CTRUNC) {
640  void *tmp;
641  msg.msg_controllen *= 2;
642  tmp = realloc(msg.msg_control, msg.msg_controllen);
643  if (!tmp) {
644  retval = -NLE_NOMEM;
645  goto abort;
646  }
647  msg.msg_control = tmp;
648  goto retry;
649  }
650 
651  if (iov.iov_len < n || (msg.msg_flags & MSG_TRUNC)) {
652  void *tmp;
653  /* Provided buffer is not long enough, enlarge it
654  * to size of n (which should be total length of the message)
655  * and try again. */
656  iov.iov_len = n;
657  tmp = realloc(iov.iov_base, iov.iov_len);
658  if (!tmp) {
659  retval = -NLE_NOMEM;
660  goto abort;
661  }
662  iov.iov_base = tmp;
663  flags = 0;
664  goto retry;
665  }
666 
667  if (flags != 0) {
668  /* Buffer is big enough, do the actual reading */
669  flags = 0;
670  goto retry;
671  }
672 
673  if (msg.msg_namelen != sizeof(struct sockaddr_nl)) {
674  retval = -NLE_NOADDR;
675  goto abort;
676  }
677 
678  if (creds && (sk->s_flags & NL_SOCK_PASSCRED)) {
679  struct cmsghdr *cmsg;
680 
681  for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
682  if (cmsg->cmsg_level != SOL_SOCKET)
683  continue;
684  if (cmsg->cmsg_type != SCM_CREDENTIALS)
685  continue;
686  tmpcreds = malloc(sizeof(*tmpcreds));
687  if (!tmpcreds) {
688  retval = -NLE_NOMEM;
689  goto abort;
690  }
691  memcpy(tmpcreds, CMSG_DATA(cmsg), sizeof(*tmpcreds));
692  break;
693  }
694  }
695 
696  retval = n;
697 abort:
698  free(msg.msg_control);
699 
700  if (retval <= 0) {
701  free(iov.iov_base);
702  iov.iov_base = NULL;
703  free(tmpcreds);
704  tmpcreds = NULL;
705  } else
706  *buf = iov.iov_base;
707 
708  if (creds)
709  *creds = tmpcreds;
710 
711  return retval;
712 }
713 
714 /** @cond SKIP */
715 #define NL_CB_CALL(cb, type, msg) \
716 do { \
717  err = nl_cb_call(cb, type, msg); \
718  switch (err) { \
719  case NL_OK: \
720  err = 0; \
721  break; \
722  case NL_SKIP: \
723  goto skip; \
724  case NL_STOP: \
725  goto stop; \
726  default: \
727  goto out; \
728  } \
729 } while (0)
730 /** @endcond */
731 
732 static int recvmsgs(struct nl_sock *sk, struct nl_cb *cb)
733 {
734  int n, err = 0, multipart = 0, interrupted = 0, nrecv = 0;
735  unsigned char *buf = NULL;
736  struct nlmsghdr *hdr;
737 
738  /*
739  nla is passed on to not only to nl_recv() but may also be passed
740  to a function pointer provided by the caller which may or may not
741  initialize the variable. Thomas Graf.
742  */
743  struct sockaddr_nl nla = {0};
744  struct nl_msg *msg = NULL;
745  struct ucred *creds = NULL;
746 
747 continue_reading:
748  NL_DBG(3, "Attempting to read from %p\n", sk);
749  if (cb->cb_recv_ow)
750  n = cb->cb_recv_ow(sk, &nla, &buf, &creds);
751  else
752  n = nl_recv(sk, &nla, &buf, &creds);
753 
754  if (n <= 0)
755  return n;
756 
757  NL_DBG(3, "recvmsgs(%p): Read %d bytes\n", sk, n);
758 
759  hdr = (struct nlmsghdr *) buf;
760  while (nlmsg_ok(hdr, n)) {
761  NL_DBG(3, "recvmsgs(%p): Processing valid message...\n", sk);
762 
763  nlmsg_free(msg);
764  msg = nlmsg_convert(hdr);
765  if (!msg) {
766  err = -NLE_NOMEM;
767  goto out;
768  }
769 
770  nlmsg_set_proto(msg, sk->s_proto);
771  nlmsg_set_src(msg, &nla);
772  if (creds)
773  nlmsg_set_creds(msg, creds);
774 
775  nrecv++;
776 
777  /* Raw callback is the first, it gives the most control
778  * to the user and he can do his very own parsing. */
779  if (cb->cb_set[NL_CB_MSG_IN])
780  NL_CB_CALL(cb, NL_CB_MSG_IN, msg);
781 
782  /* Sequence number checking. The check may be done by
783  * the user, otherwise a very simple check is applied
784  * enforcing strict ordering */
785  if (cb->cb_set[NL_CB_SEQ_CHECK]) {
786  NL_CB_CALL(cb, NL_CB_SEQ_CHECK, msg);
787 
788  /* Only do sequence checking if auto-ack mode is enabled */
789  } else if (!(sk->s_flags & NL_NO_AUTO_ACK)) {
790  if (hdr->nlmsg_seq != sk->s_seq_expect) {
791  if (cb->cb_set[NL_CB_INVALID])
792  NL_CB_CALL(cb, NL_CB_INVALID, msg);
793  else {
794  err = -NLE_SEQ_MISMATCH;
795  goto out;
796  }
797  }
798  }
799 
800  if (hdr->nlmsg_type == NLMSG_DONE ||
801  hdr->nlmsg_type == NLMSG_ERROR ||
802  hdr->nlmsg_type == NLMSG_NOOP ||
803  hdr->nlmsg_type == NLMSG_OVERRUN) {
804  /* We can't check for !NLM_F_MULTI since some netlink
805  * users in the kernel are broken. */
806  sk->s_seq_expect++;
807  NL_DBG(3, "recvmsgs(%p): Increased expected " \
808  "sequence number to %d\n",
809  sk, sk->s_seq_expect);
810  }
811 
812  if (hdr->nlmsg_flags & NLM_F_MULTI)
813  multipart = 1;
814 
815  if (hdr->nlmsg_flags & NLM_F_DUMP_INTR) {
816  if (cb->cb_set[NL_CB_DUMP_INTR])
817  NL_CB_CALL(cb, NL_CB_DUMP_INTR, msg);
818  else {
819  /*
820  * We have to continue reading to clear
821  * all messages until a NLMSG_DONE is
822  * received and report the inconsistency.
823  */
824  interrupted = 1;
825  }
826  }
827 
828  /* Other side wishes to see an ack for this message */
829  if (hdr->nlmsg_flags & NLM_F_ACK) {
830  if (cb->cb_set[NL_CB_SEND_ACK])
831  NL_CB_CALL(cb, NL_CB_SEND_ACK, msg);
832  else {
833  /* FIXME: implement */
834  }
835  }
836 
837  /* messages terminates a multpart message, this is
838  * usually the end of a message and therefore we slip
839  * out of the loop by default. the user may overrule
840  * this action by skipping this packet. */
841  if (hdr->nlmsg_type == NLMSG_DONE) {
842  multipart = 0;
843  if (cb->cb_set[NL_CB_FINISH])
844  NL_CB_CALL(cb, NL_CB_FINISH, msg);
845  }
846 
847  /* Message to be ignored, the default action is to
848  * skip this message if no callback is specified. The
849  * user may overrule this action by returning
850  * NL_PROCEED. */
851  else if (hdr->nlmsg_type == NLMSG_NOOP) {
852  if (cb->cb_set[NL_CB_SKIPPED])
853  NL_CB_CALL(cb, NL_CB_SKIPPED, msg);
854  else
855  goto skip;
856  }
857 
858  /* Data got lost, report back to user. The default action is to
859  * quit parsing. The user may overrule this action by retuning
860  * NL_SKIP or NL_PROCEED (dangerous) */
861  else if (hdr->nlmsg_type == NLMSG_OVERRUN) {
862  if (cb->cb_set[NL_CB_OVERRUN])
863  NL_CB_CALL(cb, NL_CB_OVERRUN, msg);
864  else {
865  err = -NLE_MSG_OVERFLOW;
866  goto out;
867  }
868  }
869 
870  /* Message carries a nlmsgerr */
871  else if (hdr->nlmsg_type == NLMSG_ERROR) {
872  struct nlmsgerr *e = nlmsg_data(hdr);
873 
874  if (hdr->nlmsg_len < nlmsg_size(sizeof(*e))) {
875  /* Truncated error message, the default action
876  * is to stop parsing. The user may overrule
877  * this action by returning NL_SKIP or
878  * NL_PROCEED (dangerous) */
879  if (cb->cb_set[NL_CB_INVALID])
880  NL_CB_CALL(cb, NL_CB_INVALID, msg);
881  else {
882  err = -NLE_MSG_TRUNC;
883  goto out;
884  }
885  } else if (e->error) {
886  /* Error message reported back from kernel. */
887  if (cb->cb_err) {
888  err = cb->cb_err(&nla, e,
889  cb->cb_err_arg);
890  if (err < 0)
891  goto out;
892  else if (err == NL_SKIP)
893  goto skip;
894  else if (err == NL_STOP) {
895  err = -nl_syserr2nlerr(e->error);
896  goto out;
897  }
898  } else {
899  err = -nl_syserr2nlerr(e->error);
900  goto out;
901  }
902  } else if (cb->cb_set[NL_CB_ACK])
903  NL_CB_CALL(cb, NL_CB_ACK, msg);
904  } else {
905  /* Valid message (not checking for MULTIPART bit to
906  * get along with broken kernels. NL_SKIP has no
907  * effect on this. */
908  if (cb->cb_set[NL_CB_VALID])
909  NL_CB_CALL(cb, NL_CB_VALID, msg);
910  }
911 skip:
912  err = 0;
913  hdr = nlmsg_next(hdr, &n);
914  }
915 
916  nlmsg_free(msg);
917  free(buf);
918  free(creds);
919  buf = NULL;
920  msg = NULL;
921  creds = NULL;
922 
923  if (multipart) {
924  /* Multipart message not yet complete, continue reading */
925  goto continue_reading;
926  }
927 stop:
928  err = 0;
929 out:
930  nlmsg_free(msg);
931  free(buf);
932  free(creds);
933 
934  if (interrupted)
935  err = -NLE_DUMP_INTR;
936 
937  if (!err)
938  err = nrecv;
939 
940  return err;
941 }
942 
943 /**
944  * Receive a set of messages from a netlink socket and report parsed messages
945  * @arg sk Netlink socket.
946  * @arg cb set of callbacks to control behaviour.
947  *
948  * This function is identical to nl_recvmsgs() to the point that it will
949  * return the number of parsed messages instead of 0 on success.
950  *
951  * @see nl_recvmsgs()
952  *
953  * @return Number of received messages or a negative error code from nl_recv().
954  */
955 int nl_recvmsgs_report(struct nl_sock *sk, struct nl_cb *cb)
956 {
957  if (cb->cb_recvmsgs_ow)
958  return cb->cb_recvmsgs_ow(sk, cb);
959  else
960  return recvmsgs(sk, cb);
961 }
962 
963 /**
964  * Receive a set of messages from a netlink socket.
965  * @arg sk Netlink socket.
966  * @arg cb set of callbacks to control behaviour.
967  *
968  * Repeatedly calls nl_recv() or the respective replacement if provided
969  * by the application (see nl_cb_overwrite_recv()) and parses the
970  * received data as netlink messages. Stops reading if one of the
971  * callbacks returns NL_STOP or nl_recv returns either 0 or a negative error code.
972  *
973  * A non-blocking sockets causes the function to return immediately if
974  * no data is available.
975  *
976  * @see nl_recvmsgs_report()
977  *
978  * @return 0 on success or a negative error code from nl_recv().
979  */
980 int nl_recvmsgs(struct nl_sock *sk, struct nl_cb *cb)
981 {
982  int err;
983 
984  if ((err = nl_recvmsgs_report(sk, cb)) > 0)
985  err = 0;
986 
987  return err;
988 }
989 
990 /**
991  * Receive a set of message from a netlink socket using handlers in nl_sock.
992  * @arg sk Netlink socket.
993  *
994  * Calls nl_recvmsgs() with the handlers configured in the netlink socket.
995  */
996 int nl_recvmsgs_default(struct nl_sock *sk)
997 {
998  return nl_recvmsgs(sk, sk->s_cb);
999 
1000 }
1001 
1002 static int ack_wait_handler(struct nl_msg *msg, void *arg)
1003 {
1004  return NL_STOP;
1005 }
1006 
1007 /**
1008  * Wait for ACK.
1009  * @arg sk Netlink socket.
1010  * @pre The netlink socket must be in blocking state.
1011  *
1012  * Waits until an ACK is received for the latest not yet acknowledged
1013  * netlink message.
1014  */
1015 int nl_wait_for_ack(struct nl_sock *sk)
1016 {
1017  int err;
1018  struct nl_cb *cb;
1019 
1020  cb = nl_cb_clone(sk->s_cb);
1021  if (cb == NULL)
1022  return -NLE_NOMEM;
1023 
1024  nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ack_wait_handler, NULL);
1025  err = nl_recvmsgs(sk, cb);
1026  nl_cb_put(cb);
1027 
1028  return err;
1029 }
1030 
1031 /** @cond SKIP */
1032 struct pickup_param
1033 {
1034  int (*parser)(struct nl_cache_ops *, struct sockaddr_nl *,
1035  struct nlmsghdr *, struct nl_parser_param *);
1036  struct nl_object *result;
1037 };
1038 
1039 static int __store_answer(struct nl_object *obj, struct nl_parser_param *p)
1040 {
1041  struct pickup_param *pp = p->pp_arg;
1042  /*
1043  * the parser will put() the object at the end, expecting the cache
1044  * to take the reference.
1045  */
1046  nl_object_get(obj);
1047  pp->result = obj;
1048 
1049  return 0;
1050 }
1051 
1052 static int __pickup_answer(struct nl_msg *msg, void *arg)
1053 {
1054  struct pickup_param *pp = arg;
1055  struct nl_parser_param parse_arg = {
1056  .pp_cb = __store_answer,
1057  .pp_arg = pp,
1058  };
1059 
1060  return pp->parser(NULL, &msg->nm_src, msg->nm_nlh, &parse_arg);
1061 }
1062 
1063 /** @endcond */
1064 
1065 /**
1066  * Pickup netlink answer, parse is and return object
1067  * @arg sk Netlink socket
1068  * @arg parser Parser function to parse answer
1069  * @arg result Result pointer to return parsed object
1070  *
1071  * @return 0 on success or a negative error code.
1072  */
1073 int nl_pickup(struct nl_sock *sk,
1074  int (*parser)(struct nl_cache_ops *, struct sockaddr_nl *,
1075  struct nlmsghdr *, struct nl_parser_param *),
1076  struct nl_object **result)
1077 {
1078  struct nl_cb *cb;
1079  int err;
1080  struct pickup_param pp = {
1081  .parser = parser,
1082  };
1083 
1084  cb = nl_cb_clone(sk->s_cb);
1085  if (cb == NULL)
1086  return -NLE_NOMEM;
1087 
1088  nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, __pickup_answer, &pp);
1089 
1090  err = nl_recvmsgs(sk, cb);
1091  if (err < 0)
1092  goto errout;
1093 
1094  *result = pp.result;
1095 errout:
1096  nl_cb_put(cb);
1097 
1098  return err;
1099 }
1100 
1101 /** @} */
1102 
1103 /**
1104  * @name Deprecated
1105  * @{
1106  */
1107 
1108 /**
1109  * @deprecated Please use nl_complete_msg()
1110  */
1111 void nl_auto_complete(struct nl_sock *sk, struct nl_msg *msg)
1112 {
1113  nl_complete_msg(sk, msg);
1114 }
1115 
1116 /**
1117  * @deprecated Please use nl_send_auto()
1118  */
1119 int nl_send_auto_complete(struct nl_sock *sk, struct nl_msg *msg)
1120 {
1121  return nl_send_auto(sk, msg);
1122 }
1123 
1124 
1125 /** @} */
1126 
1127 /** @} */
1128 
1129 /** @} */