libnl  1.1
socket.c
1 /*
2  * lib/socket.c Netlink Socket Handle
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-2006 Thomas Graf <tgraf@suug.ch>
10  */
11 
12 /**
13  * @ingroup nl
14  * @defgroup socket Socket
15  * @brief Handle representing a netlink socket.
16  *
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.
22  *
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.
54  * (See nl_connect())
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
61  * number.)
62  * - \b Callbacks \b Configuration:
63  *
64  * @par 1) Creating the netlink handle
65  * @code
66  * struct nl_handle *handle;
67  *
68  * // Allocate and initialize a new netlink handle
69  * handle = nl_handle_alloc();
70  *
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);
74  * @endcode
75  *
76  * @par 2) Group Subscriptions
77  * @code
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);
81  * @endcode
82  *
83  * @par 6) Cleaning up
84  * @code
85  * // Finally destroy the netlink handle
86  * nl_handle_destroy(handle);
87  * @endcode
88  *
89  * @{
90  */
91 
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>
98 
99 static int default_cb = NL_CB_DEFAULT;
100 
101 static void __init init_default_cb(void)
102 {
103  char *nlcb;
104 
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;
112  else {
113  fprintf(stderr, "Unknown value for NLCB, valid values: "
114  "{default | verbose | debug}\n");
115  }
116  }
117 }
118 
119 static uint32_t used_ports_map[32];
120 
121 static uint32_t generate_local_port(void)
122 {
123  int i, n;
124  uint32_t pid = getpid() & 0x3FFFFF;
125 
126  for (i = 0; i < 32; i++) {
127  if (used_ports_map[i] == 0xFFFFFFFF)
128  continue;
129 
130  for (n = 0; n < 32; n++) {
131  if (1UL & (used_ports_map[i] >> n))
132  continue;
133 
134  used_ports_map[i] |= (1UL << n);
135  n += (i * 32);
136 
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);
140 
141  }
142  }
143 
144  /* Out of sockets in our own PID namespace, what to do? FIXME */
145  return UINT_MAX;
146 }
147 
148 static void release_local_port(uint32_t port)
149 {
150  int nr;
151 
152  if (port == UINT_MAX)
153  return;
154 
155  nr = port >> 22;
156  used_ports_map[nr / 32] &= ~(1 << nr % 32);
157 }
158 
159 /**
160  * @name Allocation
161  * @{
162  */
163 
164 static struct nl_handle *__alloc_handle(struct nl_cb *cb)
165 {
166  struct nl_handle *handle;
167 
168  handle = calloc(1, sizeof(*handle));
169  if (!handle) {
170  nl_errno(ENOMEM);
171  return NULL;
172  }
173 
174  handle->h_fd = -1;
175  handle->h_cb = cb;
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");
183  return NULL;
184  }
185 
186  return handle;
187 }
188 
189 /**
190  * Allocate new netlink socket handle.
191  *
192  * @return Newly allocated netlink socket handle or NULL.
193  */
194 struct nl_handle *nl_handle_alloc(void)
195 {
196  struct nl_cb *cb;
197 
198  cb = nl_cb_alloc(default_cb);
199  if (!cb) {
200  nl_errno(ENOMEM);
201  return NULL;
202  }
203 
204  return __alloc_handle(cb);
205 }
206 
207 /**
208  * Allocate new socket handle with custom callbacks
209  * @arg cb Callback handler
210  *
211  * The reference to the callback handler is taken into account
212  * automatically, it is released again upon calling nl_handle_destroy().
213  *
214  *@return Newly allocted socket handle or NULL.
215  */
216 struct nl_handle *nl_handle_alloc_cb(struct nl_cb *cb)
217 {
218  if (cb == NULL)
219  BUG();
220 
221  return __alloc_handle(nl_cb_get(cb));
222 }
223 
224 /**
225  * Destroy netlink handle.
226  * @arg handle Netlink handle.
227  */
228 void nl_handle_destroy(struct nl_handle *handle)
229 {
230  if (!handle)
231  return;
232 
233  if (handle->h_fd >= 0)
234  close(handle->h_fd);
235 
236  if (!(handle->h_flags & NL_OWN_PORT))
237  release_local_port(handle->h_local.nl_pid);
238 
239  nl_cb_put(handle->h_cb);
240  free(handle);
241 }
242 
243 /** @} */
244 
245 /**
246  * @name Sequence Numbers
247  * @{
248  */
249 
250 static int noop_seq_check(struct nl_msg *msg, void *arg)
251 {
252  return NL_OK;
253 }
254 
255 
256 /**
257  * Disable sequence number checking.
258  * @arg handle Netlink handle.
259  *
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.
263  *
264  * @note This function modifies the NL_CB_SEQ_CHECK configuration in
265  * the callback handle associated with the socket.
266  */
267 void nl_disable_sequence_check(struct nl_handle *handle)
268 {
269  nl_cb_set(handle->h_cb, NL_CB_SEQ_CHECK,
270  NL_CB_CUSTOM, noop_seq_check, NULL);
271 }
272 
273 /**
274  * Use next sequence number
275  * @arg handle Netlink handle
276  *
277  * Uses the next available sequence number and increases the counter
278  * by one for subsequent calls.
279  *
280  * @return Unique serial sequence number
281  */
282 unsigned int nl_socket_use_seq(struct nl_handle *handle)
283 {
284  return handle->h_seq_next++;
285 }
286 
287 /** @} */
288 
289 /**
290  * @name Source Idenficiation
291  * @{
292  */
293 
294 uint32_t nl_socket_get_local_port(struct nl_handle *handle)
295 {
296  return handle->h_local.nl_pid;
297 }
298 
299 /**
300  * Set local port of socket
301  * @arg handle Netlink handle
302  * @arg port Local port identifier
303  *
304  * Assigns a local port identifier to the socket. If port is 0
305  * a unique port identifier will be generated automatically.
306  */
307 void nl_socket_set_local_port(struct nl_handle *handle, uint32_t port)
308 {
309  if (port == 0) {
310  port = generate_local_port();
311  handle->h_flags &= ~NL_OWN_PORT;
312  } else {
313  if (!(handle->h_flags & NL_OWN_PORT))
314  release_local_port(handle->h_local.nl_pid);
315  handle->h_flags |= NL_OWN_PORT;
316  }
317 
318  handle->h_local.nl_pid = port;
319 }
320 
321 /** @} */
322 
323 /**
324  * @name Group Subscriptions
325  * @{
326  */
327 
328 /**
329  * Join a group
330  * @arg handle Netlink handle
331  * @arg group Group identifier
332  *
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.
336  *
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.
340  *
341  * @return 0 on sucess or a negative error code.
342  */
343 int nl_socket_add_membership(struct nl_handle *handle, int group)
344 {
345  int err;
346 
347  if (handle->h_fd == -1)
348  return nl_error(EBADFD, "Socket not connected");
349 
350  err = setsockopt(handle->h_fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
351  &group, sizeof(group));
352  if (err < 0)
353  return nl_error(errno, "setsockopt(NETLINK_ADD_MEMBERSHIP) "
354  "failed");
355 
356  return 0;
357 }
358 
359 /**
360  * Leave a group
361  * @arg handle Netlink handle
362  * @arg group Group identifier
363  *
364  * Leaves the specified group using the modern socket option
365  * which is available since kernel version 2.6.14.
366  *
367  * @see nl_socket_add_membership
368  * @return 0 on success or a negative error code.
369  */
370 int nl_socket_drop_membership(struct nl_handle *handle, int group)
371 {
372  int err;
373 
374  if (handle->h_fd == -1)
375  return nl_error(EBADFD, "Socket not connected");
376 
377  err = setsockopt(handle->h_fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
378  &group, sizeof(group));
379  if (err < 0)
380  return nl_error(errno, "setsockopt(NETLINK_DROP_MEMBERSHIP) "
381  "failed");
382 
383  return 0;
384 }
385 
386 /**
387  * Join multicast groups (deprecated)
388  * @arg handle Netlink handle.
389  * @arg groups Bitmask of groups to join.
390  *
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.
394  */
395 void nl_join_groups(struct nl_handle *handle, int groups)
396 {
397  handle->h_local.nl_groups |= groups;
398 }
399 
400 
401 /** @} */
402 
403 /**
404  * @name Peer Identfication
405  * @{
406  */
407 
408 uint32_t nl_socket_get_peer_port(struct nl_handle *handle)
409 {
410  return handle->h_peer.nl_pid;
411 }
412 
413 void nl_socket_set_peer_port(struct nl_handle *handle, uint32_t port)
414 {
415  handle->h_peer.nl_pid = port;
416 }
417 
418 /** @} */
419 
420 /**
421  * @name File Descriptor
422  * @{
423  */
424 
425 int nl_socket_get_fd(struct nl_handle *handle)
426 {
427  return handle->h_fd;
428 }
429 
430 /**
431  * Set file descriptor of socket handle to non-blocking state
432  * @arg handle Netlink socket
433  *
434  * @return 0 on success or a negative error code.
435  */
436 int nl_socket_set_nonblocking(struct nl_handle *handle)
437 {
438  if (handle->h_fd == -1)
439  return nl_error(EBADFD, "Socket not connected");
440 
441  if (fcntl(handle->h_fd, F_SETFL, O_NONBLOCK) < 0)
442  return nl_error(errno, "fcntl(F_SETFL, O_NONBLOCK) failed");
443 
444  return 0;
445 }
446 
447 /**
448  * Enable use of MSG_PEEK when reading from socket
449  * @arg handle Netlink socket
450  */
451 void nl_socket_enable_msg_peek(struct nl_handle *handle)
452 {
453  handle->h_flags |= NL_MSG_PEEK;
454 }
455 
456 /**
457  * Disable use of MSG_PEEK when reading from socket
458  * @arg handle Netlink socket
459  */
460 void nl_socket_disable_msg_peek(struct nl_handle *handle)
461 {
462  handle->h_flags &= ~NL_MSG_PEEK;
463 }
464 
465 /** @} */
466 
467 /**
468  * @name Callback Handler
469  * @{
470  */
471 
472 struct nl_cb *nl_socket_get_cb(struct nl_handle *handle)
473 {
474  return nl_cb_get(handle->h_cb);
475 }
476 
477 void nl_socket_set_cb(struct nl_handle *handle, struct nl_cb *cb)
478 {
479  nl_cb_put(handle->h_cb);
480  handle->h_cb = nl_cb_get(cb);
481 }
482 
483 /**
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
490  *
491  * @see nl_cb_set
492  */
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,
495  void *arg)
496 {
497  return nl_cb_set(handle->h_cb, type, kind, func, arg);
498 }
499 
500 /** @} */
501 
502 /**
503  * @name Utilities
504  * @{
505  */
506 
507 /**
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.
512  *
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.
516  *
517  * @note It is not required to call this function prior to nl_connect().
518  * @return 0 on sucess or a negative error code.
519  */
520 int nl_set_buffer_size(struct nl_handle *handle, int rxbuf, int txbuf)
521 {
522  int err;
523 
524  if (rxbuf <= 0)
525  rxbuf = 32768;
526 
527  if (txbuf <= 0)
528  txbuf = 32768;
529 
530  if (handle->h_fd == -1)
531  return nl_error(EBADFD, "Socket not connected");
532 
533  err = setsockopt(handle->h_fd, SOL_SOCKET, SO_SNDBUF,
534  &txbuf, sizeof(txbuf));
535  if (err < 0)
536  return nl_error(errno, "setsockopt(SO_SNDBUF) failed");
537 
538  err = setsockopt(handle->h_fd, SOL_SOCKET, SO_RCVBUF,
539  &rxbuf, sizeof(rxbuf));
540  if (err < 0)
541  return nl_error(errno, "setsockopt(SO_RCVBUF) failed");
542 
543  handle->h_flags |= NL_SOCK_BUFSIZE_SET;
544 
545  return 0;
546 }
547 
548 /**
549  * Enable/disable credential passing on netlink handle.
550  * @arg handle Netlink handle
551  * @arg state New state (0 - disabled, 1 - enabled)
552  *
553  * @return 0 on success or a negative error code
554  */
555 int nl_set_passcred(struct nl_handle *handle, int state)
556 {
557  int err;
558 
559  if (handle->h_fd == -1)
560  return nl_error(EBADFD, "Socket not connected");
561 
562  err = setsockopt(handle->h_fd, SOL_SOCKET, SO_PASSCRED,
563  &state, sizeof(state));
564  if (err < 0)
565  return nl_error(errno, "setsockopt(SO_PASSCRED) failed");
566 
567  if (state)
568  handle->h_flags |= NL_SOCK_PASSCRED;
569  else
570  handle->h_flags &= ~NL_SOCK_PASSCRED;
571 
572  return 0;
573 }
574 
575 /**
576  * Enable/disable receival of additional packet information
577  * @arg handle Netlink handle
578  * @arg state New state (0 - disabled, 1 - enabled)
579  *
580  * @return 0 on success or a negative error code
581  */
582 int nl_socket_recv_pktinfo(struct nl_handle *handle, int state)
583 {
584  int err;
585 
586  if (handle->h_fd == -1)
587  return nl_error(EBADFD, "Socket not connected");
588 
589  err = setsockopt(handle->h_fd, SOL_NETLINK, NETLINK_PKTINFO,
590  &state, sizeof(state));
591  if (err < 0)
592  return nl_error(errno, "setsockopt(NETLINK_PKTINFO) failed");
593 
594  return 0;
595 }
596 
597 /** @} */
598 
599 /** @} */