2 * lib/socket.c Netlink Socket Handle
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
9 * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
14 * @defgroup socket Socket
15 * @brief Handle representing a netlink socket.
17 * The socket is represented in a structure called the netlink handle,
18 * besides the socket, it stores various settings and values related
19 * to the socket. Every socket handle has a mandatory association with
20 * a set of callbacks which can be used to modify the behaviour when
21 * sending/receiving data from the socket.
23 * @par Socket Attributes
24 * - \b Local \b Port: The local port is a netlink port identifying the
25 * local endpoint. It is used as source address for outgoing messages
26 * and will be addressed in replies. It must therefore be unique among
27 * all userspace applications. When the socket handle is allocated, a
28 * unique port number is generated automatically in the form of 22 bits
29 * Process Identifier + 10 bits Arbitary Number. Therefore the library
30 * is capable of generating 1024 unique local port numbers for every
31 * process. If more sockets are required, the application has to manage
32 * port numbers itself using nl_socket_set_local_port().
33 * - \b Group \b Subscriptions: A socket can subscribe to any number of
34 * multicast groups. It will then receive a copy of all messages sent
35 * to one of the groups. This method is mainly used for event notification.
36 * Prior to kernel 2.6.14, the group subscription was done via bitmask
37 * which limited to a total number of groups of 32. With 2.6.14 a new
38 * method was added based on continous identifiers which supports an
39 * arbitary number of groups. Both methods are supported, see
40 * nl_join_groups() respectively nl_socket_add_membership() and
41 * nl_socket_drop_membership().
42 * - \b Peer \b Port: The peer port is a netlink port identifying the
43 * peer's endpoint. If no peer port is specified, the kernel will try to
44 * autobind to a socket of the specified netlink family automatically.
45 * This is very common as typically only one listening socket exists
46 * on the kernel side. The peer port can be modified using
47 * nl_socket_set_peer_port().
48 * - \b Peer \b Groups:
49 * - \b File \b Descriptor: The file descriptor of the socket, it can be
50 * accessed via nl_socket_get_fd() to change socket options or monitor
51 * activity using poll()/select().
52 * - \b Protocol: Once connected, the socket is bound to stick to one
53 * netlink family. This field is invisible, it is maintained automatically.
55 * - \b Next \b Sequence \b Number: Next available sequence number to be used
56 * for the next message being sent out. (Initial value: UNIX time when the
57 * socket was allocated.) Sequence numbers can be used via
58 * nl_socket_use_seq().
59 * - \b Expected \b Sequence \b Number: Expected sequence number in the next
60 * message received from the socket. (Initial value: Equal to next sequence
62 * - \b Callbacks \b Configuration:
64 * @par 1) Creating the netlink handle
66 * struct nl_handle *handle;
68 * // Allocate and initialize a new netlink handle
69 * handle = nl_handle_alloc();
71 * // Use nl_socket_get_fd() to fetch the file description, for example to
72 * // put a socket into non-blocking i/o mode.
73 * fcntl(nl_socket_get_fd(handle), F_SETFL, O_NONBLOCK);
76 * @par 2) Group Subscriptions
78 * // Event notifications are typically sent to multicast addresses which
79 * // represented by groups. Join a group to f.e. receive link notifications.
80 * nl_socket_add_membership(handle, RTNLGRP_LINK);
85 * // Finally destroy the netlink handle
86 * nl_handle_destroy(handle);
92 #include <netlink-local.h>
93 #include <netlink/netlink.h>
94 #include <netlink/utils.h>
95 #include <netlink/handlers.h>
96 #include <netlink/msg.h>
97 #include <netlink/attr.h>
99 static int default_cb = NL_CB_DEFAULT;
101 static void __init init_default_cb(void)
105 if ((nlcb = getenv("NLCB"))) {
106 if (!strcasecmp(nlcb, "default"))
107 default_cb = NL_CB_DEFAULT;
108 else if (!strcasecmp(nlcb, "verbose"))
109 default_cb = NL_CB_VERBOSE;
110 else if (!strcasecmp(nlcb, "debug"))
111 default_cb = NL_CB_DEBUG;
113 fprintf(stderr, "Unknown value for NLCB, valid values: "
114 "{default | verbose | debug}\n");
119 static uint32_t used_ports_map[32];
121 static uint32_t generate_local_port(void)
124 uint32_t pid = getpid() & 0x3FFFFF;
126 for (i = 0; i < 32; i++) {
127 if (used_ports_map[i] == 0xFFFFFFFF)
130 for (n = 0; n < 32; n++) {
131 if (1UL & (used_ports_map[i] >> n))
134 used_ports_map[i] |= (1UL << n);
137 /* PID_MAX_LIMIT is currently at 2^22, leaving 10 bit
138 * to, i.e. 1024 unique ports per application. */
139 return pid + (n << 22);
144 /* Out of sockets in our own PID namespace, what to do? FIXME */
148 static void release_local_port(uint32_t port)
152 if (port == UINT_MAX)
156 used_ports_map[nr / 32] &= ~((nr % 32) + 1);
164 static struct nl_handle *__alloc_handle(struct nl_cb *cb)
166 struct nl_handle *handle;
168 handle = calloc(1, sizeof(*handle));
176 handle->h_local.nl_family = AF_NETLINK;
177 handle->h_peer.nl_family = AF_NETLINK;
178 handle->h_seq_expect = handle->h_seq_next = time(0);
179 handle->h_local.nl_pid = generate_local_port();
180 if (handle->h_local.nl_pid == UINT_MAX) {
181 nl_handle_destroy(handle);
182 nl_error(ENOBUFS, "Out of local ports");
190 * Allocate new netlink socket handle.
192 * @return Newly allocated netlink socket handle or NULL.
194 struct nl_handle *nl_handle_alloc(void)
198 cb = nl_cb_alloc(default_cb);
204 return __alloc_handle(cb);
208 * Allocate new socket handle with custom callbacks
209 * @arg cb Callback handler
211 * The reference to the callback handler is taken into account
212 * automatically, it is released again upon calling nl_handle_destroy().
214 *@return Newly allocted socket handle or NULL.
216 struct nl_handle *nl_handle_alloc_cb(struct nl_cb *cb)
221 return __alloc_handle(nl_cb_get(cb));
225 * Destroy netlink handle.
226 * @arg handle Netlink handle.
228 void nl_handle_destroy(struct nl_handle *handle)
233 if (handle->h_fd >= 0)
236 if (!(handle->h_flags & NL_OWN_PORT))
237 release_local_port(handle->h_local.nl_pid);
239 nl_cb_put(handle->h_cb);
246 * @name Sequence Numbers
250 static int noop_seq_check(struct nl_msg *msg, void *arg)
257 * Disable sequence number checking.
258 * @arg handle Netlink handle.
260 * Disables checking of sequence numbers on the netlink handle. This is
261 * required to allow messages to be processed which were not requested by
262 * a preceding request message, e.g. netlink events.
264 * @note This function modifies the NL_CB_SEQ_CHECK configuration in
265 * the callback handle associated with the socket.
267 void nl_disable_sequence_check(struct nl_handle *handle)
269 nl_cb_set(handle->h_cb, NL_CB_SEQ_CHECK,
270 NL_CB_CUSTOM, noop_seq_check, NULL);
274 * Use next sequence number
275 * @arg handle Netlink handle
277 * Uses the next available sequence number and increases the counter
278 * by one for subsequent calls.
280 * @return Unique serial sequence number
282 unsigned int nl_socket_use_seq(struct nl_handle *handle)
284 return handle->h_seq_next++;
290 * @name Source Idenficiation
294 uint32_t nl_socket_get_local_port(struct nl_handle *handle)
296 return handle->h_local.nl_pid;
300 * Set local port of socket
301 * @arg handle Netlink handle
302 * @arg port Local port identifier
304 * Assigns a local port identifier to the socket. If port is 0
305 * a unique port identifier will be generated automatically.
307 void nl_socket_set_local_port(struct nl_handle *handle, uint32_t port)
310 port = generate_local_port();
311 handle->h_flags &= ~NL_OWN_PORT;
313 if (!(handle->h_flags & NL_OWN_PORT))
314 release_local_port(handle->h_local.nl_pid);
315 handle->h_flags |= NL_OWN_PORT;
318 handle->h_local.nl_pid = port;
324 * @name Group Subscriptions
330 * @arg handle Netlink handle
331 * @arg group Group identifier
333 * Joins the specified group using the modern socket option which
334 * is available since kernel version 2.6.14. It allows joining an
335 * almost arbitary number of groups without limitation.
337 * Make sure to use the correct group definitions as the older
338 * bitmask definitions for nl_join_groups() are likely to still
339 * be present for backward compatibility reasons.
341 * @return 0 on sucess or a negative error code.
343 int nl_socket_add_membership(struct nl_handle *handle, int group)
347 if (handle->h_fd == -1)
348 return nl_error(EBADFD, "Socket not connected");
350 err = setsockopt(handle->h_fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
351 &group, sizeof(group));
353 return nl_error(errno, "setsockopt(NETLINK_ADD_MEMBERSHIP) "
361 * @arg handle Netlink handle
362 * @arg group Group identifier
364 * Leaves the specified group using the modern socket option
365 * which is available since kernel version 2.6.14.
367 * @see nl_socket_add_membership
368 * @return 0 on success or a negative error code.
370 int nl_socket_drop_membership(struct nl_handle *handle, int group)
374 if (handle->h_fd == -1)
375 return nl_error(EBADFD, "Socket not connected");
377 err = setsockopt(handle->h_fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
378 &group, sizeof(group));
380 return nl_error(errno, "setsockopt(NETLINK_DROP_MEMBERSHIP) "
387 * Join multicast groups (deprecated)
388 * @arg handle Netlink handle.
389 * @arg groups Bitmask of groups to join.
391 * This function defines the old way of joining multicast group which
392 * has to be done prior to calling nl_connect(). It works on any kernel
393 * version but is very limited as only 32 groups can be joined.
395 void nl_join_groups(struct nl_handle *handle, int groups)
397 handle->h_local.nl_groups |= groups;
404 * @name Peer Identfication
408 uint32_t nl_socket_get_peer_port(struct nl_handle *handle)
410 return handle->h_peer.nl_pid;
413 void nl_socket_set_peer_port(struct nl_handle *handle, uint32_t port)
415 handle->h_peer.nl_pid = port;
421 * @name File Descriptor
425 int nl_socket_get_fd(struct nl_handle *handle)
431 * Set file descriptor of socket handle to non-blocking state
432 * @arg handle Netlink socket
434 * @return 0 on success or a negative error code.
436 int nl_socket_set_nonblocking(struct nl_handle *handle)
438 if (handle->h_fd == -1)
439 return nl_error(EBADFD, "Socket not connected");
441 if (fcntl(handle->h_fd, F_SETFL, O_NONBLOCK) < 0)
442 return nl_error(errno, "fcntl(F_SETFL, O_NONBLOCK) failed");
448 * Enable use of MSG_PEEK when reading from socket
449 * @arg handle Netlink socket
451 void nl_socket_enable_msg_peek(struct nl_handle *handle)
453 handle->h_flags |= NL_MSG_PEEK;
457 * Disable use of MSG_PEEK when reading from socket
458 * @arg handle Netlink socket
460 void nl_socket_disable_msg_peek(struct nl_handle *handle)
462 handle->h_flags &= ~NL_MSG_PEEK;
468 * @name Callback Handler
472 struct nl_cb *nl_socket_get_cb(struct nl_handle *handle)
474 return nl_cb_get(handle->h_cb);
477 void nl_socket_set_cb(struct nl_handle *handle, struct nl_cb *cb)
479 nl_cb_put(handle->h_cb);
480 handle->h_cb = nl_cb_get(cb);
484 * Modify the callback handler associated to the socket
485 * @arg handle netlink handle
486 * @arg type which type callback to set
487 * @arg kind kind of callback
488 * @arg func callback function
489 * @arg arg argument to be passwd to callback function
493 int nl_socket_modify_cb(struct nl_handle *handle, enum nl_cb_type type,
494 enum nl_cb_kind kind, nl_recvmsg_msg_cb_t func,
497 return nl_cb_set(handle->h_cb, type, kind, func, arg);
508 * Set socket buffer size of netlink handle.
509 * @arg handle Netlink handle.
510 * @arg rxbuf New receive socket buffer size in bytes.
511 * @arg txbuf New transmit socket buffer size in bytes.
513 * Sets the socket buffer size of a netlink handle to the specified
514 * values \c rxbuf and \c txbuf. Providing a value of \c 0 assumes a
515 * good default value.
517 * @note It is not required to call this function prior to nl_connect().
518 * @return 0 on sucess or a negative error code.
520 int nl_set_buffer_size(struct nl_handle *handle, int rxbuf, int txbuf)
530 if (handle->h_fd == -1)
531 return nl_error(EBADFD, "Socket not connected");
533 err = setsockopt(handle->h_fd, SOL_SOCKET, SO_SNDBUF,
534 &txbuf, sizeof(txbuf));
536 return nl_error(errno, "setsockopt(SO_SNDBUF) failed");
538 err = setsockopt(handle->h_fd, SOL_SOCKET, SO_RCVBUF,
539 &rxbuf, sizeof(rxbuf));
541 return nl_error(errno, "setsockopt(SO_RCVBUF) failed");
543 handle->h_flags |= NL_SOCK_BUFSIZE_SET;
549 * Enable/disable credential passing on netlink handle.
550 * @arg handle Netlink handle
551 * @arg state New state (0 - disabled, 1 - enabled)
553 * @return 0 on success or a negative error code
555 int nl_set_passcred(struct nl_handle *handle, int state)
559 if (handle->h_fd == -1)
560 return nl_error(EBADFD, "Socket not connected");
562 err = setsockopt(handle->h_fd, SOL_SOCKET, SO_PASSCRED,
563 &state, sizeof(state));
565 return nl_error(errno, "setsockopt(SO_PASSCRED) failed");
568 handle->h_flags |= NL_SOCK_PASSCRED;
570 handle->h_flags &= ~NL_SOCK_PASSCRED;
576 * Enable/disable receival of additional packet information
577 * @arg handle Netlink handle
578 * @arg state New state (0 - disabled, 1 - enabled)
580 * @return 0 on success or a negative error code
582 int nl_socket_recv_pktinfo(struct nl_handle *handle, int state)
586 if (handle->h_fd == -1)
587 return nl_error(EBADFD, "Socket not connected");
589 err = setsockopt(handle->h_fd, SOL_NETLINK, NETLINK_PKTINFO,
590 &state, sizeof(state));
592 return nl_error(errno, "setsockopt(NETLINK_PKTINFO) failed");