nl.c 30 KB

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