socket.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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. * @ingroup nl
  13. * @defgroup socket Socket
  14. * @brief Handle representing a netlink socket.
  15. *
  16. * The socket is represented in a structure called the netlink handle,
  17. * besides the socket, it stores various settings and values related
  18. * to the socket. Every socket handle has a mandatory association with
  19. * a set of callbacks which can be used to modify the behaviour when
  20. * sending/receiving data from the socket.
  21. *
  22. * @par Socket Attributes
  23. * - \b Local \b Port: The local port is a netlink port identifying the
  24. * local endpoint. It is used as source address for outgoing messages
  25. * and will be addressed in replies. It must therefore be unique among
  26. * all userspace applications. When the socket handle is allocated, a
  27. * unique port number is generated automatically in the form of 22 bits
  28. * Process Identifier + 10 bits Arbitary Number. Therefore the library
  29. * is capable of generating 1024 unique local port numbers for every
  30. * process. If more sockets are required, the application has to manage
  31. * port numbers itself using nl_socket_set_local_port().
  32. * - \b Group \b Subscriptions: A socket can subscribe to any number of
  33. * multicast groups. It will then receive a copy of all messages sent
  34. * to one of the groups. This method is mainly used for event notification.
  35. * Prior to kernel 2.6.14, the group subscription was done via bitmask
  36. * which limited to a total number of groups of 32. With 2.6.14 a new
  37. * method was added based on continous identifiers which supports an
  38. * arbitary number of groups. Both methods are supported, see
  39. * nl_join_groups() respectively nl_socket_add_membership() and
  40. * nl_socket_drop_membership().
  41. * - \b Peer \b Port: The peer port is a netlink port identifying the
  42. * peer's endpoint. If no peer port is specified, the kernel will try to
  43. * autobind to a socket of the specified netlink family automatically.
  44. * This is very common as typically only one listening socket exists
  45. * on the kernel side. The peer port can be modified using
  46. * nl_socket_set_peer_port().
  47. * - \b Peer \b Groups:
  48. * - \b File \b Descriptor: The file descriptor of the socket, it can be
  49. * accessed via nl_socket_get_fd() to change socket options or monitor
  50. * activity using poll()/select().
  51. * - \b Protocol: Once connected, the socket is bound to stick to one
  52. * netlink family. This field is invisible, it is maintained automatically.
  53. * (See nl_connect())
  54. * - \b Next \b Sequence \b Number: Next available sequence number to be used
  55. * for the next message being sent out. (Initial value: UNIX time when the
  56. * socket was allocated.) Sequence numbers can be used via
  57. * nl_socket_use_seq().
  58. * - \b Expected \b Sequence \b Number: Expected sequence number in the next
  59. * message received from the socket. (Initial value: Equal to next sequence
  60. * number.)
  61. * - \b Callbacks \b Configuration:
  62. *
  63. * @par 1) Creating the netlink handle
  64. * @code
  65. * struct nl_handle *handle;
  66. *
  67. * // Allocate and initialize a new netlink handle
  68. * handle = nl_handle_alloc();
  69. *
  70. * // Use nl_socket_get_fd() to fetch the file description, for example to
  71. * // put a socket into non-blocking i/o mode.
  72. * fcntl(nl_socket_get_fd(handle), F_SETFL, O_NONBLOCK);
  73. * @endcode
  74. *
  75. * @par 2) Group Subscriptions
  76. * @code
  77. * // Event notifications are typically sent to multicast addresses which
  78. * // represented by groups. Join a group to f.e. receive link notifications.
  79. * nl_socket_add_membership(handle, RTNLGRP_LINK);
  80. * @endcode
  81. *
  82. * @par 6) Cleaning up
  83. * @code
  84. * // Finally destroy the netlink handle
  85. * nl_handle_destroy(handle);
  86. * @endcode
  87. *
  88. * @{
  89. */
  90. #include "defs.h"
  91. #include <netlink-local.h>
  92. #include <netlink/netlink.h>
  93. #include <netlink/utils.h>
  94. #include <netlink/handlers.h>
  95. #include <netlink/msg.h>
  96. #include <netlink/attr.h>
  97. static int default_cb = NL_CB_DEFAULT;
  98. static void __init init_default_cb(void)
  99. {
  100. char *nlcb;
  101. if ((nlcb = getenv("NLCB"))) {
  102. if (!strcasecmp(nlcb, "default"))
  103. default_cb = NL_CB_DEFAULT;
  104. else if (!strcasecmp(nlcb, "verbose"))
  105. default_cb = NL_CB_VERBOSE;
  106. else if (!strcasecmp(nlcb, "debug"))
  107. default_cb = NL_CB_DEBUG;
  108. else {
  109. fprintf(stderr, "Unknown value for NLCB, valid values: "
  110. "{default | verbose | debug}\n");
  111. }
  112. }
  113. }
  114. static uint32_t used_ports_map[32];
  115. static NL_RW_LOCK(port_map_lock);
  116. static uint32_t generate_local_port(void)
  117. {
  118. int i, n;
  119. uint32_t pid = getpid() & 0x3FFFFF;
  120. nl_write_lock(&port_map_lock);
  121. for (i = 0; i < 32; i++) {
  122. if (used_ports_map[i] == 0xFFFFFFFF)
  123. continue;
  124. for (n = 0; n < 32; n++) {
  125. if (1UL & (used_ports_map[i] >> n))
  126. continue;
  127. used_ports_map[i] |= (1UL << n);
  128. n += (i * 32);
  129. /* PID_MAX_LIMIT is currently at 2^22, leaving 10 bit
  130. * to, i.e. 1024 unique ports per application. */
  131. nl_write_unlock(&port_map_lock);
  132. return pid + (n << 22);
  133. }
  134. }
  135. nl_write_unlock(&port_map_lock);
  136. /* Out of sockets in our own PID namespace, what to do? FIXME */
  137. return UINT_MAX;
  138. }
  139. static void release_local_port(uint32_t port)
  140. {
  141. int nr;
  142. if (port == UINT_MAX)
  143. return;
  144. nr = port >> 22;
  145. nl_write_lock(&port_map_lock);
  146. used_ports_map[nr / 32] &= ~(1 << (nr % 32));
  147. nl_write_unlock(&port_map_lock);
  148. }
  149. /**
  150. * @name Allocation
  151. * @{
  152. */
  153. static struct nl_handle *__alloc_handle(struct nl_cb *cb)
  154. {
  155. struct nl_handle *handle;
  156. handle = calloc(1, sizeof(*handle));
  157. if (!handle) {
  158. nl_errno(ENOMEM);
  159. return NULL;
  160. }
  161. handle->h_fd = -1;
  162. handle->h_cb = nl_cb_get(cb);
  163. handle->h_local.nl_family = AF_NETLINK;
  164. handle->h_peer.nl_family = AF_NETLINK;
  165. handle->h_seq_expect = handle->h_seq_next = time(0);
  166. handle->h_local.nl_pid = generate_local_port();
  167. if (handle->h_local.nl_pid == UINT_MAX) {
  168. nl_handle_destroy(handle);
  169. nl_error(ENOBUFS, "Out of local ports");
  170. return NULL;
  171. }
  172. return handle;
  173. }
  174. /**
  175. * Allocate new netlink socket handle.
  176. *
  177. * @return Newly allocated netlink socket handle or NULL.
  178. */
  179. struct nl_handle *nl_handle_alloc(void)
  180. {
  181. struct nl_cb *cb;
  182. struct nl_handle *sk;
  183. cb = nl_cb_alloc(default_cb);
  184. if (!cb) {
  185. nl_errno(ENOMEM);
  186. return NULL;
  187. }
  188. /* will increment cb reference count on success */
  189. sk = __alloc_handle(cb);
  190. nl_cb_put(cb);
  191. return sk;
  192. }
  193. /**
  194. * Allocate new socket handle with custom callbacks
  195. * @arg cb Callback handler
  196. *
  197. * The reference to the callback handler is taken into account
  198. * automatically, it is released again upon calling nl_handle_destroy().
  199. *
  200. *@return Newly allocted socket handle or NULL.
  201. */
  202. struct nl_handle *nl_handle_alloc_cb(struct nl_cb *cb)
  203. {
  204. if (cb == NULL)
  205. BUG();
  206. return __alloc_handle(cb);
  207. }
  208. /**
  209. * Destroy netlink handle.
  210. * @arg handle Netlink handle.
  211. */
  212. void nl_handle_destroy(struct nl_handle *handle)
  213. {
  214. if (!handle)
  215. return;
  216. if (handle->h_fd >= 0)
  217. close(handle->h_fd);
  218. if (!(handle->h_flags & NL_OWN_PORT))
  219. release_local_port(handle->h_local.nl_pid);
  220. nl_cb_put(handle->h_cb);
  221. free(handle);
  222. }
  223. /** @} */
  224. /**
  225. * @name Sequence Numbers
  226. * @{
  227. */
  228. static int noop_seq_check(struct nl_msg *msg, void *arg)
  229. {
  230. return NL_OK;
  231. }
  232. /**
  233. * Disable sequence number checking.
  234. * @arg handle Netlink handle.
  235. *
  236. * Disables checking of sequence numbers on the netlink handle. This is
  237. * required to allow messages to be processed which were not requested by
  238. * a preceding request message, e.g. netlink events.
  239. *
  240. * @note This function modifies the NL_CB_SEQ_CHECK configuration in
  241. * the callback handle associated with the socket.
  242. */
  243. void nl_disable_sequence_check(struct nl_handle *handle)
  244. {
  245. nl_cb_set(handle->h_cb, NL_CB_SEQ_CHECK,
  246. NL_CB_CUSTOM, noop_seq_check, NULL);
  247. }
  248. /**
  249. * Use next sequence number
  250. * @arg handle Netlink handle
  251. *
  252. * Uses the next available sequence number and increases the counter
  253. * by one for subsequent calls.
  254. *
  255. * @return Unique serial sequence number
  256. */
  257. unsigned int nl_socket_use_seq(struct nl_handle *handle)
  258. {
  259. return handle->h_seq_next++;
  260. }
  261. /** @} */
  262. /**
  263. * @name Source Idenficiation
  264. * @{
  265. */
  266. uint32_t nl_socket_get_local_port(struct nl_handle *handle)
  267. {
  268. return handle->h_local.nl_pid;
  269. }
  270. /**
  271. * Set local port of socket
  272. * @arg handle Netlink handle
  273. * @arg port Local port identifier
  274. *
  275. * Assigns a local port identifier to the socket. If port is 0
  276. * a unique port identifier will be generated automatically.
  277. */
  278. void nl_socket_set_local_port(struct nl_handle *handle, uint32_t port)
  279. {
  280. if (port == 0) {
  281. port = generate_local_port();
  282. handle->h_flags &= ~NL_OWN_PORT;
  283. } else {
  284. if (!(handle->h_flags & NL_OWN_PORT))
  285. release_local_port(handle->h_local.nl_pid);
  286. handle->h_flags |= NL_OWN_PORT;
  287. }
  288. handle->h_local.nl_pid = port;
  289. }
  290. /** @} */
  291. /**
  292. * @name Group Subscriptions
  293. * @{
  294. */
  295. /**
  296. * Join a group
  297. * @arg handle Netlink handle
  298. * @arg group Group identifier
  299. *
  300. * Joins the specified group using the modern socket option which
  301. * is available since kernel version 2.6.14. It allows joining an
  302. * almost arbitary number of groups without limitation.
  303. *
  304. * Make sure to use the correct group definitions as the older
  305. * bitmask definitions for nl_join_groups() are likely to still
  306. * be present for backward compatibility reasons.
  307. *
  308. * @return 0 on sucess or a negative error code.
  309. */
  310. int nl_socket_add_membership(struct nl_handle *handle, int group)
  311. {
  312. int err;
  313. if (handle->h_fd == -1)
  314. return nl_error(EBADFD, "Socket not connected");
  315. err = setsockopt(handle->h_fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
  316. &group, sizeof(group));
  317. if (err < 0)
  318. return nl_error(errno, "setsockopt(NETLINK_ADD_MEMBERSHIP) "
  319. "failed");
  320. return 0;
  321. }
  322. /**
  323. * Leave a group
  324. * @arg handle Netlink handle
  325. * @arg group Group identifier
  326. *
  327. * Leaves the specified group using the modern socket option
  328. * which is available since kernel version 2.6.14.
  329. *
  330. * @see nl_socket_add_membership
  331. * @return 0 on success or a negative error code.
  332. */
  333. int nl_socket_drop_membership(struct nl_handle *handle, int group)
  334. {
  335. int err;
  336. if (handle->h_fd == -1)
  337. return nl_error(EBADFD, "Socket not connected");
  338. err = setsockopt(handle->h_fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
  339. &group, sizeof(group));
  340. if (err < 0)
  341. return nl_error(errno, "setsockopt(NETLINK_DROP_MEMBERSHIP) "
  342. "failed");
  343. return 0;
  344. }
  345. /**
  346. * Join multicast groups (deprecated)
  347. * @arg handle Netlink handle.
  348. * @arg groups Bitmask of groups to join.
  349. *
  350. * This function defines the old way of joining multicast group which
  351. * has to be done prior to calling nl_connect(). It works on any kernel
  352. * version but is very limited as only 32 groups can be joined.
  353. */
  354. void nl_join_groups(struct nl_handle *handle, int groups)
  355. {
  356. handle->h_local.nl_groups |= groups;
  357. }
  358. /** @} */
  359. /**
  360. * @name Peer Identfication
  361. * @{
  362. */
  363. uint32_t nl_socket_get_peer_port(struct nl_handle *handle)
  364. {
  365. return handle->h_peer.nl_pid;
  366. }
  367. void nl_socket_set_peer_port(struct nl_handle *handle, uint32_t port)
  368. {
  369. handle->h_peer.nl_pid = port;
  370. }
  371. /** @} */
  372. /**
  373. * @name File Descriptor
  374. * @{
  375. */
  376. int nl_socket_get_fd(struct nl_handle *handle)
  377. {
  378. return handle->h_fd;
  379. }
  380. /**
  381. * Set file descriptor of socket handle to non-blocking state
  382. * @arg handle Netlink socket
  383. *
  384. * @return 0 on success or a negative error code.
  385. */
  386. int nl_socket_set_nonblocking(struct nl_handle *handle)
  387. {
  388. if (handle->h_fd == -1)
  389. return nl_error(EBADFD, "Socket not connected");
  390. if (fcntl(handle->h_fd, F_SETFL, O_NONBLOCK) < 0)
  391. return nl_error(errno, "fcntl(F_SETFL, O_NONBLOCK) failed");
  392. return 0;
  393. }
  394. /**
  395. * Enable use of MSG_PEEK when reading from socket
  396. * @arg handle Netlink socket
  397. */
  398. void nl_socket_enable_msg_peek(struct nl_handle *handle)
  399. {
  400. handle->h_flags |= NL_MSG_PEEK;
  401. }
  402. /**
  403. * Disable use of MSG_PEEK when reading from socket
  404. * @arg handle Netlink socket
  405. */
  406. void nl_socket_disable_msg_peek(struct nl_handle *handle)
  407. {
  408. handle->h_flags &= ~NL_MSG_PEEK;
  409. }
  410. /** @} */
  411. /**
  412. * @name Callback Handler
  413. * @{
  414. */
  415. struct nl_cb *nl_socket_get_cb(struct nl_handle *handle)
  416. {
  417. return nl_cb_get(handle->h_cb);
  418. }
  419. void nl_socket_set_cb(struct nl_handle *handle, struct nl_cb *cb)
  420. {
  421. if (cb == NULL)
  422. BUG();
  423. nl_cb_put(handle->h_cb);
  424. handle->h_cb = nl_cb_get(cb);
  425. }
  426. /**
  427. * Modify the callback handler associated to the socket
  428. * @arg handle netlink handle
  429. * @arg type which type callback to set
  430. * @arg kind kind of callback
  431. * @arg func callback function
  432. * @arg arg argument to be passwd to callback function
  433. *
  434. * @see nl_cb_set
  435. */
  436. int nl_socket_modify_cb(struct nl_handle *handle, enum nl_cb_type type,
  437. enum nl_cb_kind kind, nl_recvmsg_msg_cb_t func,
  438. void *arg)
  439. {
  440. return nl_cb_set(handle->h_cb, type, kind, func, arg);
  441. }
  442. /** @} */
  443. /**
  444. * @name Utilities
  445. * @{
  446. */
  447. /**
  448. * Set socket buffer size of netlink handle.
  449. * @arg handle Netlink handle.
  450. * @arg rxbuf New receive socket buffer size in bytes.
  451. * @arg txbuf New transmit socket buffer size in bytes.
  452. *
  453. * Sets the socket buffer size of a netlink handle to the specified
  454. * values \c rxbuf and \c txbuf. Providing a value of \c 0 assumes a
  455. * good default value.
  456. *
  457. * @note It is not required to call this function prior to nl_connect().
  458. * @return 0 on sucess or a negative error code.
  459. */
  460. int nl_set_buffer_size(struct nl_handle *handle, int rxbuf, int txbuf)
  461. {
  462. int err;
  463. if (rxbuf <= 0)
  464. rxbuf = 32768;
  465. if (txbuf <= 0)
  466. txbuf = 32768;
  467. if (handle->h_fd == -1)
  468. return nl_error(EBADFD, "Socket not connected");
  469. err = setsockopt(handle->h_fd, SOL_SOCKET, SO_SNDBUF,
  470. &txbuf, sizeof(txbuf));
  471. if (err < 0)
  472. return nl_error(errno, "setsockopt(SO_SNDBUF) failed");
  473. err = setsockopt(handle->h_fd, SOL_SOCKET, SO_RCVBUF,
  474. &rxbuf, sizeof(rxbuf));
  475. if (err < 0)
  476. return nl_error(errno, "setsockopt(SO_RCVBUF) failed");
  477. handle->h_flags |= NL_SOCK_BUFSIZE_SET;
  478. return 0;
  479. }
  480. /**
  481. * Enable/disable credential passing on netlink handle.
  482. * @arg handle Netlink handle
  483. * @arg state New state (0 - disabled, 1 - enabled)
  484. *
  485. * @return 0 on success or a negative error code
  486. */
  487. int nl_set_passcred(struct nl_handle *handle, int state)
  488. {
  489. int err;
  490. if (handle->h_fd == -1)
  491. return nl_error(EBADFD, "Socket not connected");
  492. err = setsockopt(handle->h_fd, SOL_SOCKET, SO_PASSCRED,
  493. &state, sizeof(state));
  494. if (err < 0)
  495. return nl_error(errno, "setsockopt(SO_PASSCRED) failed");
  496. if (state)
  497. handle->h_flags |= NL_SOCK_PASSCRED;
  498. else
  499. handle->h_flags &= ~NL_SOCK_PASSCRED;
  500. return 0;
  501. }
  502. /**
  503. * Enable/disable receival of additional packet information
  504. * @arg handle Netlink handle
  505. * @arg state New state (0 - disabled, 1 - enabled)
  506. *
  507. * @return 0 on success or a negative error code
  508. */
  509. int nl_socket_recv_pktinfo(struct nl_handle *handle, int state)
  510. {
  511. int err;
  512. if (handle->h_fd == -1)
  513. return nl_error(EBADFD, "Socket not connected");
  514. err = setsockopt(handle->h_fd, SOL_NETLINK, NETLINK_PKTINFO,
  515. &state, sizeof(state));
  516. if (err < 0)
  517. return nl_error(errno, "setsockopt(NETLINK_PKTINFO) failed");
  518. return 0;
  519. }
  520. /** @} */
  521. /** @} */