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