/build/buildd/libnl-1.0~pre6/lib/nl.c

00001 /*
00002  * lib/nl.c             Core Netlink Interface
00003  *
00004  *      This library is free software; you can redistribute it and/or
00005  *      modify it under the terms of the GNU Lesser General Public
00006  *      License as published by the Free Software Foundation version 2.1
00007  *      of the License.
00008  *
00009  * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
00010  */
00011 
00012 /**
00013  * @defgroup nl Core Netlink API
00014  * @brief
00015  *
00016  * @par 1) Creating the netlink handle
00017  * @code
00018  * struct nl_handle *handle;
00019  *
00020  * // Allocate and initialize a new netlink handle
00021  * handle = nl_handle_new();
00022  *
00023  * // Are multiple handles being allocated? You have to provide a unique
00024  * // netlink process id and overwrite the default local process id.
00025  * nl_handle_set_pid(handle, MY_UNIQUE_PID);
00026  *
00027  * // Is this socket used for event processing? You need to disable sequence
00028  * // number checking in order to be able to receive messages not explicitely
00029  * // requested.
00030  * nl_disable_sequence_check(handle);
00031  *
00032  * // Use nl_handle_get_fd() to fetch the file description, for example to
00033  * // put a socket into non-blocking i/o mode.
00034  * fcntl(nl_handle_get_fd(handle), F_SETFL, O_NONBLOCK);
00035  * @endcode
00036  *
00037  * @par 2) Joining Groups
00038  * @code
00039  * // You may join/subscribe to as many groups as you want, don't forget
00040  * // to eventually disable sequence number checking. Note: Joining must
00041  * // be done before connecting/binding the socket.
00042  * nl_join_groups(handle, GROUP_ID1 | GROUP_ID2);
00043  * @endcode
00044  *
00045  * @par 3) Connecting the socket
00046  * @code
00047  * // Bind and connect the socket to a protocol, NETLINK_ROUTE in this example.
00048  * nl_connect(handle, NETLINK_ROUTE);
00049  * @endcode
00050  *
00051  * @par 4) Sending data
00052  * @code
00053  * // The most rudimentary method is to use nl_sendto() simply pushing
00054  * // a piece of data to the other netlink peer. This method is not
00055  * // recommended.
00056  * const char buf[] = { 0x01, 0x02, 0x03, 0x04 };
00057  * nl_sendto(handle, buf, sizeof(buf));
00058  *
00059  * // A more comfortable interface is nl_send() taking a pointer to
00060  * // a netlink message.
00061  * struct nl_msg *msg = my_msg_builder();
00062  * nl_send(handle, nlmsg_hdr(msg));
00063  *
00064  * // nl_sendmsg() provides additional control over the sendmsg() message
00065  * // header in order to allow more specific addressing of multiple peers etc.
00066  * struct msghdr hdr = { ... };
00067  * nl_sendmsg(handle, nlmsg_hdr(msg), &hdr);
00068  *
00069  * // You're probably too lazy to fill out the netlink pid, sequence number
00070  * // and message flags all the time. nl_send_auto_complete() automatically
00071  * // extends your message header as needed with an appropriate sequence
00072  * // number, the netlink pid stored in the netlink handle and the message
00073  * // flags NLM_F_REQUEST and NLM_F_ACK
00074  * nl_send_auto_complete(handle, nlmsg_hdr(msg));
00075  *
00076  * // Simple protocols don't require the complex message construction interface
00077  * // and may favour nl_send_simple() to easly send a bunch of payload
00078  * // encapsulated in a netlink message header.
00079  * nl_send_simple(handle, MY_MSG_TYPE, 0, buf, sizeof(buf));
00080  * @endcode
00081  *
00082  * @par 5) Receiving data
00083  * @code
00084  * // nl_recv() receives a single message allocating a buffer for the message
00085  * // content and gives back the pointer to you.
00086  * struct sockaddr_nl peer;
00087  * unsigned char *msg;
00088  * nl_recv(handle, &peer, &msg);
00089  *
00090  * // nl_recvmsgs() receives a bunch of messages until the callback system
00091  * // orders it to state, usually after receving a compolete multi part
00092  * // message series.
00093  * nl_recvmsgs(handle, my_callback_configuration);
00094  *
00095  * // nl_recvmsgs_def() acts just like nl_recvmsg() but uses the callback
00096  * // configuration stored in the handle.
00097  * nl_recvmsgs_def(handle);
00098  *
00099  * // In case you want to wait for the ACK to be recieved that you requested
00100  * // with your latest message, you can call nl_wait_for_ack()
00101  * nl_wait_for_ack(handle);
00102  * @endcode
00103  *
00104  * @par 6) Cleaning up
00105  * @code
00106  * // Close the socket first to release kernel memory
00107  * nl_close(handle);
00108  *
00109  * // Finally destroy the netlink handle
00110  * nl_handle_destroy(handle);
00111  * @endcode
00112  * 
00113  * @{
00114  */
00115 
00116 #include <netlink-local.h>
00117 #include <netlink/netlink.h>
00118 #include <netlink/utils.h>
00119 #include <netlink/handlers.h>
00120 #include <netlink/msg.h>
00121 #include <netlink/attr.h>
00122 
00123 /**
00124  * @name Handle Management
00125  * @{
00126  */
00127 
00128 /**
00129  * Allocate and initialize new non-default netlink handle.
00130  * @arg kind            Kind of callback handler to use per default.
00131  *
00132  * Allocates and initializes a new netlink handle, the netlink process id
00133  * is set to the local process id which may conflict if multiple handles
00134  * are created, therefore you may have to overwrite it using
00135  * nl_handle_set_pid(). The initial sequence number is initialized to the
00136  * current UNIX time.
00137  *
00138  * @return Newly allocated netlink handle or NULL.
00139  */
00140 struct nl_handle *nl_handle_alloc_nondefault(enum nl_cb_kind kind)
00141 {
00142         struct nl_handle *handle;
00143         
00144         handle = calloc(1, sizeof(*handle));
00145         if (!handle)
00146                 goto errout;
00147 
00148         handle->h_cb = nl_cb_new(kind);
00149         if (!handle->h_cb)
00150                 goto errout;
00151         
00152         handle->h_local.nl_family = AF_NETLINK;
00153         handle->h_peer.nl_family = AF_NETLINK;
00154         handle->h_local.nl_pid = getpid();
00155         handle->h_seq_expect = handle->h_seq_next = time(0);
00156 
00157         return handle;
00158 errout:
00159         nl_handle_destroy(handle);
00160         nl_errno(ENOMEM);
00161         return NULL;
00162 }
00163 
00164 /**
00165  * Allocate and initialize new netlink handle.
00166  *
00167  * Allocates and initializes a new netlink handle, the netlink process id
00168  * is set to the local process id which may conflict if multiple handles
00169  * are created, therefore you may have to overwrite it using
00170  * nl_handle_set_pid(). The initial sequence number is initialized to the
00171  * current UNIX time. The default callback (NL_CB_DEFAULT) handlers are
00172  * being used.
00173  *
00174  * @return Newly allocated netlink handle or NULL.
00175  */
00176 struct nl_handle *nl_handle_alloc(void)
00177 {
00178         return nl_handle_alloc_nondefault(NL_CB_DEFAULT);
00179 }
00180 
00181 /**
00182  * Destroy netlink handle.
00183  * @arg handle          Netlink handle.
00184  */
00185 void nl_handle_destroy(struct nl_handle *handle)
00186 {
00187         if (!handle)
00188                 return;
00189 
00190         nl_cb_destroy(handle->h_cb);
00191         free(handle);
00192 }
00193 
00194 /** @} */
00195 
00196 /**
00197  * @name Utilities
00198  * @{
00199  */
00200 
00201 /**
00202  * Set socket buffer size of netlink handle.
00203  * @arg handle          Netlink handle.
00204  * @arg rxbuf           New receive socket buffer size in bytes.
00205  * @arg txbuf           New transmit socket buffer size in bytes.
00206  *
00207  * Sets the socket buffer size of a netlink handle to the specified
00208  * values \c rxbuf and \c txbuf. Providing a value of \c 0 assumes a
00209  * good default value.
00210  *
00211  * @note It is not required to call this function prior to nl_connect().
00212  * @return 0 on sucess or a negative error code.
00213  */
00214 int nl_set_buffer_size(struct nl_handle *handle, int rxbuf, int txbuf)
00215 {
00216         int err;
00217 
00218         if (rxbuf <= 0)
00219                 rxbuf = 32768;
00220 
00221         if (txbuf <= 0)
00222                 txbuf = 32768;
00223         
00224         err = setsockopt(handle->h_fd, SOL_SOCKET, SO_SNDBUF,
00225                          &txbuf, sizeof(txbuf));
00226         if (err < 0)
00227                 return nl_error(errno, "setsockopt(SO_SNDBUF) failed");
00228 
00229         err = setsockopt(handle->h_fd, SOL_SOCKET, SO_RCVBUF,
00230                          &rxbuf, sizeof(rxbuf));
00231         if (err < 0)
00232                 return nl_error(errno, "setsockopt(SO_RCVBUF) failed");
00233 
00234         handle->h_flags |= NL_SOCK_BUFSIZE_SET;
00235 
00236         return 0;
00237 }
00238 
00239 /**
00240  * Enable/disable credential passing on netlink handle.
00241  * @arg handle          Netlink handle
00242  * @arg state           New state (0 - disabled, 1 - enabled)
00243  */
00244 int nl_set_passcred(struct nl_handle *handle, int state)
00245 {
00246         int err;
00247 
00248         err = setsockopt(handle->h_fd, SOL_SOCKET, SO_PASSCRED,
00249                          &state, sizeof(state));
00250         if (err < 0)
00251                 return nl_error(errno, "setsockopt(SO_PASSCRED) failed");
00252 
00253         if (state)
00254                 handle->h_flags |= NL_SOCK_PASSCRED;
00255         else
00256                 handle->h_flags &= ~NL_SOCK_PASSCRED;
00257 
00258         return 0;
00259 }
00260 
00261 /**
00262  * Join multicast groups.
00263  * @arg handle          Netlink handle.
00264  * @arg groups          Bitmask of groups to join.
00265  *
00266  * @note Joining of groups must be done prior to connecting/binding
00267  *       the socket (nl_connect()).
00268  */
00269 void nl_join_groups(struct nl_handle *handle, int groups)
00270 {
00271         handle->h_local.nl_groups |= groups;
00272 }
00273 
00274 #ifndef SOL_NETLINK
00275 #define SOL_NETLINK 270
00276 #endif
00277 
00278 int nl_join_group(struct nl_handle *handle, int group)
00279 {
00280         int err;
00281 
00282         err = setsockopt(handle->h_fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
00283                          &group, sizeof(group));
00284         if (err < 0)
00285                 return nl_error(errno, "setsockopt(NETLINK_ADD_MEMBERSHIP) "
00286                                        "failed");
00287 
00288         return 0;
00289 }
00290 
00291 static int noop_seq_check(struct nl_msg *msg, void *arg)
00292 {
00293         return NL_PROCEED;
00294 }
00295 
00296 /**
00297  * Disable sequence number checking.
00298  * @arg handle          Netlink handle.
00299  *
00300  * Disables checking of sequence numbers on the netlink handle. This is
00301  * required to allow messages to be processed which were not requested by
00302  * a preceding request message, e.g. netlink events.
00303  */
00304 void nl_disable_sequence_check(struct nl_handle *handle)
00305 {
00306         nl_cb_set(nl_handle_get_cb(handle), NL_CB_SEQ_CHECK,
00307                   NL_CB_CUSTOM, noop_seq_check, NULL);
00308 }
00309 
00310 /** @} */
00311 
00312 /**
00313  * @name Acccess Functions
00314  * @{
00315  */
00316 
00317 /**
00318  * Get netlink process identifier of netlink handle.
00319  * @arg handle          Netlink handle.
00320  * @return Netlink process identifier.
00321  */
00322 pid_t nl_handle_get_pid(struct nl_handle *handle)
00323 {
00324         return handle->h_local.nl_pid;
00325 }
00326 
00327 /**
00328  * Set netlink process identifier of netlink handle.
00329  * @arg handle          Netlink handle.
00330  * @arg pid             New netlink process identifier.
00331  */
00332 void nl_handle_set_pid(struct nl_handle *handle, pid_t pid)
00333 {
00334         handle->h_local.nl_pid = pid;
00335 }
00336 
00337 /**
00338  * Get netlink process identifier of peer from netlink handle.
00339  * @arg handle          Netlink handle.
00340  * @return Netlink process identifier.
00341  */
00342 pid_t nl_handle_get_peer_pid(struct nl_handle *handle)
00343 {
00344         return handle->h_peer.nl_pid;
00345 }
00346 
00347 /**
00348  * Set netlink process identifier of peer in netlink handle.
00349  * @arg handle          Netlink handle.
00350  * @arg pid             New netlink process identifier.
00351  */
00352 void nl_handle_set_peer_pid(struct nl_handle *handle, pid_t pid)
00353 {
00354         handle->h_peer.nl_pid = pid;
00355 }
00356 
00357 /**
00358  * Get file descriptor of netlink handle.
00359  * @arg handle          Netlink handle.
00360  * @return File descriptor of netlink socket or -1 if not connected.
00361  */
00362 int nl_handle_get_fd(struct nl_handle *handle)
00363 {
00364         return handle->h_fd;
00365 }
00366 
00367 /**
00368  * Get local netlink address of netlink handle.
00369  * @arg handle          Netlink handle.
00370  * @return Local netlink address.
00371  */
00372 struct sockaddr_nl *nl_handle_get_local_addr(struct nl_handle *handle)
00373 {
00374         return &handle->h_local;
00375 }
00376 
00377 /**
00378  * Get peer netlink address of netlink handle.
00379  * @arg handle          Netlink handle.
00380  * @note The peer address is undefined while the socket is unconnected.
00381  * @return Netlink address of the peer.
00382  */
00383 struct sockaddr_nl *nl_handle_get_peer_addr(struct nl_handle *handle)
00384 {
00385         return &handle->h_peer;
00386 }
00387 
00388 /**
00389  * Get callback configuration of netlink handle.
00390  * @arg handle          Netlink handle.
00391  * @return Currently active callback configuration or NULL if not available.
00392  */
00393 struct nl_cb *nl_handle_get_cb(struct nl_handle *handle)
00394 {
00395         return handle->h_cb;
00396 }
00397 
00398 /** @} */
00399 
00400 /**
00401  * @name Connection Management
00402  * @{
00403  */
00404 
00405 /**
00406  * Create and connect netlink socket.
00407  * @arg handle          Netlink handle.
00408  * @arg protocol        Netlink protocol to use.
00409  *
00410  * Creates a netlink socket using the specified protocol, binds the socket
00411  * and issues a connection attempt.
00412  *
00413  * @return 0 on success or a negative error code.
00414  */
00415 int nl_connect(struct nl_handle *handle, int protocol)
00416 {
00417         int err;
00418         socklen_t addrlen;
00419 
00420         handle->h_fd = socket(AF_NETLINK, SOCK_RAW, protocol);
00421         if (handle->h_fd < 0)
00422                 return nl_error(1, "socket(AF_NETLINK, ...) failed");
00423 
00424         if (!(handle->h_flags & NL_SOCK_BUFSIZE_SET)) {
00425                 err = nl_set_buffer_size(handle, 0, 0);
00426                 if (err < 0)
00427                         return err;
00428         }
00429 
00430         err = bind(handle->h_fd, (struct sockaddr*) &handle->h_local,
00431                    sizeof(handle->h_local));
00432         if (err < 0)
00433                 return nl_error(1, "bind() failed");
00434 
00435         addrlen = sizeof(handle->h_local);
00436         err = getsockname(handle->h_fd, (struct sockaddr *) &handle->h_local,
00437                           &addrlen);
00438         if (err < 0)
00439                 return nl_error(1, "getsockname failed");
00440 
00441         if (addrlen != sizeof(handle->h_local))
00442                 return nl_error(EADDRNOTAVAIL, "Invalid address length");
00443 
00444         if (handle->h_local.nl_family != AF_NETLINK)
00445                 return nl_error(EPFNOSUPPORT, "Address format not supported");
00446 
00447         handle->h_proto = protocol;
00448 
00449         return 0;
00450 }
00451 
00452 /**
00453  * Close/Disconnect netlink socket.
00454  * @arg handle          Netlink handle
00455  */
00456 void nl_close(struct nl_handle *handle)
00457 {
00458         if (handle->h_fd >= 0) {
00459                 close(handle->h_fd);
00460                 handle->h_fd = -1;
00461         }
00462 
00463         handle->h_proto = 0;
00464 }
00465 
00466 /** @} */
00467 
00468 /**
00469  * @name Send
00470  * @{
00471  */
00472 
00473 /**
00474  * Send raw data over netlink socket.
00475  * @arg handle          Netlink handle.
00476  * @arg buf             Data buffer.
00477  * @arg size            Size of data buffer.
00478  * @return Number of characters written on success or a negative error code.
00479  */
00480 int nl_sendto(struct nl_handle *handle, void *buf, size_t size)
00481 {
00482         int ret;
00483 
00484         ret = sendto(handle->h_fd, buf, size, 0, (struct sockaddr *)
00485                      &handle->h_peer, sizeof(handle->h_peer));
00486         if (ret < 0)
00487                 return nl_errno(errno);
00488 
00489         return ret;
00490 }
00491 
00492 /**
00493  * Send netlink message with control over sendmsg() message header.
00494  * @arg handle          Netlink handle.
00495  * @arg msg             Netlink message to be sent.
00496  * @arg hdr             Sendmsg() message header.
00497  * @return Number of characters sent on sucess or a negative error code.
00498  */
00499 int nl_sendmsg(struct nl_handle *handle, struct nl_msg *msg, struct msghdr *hdr)
00500 {
00501         struct nl_cb *cb;
00502         int ret;
00503 
00504         struct iovec iov = {
00505                 .iov_base = (void *) nlmsg_hdr(msg),
00506                 .iov_len = nlmsg_hdr(msg)->nlmsg_len,
00507         };
00508 
00509         hdr->msg_iov = &iov;
00510         hdr->msg_iovlen = 1;
00511 
00512         nlmsg_set_src(msg, &handle->h_local);
00513 
00514         cb = nl_handle_get_cb(handle);
00515         if (cb->cb_set[NL_CB_MSG_OUT])
00516                 if (nl_cb_call(cb, NL_CB_MSG_OUT, msg) != NL_PROCEED)
00517                         return 0;
00518 
00519         ret = sendmsg(handle->h_fd, hdr, 0);
00520         if (ret < 0)
00521                 return nl_errno(errno);
00522 
00523         return ret;
00524 }
00525 
00526 
00527 /**
00528  * Send netlink message.
00529  * @arg handle          Netlink handle
00530  * @arg msg             Netlink message to be sent.
00531  * @see nl_sendmsg()
00532  * @return Number of characters sent on success or a negative error code.
00533  */
00534 int nl_send(struct nl_handle *handle, struct nl_msg *msg)
00535 {
00536         struct sockaddr_nl *dst;
00537         struct ucred *creds;
00538         
00539         struct msghdr hdr = {
00540                 .msg_name = (void *) &handle->h_peer,
00541                 .msg_namelen = sizeof(struct sockaddr_nl),
00542         };
00543 
00544         /* Overwrite destination if specified in the message itself, defaults
00545          * to the peer address of the handle.
00546          */
00547         dst = nlmsg_get_dst(msg);
00548         if (dst->nl_family == AF_NETLINK)
00549                 hdr.msg_name = dst;
00550 
00551         /* Add credentials if present. */
00552         creds = nlmsg_get_creds(msg);
00553         if (creds != NULL) {
00554                 char buf[CMSG_SPACE(sizeof(struct ucred))];
00555                 struct cmsghdr *cmsg;
00556 
00557                 hdr.msg_control = buf;
00558                 hdr.msg_controllen = sizeof(buf);
00559 
00560                 cmsg = CMSG_FIRSTHDR(&hdr);
00561                 cmsg->cmsg_level = SOL_SOCKET;
00562                 cmsg->cmsg_type = SCM_CREDENTIALS;
00563                 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
00564                 memcpy(CMSG_DATA(cmsg), creds, sizeof(struct ucred));
00565         }
00566 
00567         return nl_sendmsg(handle, msg, &hdr);
00568 }
00569 
00570 /**
00571  * Send netlink message and check & extend header values as needed.
00572  * @arg handle          Netlink handle.
00573  * @arg msg             Netlink message to be sent.
00574  *
00575  * Checks the netlink message \c nlh for completness and extends it
00576  * as required before sending it out. Checked fields include pid,
00577  * sequence nr, and flags.
00578  *
00579  * @see nl_send()
00580  * @return Number of characters sent or a negative error code.
00581  */
00582 int nl_send_auto_complete(struct nl_handle *handle, struct nl_msg *msg)
00583 {
00584         struct nlmsghdr *nlh;
00585 
00586         nlh = nlmsg_hdr(msg);
00587         if (nlh->nlmsg_pid == 0)
00588                 nlh->nlmsg_pid = handle->h_local.nl_pid;
00589 
00590         if (nlh->nlmsg_seq == 0)
00591                 nlh->nlmsg_seq = handle->h_seq_next++;
00592         
00593         nlh->nlmsg_flags |= (NLM_F_REQUEST | NLM_F_ACK);
00594 
00595         if (handle->h_cb->cb_send_ow)
00596                 return handle->h_cb->cb_send_ow(handle, msg);
00597         else
00598                 return nl_send(handle, msg);
00599 }
00600 
00601 /**
00602  * Send simple netlink message using nl_send_auto_complete()
00603  * @arg handle          Netlink handle.
00604  * @arg type            Netlink message type.
00605  * @arg flags           Netlink message flags.
00606  * @arg buf             Data buffer.
00607  * @arg size            Size of data buffer.
00608  *
00609  * Builds a netlink message with the specified type and flags and
00610  * appends the specified data as payload to the message.
00611  *
00612  * @see nl_send_auto_complete()
00613  * @return Number of characters sent on success or a negative error code.
00614  */
00615 int nl_send_simple(struct nl_handle *handle, int type, int flags, void *buf,
00616                    size_t size)
00617 {
00618         int err;
00619         struct nl_msg *msg;
00620         struct nlmsghdr nlh = {
00621                 .nlmsg_len = nlmsg_msg_size(0),
00622                 .nlmsg_type = type,
00623                 .nlmsg_flags = flags,
00624         };
00625 
00626         msg = nlmsg_build(&nlh);
00627         if (!msg)
00628                 return nl_errno(ENOMEM);
00629 
00630         if (buf && size)
00631                 nlmsg_append(msg, buf, size, 1);
00632 
00633         err = nl_send_auto_complete(handle, msg);
00634         nlmsg_free(msg);
00635 
00636         return err;
00637 }
00638 
00639 /** @} */
00640 
00641 /**
00642  * @name Receive
00643  * @{
00644  */
00645 
00646 /**
00647  * Receive netlink message from netlink socket.
00648  * @arg handle          Netlink handle.
00649  * @arg nla             Destination pointer for peer's netlink address.
00650  * @arg buf             Destination pointer for message content.
00651  * @arg creds           Destination pointer for credentials.
00652  *
00653  * Receives a netlink message, allocates a buffer in \c *buf and
00654  * stores the message content. The peer's netlink address is stored
00655  * in \c *nla. The caller is responsible for freeing the buffer allocated
00656  * in \c *buf if a positive value is returned.  Interruped system calls
00657  * are handled by repeating the read. The input buffer size is determined
00658  * by peeking before the actual read is done.
00659  *
00660  * A non-blocking sockets causes the function to return immediately if
00661  * no data is available.
00662  *
00663  * @return Number of octets read, 0 on EOF or a negative error code.
00664  */
00665 int nl_recv(struct nl_handle *handle, struct sockaddr_nl *nla,
00666             unsigned char **buf, struct ucred **creds)
00667 {
00668         int n;
00669         int flags = MSG_PEEK;
00670 
00671         struct iovec iov = {
00672                 .iov_len = 4096,
00673         };
00674 
00675         struct msghdr msg = {
00676                 .msg_name = (void *) nla,
00677                 .msg_namelen = sizeof(sizeof(struct sockaddr_nl)),
00678                 .msg_iov = &iov,
00679                 .msg_iovlen = 1,
00680                 .msg_control = NULL,
00681                 .msg_controllen = 0,
00682                 .msg_flags = 0,
00683         };
00684         struct cmsghdr *cmsg;
00685 
00686         iov.iov_base = *buf = calloc(1, iov.iov_len);
00687 
00688         if (handle->h_flags & NL_SOCK_PASSCRED) {
00689                 msg.msg_controllen = CMSG_SPACE(sizeof(struct ucred));
00690                 msg.msg_control = calloc(1, msg.msg_controllen);
00691         }
00692 retry:
00693 
00694         if ((n = recvmsg(handle->h_fd, &msg, flags)) <= 0) {
00695                 if (!n)
00696                         goto abort;
00697                 else if (n < 0) {
00698                         if (errno == EINTR)
00699                                 goto retry;
00700                         else if (errno == EAGAIN)
00701                                 goto abort;
00702                         else {
00703                                 free(msg.msg_control);
00704                                 free(*buf);
00705                                 return nl_error(errno, "recvmsg failed");
00706                         }
00707                 }
00708         }
00709         
00710         if (iov.iov_len < n) {
00711                 /* Provided buffer is not long enough, enlarge it
00712                  * and try again. */
00713                 iov.iov_len *= 2;
00714                 iov.iov_base = *buf = realloc(*buf, iov.iov_len);
00715                 goto retry;
00716         } else if (msg.msg_flags & MSG_CTRUNC) {
00717                 msg.msg_controllen *= 2;
00718                 msg.msg_control = realloc(msg.msg_control, msg.msg_controllen);
00719                 goto retry;
00720         } else if (flags != 0) {
00721                 /* Buffer is big enough, do the actual reading */
00722                 flags = 0;
00723                 goto retry;
00724         }
00725 
00726         if (msg.msg_namelen != sizeof(struct sockaddr_nl)) {
00727                 free(msg.msg_control);
00728                 free(*buf);
00729                 return nl_error(EADDRNOTAVAIL, "socket address size mismatch");
00730         }
00731 
00732         for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
00733                 if (cmsg->cmsg_level == SOL_SOCKET &&
00734                     cmsg->cmsg_type == SCM_CREDENTIALS) {
00735                         *creds = calloc(1, sizeof(struct ucred));
00736                         memcpy(*creds, CMSG_DATA(cmsg), sizeof(struct ucred));
00737                         break;
00738                 }
00739         }
00740 
00741         free(msg.msg_control);
00742         return n;
00743 
00744 abort:
00745         free(msg.msg_control);
00746         free(*buf);
00747         return 0;
00748 }
00749 
00750 
00751 /**
00752  * Receive a set of messages from a netlink socket.
00753  * @arg handle          netlink handle
00754  * @arg cb              set of callbacks to control the behaviour.
00755  *
00756  * Repeatedly calls nl_recv() and parses the messages as netlink
00757  * messages. Stops reading if one of the callbacks returns
00758  * NL_EXIT or nl_recv returns either 0 or a negative error code.
00759  *
00760  * A non-blocking sockets causes the function to return immediately if
00761  * no data is available.
00762  *
00763  * @return 0 on success or a negative error code from nl_recv().
00764  */
00765 int nl_recvmsgs(struct nl_handle *handle, struct nl_cb *cb)
00766 {
00767         int n, err = 0;
00768         unsigned char *buf = NULL;
00769         struct nlmsghdr *hdr;
00770         struct sockaddr_nl nla = {0};
00771         struct nl_msg *msg = NULL;
00772         struct ucred *creds = NULL;
00773 
00774 continue_reading:
00775         if (cb->cb_recv_ow)
00776                 n = cb->cb_recv_ow(handle, &nla, &buf, &creds);
00777         else
00778                 n = nl_recv(handle, &nla, &buf, &creds);
00779 
00780         if (n <= 0)
00781                 return n;
00782 
00783         NL_DBG(3, "recvmsgs(%p): Read %d bytes\n", handle, n);
00784 
00785         hdr = (struct nlmsghdr *) buf;
00786         while (nlmsg_ok(hdr, n)) {
00787                 NL_DBG(3, "recgmsgs(%p): Processing valid message...\n",
00788                        handle);
00789 
00790                 nlmsg_free(msg);
00791                 msg = nlmsg_convert(hdr);
00792                 if (!msg) {
00793                         err = nl_errno(ENOMEM);
00794                         goto out;
00795                 }
00796 
00797                 nlmsg_set_proto(msg, handle->h_proto);
00798                 nlmsg_set_src(msg, &nla);
00799                 if (creds)
00800                         nlmsg_set_creds(msg, creds);
00801 
00802                 /* Raw callback is the first, it gives the most control
00803                  * to the user and he can do his very own parsing. */
00804                 if (cb->cb_set[NL_CB_MSG_IN]) {
00805                         err = nl_cb_call(cb, NL_CB_MSG_IN, msg);
00806                         if (err == NL_SKIP)
00807                                 goto skip;
00808                         else if (err == NL_EXIT || err < 0)
00809                                 goto out;
00810                 }
00811 
00812                 /* Sequence number checking. The check may be done by
00813                  * the user, otherwise a very simple check is applied
00814                  * enforcing strict ordering */
00815                 if (cb->cb_set[NL_CB_SEQ_CHECK]) {
00816                         err = nl_cb_call(cb, NL_CB_SEQ_CHECK, msg);
00817                         if (err == NL_SKIP)
00818                                 goto skip;
00819                         else if (err == NL_EXIT || err < 0)
00820                                 goto out;
00821                 } else if (hdr->nlmsg_seq != handle->h_seq_expect) {
00822                         if (cb->cb_set[NL_CB_INVALID]) {
00823                                 err = nl_cb_call(cb, NL_CB_INVALID, msg);
00824                                 if (err == NL_SKIP)
00825                                         goto skip;
00826                                 else if (err == NL_EXIT || err < 0)
00827                                         goto out;
00828                         } else
00829                                 goto out;
00830                 }
00831 
00832                 if (hdr->nlmsg_type == NLMSG_DONE ||
00833                     hdr->nlmsg_type == NLMSG_ERROR ||
00834                     hdr->nlmsg_type == NLMSG_NOOP ||
00835                     hdr->nlmsg_type == NLMSG_OVERRUN) {
00836                         /* We can't check for !NLM_F_MULTI since some netlink
00837                          * users in the kernel are broken. */
00838                         handle->h_seq_expect++;
00839                         NL_DBG(3, "recvmsgs(%p): Increased expected " \
00840                                "sequence number to %d\n",
00841                                handle, handle->h_seq_expect);
00842                 }
00843         
00844                 /* Other side wishes to see an ack for this message */
00845                 if (hdr->nlmsg_flags & NLM_F_ACK) {
00846                         if (cb->cb_set[NL_CB_SEND_ACK]) {
00847                                 err = nl_cb_call(cb, NL_CB_SEND_ACK, msg);
00848                                 if (err == NL_SKIP)
00849                                         goto skip;
00850                                 else if (err == NL_EXIT || err < 0)
00851                                         goto out;
00852                         } else {
00853                                 /* FIXME: implement */
00854                         }
00855                 }
00856 
00857                 /* messages terminates a multpart message, this is
00858                  * usually the end of a message and therefore we slip
00859                  * out of the loop by default. the user may overrule
00860                  * this action by skipping this packet. */
00861                 if (hdr->nlmsg_type == NLMSG_DONE) {
00862                         if (cb->cb_set[NL_CB_FINISH]) {
00863                                 err = nl_cb_call(cb, NL_CB_FINISH, msg);
00864                                 if (err == NL_SKIP)
00865                                         goto skip;
00866                                 else if (err == NL_EXIT || err < 0)
00867                                         goto out;
00868                         }
00869                         err = 0;
00870                         goto out;
00871                 }
00872 
00873                 /* Message to be ignored, the default action is to
00874                  * skip this message if no callback is specified. The
00875                  * user may overrule this action by returning
00876                  * NL_PROCEED. */
00877                 else if (hdr->nlmsg_type == NLMSG_NOOP) {
00878                         if (cb->cb_set[NL_CB_SKIPPED]) {
00879                                 err = nl_cb_call(cb, NL_CB_SKIPPED, msg);
00880                                 if (err == NL_SKIP)
00881                                         goto skip;
00882                                 else if (err == NL_EXIT || err < 0)
00883                                         goto out;
00884                         } else
00885                                 goto skip;
00886                 }
00887 
00888                 /* Data got lost, report back to user. The default action is to
00889                  * quit parsing. The user may overrule this action by retuning
00890                  * NL_SKIP or NL_PROCEED (dangerous) */
00891                 else if (hdr->nlmsg_type == NLMSG_OVERRUN) {
00892                         if (cb->cb_set[NL_CB_OVERRUN]) {
00893                                 err = nl_cb_call(cb, NL_CB_OVERRUN, msg);
00894                                 if (err == NL_SKIP)
00895                                         goto skip;
00896                                 else if (err == NL_EXIT || err < 0)
00897                                         goto out;
00898                         } else
00899                                 goto out;
00900                 }
00901 
00902                 /* Message carries a nlmsgerr */
00903                 else if (hdr->nlmsg_type == NLMSG_ERROR) {
00904                         struct nlmsgerr *e = nlmsg_data(hdr);
00905 
00906                         if (hdr->nlmsg_len < nlmsg_msg_size(sizeof(*e))) {
00907                                 /* Truncated error message, the default action
00908                                  * is to stop parsing. The user may overrule
00909                                  * this action by returning NL_SKIP or
00910                                  * NL_PROCEED (dangerous) */
00911                                 if (cb->cb_set[NL_CB_INVALID]) {
00912                                         err = nl_cb_call(cb, NL_CB_INVALID,
00913                                                          msg);
00914                                         if (err == NL_SKIP)
00915                                                 goto skip;
00916                                         else if (err == NL_EXIT || err < 0)
00917                                                 goto out;
00918                                 } else
00919                                         goto out;
00920                         } else if (e->error) {
00921                                 /* Error message reported back from kernel. */
00922                                 if (cb->cb_err) {
00923                                         err = cb->cb_err(&nla, e,
00924                                                            cb->cb_err_arg);
00925                                         if (err == NL_SKIP)
00926                                                 goto skip;
00927                                         else if (err == NL_EXIT || err < 0) {
00928                                                 nl_error(-e->error,
00929                                                          "Netlink Error");
00930                                                 err = e->error;
00931                                                 goto out;
00932                                         }
00933                                 } else {
00934                                         nl_error(-e->error, "Netlink Error");
00935                                         err = e->error;
00936                                         goto out;
00937                                 }
00938                         } else if (cb->cb_set[NL_CB_ACK]) {
00939                                 /* ACK */
00940                                 err = nl_cb_call(cb, NL_CB_ACK, msg);
00941                                 if (err == NL_SKIP)
00942                                         goto skip;
00943                                 else if (err == NL_EXIT || err < 0)
00944                                         goto out;
00945                         }
00946                 } else {
00947                         /* Valid message (not checking for MULTIPART bit to
00948                          * get along with broken kernels. NL_SKIP has no
00949                          * effect on this.  */
00950                         if (cb->cb_set[NL_CB_VALID]) {
00951                                 err = nl_cb_call(cb, NL_CB_VALID, msg);
00952                                 if (err == NL_SKIP)
00953                                         goto skip;
00954                                 else if (err == NL_EXIT || err < 0)
00955                                         goto out;
00956                         }
00957                 }
00958 skip:
00959                 hdr = nlmsg_next(hdr, &n);
00960         }
00961         
00962         nlmsg_free(msg);
00963         free(buf);
00964         free(creds);
00965         buf = NULL;
00966         msg = NULL;
00967         creds = NULL;
00968 
00969         /* Multipart message not yet complete, continue reading */
00970         goto continue_reading;
00971 
00972 out:
00973         nlmsg_free(msg);
00974         free(buf);
00975         free(creds);
00976 
00977         return err;
00978 }
00979 
00980 /**
00981  * Receive a set of message from a netlink socket using handlers in nl_handle.
00982  * @arg handle          netlink handle
00983  *
00984  * Calls nl_recvmsgs() with the handlers configured in the netlink handle.
00985  */
00986 int nl_recvmsgs_def(struct nl_handle *handle)
00987 {
00988         if (handle->h_cb->cb_recvmsgs_ow)
00989                 return handle->h_cb->cb_recvmsgs_ow(handle, handle->h_cb);
00990         else
00991                 return nl_recvmsgs(handle, handle->h_cb);
00992 }
00993 
00994 static int ack_wait_handler(struct nl_msg *msg, void *arg)
00995 {
00996         return NL_EXIT;
00997 }
00998 
00999 /**
01000  * Wait for ACK.
01001  * @arg handle          netlink handle
01002  * @pre The netlink socket must be in blocking state.
01003  *
01004  * Waits until an ACK is received for the latest not yet acknowledged
01005  * netlink message.
01006  */
01007 int nl_wait_for_ack(struct nl_handle *handle)
01008 {
01009         int err;
01010         struct nl_cb *cb = nl_cb_clone(nl_handle_get_cb(handle));
01011 
01012         nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ack_wait_handler, NULL);
01013 
01014         err = nl_recvmsgs(handle, cb);
01015         nl_cb_destroy(cb);
01016 
01017         return err;
01018 }
01019 
01020 /** @} */
01021 
01022 /**
01023  * @name Netlink Family Translations
01024  * @{
01025  */
01026 
01027 static struct trans_tbl nlfamilies[] = {
01028         __ADD(NETLINK_ROUTE,route)
01029         __ADD(NETLINK_W1,w1)
01030         __ADD(NETLINK_USERSOCK,usersock)
01031         __ADD(NETLINK_FIREWALL,firewall)
01032         __ADD(NETLINK_INET_DIAG,inetdiag)
01033         __ADD(NETLINK_NFLOG,nflog)
01034         __ADD(NETLINK_XFRM,xfrm)
01035         __ADD(NETLINK_SELINUX,selinux)
01036         __ADD(NETLINK_ISCSI,iscsi)
01037         __ADD(NETLINK_AUDIT,audit)
01038         __ADD(NETLINK_FIB_LOOKUP,fib_lookup)
01039         __ADD(NETLINK_CONNECTOR,connector)
01040         __ADD(NETLINK_NETFILTER,netfilter)
01041         __ADD(NETLINK_IP6_FW,ip6_fw)
01042         __ADD(NETLINK_DNRTMSG,dnrtmsg)
01043         __ADD(NETLINK_KOBJECT_UEVENT,kobject_uevent)
01044         __ADD(NETLINK_GENERIC,generic)
01045 };
01046 
01047 /**
01048  * Convert netlink family to character string.
01049  * @arg family          Netlink family.
01050  * @arg buf             Destination buffer.
01051  * @arg size            Size of destination buffer.
01052  *
01053  * Converts a netlink family to a character string and stores it in
01054  * the specified destination buffer.
01055  *
01056  * @return The destination buffer or the family encoded in hexidecimal
01057  *         form if no match was found.
01058  */
01059 char * nl_nlfamily2str(int family, char *buf, size_t size)
01060 {
01061         return __type2str(family, buf, size, nlfamilies,
01062                           ARRAY_SIZE(nlfamilies));
01063 }
01064 
01065 /**
01066  * Convert character string to netlink family.
01067  * @arg name            Name of netlink family.
01068  *
01069  * Converts the provided character string specifying a netlink
01070  * family to the corresponding numeric value.
01071  *
01072  * @return Numeric netlink family or a negative value if no match was found.
01073  */
01074 int nl_str2nlfamily(const char *name)
01075 {
01076         return __str2type(name, nlfamilies, ARRAY_SIZE(nlfamilies));
01077 }
01078 
01079 /** @} */
01080 /** @} */

Generated on Fri Apr 27 14:14:07 2007 for libnl by  doxygen 1.5.1