• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* SPDX-License-Identifier: LGPL-2.1-only */
2 /*
3  * lib/socket.c		Netlink Socket
4  *
5  *	This library is free software; you can redistribute it and/or
6  *	modify it under the terms of the GNU Lesser General Public
7  *	License as published by the Free Software Foundation version 2.1
8  *	of the License.
9  *
10  * Copyright (c) 2003-2012 Thomas Graf <tgraf@suug.ch>
11  */
12 
13 /**
14  * @ingroup core_types
15  * @defgroup socket Socket
16  *
17  * Representation of a netlink socket
18  *
19  * Related sections in the development guide:
20  * - @core_doc{core_sockets, Netlink Sockets}
21  *
22  * @{
23  *
24  * Header
25  * ------
26  * ~~~~{.c}
27  * #include <netlink/socket.h>
28  * ~~~~
29  */
30 
31 #include "defs.h"
32 
33 #include "sys/socket.h"
34 
35 #include <netlink-private/netlink.h>
36 #include <netlink-private/socket.h>
37 #include <netlink-private/utils.h>
38 #include <netlink/netlink.h>
39 #include <netlink/utils.h>
40 #include <netlink/handlers.h>
41 #include <netlink/msg.h>
42 #include <netlink/attr.h>
43 
44 static int default_cb = NL_CB_DEFAULT;
45 
init_default_cb(void)46 static void __init init_default_cb(void)
47 {
48 	char *nlcb;
49 
50 	if ((nlcb = getenv("NLCB"))) {
51 		if (!strcasecmp(nlcb, "default"))
52 			default_cb = NL_CB_DEFAULT;
53 		else if (!strcasecmp(nlcb, "verbose"))
54 			default_cb = NL_CB_VERBOSE;
55 		else if (!strcasecmp(nlcb, "debug"))
56 			default_cb = NL_CB_DEBUG;
57 		else {
58 			fprintf(stderr, "Unknown value for NLCB, valid values: "
59 				"{default | verbose | debug}\n");
60 		}
61 	}
62 }
63 
64 static uint32_t used_ports_map[32];
65 static NL_RW_LOCK(port_map_lock);
66 
generate_local_port(void)67 static uint32_t generate_local_port(void)
68 {
69 	int i, j, n, m;
70 	static uint16_t idx_state = 0;
71 	uint32_t pid = getpid() & 0x3FFFFF;
72 
73 	nl_write_lock(&port_map_lock);
74 
75 	if (idx_state == 0) {
76 		uint32_t t = time(NULL);
77 
78 		/* from time to time (on average each 2^15 calls), the idx_state will
79 		 * be zero again. No problem, just "seed" anew with time(). */
80 		idx_state = t ^ (t >> 16) ^ 0x3047;
81 	} else
82 		idx_state = idx_state + 20011; /* add prime number */
83 
84 	i = idx_state >> 5;
85 	n = idx_state;
86 	for (j = 0; j < 32; j++) {
87 		/* walk the index somewhat randomized, with always leaving the block
88 		 * #0 as last. The reason is that libnl-1 will start at block #0,
89 		 * so just leave the first 32 ports preferably for libnl-1 owned sockets
90 		 * (this is relevant only if the applications ends up using both versions
91 		 * of the library and doesn't hurt otherwise). */
92 		if (j == 31)
93 			i = 0;
94 		else
95 			i = (((i-1) + 7) % 31) + 1;
96 
97 		if (used_ports_map[i] == 0xFFFFFFFF)
98 			continue;
99 
100 		for (m = 0; m < 32; m++) {
101 			n = (n + 13) % 32;
102 			if (1UL & (used_ports_map[i] >> n))
103 				continue;
104 
105 			used_ports_map[i] |= (1UL << n);
106 			n += (i * 32);
107 
108 			/* PID_MAX_LIMIT is currently at 2^22, leaving 10 bit
109 			 * to, i.e. 1024 unique ports per application. */
110 
111 			nl_write_unlock(&port_map_lock);
112 
113 			/* ensure we don't return zero. */
114 			pid = pid + (((uint32_t)n) << 22);
115 			return pid ? pid : 1024;
116 		}
117 	}
118 
119 	nl_write_unlock(&port_map_lock);
120 	return 0;
121 }
122 
release_local_port(uint32_t port)123 static void release_local_port(uint32_t port)
124 {
125 	int nr;
126 	uint32_t mask;
127 
128 	BUG_ON(port == 0);
129 
130 	nr = port >> 22;
131 	mask = 1UL << (nr % 32);
132 	nr /= 32;
133 
134 	nl_write_lock(&port_map_lock);
135 	BUG_ON((used_ports_map[nr] & mask) != mask);
136 	used_ports_map[nr] &= ~mask;
137 	nl_write_unlock(&port_map_lock);
138 }
139 
140 /** \cond skip */
_nl_socket_used_ports_release_all(const uint32_t * used_ports)141 void _nl_socket_used_ports_release_all(const uint32_t *used_ports)
142 {
143 	int i;
144 
145 	for (i = 0; i < 32; i++) {
146 		if (used_ports[i] != 0) {
147 			nl_write_lock(&port_map_lock);
148 			for (; i < 32; i++) {
149 				BUG_ON((used_ports_map[i] & used_ports[i]) != used_ports[i]);
150 				used_ports_map[i] &= ~(used_ports[i]);
151 			}
152 			nl_write_unlock(&port_map_lock);
153 			return;
154 		}
155 	}
156 }
157 
_nl_socket_used_ports_set(uint32_t * used_ports,uint32_t port)158 void _nl_socket_used_ports_set(uint32_t *used_ports, uint32_t port)
159 {
160 	int nr;
161 	int32_t mask;
162 
163 	nr = port >> 22;
164 	mask = 1UL << (nr % 32);
165 	nr /= 32;
166 
167 	/*
168 	BUG_ON(port == 0 || (getpid() & 0x3FFFFF) != (port & 0x3FFFFF));
169 	BUG_ON(used_ports[nr] & mask);
170 	*/
171 
172 	used_ports[nr] |= mask;
173 }
174 /** \endcond */
175 
176 /**
177  * @name Allocation
178  * @{
179  */
180 
__alloc_socket(struct nl_cb * cb)181 static struct nl_sock *__alloc_socket(struct nl_cb *cb)
182 {
183 	struct nl_sock *sk;
184 
185 	sk = calloc(1, sizeof(*sk));
186 	if (!sk)
187 		return NULL;
188 
189 	sk->s_fd = -1;
190 	sk->s_cb = nl_cb_get(cb);
191 	sk->s_local.nl_family = AF_NETLINK;
192 	sk->s_peer.nl_family = AF_NETLINK;
193 	sk->s_seq_expect = sk->s_seq_next = time(NULL);
194 
195 	/* the port is 0 (unspecified), meaning NL_OWN_PORT */
196 	sk->s_flags = NL_OWN_PORT;
197 
198 	return sk;
199 }
200 
201 /**
202  * Allocate new netlink socket
203  *
204  * @return Newly allocated netlink socket or NULL.
205  */
nl_socket_alloc(void)206 struct nl_sock *nl_socket_alloc(void)
207 {
208 	struct nl_cb *cb;
209 	struct nl_sock *sk;
210 
211 	cb = nl_cb_alloc(default_cb);
212 	if (!cb)
213 		return NULL;
214 
215 	/* will increment cb reference count on success */
216 	sk = __alloc_socket(cb);
217 
218 	nl_cb_put(cb);
219 
220 	return sk;
221 }
222 
223 /**
224  * Allocate new socket with custom callbacks
225  * @arg cb		Callback handler
226  *
227  * The reference to the callback handler is taken into account
228  * automatically, it is released again upon calling nl_socket_free().
229  *
230  *@return Newly allocted socket handle or NULL.
231  */
nl_socket_alloc_cb(struct nl_cb * cb)232 struct nl_sock *nl_socket_alloc_cb(struct nl_cb *cb)
233 {
234 	if (cb == NULL)
235 		BUG();
236 
237 	return __alloc_socket(cb);
238 }
239 
240 /**
241  * Free a netlink socket.
242  * @arg sk		Netlink socket.
243  */
nl_socket_free(struct nl_sock * sk)244 void nl_socket_free(struct nl_sock *sk)
245 {
246 	if (!sk)
247 		return;
248 
249 	if (sk->s_fd >= 0)
250 		close(sk->s_fd);
251 
252 	if (!(sk->s_flags & NL_OWN_PORT))
253 		release_local_port(sk->s_local.nl_pid);
254 
255 	nl_cb_put(sk->s_cb);
256 	free(sk);
257 }
258 
259 /** @} */
260 
261 /**
262  * @name Sequence Numbers
263  * @{
264  */
265 
noop_seq_check(struct nl_msg * msg,void * arg)266 static int noop_seq_check(struct nl_msg *msg, void *arg)
267 {
268 	return NL_OK;
269 }
270 
271 
272 /**
273  * Disable sequence number checking.
274  * @arg sk		Netlink socket.
275  *
276  * Disables checking of sequence numbers on the netlink socket This is
277  * required to allow messages to be processed which were not requested by
278  * a preceding request message, e.g. netlink events.
279  *
280  * @note This function modifies the NL_CB_SEQ_CHECK configuration in
281  * the callback handle associated with the socket.
282  */
nl_socket_disable_seq_check(struct nl_sock * sk)283 void nl_socket_disable_seq_check(struct nl_sock *sk)
284 {
285 	nl_cb_set(sk->s_cb, NL_CB_SEQ_CHECK,
286 		  NL_CB_CUSTOM, noop_seq_check, NULL);
287 }
288 
289 /**
290  * Use next sequence number
291  * @arg sk		Netlink socket.
292  *
293  * Uses the next available sequence number and increases the counter
294  * by one for subsequent calls.
295  *
296  * @return Unique serial sequence number
297  */
nl_socket_use_seq(struct nl_sock * sk)298 unsigned int nl_socket_use_seq(struct nl_sock *sk)
299 {
300 	return sk->s_seq_next++;
301 }
302 
303 /**
304  * Disable automatic request for ACK
305  * @arg sk		Netlink socket.
306  *
307  * The default behaviour of a socket is to request an ACK for
308  * each message sent to allow for the caller to synchronize to
309  * the completion of the netlink operation. This function
310  * disables this behaviour and will result in requests being
311  * sent which will not have the NLM_F_ACK flag set automatically.
312  * However, it is still possible for the caller to set the
313  * NLM_F_ACK flag explicitely.
314  */
nl_socket_disable_auto_ack(struct nl_sock * sk)315 void nl_socket_disable_auto_ack(struct nl_sock *sk)
316 {
317 	sk->s_flags |= NL_NO_AUTO_ACK;
318 }
319 
320 /**
321  * Enable automatic request for ACK (default)
322  * @arg sk		Netlink socket.
323  * @see nl_socket_disable_auto_ack
324  */
nl_socket_enable_auto_ack(struct nl_sock * sk)325 void nl_socket_enable_auto_ack(struct nl_sock *sk)
326 {
327 	sk->s_flags &= ~NL_NO_AUTO_ACK;
328 }
329 
330 /** @} */
331 
332 /** \cond skip */
_nl_socket_is_local_port_unspecified(struct nl_sock * sk)333 int _nl_socket_is_local_port_unspecified(struct nl_sock *sk)
334 {
335 	return (sk->s_local.nl_pid == 0);
336 }
337 
_nl_socket_set_local_port_no_release(struct nl_sock * sk,int generate_other)338 uint32_t _nl_socket_set_local_port_no_release(struct nl_sock *sk, int generate_other)
339 {
340 	uint32_t port;
341 
342 	/* reset the port to generate_local_port(), but do not release
343 	 * the previously generated port. */
344 
345 	if (generate_other)
346 		port = generate_local_port();
347 	else
348 		port = 0;
349 	sk->s_local.nl_pid = port;
350 	if (port == 0) {
351 		/* failed to find an unsed port. Restore the socket to have an
352 		 * unspecified port. */
353 		sk->s_flags |= NL_OWN_PORT;
354 	} else
355 		sk->s_flags &= ~NL_OWN_PORT;
356 	return port;
357 }
358 /** \endcond */
359 
360 /**
361  * @name Source Idenficiation
362  * @{
363  */
364 
nl_socket_get_local_port(const struct nl_sock * sk)365 uint32_t nl_socket_get_local_port(const struct nl_sock *sk)
366 {
367 	if (sk->s_local.nl_pid == 0) {
368 		struct nl_sock *sk_mutable = (struct nl_sock *) sk;
369 
370 		/* modify the const argument sk. This is justified, because
371 		 * nobody ever saw the local_port from externally. So, we
372 		 * initilize it on first use.
373 		 *
374 		 * Note that this also means that you cannot call this function
375 		 * from multiple threads without synchronization. But nl_sock
376 		 * is not automatically threadsafe anyway, so the user is not
377 		 * allowed to do that.
378 		 */
379 		sk_mutable->s_local.nl_pid = generate_local_port();
380 		if (sk_mutable->s_local.nl_pid == 0) {
381 			/* could not generate a local port. Assign UINT32_MAX to preserve
382 			 * backward compatibility. A user who cares can clear that anyway
383 			 * with nl_socket_set_local_port(). */
384 			sk_mutable->s_local.nl_pid = UINT32_MAX;
385 			sk_mutable->s_flags |= NL_OWN_PORT;
386 		} else
387 			sk_mutable->s_flags &= ~NL_OWN_PORT;
388 	}
389 	return sk->s_local.nl_pid;
390 }
391 
392 /**
393  * Set local port of socket
394  * @arg sk		Netlink socket.
395  * @arg port		Local port identifier
396  *
397  * Assigns a local port identifier to the socket.
398  *
399  * If port is 0, the port is reset to 'unspecified' as it is after newly
400  * calling nl_socket_alloc().
401  * Unspecified means, that the port will be generated automatically later
402  * on first use (either on nl_socket_get_local_port() or nl_connect()).
403  */
nl_socket_set_local_port(struct nl_sock * sk,uint32_t port)404 void nl_socket_set_local_port(struct nl_sock *sk, uint32_t port)
405 {
406 	if (!(sk->s_flags & NL_OWN_PORT))
407 		release_local_port(sk->s_local.nl_pid);
408 	sk->s_flags |= NL_OWN_PORT;
409 	sk->s_local.nl_pid = port;
410 }
411 
412 /** @} */
413 
414 /**
415  * @name Group Subscriptions
416  * @{
417  */
418 
419 /**
420  * Join groups
421  * @arg sk		Netlink socket
422  * @arg group		Group identifier
423  *
424  * Joins the specified groups using the modern socket option which
425  * is available since kernel version 2.6.14. It allows joining an
426  * almost arbitary number of groups without limitation.  The list
427  * of groups has to be terminated by 0 (%NFNLGRP_NONE).
428  *
429  * Make sure to use the correct group definitions as the older
430  * bitmask definitions for nl_join_groups() are likely to still
431  * be present for backward compatibility reasons.
432  *
433  * @return 0 on sucess or a negative error code.
434  */
nl_socket_add_memberships(struct nl_sock * sk,int group,...)435 int nl_socket_add_memberships(struct nl_sock *sk, int group, ...)
436 {
437 	int err;
438 	va_list ap;
439 
440 	if (sk->s_fd == -1)
441 		return -NLE_BAD_SOCK;
442 
443 	va_start(ap, group);
444 
445 	while (group != 0) {
446 		if (group < 0) {
447 			va_end(ap);
448 			return -NLE_INVAL;
449 		}
450 
451 		err = setsockopt(sk->s_fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
452 						 &group, sizeof(group));
453 		if (err < 0) {
454 			va_end(ap);
455 			NL_DBG(4, "nl_socket_add_memberships(%p): setsockopt() failed with %d (%s)\n",
456 				sk, errno, nl_strerror_l(errno));
457 			return -nl_syserr2nlerr(errno);
458 		}
459 
460 		group = va_arg(ap, int);
461 	}
462 
463 	va_end(ap);
464 
465 	return 0;
466 }
467 
nl_socket_add_membership(struct nl_sock * sk,int group)468 int nl_socket_add_membership(struct nl_sock *sk, int group)
469 {
470 	return nl_socket_add_memberships(sk, group, 0);
471 }
472 
473 /**
474  * Leave groups
475  * @arg sk		Netlink socket
476  * @arg group		Group identifier
477  *
478  * Leaves the specified groups using the modern socket option
479  * which is available since kernel version 2.6.14. The list of groups
480  * has to terminated by 0 (%NFNLGRP_NONE).
481  *
482  * @see nl_socket_add_membership
483  * @return 0 on success or a negative error code.
484  */
nl_socket_drop_memberships(struct nl_sock * sk,int group,...)485 int nl_socket_drop_memberships(struct nl_sock *sk, int group, ...)
486 {
487 	int err;
488 	va_list ap;
489 
490 	if (sk->s_fd == -1)
491 		return -NLE_BAD_SOCK;
492 
493 	va_start(ap, group);
494 
495 	while (group != 0) {
496 		if (group < 0) {
497 			va_end(ap);
498 			return -NLE_INVAL;
499 		}
500 
501 		err = setsockopt(sk->s_fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
502 						 &group, sizeof(group));
503 		if (err < 0) {
504 			va_end(ap);
505 			NL_DBG(4, "nl_socket_drop_memberships(%p): setsockopt() failed with %d (%s)\n",
506 				sk, errno, nl_strerror_l(errno));
507 			return -nl_syserr2nlerr(errno);
508 		}
509 
510 		group = va_arg(ap, int);
511 	}
512 
513 	va_end(ap);
514 
515 	return 0;
516 }
517 
nl_socket_drop_membership(struct nl_sock * sk,int group)518 int nl_socket_drop_membership(struct nl_sock *sk, int group)
519 {
520 	return nl_socket_drop_memberships(sk, group, 0);
521 }
522 
523 
524 /**
525  * Join multicast groups (deprecated)
526  * @arg sk		Netlink socket.
527  * @arg groups		Bitmask of groups to join.
528  *
529  * This function defines the old way of joining multicast group which
530  * has to be done prior to calling nl_connect(). It works on any kernel
531  * version but is very limited as only 32 groups can be joined.
532  */
nl_join_groups(struct nl_sock * sk,int groups)533 void nl_join_groups(struct nl_sock *sk, int groups)
534 {
535 	sk->s_local.nl_groups |= groups;
536 }
537 
538 
539 /** @} */
540 
541 /**
542  * @name Peer Identfication
543  * @{
544  */
545 
nl_socket_get_peer_port(const struct nl_sock * sk)546 uint32_t nl_socket_get_peer_port(const struct nl_sock *sk)
547 {
548 	return sk->s_peer.nl_pid;
549 }
550 
nl_socket_set_peer_port(struct nl_sock * sk,uint32_t port)551 void nl_socket_set_peer_port(struct nl_sock *sk, uint32_t port)
552 {
553 	sk->s_peer.nl_pid = port;
554 }
555 
nl_socket_get_peer_groups(const struct nl_sock * sk)556 uint32_t nl_socket_get_peer_groups(const struct nl_sock *sk)
557 {
558 	return sk->s_peer.nl_groups;
559 }
560 
nl_socket_set_peer_groups(struct nl_sock * sk,uint32_t groups)561 void nl_socket_set_peer_groups(struct nl_sock *sk, uint32_t groups)
562 {
563 	sk->s_peer.nl_groups = groups;
564 }
565 
566 
567 
568 /** @} */
569 
570 /**
571  * @name File Descriptor
572  * @{
573  */
574 
575 /**
576  * Return the file descriptor of the backing socket
577  * @arg sk		Netlink socket
578  *
579  * Only valid after calling nl_connect() to create and bind the respective
580  * socket.
581  *
582  * @return File descriptor or -1 if not available.
583  */
nl_socket_get_fd(const struct nl_sock * sk)584 int nl_socket_get_fd(const struct nl_sock *sk)
585 {
586 	return sk->s_fd;
587 }
588 
589 /**
590  * Set the socket file descriptor externally which initializes the
591  * socket similar to nl_connect().
592  *
593  * @arg sk         Netlink socket (required)
594  * @arg protocol   The socket protocol (optional). Linux 2.6.32 supports
595  *                 the socket option SO_PROTOCOL. In this case, you can set
596  *                 protocol to a negative value and let it autodetect.
597  *                 If you set it to a non-negative value, the detected protocol
598  *                 must match the one provided.
599  *                 To support older kernels, you must specify the protocol.
600  * @arg fd         Socket file descriptor to use (required)
601  *
602  * Set the socket file descriptor. @fd must be valid and bind'ed.
603  *
604  * This is an alternative to nl_connect(). nl_connect() creates, binds and
605  * sets the socket. With this function you can set the socket to an externally
606  * created file descriptor.
607  *
608  * @see nl_connect()
609  *
610  * @return 0 on success or a negative error code. On error, @fd is not closed but
611  * possibly unusable.
612  *
613  * @retval -NLE_BAD_SOCK Netlink socket is already connected
614  * @retval -NLE_INVAL Socket is of unexpected type
615  */
nl_socket_set_fd(struct nl_sock * sk,int protocol,int fd)616 int nl_socket_set_fd(struct nl_sock *sk, int protocol, int fd)
617 {
618 	int err = 0;
619 	socklen_t addrlen;
620 	struct sockaddr_nl local = { 0 };
621 	int so_type = -1, so_protocol = -1;
622 
623 	if (sk->s_fd != -1)
624 		return -NLE_BAD_SOCK;
625 	if (fd < 0)
626 		return -NLE_INVAL;
627 
628 	addrlen = sizeof(local);
629 	err = getsockname(fd, (struct sockaddr *) &local,
630 	                  &addrlen);
631 	if (err < 0) {
632 		NL_DBG(4, "nl_socket_set_fd(%p,%d): getsockname() failed with %d (%s)\n",
633 		       sk, fd, errno, nl_strerror_l(errno));
634 		return -nl_syserr2nlerr(errno);
635 	}
636 	if (addrlen != sizeof(local))
637 		return -NLE_INVAL;
638 	if (local.nl_family != AF_NETLINK) {
639 		NL_DBG(4, "nl_socket_set_fd(%p,%d): getsockname() returned family %d instead of %d (AF_NETLINK)\n",
640 		       sk, fd, local.nl_family, AF_NETLINK);
641 		return -NLE_INVAL;
642 	}
643 
644 	addrlen = sizeof(so_type);
645 	err = getsockopt(fd, SOL_SOCKET, SO_TYPE, &so_type, &addrlen);
646 	if (err < 0) {
647 		NL_DBG(4, "nl_socket_set_fd(%p,%d): getsockopt() for SO_TYPE failed with %d (%s)\n",
648 		       sk, fd, errno, nl_strerror_l(errno));
649 		return -nl_syserr2nlerr(errno);
650 	}
651 	if (addrlen != sizeof(so_type))
652 		return -NLE_INVAL;
653 	if (so_type != SOCK_RAW) {
654 		NL_DBG(4, "nl_socket_set_fd(%p,%d): getsockopt() returned SO_TYPE %d instead of %d (SOCK_RAW)\n",
655 		       sk, fd, so_type, SOCK_RAW);
656 		return -NLE_INVAL;
657 	}
658 
659 #if SO_PROTOCOL
660 	addrlen = sizeof(so_protocol);
661 	err = getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &so_protocol, &addrlen);
662 	if (err < 0) {
663 		if (errno == ENOPROTOOPT)
664 			goto no_so_protocol;
665 		NL_DBG(4, "nl_socket_set_fd(%p,%d): getsockopt() for SO_PROTOCOL failed with %d (%s)\n",
666 		       sk, fd, errno, nl_strerror_l(errno));
667 		return -nl_syserr2nlerr(errno);
668 	}
669 	if (addrlen != sizeof(so_protocol))
670 		return -NLE_INVAL;
671 	if (protocol >= 0 && protocol != so_protocol) {
672 		NL_DBG(4, "nl_socket_set_fd(%p,%d): getsockopt() for SO_PROTOCOL returned %d instead of %d\n",
673 		       sk, fd, so_protocol, protocol);
674 		return -NLE_INVAL;
675 	}
676 
677 	if (0)
678 #endif
679 	{
680 no_so_protocol:
681 		if (protocol < 0) {
682 			NL_DBG(4, "nl_socket_set_fd(%p,%d): unknown protocol and unable to detect it via SO_PROTOCOL socket option\n",
683 			       sk, fd);
684 			return -NLE_INVAL;
685 		}
686 		so_protocol = protocol;
687 	}
688 
689 	nl_socket_set_local_port (sk, local.nl_pid);
690 	sk->s_local = local;
691 	sk->s_fd = fd;
692 	sk->s_proto = so_protocol;
693 
694 	return 0;
695 }
696 
697 /**
698  * Set file descriptor of socket to non-blocking state
699  * @arg sk		Netlink socket.
700  *
701  * @return 0 on success or a negative error code.
702  */
nl_socket_set_nonblocking(const struct nl_sock * sk)703 int nl_socket_set_nonblocking(const struct nl_sock *sk)
704 {
705 	if (sk->s_fd == -1)
706 		return -NLE_BAD_SOCK;
707 
708 	if (fcntl(sk->s_fd, F_SETFL, O_NONBLOCK) < 0) {
709 		NL_DBG(4, "nl_socket_set_nonblocking(%p): fcntl() failed with %d (%s)\n",
710 			sk, errno, nl_strerror_l(errno));
711 		return -nl_syserr2nlerr(errno);
712 	}
713 
714 	return 0;
715 }
716 
717 /**
718  * Enable use of MSG_PEEK when reading from socket
719  * @arg sk		Netlink socket.
720  *
721  * See also NL_CAPABILITY_NL_RECVMSGS_PEEK_BY_DEFAULT capability
722  */
nl_socket_enable_msg_peek(struct nl_sock * sk)723 void nl_socket_enable_msg_peek(struct nl_sock *sk)
724 {
725 	sk->s_flags |= (NL_MSG_PEEK | NL_MSG_PEEK_EXPLICIT);
726 }
727 
728 /**
729  * Disable use of MSG_PEEK when reading from socket
730  * @arg sk		Netlink socket.
731  *
732  * See also NL_CAPABILITY_NL_RECVMSGS_PEEK_BY_DEFAULT capability
733  */
nl_socket_disable_msg_peek(struct nl_sock * sk)734 void nl_socket_disable_msg_peek(struct nl_sock *sk)
735 {
736 	sk->s_flags |= NL_MSG_PEEK_EXPLICIT;
737 	sk->s_flags &= ~NL_MSG_PEEK;
738 }
739 
740 /** @} */
741 
742 /**
743  * @name Callback Handler
744  * @{
745  */
746 
nl_socket_get_cb(const struct nl_sock * sk)747 struct nl_cb *nl_socket_get_cb(const struct nl_sock *sk)
748 {
749 	return nl_cb_get(sk->s_cb);
750 }
751 
nl_socket_set_cb(struct nl_sock * sk,struct nl_cb * cb)752 void nl_socket_set_cb(struct nl_sock *sk, struct nl_cb *cb)
753 {
754 	if (cb == NULL)
755 		BUG();
756 
757 	nl_cb_put(sk->s_cb);
758 	sk->s_cb = nl_cb_get(cb);
759 }
760 
761 /**
762  * Modify the callback handler associated with the socket
763  * @arg sk		Netlink socket.
764  * @arg type		which type callback to set
765  * @arg kind		kind of callback
766  * @arg func		callback function
767  * @arg arg		argument to be passed to callback function
768  *
769  * @see nl_cb_set
770  */
nl_socket_modify_cb(struct nl_sock * sk,enum nl_cb_type type,enum nl_cb_kind kind,nl_recvmsg_msg_cb_t func,void * arg)771 int nl_socket_modify_cb(struct nl_sock *sk, enum nl_cb_type type,
772 			enum nl_cb_kind kind, nl_recvmsg_msg_cb_t func,
773 			void *arg)
774 {
775 	return nl_cb_set(sk->s_cb, type, kind, func, arg);
776 }
777 
778 /**
779  * Modify the error callback handler associated with the socket
780  * @arg sk		Netlink socket.
781  * @arg kind		kind of callback
782  * @arg func		callback function
783  * @arg arg		argument to be passed to callback function
784  *
785  * @see nl_cb_err
786  */
nl_socket_modify_err_cb(struct nl_sock * sk,enum nl_cb_kind kind,nl_recvmsg_err_cb_t func,void * arg)787 int nl_socket_modify_err_cb(struct nl_sock *sk, enum nl_cb_kind kind,
788 			    nl_recvmsg_err_cb_t func, void *arg)
789 {
790 	return nl_cb_err(sk->s_cb, kind, func, arg);
791 }
792 
793 /** @} */
794 
795 /**
796  * @name Utilities
797  * @{
798  */
799 
800 /**
801  * Set socket buffer size of netlink socket.
802  * @arg sk		Netlink socket.
803  * @arg rxbuf		New receive socket buffer size in bytes.
804  * @arg txbuf		New transmit socket buffer size in bytes.
805  *
806  * Sets the socket buffer size of a netlink socket to the specified
807  * values \c rxbuf and \c txbuf. Providing a value of \c 0 assumes a
808  * good default value.
809  *
810  * @note It is not required to call this function prior to nl_connect().
811  * @return 0 on sucess or a negative error code.
812  */
nl_socket_set_buffer_size(struct nl_sock * sk,int rxbuf,int txbuf)813 int nl_socket_set_buffer_size(struct nl_sock *sk, int rxbuf, int txbuf)
814 {
815 	int err;
816 
817 	if (rxbuf <= 0)
818 		rxbuf = 32768;
819 
820 	if (txbuf <= 0)
821 		txbuf = 32768;
822 
823 	if (sk->s_fd == -1)
824 		return -NLE_BAD_SOCK;
825 
826 	err = setsockopt(sk->s_fd, SOL_SOCKET, SO_SNDBUF,
827 			 &txbuf, sizeof(txbuf));
828 	if (err < 0) {
829 		NL_DBG(4, "nl_socket_set_buffer_size(%p): setsockopt() failed with %d (%s)\n",
830 			sk, errno, nl_strerror_l(errno));
831 		return -nl_syserr2nlerr(errno);
832 	}
833 
834 	err = setsockopt(sk->s_fd, SOL_SOCKET, SO_RCVBUF,
835 			 &rxbuf, sizeof(rxbuf));
836 	if (err < 0) {
837 		NL_DBG(4, "nl_socket_set_buffer_size(%p): setsockopt() failed with %d (%s)\n",
838 			sk, errno, nl_strerror_l(errno));
839 		return -nl_syserr2nlerr(errno);
840 	}
841 
842 	return 0;
843 }
844 
845 /**
846  * Set default message buffer size of netlink socket.
847  * @arg sk		Netlink socket.
848  * @arg bufsize		Default message buffer size in bytes.
849  *
850  * Sets the default message buffer size to the specified length in bytes.
851  * The default message buffer size limits the maximum message size the
852  * socket will be able to receive. It is generally recommneded to specify
853  * a buffer size no less than the size of a memory page.
854  *
855  * Setting the @bufsize to zero means to use a default of 4 times getpagesize().
856  *
857  * When MSG_PEEK is enabled, the buffer size is used for the initial choice
858  * of the buffer while peeking. It still makes sense to choose an optimal value
859  * to avoid realloc().
860  *
861  * When MSG_PEEK is disabled, the buffer size is important because a too small
862  * size will lead to failure of receiving the message via nl_recvmsgs().
863  *
864  * By default, MSG_PEEK is enabled unless the user calls either nl_socket_disable_msg_peek()/
865  * nl_socket_enable_msg_peek() or sets the message buffer size to a positive value.
866  * See capability NL_CAPABILITY_NL_RECVMSGS_PEEK_BY_DEFAULT for that.
867  *
868  * @return 0 on success or a negative error code.
869  */
nl_socket_set_msg_buf_size(struct nl_sock * sk,size_t bufsize)870 int nl_socket_set_msg_buf_size(struct nl_sock *sk, size_t bufsize)
871 {
872 	sk->s_bufsize = bufsize;
873 
874 	return 0;
875 }
876 
877 /**
878  * Get default message buffer size of netlink socket.
879  * @arg sk		Netlink socket.
880  *
881  * @return Size of default message buffer.
882  */
nl_socket_get_msg_buf_size(struct nl_sock * sk)883 size_t nl_socket_get_msg_buf_size(struct nl_sock *sk)
884 {
885 	return sk->s_bufsize;
886 }
887 
888 /**
889  * Enable/disable credential passing on netlink socket.
890  * @arg sk		Netlink socket.
891  * @arg state		New state (0 - disabled, 1 - enabled)
892  *
893  * @return 0 on success or a negative error code
894  */
nl_socket_set_passcred(struct nl_sock * sk,int state)895 int nl_socket_set_passcred(struct nl_sock *sk, int state)
896 {
897 	int err;
898 
899 	if (sk->s_fd == -1)
900 		return -NLE_BAD_SOCK;
901 
902 	err = setsockopt(sk->s_fd, SOL_SOCKET, SO_PASSCRED,
903 			 &state, sizeof(state));
904 	if (err < 0) {
905 		NL_DBG(4, "nl_socket_set_passcred(%p): setsockopt() failed with %d (%s)\n",
906 			sk, errno, nl_strerror_l(errno));
907 		return -nl_syserr2nlerr(errno);
908 	}
909 
910 	if (state)
911 		sk->s_flags |= NL_SOCK_PASSCRED;
912 	else
913 		sk->s_flags &= ~NL_SOCK_PASSCRED;
914 
915 	return 0;
916 }
917 
918 /**
919  * Enable/disable receival of additional packet information
920  * @arg sk		Netlink socket.
921  * @arg state		New state (0 - disabled, 1 - enabled)
922  *
923  * @return 0 on success or a negative error code
924  */
nl_socket_recv_pktinfo(struct nl_sock * sk,int state)925 int nl_socket_recv_pktinfo(struct nl_sock *sk, int state)
926 {
927 	int err;
928 
929 	if (sk->s_fd == -1)
930 		return -NLE_BAD_SOCK;
931 
932 	err = setsockopt(sk->s_fd, SOL_NETLINK, NETLINK_PKTINFO,
933 			 &state, sizeof(state));
934 	if (err < 0) {
935 		NL_DBG(4, "nl_socket_recv_pktinfo(%p): setsockopt() failed with %d (%s)\n",
936 			sk, errno, nl_strerror_l(errno));
937 		return -nl_syserr2nlerr(errno);
938 	}
939 
940 	return 0;
941 }
942 
943 /** @} */
944 
945 /** @} */
946