core.c

00001 /**
00002  * \cond skip
00003  * vim:syntax=c.doxygen
00004  * \endcond
00005 
00006 \page core_doc Netlink Core Library (-lnl)
00007 
00008 \section core_intro Introduction
00009 
00010 The core library contains the fundamentals required to communicate over
00011 netlink sockets. It deals with connecting and disconnectng of sockets,
00012 sending and receiving of data, construction and parsing of messages,
00013 provides a customizeable receiving state machine, and provides a abstract
00014 data type framework which eases the implementation of object based netlink
00015 protocols where objects are added, removed, or modified with the help of
00016 netlink messages.
00017 
00018 \section core_toc Table of Contents
00019 
00020 - \ref core_lib
00021   - \ref core_lib_howto
00022   - \ref core_lib_link
00023 - \ref proto_fund
00024   - \ref core_format
00025   - \ref core_msg_type
00026     - \ref core_multipart
00027     - \ref core_errmsg
00028     - \ref core_ack
00029   - \ref core_msg_flags
00030   - \ref core_seq
00031   - \ref core_multicast
00032 - \ref sk_doc
00033   - \ref core_sk_alloc
00034   - \ref core_sk_seq_num
00035   - \ref core_sk_groups
00036   - \ref core_sk_cb
00037   - \ref core_sk_attrs
00038     - \ref core_sk_local_port
00039     - \ref core_sk_peer_port
00040     - \ref core_sk_fd
00041     - \ref core_sk_buffer_size
00042     - \ref core_sk_cred
00043     - \ref core_sk_auto_ack
00044     - \ref core_sk_msg_peek
00045     - \ref core_sk_pktinfo
00046 - \ref core_send_recv
00047   - \ref core_send
00048     - \ref core_nl_send
00049     - \ref core_nl_send_iovec
00050     - \ref core_nl_sendmsg
00051     - \ref core_send_raw
00052     - \ref core_send_simple
00053   - \ref core_recv
00054     - \ref core_nl_recvmsgs
00055     - \ref core_recvmsgs
00056     - \ref core_recv_parse
00057   - \ref core_auto_ack
00058 - \ref core_msg
00059   - \ref core_msg_format
00060     - \ref core_msg_fmt_align
00061   - \ref core_msg_parse
00062     - \ref core_msg_split
00063     - \ref core_msg_payload
00064     - \ref core_msg_parse_attr
00065     - \ref core_nlmsg_parse
00066   - \ref core_msg_constr
00067     - \ref core_msg_alloc
00068     - \ref core_msg_nlmsg_put
00069     - \ref core_msg_reserve
00070     - \ref core_msg_append
00071 - \ref core_attr
00072   - \ref core_attr_format
00073   - \ref core_attr_parse
00074     - \ref core_attr_parse_split
00075     - \ref core_attr_payload
00076     - \ref core_attr_validation
00077     - \ref core_attr_nla_parse
00078     - \ref core_attr_find
00079     - \ref core_attr_iterate
00080   - \ref core_attr_constr
00081     - \ref core_attr_exception
00082   - \ref core_attr_data_type
00083     - \ref core_attr_int
00084     - \ref core_attr_string
00085     - \ref core_attr_flag
00086     - \ref core_attr_nested
00087     - \ref core_attr_unspec
00088   - \ref core_attr_examples
00089     - \ref core_attr_example_constr
00090     - \ref core_attr_example_parse
00091 - \ref core_cb
00092   - \ref core_cb_hooks
00093     - \ref core_cb_default
00094     - \ref core_cb_msg_proc
00095     - \ref core_cb_errmsg
00096     - \ref core_cb_example
00097   - \ref core_cb_overwrite
00098     - \ref core_cb_ow_recvmsgs
00099     - \ref core_cb_ow_recv
00100     - \ref core_cb_ow_send
00101 - \ref core_cache
00102 - \ref core_abstract_types
00103   - \ref core_abstract_addr
00104     - \ref core_abstract_addr_alloc
00105     - \ref core_abstract_addr_ref
00106     - \ref core_abstract_addr_attr
00107     - \ref core_abstract_addr_prefix
00108     - \ref core_abstract_addr_helpers
00109   - \ref core_abstract_data
00110     - \ref core_abstract_data_alloc
00111     - \ref core_abstract_data_access
00112     - \ref core_abstract_data_helpers
00113 
00114 \section core_lib 1. Introduction to the Library
00115 
00116 \subsection core_lib_howto 1.1 How To Read This Documentation
00117 
00118 The documentation consists of this manual and the API reference pages.
00119 Both contain references to each other and as many examples as possible.
00120 
00121 Even though the library tries to be as consistent and as intuitive as
00122 possible it may be difficult to understand where to start looking for
00123 information.
00124 
00125 
00126 
00127 \subsection core_lib_link 1.2 Linking to this Library
00128 
00129 
00130 \subsection flags Flags to Character StringTranslations
00131 
00132 All functions converting a set of flags to a character string follow
00133 the same principles, therefore, the following information applies
00134 to all functions convertings flags to a character string and vice versa.
00135 
00136 \subsubsection flags2str Flags to Character String
00137 \code
00138 char *<object name>_flags2str(int flags, char *buf, size_t len)
00139 \endcode
00140 \arg flags              Flags.
00141 \arg buf                Destination buffer.
00142 \arg len                Buffer length.
00143 
00144 Converts the specified flags to a character string separated by
00145 commas and stores it in the specified destination buffer.
00146 
00147 \return The destination buffer
00148 
00149 \subsubsection str2flags Character String to Flags
00150 \code
00151 int <object name>_str2flags(const char *name)
00152 \endcode
00153 \arg name               Name of flag.
00154 
00155 Converts the provided character string specifying a flag
00156 to the corresponding numeric value.
00157 
00158 \return Link flag or a negative value if none was found.
00159 
00160 \subsubsection type2str Type to Character String
00161 \code
00162 char *<object name>_<type>2str(int type, char *buf, size_t len)
00163 \endcode
00164 \arg type               Type as numeric value
00165 \arg buf                Destination buffer.
00166 \arg len                Buffer length.
00167 
00168 Converts an identifier (type) to a character string and stores
00169 it in the specified destination buffer.
00170 
00171 \return The destination buffer or the type encoded in hexidecimal
00172         form if the identifier is unknown.
00173 
00174 \subsubsection str2type Character String to Type
00175 \code
00176 int <object name>_str2<type>(const char *name)
00177 \endcode
00178 \arg name               Name of identifier (type).
00179 
00180 Converts the provided character string specifying a identifier
00181 to the corresponding numeric value.
00182 
00183 \return Identifier as numeric value or a negative value if none was found.
00184 
00185 
00186 \section proto_fund 1. Netlink Protocol Fundamentals
00187 
00188 The netlink protocol is a socket based IPC mechanism used for communication
00189 between userspace processes and the kernel or between userspace processes
00190 themselves. The netlink protocol is based on BSD sockets and uses the
00191 \c AF_NETLINK address family. Every netlink protocol uses its own protocol
00192 number (e.g. NETLINK_ROUTE, NETLINK_NETFILTER, etc). Its addressing schema
00193 is based on a 32 bit port number, formerly referred to as PID, which uniquely
00194 identifies each peer.
00195 
00196 \subsection core_format 1.1 Message Format
00197 
00198 A netlink protocol is typically based on messages and consists of the
00199 netlink message header (struct nlmsghdr) plus the payload attached to it.
00200 The payload can consist of arbitary data but usually contains a fixed
00201 size protocol specific header followed by a stream of attributes.
00202 
00203 The netlink message header (struct nlmsghdr) has the following format:
00204 
00205 \code   
00206 0                   1                   2                   3
00207 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
00208 +-------------------------------------------------------------+
00209 |                          Length                             |
00210 +------------------------------+------------------------------+
00211 |            Type              |           Flags              |
00212 +------------------------------+------------------------------+
00213 |                      Sequence Number                        |
00214 +-------------------------------------------------------------+
00215 |                       Port (Address)                        |
00216 +-------------------------------------------------------------+
00217 \endcode
00218 
00219 \subsection core_msg_type 1.2 Message Types
00220 
00221 Netlink differs between requests, notifications, and replies. Requests
00222 are messages which have the \c NLM_F_REQUEST flag set and are meant to
00223 request an action from the receiver. A request is typically sent from
00224 a userspace process to the kernel. While not strictly enforced, requests
00225 should carry a sequence number incremented for each request sent.
00226 
00227 Depending on the nature of the request, the receiver may reply to the
00228 request with another netlink message. The sequence number of a reply
00229 must match the sequence number of the request it relates to.
00230 
00231 Notifications are of informal nature and no reply is expected, therefore
00232 the sequence number is typically set to 0.
00233 
00234 \msc
00235 A,B;
00236 A=>B [label="GET (seq=1, NLM_F_REQUEST)"];
00237 A<=B [label="PUT (seq=1)"];
00238 ...;
00239 A<=B [label="NOTIFY (seq=0)"];
00240 \endmsc
00241 
00242 The type of message is primarly identified by its 16 bit message type set
00243 in the message header. The following standard message types are defined:
00244 
00245 - \c NLMSG_NOOP - No operation, message must be discarded
00246 - \c NLMSG_ERROR - Error message or ACK, see \ref core_errmsg,
00247   respectively \ref core_ack
00248 - \c NLMSG_DONE - End of multipart sequence, see \ref core_multipart.
00249 - \c NLMSG_OVERRUN - Overrun notification (Error)
00250 
00251 Every netlink protocol is free to define own message types. Note that
00252 message type values  < \c NLMSG_MIN_TYPE (0x10) are reserved and may not
00253 be used.
00254 
00255 It is common practice to use own message types to implement RPC schemas.
00256 Suppose the goal of the netlink protocol you are implementing is allow
00257 configuration of a particular network device, therefore you want to
00258 provide read/write access to various configuration options. The typical
00259 "netlink way" of doing this would be to define two message types
00260 \c MSG_SETCFG, \c MSG_GETCFG:
00261 
00262 \code
00263 #define MSG_SETCFG      0x11
00264 #define MSG_GETCFG      0x12
00265 \endcode
00266 
00267 Sending a \c MSG_GETCFG request message will typically trigger a reply
00268 with the message type \c MSG_SETCFG containing the current configuration.
00269 In object oriented terms one would describe this as "the kernel sets
00270 the local copy of the configuration in userspace".
00271 
00272 \msc
00273 A,B;
00274 A=>B [label="MSG_GETCFG (seq=1, NLM_F_REQUEST)"];
00275 A<=B [label="MSG_SETCFG (seq=1)"];
00276 \endmsc
00277 
00278 The configuration may be changed by sending a \c MSG_SETCFG which will
00279 be responded to with either a ACK (see \ref core_ack) or a error
00280 message (see \ref core_errmsg).
00281 
00282 \msc
00283 A,B;
00284 A=>B [label="MSG_SETCFG (seq=1, NLM_F_REQUEST, NLM_F_ACK)"];
00285 A<=B [label="ACK (seq=1)"];
00286 \endmsc
00287 
00288 Optionally, the kernel may send out notifications for configuration
00289 changes allowing userspace to listen for changes instead of polling
00290 frequently. Notifications typically reuse an existing message type
00291 and rely on the application using a separate socket to differ between
00292 requests and notifications but you may also specify a separate message
00293 type.
00294 
00295 \msc
00296 A,B;
00297 A<=B [label="MSG_SETCFG (seq=0)"];
00298 \endmsc
00299 
00300 \subsubsection core_multipart 1.2.1 Multipart Messages
00301 
00302 Although in theory a netlink message can be up to 4GiB in size. The socket
00303 buffers are very likely not large enough to hold message of such sizes.
00304 Therefore it is common to limit messages to one page size (PAGE_SIZE) and
00305 use the multipart mechanism to split large pieces of data into several
00306 messages.  A multipart message has the \c flag NLM_F_MULTI set and the
00307 receiver is expected to continue receiving and parsing until the special
00308 message type \c NLMSG_DONE is received.
00309 
00310 Multipart messages unlike fragmented ip packets must not be reassmbled
00311 even though it is perfectly legal to do so if the protocols wishes to
00312 work this way. Often multipart message are used to send lists or trees
00313 of objects were each multipart message simply carries multiple objects
00314 allow for each message to be parsed independently.
00315 
00316 \msc
00317 A,B;
00318 A=>B [label="GET (seq=1, NLM_F_REQUEST)"];
00319 A<=B [label="PUT (seq=1, NLM_F_MULTI)"];
00320 ...;
00321 A<=B [label="PUT (seq=1, NLM_F_MULTI)"];
00322 A<=B [label="NLMSG_DONE (seq=1)"];
00323 \endmsc
00324 
00325 \subsubsection core_errmsg 1.2.2 Error Message
00326 
00327 Error messages can be sent in response to a request. Error messages must
00328 use the standard message type \c NLMSG_ERROR. The payload consists of a
00329 error code and the original netlink mesage header of the request. 
00330 
00331 \code
00332 0                   1                   2                   3
00333 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
00334 +-------------------------------------------------------------+
00335 |                            Length                           |
00336 +------------------------------+------------------------------+
00337 |  .nlmsg_type = NLMSG_ERROR   |       .nlmsg_flags = 0       |
00338 +------------------------------+------------------------------+
00339 |              Sequence number of the orig request            |
00340 +-------------------------------------------------------------+
00341 |                Port number of the orig request              |
00342 +-------------------------------------------------------------+
00343 |                     Error Code (e.g. EINVAL)                |
00344 +-------------------------------------------------------------+
00345 |             Netlink Message Header of orig. request         |
00346 .                                                             .
00347 .                                                             .
00348 +-------------------------------------------------------------+
00349 \endcode
00350 
00351 Error messages should set the sequence number to the sequence number
00352 of the request which caused the error.
00353 
00354 \msc
00355 A,B;
00356 A=>B [label="GET (seq=1, NLM_F_REQUEST)"];
00357 A<=B [label="NLMSG_ERROR code=EINVAL (seq=1)"];
00358 \endmsc
00359 
00360 \subsubsection core_ack 1.2.3 ACKs
00361 
00362 A sender can request an ACK message to be sent back for each request
00363 processed by setting the \c NLM_F_ACK flag in the request. This is typically
00364 used to allow the sender to synchronize further processing until the
00365 request has been processed by the receiver.
00366 
00367 \msc
00368 A,B;
00369 A=>B [label="GET (seq=1, NLM_F_REQUEST | NLM_F_ACK)"];
00370 A<=B [label="ACK (seq=1)"];
00371 \endmsc
00372 
00373 ACK messages also use the message type \c NLMSG_ERROR and payload format
00374 but the error code is set to 0.
00375 
00376 \subsubsection core_msg_flags 1.3 Message Flags
00377 
00378 The following standard flags are defined
00379 
00380 \code
00381 #define NLM_F_REQUEST           1
00382 #define NLM_F_MULTI             2
00383 #define NLM_F_ACK               4
00384 #define NLM_F_ECHO              8
00385 \endcode
00386 
00387 - \c NLM_F_REQUEST - Message is a request, see \ref core_msg_type.
00388 - \c NLM_F_MULTI - Multipart message, see \ref core_multipart.
00389 - \c NLM_F_ACK - ACK message requested, see \ref core_ack.
00390 - \c NLM_F_ECHO - Request to echo the request.
00391 
00392 The flag \c NLM_F_ECHO is similar to the \c NLM_F_ACK flag. It can be
00393 used in combination with \c NLM_F_REQUEST and causes a notification
00394 which is sent as a result of a request to also be sent to the sender
00395 regardless of whether the sender has subscribed to the corresponding
00396 multicast group or not. See \ref core_multicast.
00397 
00398 Additional universal message flags are defined which only apply for
00399 \c GET requests:
00400 
00401 \code
00402 #define NLM_F_ROOT      0x100
00403 #define NLM_F_MATCH     0x200
00404 #define NLM_F_ATOMIC    0x400
00405 #define NLM_F_DUMP      (NLM_F_ROOT|NLM_F_MATCH)
00406 \endcode
00407 
00408 - \c NLM_F_ROOT - Return based on root of tree.
00409 - \c NLM_F_MATCH - Return all matching entries.
00410 - \c NLM_F_ATOMIC - Obsoleted, once used to request an atomic operation.
00411 - \c NLM_F_DUMP - Return a list of all objects \c (NLM_F_ROOT|NLM_F_MATCH).
00412 
00413 Use of these flags is completely optional and many netlink protocols only
00414 make use of the \c NLM_F_DUMP flag which typically requests the receiver
00415 to send a list of all objects in the context of the message type as a
00416 sequence of multipart messages (see \ref core_multipart).
00417 
00418 Another set of flags exist related to \c NEW or \c SET requests. These
00419 flags are mutually exclusive to the \c GET flags:
00420 
00421 \code
00422 #define NLM_F_REPLACE   0x100
00423 #define NLM_F_EXCL      0x200
00424 #define NLM_F_CREATE    0x400
00425 #define NLM_F_APPEND    0x800
00426 \endcode
00427 
00428 - \c NLM_F_REPLACE - Replace an existing object if it exists.
00429 - \c NLM_F_EXCL - Do not update object if it exists already.
00430 - \c NLM_F_CREATE - Create object if it does not exist yet.
00431 - \c NLM_F_APPEND - Add object at end of list.
00432 
00433 Behaviour of these flags may differ slightly between different netlink
00434 protocols.
00435 
00436 \subsection core_seq 1.4 Sequence Numbers
00437 
00438 Netlink allows the use of sequence numbers to help relate replies to
00439 requests. It should be noted that unlike in protocols such as TCP there
00440 is no strict enforcment of the sequence number. The sole purpose of
00441 sequence numbers is to assist a sender in relating replies to the
00442 corresponding requests. See \ref core_msg_type for more information.
00443 
00444 Sequence numbers are managed on a per socket basis, see
00445 \ref core_sk_seq_num for more information on how to use sequence numbers.
00446 
00447 \subsection core_multicast 1.5 Multicast Groups
00448 
00449 TODO
00450 
00451 See \ref core_sk_groups.
00452 
00453 \section sk_doc 2. Netlink Sockets
00454 
00455 In order to use the netlink protocol, a netlink socket is required. Each
00456 socket defines a completely independent context for sending and receiving
00457 of messages. An application may use multiple sockets for the same netlink
00458 protocol, e.g. one socket to send requests and receive replies and another
00459 socket subscribed to a multicast group to receive notifications.
00460 
00461 \subsection core_sk_alloc 2.1 Socket Allocation & Freeing
00462 
00463 The netlink socket and all its related attributes are represented by
00464 struct nl_sock.
00465 
00466 \code
00467 #include <netlink/socket.h>
00468 
00469 struct nl_sock *nl_socket_alloc(void)
00470 void nl_socket_free(struct nl_sock *sk)
00471 \endcode
00472 
00473 \subsection core_sk_seq_num 2.2 Sequence Numbers
00474 
00475 The library will automatically take care of sequence number handling for
00476 the application. A sequence number counter is stored in struct nl_sock which
00477 is meant to be used when sending messages which will produce a reply, error
00478 or any other message which needs to be related to the original message.
00479 
00480 The counter can be used directly with the function nl_socket_use_seq()
00481 which will return the current value of the counter and increment it by
00482 one afterwards.
00483 
00484 \code
00485 #include <netlink/socket.h>
00486 
00487 unsigned int nl_socket_use_seq(struct nl_sock *sk);
00488 \endcode
00489 
00490 Most applications will not want to deal with sequence number handling
00491 themselves though. When using nl_send_auto() the sequence number is
00492 filled out automatically and matched again on the receiving side. See
00493 \ref core_send_recv for more information.
00494 
00495 This behaviour can and must be disabled if the netlink protocol
00496 implemented does not use a request/reply model, e.g. when a socket is
00497 used to receive notification messages.
00498 
00499 \code
00500 #include <netlink/socket.h>
00501 
00502 void nl_socket_disable_seq_check(struct nl_sock *sk);
00503 \endcode
00504 
00505 \subsection core_sk_groups 2.3 Multicast Group Subscriptions
00506 
00507 Each socket can subscribe to any number of multicast groups of the
00508 netlink protocol it is connected to. The socket will then receive a copy
00509 of each message sent to any of the groups. Multicast groups are commonly
00510 used to implement event notifications.
00511 
00512 Prior to kernel 2.6.14 the group subscription was performed using a bitmask
00513 which limited the number of groups per protocol family to 32. This outdated
00514 interface can still be accessed via the function nl_join_groups even though
00515 it is not recommended for new code.
00516 
00517 \code
00518 #include <netlink/socket.h>
00519 
00520 void nl_join_groups(struct nl_sock *sk, int bitmask);
00521 \endcode
00522 
00523 Starting with 2.6.14 a new method was introduced which supports subscribing
00524 to an almost infinite number of multicast groups.
00525 
00526 \code
00527 #include <netlink/socket.h>
00528 
00529 int nl_socket_add_memberships(struct nl_sock *sk, int group, ...);
00530 int nl_socket_drop_memberships(struct nl_sock *sk, int group, ...);
00531 \endcode
00532 
00533 \subsubsection core_sk_group_example 2.3.1 Multicast Example
00534 
00535 \include sk_group_example.c
00536 
00537 \subsection core_sk_cb 2.4 Modifiying Socket Callback Configuration
00538 
00539 See \ref core_cb for more information on callback hooks and overwriting
00540 capabilities
00541 
00542 Each socket is assigned a callback configuration which controls the
00543 behaviour of the socket. This is f.e. required to have a separate message
00544 receive function per socket. It is perfectly legal to share callback
00545 configurations between sockets though.
00546 
00547 The following functions can be used to access and set the callback
00548 configuration of a socket:
00549 
00550 \code
00551 #include <netlink/socket.h>
00552 
00553 struct nl_cb *nl_socket_get_cb(const struct nl_sock *sk);
00554 void nl_socket_set_cb(struct nl_sock *sk, struct nl_cb *cb);
00555 \endcode
00556 
00557 Additionaly a shortcut exists to modify the callback configuration assigned
00558 to a socket directly:
00559 
00560 \code
00561 #include <netlink/socket.h>
00562 
00563 int nl_socket_modify_cb(struct nl_sock *sk, enum nl_cb_type type, enum nl_cb_kind kind,
00564                         nl_recvmsg_msg_cb_t func, void *arg);
00565 \endcode
00566 
00567 Example:
00568 \code
00569 #include <netlink/socket.h>
00570 
00571 // Call my_input() for all valid messages received in socket sk
00572 nl_socket_modify_cb(sk, NL_CB_VALID, NL_CB_CUSTOM, my_input, NULL);
00573 \endcode
00574 
00575 \subsection core_sk_attrs 2.5 Socket Attributes
00576 
00577 \subsubsection core_sk_local_port 2.5.1 Local Port
00578 
00579 The local port number uniquely identifies the socket and is used to
00580 address it. A unique local port is generated automatically when the socket
00581 is allocated. It will consist of the Process ID (22 bits) and a random
00582 number (10 bits) thus allowing up to 1024 sockets per process.
00583 
00584 \code
00585 #include <netlink/socket.h>
00586 
00587 uint32_t nl_socket_get_local_port(const struct nl_sock *sk);
00588 void nl_socket_set_local_port(struct nl_sock *sk, uint32_t port);
00589 \endcode
00590 
00591 \b Note: Overwriting the local port is possible but you have to ensure
00592 that the provided value is unique and no other socket in any other
00593 application is using the same value.
00594 
00595 \subsubsection core_sk_peer_port 2.5.2 Peer Port
00596 
00597 A peer port can be assigned to the socket which will result in all unicast
00598 messages sent over the socket to be addresses to the peer. If no peer is
00599 specified, the message is sent to the kernel which will try to automatically
00600 bind the socket to a kernel side socket of the same netlink protocol family.
00601 It is common practice not to bind the socket to a peer port as typically
00602 only one kernel side socket exists per netlink protocol family.
00603 
00604 \code
00605 #include <netlink/socket.h>
00606 
00607 uint32_t nl_socket_get_peer_port(const struct nl_sock *sk);
00608 void nl_socket_set_peer_port(struct nl_sock *sk, uint32_t port);
00609 \endcode
00610 
00611 \subsubsection core_sk_fd 2.5.3 File Descriptor
00612 
00613 Netlink uses the BSD socket interface, therefore a file descriptor
00614 is behind each socket and you may use it directly.
00615 
00616 \code
00617 #include <netlink/socket.h>
00618 
00619 int nl_socket_get_fd(const struct nl_sock *sk);
00620 \endcode
00621 
00622 If a socket is used to only receive notifications it usually is best
00623 to put the socket in non-blocking mode and periodically poll for new
00624 notifications.
00625 
00626 \code
00627 #include <netlink/socket.h>
00628 
00629 int nl_socket_set_nonblocking(const struct nl_sock *sk);
00630 \endcode
00631 
00632 \subsubsection core_sk_buffer_size 2.5.4 Send/Receive Buffer Size
00633 
00634 The socket buffer is used to queue netlink messages between sender
00635 and receiver. The size of these buffers specifies the maximum size
00636 you will be able to write() to a netlink socket, i.e. it will indirectly
00637 define the maximum message size. The default is 32KiB.
00638 
00639 \code
00640 #include <netlink/socket.h>
00641 
00642 int nl_socket_set_buffer_size(struct nl_sock *sk, int rx, int tx);
00643 \endcode
00644 
00645 
00646 \subsubsection core_sk_cred 2.5.5 Enable/Disable Credentials
00647 
00648 TODO
00649 
00650 \code
00651 #include <netlink/socket.h>
00652 
00653 int nl_socket_set_passcred(struct nl_sock *sk, int state);
00654 \endcode
00655 
00656 \subsubsection core_sk_auto_ack 2.5.6 Enable/Disable Auto-ACK Mode
00657 
00658 The following functions allow to enable/disable Auto-ACK mode on a
00659 socket. See \ref core_auto_ack for more information on what implications
00660 that has. Auto-ACK mode is enabled by default.
00661 
00662 \code
00663 #include <netlink/socket.h>
00664 
00665 void nl_socket_enable_auto_ack(struct nl_sock *sk);
00666 void nl_socket_disable_auto_ack(struct nl_sock *sk);
00667 \endcode
00668 
00669 \subsubsection core_sk_msg_peek 2.5.7 Enable/Disable Message Peeking
00670 
00671 If enabled, message peeking causes nl_recv() to try and use MSG_PEEK to
00672 retrieve the size of the next message received and allocate a buffer
00673 of that size. Message peeking is enabled by default but can be disabled
00674 using the following function:
00675 
00676 \code
00677 #include <netlink/socket.h>
00678 
00679 void nl_socket_enable_msg_peek(struct nl_sock *sk);
00680 void nl_socket_disable_msg_peek(struct nl_sock *sk);
00681 \endcode
00682 
00683 \subsubsection core_sk_pktinfo 2.5.8 Enable/Disable Receival of Packet Information
00684 
00685 If enabled, each received netlink message from the kernel will include an
00686 additional struct nl_pktinfo in the control message. The following function
00687 can be used to enable/disable receival of packet information.
00688 
00689 \code
00690 #include <netlink/socket.h>
00691 
00692 int nl_socket_recv_pktinfo(struct nl_sock *sk, int state);
00693 \endcode
00694 
00695 \b Note: Processing of NETLINK_PKTINFO has not been implemented yet.
00696 
00697 \section core_send_recv 3. Sending and Receiving of Messages / Data
00698 
00699 \subsection core_send 3.1 Sending Netlink Messages
00700 
00701 The standard method of sending a netlink message over a netlink socket
00702 is to use the function nl_send_auto(). It will automatically complete
00703 the netlink message by filling the missing bits and pieces in the
00704 netlink message header and will deal with addressing based on the
00705 options and address set in the netlink socket. The message is then passed
00706 on to nl_send().
00707 
00708 If the default sending semantics implemented by nl_send() do not suit the
00709 application, it may overwrite the sending function nl_send() by
00710 specifying an own implementation using the function nl_cb_overwrite_send().
00711 
00712 \code
00713    nl_send_auto(sk, msg)
00714          |
00715          |-----> nl_complete_msg(sk, msg)
00716          |
00717          |
00718          |              Own send function specified via nl_cb_overwrite_send()
00719          |- - - - - - - - - - - - - - - - - - - -
00720          v                                      v
00721    nl_send(sk, msg)                         send_func()
00722 \endcode
00723 
00724 \subsubsection core_nl_send 3.1.1 Using nl_send()
00725 
00726 If you do not require any of the automatic message completion functionality
00727 you may use nl_send() directly but beware that any internal calls to
00728 nl_send_auto() by the library to send netlink messages will still use
00729 nl_send(). Therefore if you wish to use any higher level interfaces and the
00730 behaviour of nl_send() is to your dislike then you must overwrite the
00731 nl_send() function via nl_cb_overwrite_send()
00732 
00733 The purpose of nl_send() is to embed the netlink message into a iovec
00734 structure and pass it on to nl_send_iovec().
00735 
00736 \code
00737    nl_send(sk, msg)
00738          |
00739          v
00740    nl_send_iovec(sk, msg, iov, iovlen)
00741 \endcode
00742 
00743 \subsubsection core_nl_send_iovec 3.1.2 Using nl_send_iovec()
00744 
00745 nl_send_iovec() expects a finalized netlink message and fills out the
00746 struct msghdr used for addressing. It will first check if the struct nl_msg
00747 is addressed to a specific peer (see nlmsg_set_dst()). If not, it will try
00748 to fall back to the peer address specified in the socket (see
00749 nl_socket_set_peer_port(). Otherwise the message will be sent unaddressed
00750 and it is left to the kernel to find the correct peer.
00751 
00752 nl_send_iovec() also adds credentials if present and enabled
00753 (see \ref core_sk_cred).
00754 
00755 The message is then passed on to nl_sendmsg().
00756 
00757 \code
00758    nl_send_iovec(sk, msg, iov, iovlen)
00759          |
00760          v
00761    nl_sendmsg(sk, msg, msghdr)
00762 \endcode
00763 
00764 \subsubsection core_nl_sendmsg 3.1.3 Using nl_sendmsg()
00765 
00766 nl_sendmsg() expects a finalized netlink message and an optional struct
00767 msghdr containing the peer address. It will copy the local address as
00768 defined in the socket (see nl_socket_set_local_port()) into the netlink
00769 message header.
00770 
00771 At this point, construction of the message finished and it is ready to
00772 be sent.
00773 
00774 \code
00775    nl_sendmsg(sk, msg, msghdr)
00776          |- - - - - - - - - - - - - - - - - - - - v
00777          |                                 NL_CB_MSG_OUT()
00778          |<- - - - - - - - - - - - - - - - - - - -+
00779          v
00780    sendmsg()
00781 \endcode
00782 
00783 Before sending the application has one last chance to modify the message.
00784 It is passed to the NL_CB_MSG_OUT callback function which may inspect or
00785 modify the message and return an error code. If this error code is NL_OK
00786 the message is sent using sendmsg() resulting in the number of bytes
00787 written being returned. Otherwise the message sending process is aborted
00788 and the error code specified by the callback function is returned. See
00789 \ref core_sk_cb for more information on how to set callbacks.
00790 
00791 \subsubsection core_send_raw 3.1.4 Sending Raw Data with nl_sendto()
00792 
00793 If you wish to send raw data over a netlink socket, the following
00794 function will pass on any buffer provided to it directly to sendto():
00795 
00796 \code
00797 #include <netlink/netlink.h>
00798 
00799 int nl_sendto(struct nl_sock *sk, void *buf, size_t size);
00800 \endcode
00801 
00802 \subsubsection core_send_simple 3.1.5 Sending of Simple Messages
00803 
00804 A special interface exists for sending of trivial messages. The function
00805 expects the netlink message type, optional netlink message flags, and an
00806 optional data buffer and data length.  
00807 \code
00808 #include <netlink/netlink.h>
00809 
00810 int nl_send_simple(struct nl_sock *sk, int type, int flags,
00811                    void *buf, size_t size);
00812 \endcode
00813 
00814 The function will construct a netlink message header based on the message
00815 type and flags provided and append the data buffer as message payload. The
00816 newly constructed message is sent with nl_send_auto().
00817 
00818 The following example will send a netlink request message causing the
00819 kernel to dump a list of all network links to userspace:
00820 \include nl_send_simple.c
00821 
00822 \subsection core_recv 3.2 Receiving Netlink Messages
00823 
00824 The easiest method to receive netlink messages is to call nl_recvmsgs_default().
00825 It will receive messages based on the semantics defined in the socket. The
00826 application may customize these in detail although the default behaviour will
00827 probably suit most applications.
00828 
00829 nl_recvmsgs_default() will also be called internally by the library whenever
00830 it needs to receive and parse a netlink message.
00831 
00832 The function will fetch the callback configuration stored in the socket and
00833 call nl_recvmsgs():
00834 
00835 \code
00836    nl_recvmsgs_default(sk)
00837          |
00838          | cb = nl_socket_get_cb(sk)
00839          v
00840    nl_recvmsgs(sk, cb)
00841 \endcode
00842 
00843 \subsubsection core_nl_recvmsgs 3.2.1 Using nl_recvmsgs()
00844 
00845 nl_recvmsgs() implements the actual receiving loop, it blocks until a
00846 netlink message has been received unless the socket has been put into
00847 non-blocking mode.
00848 
00849 See \ref core_recvmsgs for more information on the behaviour of
00850 nl_recvmsgs().
00851 
00852 For the unlikely scenario that certain required receive characteristics
00853 can not be achieved by fine tuning the internal recvmsgs function using
00854 the callback configuration (see \ref core_sk_cb) the application may
00855 provide a complete own implementation of it and overwrite all calls to
00856 nl_recvmsgs() with the function nl_cb_overwrite_recvmsgs().
00857 
00858 \code
00859    nl_recvmsgs(sk, cb)
00860          |
00861          |     Own recvmsgs function specified via nl_cb_overwrite_recvmsgs()
00862          |- - - - - - - - - - - - - - - - - - - -
00863          v                                      v
00864    internal_recvmsgs()                    my_recvmsgs()
00865 \endcode
00866 
00867 \subsubsection core_recvmsgs 3.2.2 Receive Characteristics
00868 
00869 If the application does not provide its own recvmsgs() implementation
00870 with the function nl_cb_overwrite_recvmsgs() the following characteristics
00871 apply while receiving data from a netlink socket:
00872 
00873 \code
00874         internal_recvmsgs()
00875                 |
00876 +-------------->|     Own recv function specified with nl_cb_overwrite_recv()
00877 |               |- - - - - - - - - - - - - - - -
00878 |               v                              v
00879 |           nl_recv()                      my_recv()
00880 |               |<- - - - - - - - - - - - - - -+
00881 |               |<-------------+
00882 |               v              | More data to parse? (nlmsg_next())
00883 |         Parse Message        | 
00884 |               |--------------+
00885 |               v
00886 +------- NLM_F_MULTI set?
00887                 |
00888                 v
00889             (SUCCESS)
00890 \endcode
00891 
00892 The function nl_recv() is invoked first to receive data from the netlink
00893 socket.  This function may be overwritten by the application by an own
00894 implementation using the function nl_cb_overwrite_recv(). This may be
00895 useful if the netlink byte stream is in fact not received from a socket
00896 directly but is read from a file or another source.
00897 
00898 If data has been read, it will be attemped to parse the data
00899 (see \ref core_recv_parse). This will be done repeately until the parser
00900 returns NL_STOP, an error was returned or all data has been parsed.
00901 
00902 In case the last message parsed successfully was a multipart message
00903 (see \ref core_multipart) and the parser did not quit due to either an
00904 error or NL_STOP nl_recv() respectively the applications own implementation
00905 will be called again and the parser starts all over.
00906 
00907 See \ref core_recv_parse for information on how to extract valid netlink
00908 messages from the parser and on how to control the behaviour of it.
00909 
00910 \subsubsection core_recv_parse 3.2.3 Parsing Characteristics
00911 
00912 The internal parser is invoked for each netlink message received from a
00913 netlink socket. It is typically fed by nl_recv() (see \ref core_recvmsgs).
00914 
00915 The parser will first ensure that the length of the data stream provided
00916 is sufficient to contain a netlink message header and that the message
00917 length as specified in the message header does not exceed it.
00918 
00919 If this criteria is met, a new struct nl_msg is allocated and the message
00920 is passed on to the the callback function NL_CB_MSG_IN if one is set. Like
00921 any other callback function, it may return NL_SKIP to skip the current
00922 message but continue parsing the next message or NL_STOP to stop parsing
00923 completely.
00924 
00925 The next step is to check the sequence number of the message against the
00926 currently expected sequence number. The application may provide its own
00927 sequence number checking algorithm by setting the callback function
00928 NL_CB_SEQ_CHECK to its own implementation. In fact, calling
00929 nl_socket_disable_seq_check() to disable sequence number checking will
00930 do nothing more than set the NL_CB_SEQ_CHECK hook to a function which
00931 always returns NL_OK.
00932 
00933 Another callback hook NL_CB_SEND_ACK exists which is called if the
00934 message has the NLM_F_ACK flag set. Although I am not aware of any
00935 userspace netlink socket doing this, the application may want to send
00936 an ACK message back to the sender (see \ref core_ack).
00937 
00938 \code
00939         parse()
00940           |
00941           v
00942       nlmsg_ok() --> Ignore
00943           |
00944           |- - - - - - - - - - - - - - - v
00945           |                         NL_CB_MSG_IN()
00946           |<- - - - - - - - - - - - - - -+
00947           |
00948           |- - - - - - - - - - - - - - - v
00949      Sequence Check                NL_CB_SEQ_CHECK()
00950           |<- - - - - - - - - - - - - - -+
00951           |
00952           |              Message has NLM_F_ACK set
00953           |- - - - - - - - - - - - - - - v 
00954           |                      NL_CB_SEND_ACK()
00955           |<- - - - - - - - - - - - - - -+
00956           |
00957  Handle Message Type
00958 \endcode
00959 
00960 \subsection core_auto_ack 3.3 Auto-ACK Mode
00961 
00962 TODO
00963 
00964 \section core_msg 4. Netlink Message Parsing & Construction
00965 
00966 \subsection core_msg_format 4.1 Message Format
00967 
00968 See \ref proto_fund for an introduction to the netlink protocol and its
00969 message format.
00970 
00971 \subsubsection core_msg_fmt_align 4.1.1 Alignment
00972 
00973 Most netlink protocols enforce a strict alignment policy for all boundries.
00974 The alignment value is defined by NLMSG_ALIGNTO and is fixed to 4 bytes.
00975 Therefore all netlink message headers, begin of payload sections, protocol
00976 specific headers, and attribute sections must start at an offset which is
00977 a multiple of NLMSG_ALIGNTO.
00978 
00979 \code
00980 #include <netlink/msg.h>
00981 
00982 int nlmsg_size(int payloadlen);
00983 int nlmsg_total_size(int payloadlen);
00984 \endcode
00985 
00986 The library provides a set of function to handle alignment requirements
00987 automatically. The function nlmsg_total_size() returns the total size
00988 of a netlink message including the padding to ensure the next message
00989 header is aligned correctly.
00990 
00991 \code
00992      <----------- nlmsg_total_size(len) ------------>
00993      <----------- nlmsg_size(len) ------------>
00994     +-------------------+- - -+- - - - - - - - +- - -+-------------------+- - -
00995     |  struct nlmsghdr  | Pad |     Payload    | Pad |  struct nlsmghdr  |
00996     +-------------------+- - -+- - - - - - - - +- - -+-------------------+- - -
00997      <---- NLMSG_HDRLEN -----> <- NLMSG_ALIGN(len) -> <---- NLMSG_HDRLEN ---
00998 \endcode
00999 
01000 If you need to know if padding needs to be added at the end of a message,
01001 nlmsg_padlen() returns the number of padding bytes that need to be added
01002 for a specific payload length.
01003 
01004 \code
01005 #include <netlink/msg.h>
01006 int nlmsg_padlen(int payloadlen);
01007 \endcode
01008 
01009 \subsection core_msg_parse 4.2 Parsing a Message
01010 
01011 The library offers two different methods of parsing netlink messages.
01012 It offers a low level interface for applications which want to do all
01013 the parsing manually. This method is described below. Alternatively
01014 the library also offers an interface to implement a parser as part of
01015 a cache operations set which is especially useful when your protocol
01016 deals with objects of any sort such as network links, routes, etc.
01017 This high level interface is described in \ref core_cache.
01018 
01019 \subsubsection core_msg_split 4.2.1 Splitting a byte stream into separate messages
01020 
01021 What you receive from a netlink socket is typically a stream of
01022 messages. You will be given a buffer and its length, the buffer may
01023 contain any number of netlink messages.
01024 
01025 The first message header starts at the beginning of message stream. Any
01026 subsequent message headers are access by calling nlmsg_next() on the
01027 previous header.
01028 
01029 \code
01030 #include <netlink/msg.h>
01031 
01032 struct nlmsghdr *nlmsg_next(struct nlmsghdr *hdr, int *remaining);
01033 \endcode
01034 
01035 The function nlmsg_next() will automatically substract the size of
01036 the previous message from the remaining number of bytes.
01037 
01038 Please note, there is no indication in the previous message whether
01039 another message follows or not. You must assume that more messages
01040 follow until all bytes of the message stream have been processed.
01041 
01042 To simplify this, the function nlmsg_ok() exists which returns true if
01043 another message fits into the remaining number of bytes in the message
01044 stream. nlmsg_valid_hdr() is similar, it checks whether a specific
01045 netlink message contains at least a minimum of payload.
01046 
01047 \code
01048 #include <netlink/msg.h>
01049 
01050 int nlmsg_valid_hdr(const struct nlmsghdr *hdr, int payloadlen);
01051 int nlmsg_ok(const struct nlmsghdr *hdr, int remaining);
01052 \endcode
01053 
01054 A typical use of these functions looks like this:
01055 
01056 \include my_parse.c
01057 
01058 \b Note: nlmsg_ok() only returns true if the \b complete message including
01059          the message payload fits into the remaining buffer length. It will
01060          return false if only a part of it fits.
01061 
01062 The above can also be written using the iterator nlmsg_for_each():
01063 
01064 \include nlmsg_for_each.c
01065 
01066 
01067 \subsubsection core_msg_payload 4.2.2 Message Payload
01068 
01069 The message payload is appended to the message header and is guranteed
01070 to start at a multiple of NLMSG_ALIGNTO. Padding at the end of the
01071 message header is added if necessary to ensure this. The function
01072 nlmsg_data() will calculate the necessary offset based on the message
01073 and returns a pointer to the start of the message payload.
01074 
01075 \code
01076 #include <netlink/msg.h>
01077 
01078 void *nlmsg_data(const struct nlmsghdr *nlh);
01079 void *nlmsg_tail(const struct nlmsghdr *nlh);
01080 int nlmsg_datalen(const struct nlmsghdr *nlh);
01081 \endcode
01082 
01083 The length of the message payload is returned by nlmsg_datalen().
01084 
01085 \code
01086                                <--- nlmsg_datalen(nlh) --->
01087     +-------------------+- - -+----------------------------+- - -+
01088     |  struct nlmsghdr  | Pad |           Payload          | Pad |
01089     +-------------------+- - -+----------------------------+- - -+
01090 nlmsg_data(nlh) ---------------^                                  ^
01091 nlmsg_tail(nlh) --------------------------------------------------^
01092 \endcode
01093 
01094 The payload may consist of arbitary data but may have strict alignment
01095 and formatting rules depening on the actual netlink protocol.
01096 
01097 \subsubsection core_msg_parse_attr 4.2.3 Message Attributes
01098 
01099 Most netlink protocols use netlink attributes. It not only makes the
01100 protocol self documenting but also gives flexibility in expanding
01101 the protocol at a later point. New attributes can be added at any time
01102 and older attributes can be obsoleted by newer ones without breaking
01103 binary compatibility of the protocol.
01104 
01105 \code
01106                                <---------------------- payload ------------------------->
01107                                <----- hdrlen ---->       <- nlmsg_attrlen(nlh, hdrlen) ->
01108     +-------------------+- - -+-----  ------------+- - -+--------------------------------+- - -+
01109     |  struct nlmsghdr  | Pad |  Protocol Header  | Pad |           Attributes           | Pad |
01110     +-------------------+- - -+-------------------+- - -+--------------------------------+- - -+
01111 nlmsg_attrdata(nlh, hdrlen) -----------------------------^
01112 \endcode
01113 
01114 The function nlmsg_attrdata() returns a pointer to the begin of the
01115 attributes section. The length of the attributes section is returned
01116 by the function nlmsg_attrlen().
01117 
01118 \code
01119 #include <netlink/msg.h>
01120 
01121 struct nlattr *nlmsg_attrdata(const struct nlmsghdr *hdr, int hdrlen);
01122 int nlmsg_attrlen(const struct nlmsghdr *hdr, int hdrlen);
01123 \endcode
01124 
01125 See \ref core_attr for more information on how to use netlink attributes.
01126 
01127 \subsubsection core_nlmsg_parse 4.2.4 Parsing a Message the Easy Way
01128 
01129 The function nlmsg_parse() validate a complete netlink message in
01130 one step. If \p hdrlen > 0 it will first call nlmsg_valid_hdr() to
01131 check if the protocol header fits into the message. If there is
01132 more payload to parse, it will assume it to be attributes and parse
01133 the payload accordingly. The function behaves exactly like nla_parse()
01134 when parsing attributes, see \ref core_attr_nla_parse.
01135 
01136 \code
01137 int nlmsg_parse(struct nlmsghdr *hdr, int hdrlen, struct nlattr **attrs,
01138                 int maxtype, struct nla_policy *policy);
01139 \endcode
01140 
01141 The function nlmsg_validate() is based on nla_validate() and behaves
01142 exactly the same as nlmsg_parse() except that it only validates and will
01143 not fill a array with pointers to each attribute.
01144 
01145 \code
01146 int nlmsg_validate(struct nlmsghdr *hdr, int hdrlen, intmaxtype,
01147                    struct nla_policy *policy);
01148 \endcode
01149 
01150 See \ref core_attr_nla_parse for an example and more information on
01151 attribute parsing.
01152 
01153 \subsection core_msg_constr 4.3 Construction of a Message
01154 
01155 See \ref core_msg_format for information on the netlink message format
01156 and alignment requirements.
01157 
01158 Message construction is based on struct nl_msg which uses an internal
01159 buffer to store the actual netlink message. struct nl_msg \b does \b not
01160 point to the netlink message header. Use nlmsg_hdr() to retrieve a
01161 pointer to the netlink message header.
01162 
01163 At allocation time, a maximum message size is specified. It defaults to
01164 a page (PAGE_SIZE). The application constructing the message will reserve
01165 space out of this maximum message size repeatedly for each header or
01166 attribute added. This allows construction of messages across various
01167 layers of code where lower layers do not need to know about the space
01168 requirements of upper layers.
01169 
01170 <b>Why is setting the maximum message size necessary?</b> This question
01171 is often raised in combination with the proposed solution of reallocating
01172 the message payload buffer on the fly using realloc(). While it is
01173 possible to reallocate the buffer during construction using nlmsg_expand()
01174 it will make all pointers into the message buffer become stale. This
01175 breaks usage of nlmsg_hdr(), nla_nest_start(), and nla_nest_end() and is
01176 therefore not acceptable as default behaviour.
01177 
01178 \subsubsection core_msg_alloc 4.3.1 Allocating struct nl_msg
01179 
01180 The first step in constructing a new netlink message it to allocate a
01181 \c struct \c nl_msg to hold the message header and payload. Several
01182 functions exist to simplify various tasks.
01183 
01184 \code
01185 #include <netlink/msg.h>
01186 
01187 struct nl_msg *nlmsg_alloc(void);
01188 void nlmsg_free(struct nl_msg *msg);
01189 \endcode
01190 
01191 The function nlmsg_alloc() is the default message allocation function.
01192 It allocates a new message using the default maximum message size which
01193 equals to one page (PAGE_SIZE). The application can change the default
01194 size for messages by calling nlmsg_set_default_size():
01195 
01196 \code
01197 void      nlmsg_set_default_size(size_t);
01198 \endcode
01199 
01200 \b Note: Calling nlmsg_set_default_size() does not change the maximum
01201          message size of already allocated messages.
01202 
01203 \code
01204 struct nl_msg *nlmsg_alloc_size(size_t max);
01205 \endcode
01206 
01207 Instead of changing the default message size, the function
01208 nlmsg_alloc_size() can be used to allocate a message with a individual
01209 maximum message size.
01210 
01211 
01212 If the netlink message header is already known at allocation time, the
01213 application may sue nlmsg_inherit(). It will allocate a message using
01214 the default maximum message size and copy the header into the message.
01215 Calling nlmsg_inherit with \p set to NULL is equivalent to calling
01216 nlmsg_alloc().
01217 
01218 \code
01219 struct nl_msg *nlmsg_inherit(struct nlmsghdr *hdr);
01220 \endcode
01221 
01222 Alternatively nlmsg_alloc_simple() takes a netlink message type and
01223 netlink message flags. It is equivalent to nlmsg_inherit() except that it
01224 takes the two common header fields as arguments instead of a complete
01225 header.
01226 
01227 \code
01228 #include <netlink/msg.h>
01229 
01230 struct nl_msg *nlmsg_alloc_simple(int nlmsg_type, int flags);
01231 \endcode
01232 
01233 \subsubsection core_msg_nlmsg_put 4.3.2 Appending the netlink message header
01234 
01235 After allocating struct nl_msg, the netlink message header needs to be
01236 added unless one of the function nlmsg_alloc_simple() or nlmsg_inherit()
01237 have been used for allocation in which case this step will replace the
01238 netlink message header already in place.
01239 
01240 \code
01241 #include <netlink/msg.h>
01242 
01243 struct nlmsghdr *nlmsg_put(struct nl_msg *msg, uint32_t port, uint32_t seqnr,
01244                            int nlmsg_type, int payload, int nlmsg_flags);
01245 \endcode
01246 
01247 The function nlmsg_put() will build a netlink message header out of
01248 \p nlmsg_type, \p nlmsg_flags, \p seqnr, and \p port and copy it into
01249 the netlink message. \p seqnr can be set to \p NL_AUTO_SEQ to indiciate
01250 that the next possible sequence number should be used automatically. To
01251 use this feature, the message must be sent using the function
01252 nl_send_auto(). Like \p port, the argument \p seqnr can be set to
01253 \c NL_AUTO_PORT indicating that the local port assigned to the socket
01254 should be used as source port. This is generally a good idea unless you
01255 are replying to a request. See \ref proto_fund for more information on
01256 how to fill the header.
01257 
01258 The argument \p payload can be used by the application to reserve room
01259 for additional data after the header. A value of > 0 is equivalent to
01260 calling nlmsg_reserve(msg, payload, NLMSG_ALIGNTO). See
01261 \ref core_msg_reserve for more information on reserving room for data.
01262 
01263 \b Example:
01264 \include nlmsg_put.c
01265 
01266 \subsubsection core_msg_reserve 4.3.3 Reserving room at the end of the message
01267 
01268 Most functions described later on will automatically take care of
01269 reserving room for the data that is added to the end of the netlink
01270 message. In some situations it may be requried for the application
01271 to reserve room directly though.
01272 
01273 \code
01274 #include <netlink/msg.h>
01275 
01276 void *nlmsg_reserve(struct nl_msg *msg, size_t len, int pad);
01277 \endcode
01278 
01279 The function nlmsg_reserve() reserves \p len bytes at the end of the
01280 netlink message and returns a pointer to the start of the reserved area.
01281 The \p pad argument can be used to request \p len to be aligned to any
01282 number of bytes prior to reservation.
01283 
01284 The following example requests to reserve a 17 bytes area at the end of
01285 message aligned to 4 bytes. Therefore a total of 20 bytes will be
01286 reserved.
01287 
01288 \code
01289 #include <netlink/msg.h>
01290 
01291 void *buf = nlmsg_reserve(msg, 17, 4);
01292 \endcode
01293 
01294 \b Note: nlmsg_reserve() will \b not align the start of the buffer. Any
01295          alignment requirements must be provided by the owner of the
01296          previous message section.
01297 
01298 \subsubsection core_msg_append 4.3.4 Appending data at the end of the message
01299 
01300 The function nlmsg_append() appends \p len bytes at the end of the message,
01301 padding it if requested and necessary.
01302 
01303 \code
01304 #include <netlink/msg.h>
01305 
01306 int nlmsg_append(struct nl_msg *msg, void *data, size_t len, int pad);
01307 \endcode
01308 
01309 It is equivalent to calling nlmsg_reserve() and memcpy()ing the data into
01310 the freshly reserved data section.
01311 
01312 \b Note: nlmsg_append() will \b not align the start of the data. Any
01313          alignment requirements must be provided by the owner of the
01314          previous message section.
01315 
01316 \subsubsection core_msg_put_attr 4.3.5 Adding attribtues to a message
01317 
01318 Construction of attributes and addition of attribtues to the message is
01319 covereted in section \ref core_attr.
01320 
01321 \section core_attr 5. Netlink Attributes
01322 
01323 Any form of payload should be encoded as netlink attributes whenever
01324 possible. Use of attributes allows to extend any netlink protocol in
01325 the future without breaking binary compatibility. F.e. Suppose your
01326 device may currently be using 32 bit counters for statistics but years
01327 later the device switches to maintaining 64 bit counters to account
01328 for faster network hardware. If your protocol is using attributes the
01329 move to 64 bit counters is trivial and only involves in sending an
01330 additional attribute containing the 64 bit variants while still
01331 providing the old legacy 32 bit counters. If your protocol is not using
01332 attributes you will not be able to switch data types without breaking
01333 all existing users of the protocol. 
01334 
01335 The concept of nested attributes also allows for subsystems of your
01336 protocol to implement and maintain their own attribute schemas. Suppose
01337 a new generation of network device is introduced which requires a
01338 completely new set of configuration settings which was unthinkable when
01339 the netlink protocol was initially designed. Using attributes the new
01340 generation of devices may define a new attribute and fill it with its
01341 own new structure of attributes which extend or even obsolete the old
01342 attributes.
01343 
01344 Therefore, \e always use attributes even if you are almost certain that
01345 the message format will never ever change in the future.
01346 
01347 \subsection core_attr_format 5.1 Attribute Format
01348 
01349 Netlink attributes allow for any number of data chunks of arbitary
01350 length to be attached to a netlink message. See \ref core_msg_parse_attr
01351 for more information on where attributes are stored in the message.
01352 
01353 The format of the attributes data returned by nlmsg_attrdata() is as
01354 follows:
01355 
01356 \code
01357      <----------- nla_total_size(payload) ----------->
01358      <---------- nla_size(payload) ----------->
01359     +-----------------+- - -+- - - - - - - - - +- - -+-----------------+- - -
01360     |  struct nlattr  | Pad |     Payload      | Pad |  struct nlattr  |
01361     +-----------------+- - -+- - - - - - - - - +- - -+-----------------+- - -
01362      <---- NLA_HDRLEN -----> <--- NLA_ALIGN(len) ---> <---- NLA_HDRLEN ---
01363 \endcode
01364 
01365 Every attribute must start at an offset which is a multiple of
01366 \c NLA_ALIGNTO (4 bytes). If you need to know whether an attribute needs
01367 to be padded at the end, the function nla_padlen() returns the number
01368 of padding bytes that will or need to be added.
01369 
01370 \code   
01371 0                   1                   2                   3
01372 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
01373 +-------------------------------------------------------------+
01374 |           Length             |            Type              |
01375 +------------------------------+------------------------------+
01376 |                     Attribute Payload                       |
01377 .                                                             .
01378 .                                                             .
01379 +-------------------------------------------------------------+
01380 \endcode
01381 
01382 Every attribute is encoded with a type and length field, both 16 bits,
01383 stored in the attribute header (struct nlattr) preceding the attribute
01384 payload. The length of an attribute is used to calculate the offset to
01385 the next attribute.
01386 
01387 \subsection core_attr_parse 5.2 Parsing Attributes
01388 
01389 \subsubsection core_attr_parse_split 5.2.1 Splitting an Attributes Stream into Attributes
01390 
01391 Although most applications will use one of the functions from the
01392 nlmsg_parse() family (See \ref core_attr_nla_parse) an interface
01393 exists to split the attributes stream manually.
01394 
01395 As described in \ref core_attr_format the attributes section contains a
01396 infinite sequence or stream of attributes. The pointer returned by
01397 nlmsg_attrdata() (See \ref core_msg_parse_attr) points to the first
01398 attribute header. Any subsequent attribute is accessed with the function
01399 nla_next() based on the previous header.
01400 
01401 \code
01402 #include <netlink/attr.h>
01403 
01404 struct nlattr *nla_next(const struct nlattr *attr, int *remaining);
01405 \endcode
01406 
01407 The semantics are equivalent to nlmsg_next() and thus nla_next() will also
01408 subtract the size of the previous attribute from the remaining number of
01409 bytes in the attributes stream.
01410 
01411 Like messages, attributes do not contain an indicator whether another
01412 attribute follows or not. The only indication is the number of bytes left
01413 in the attribute stream. The function nla_ok() exists to determine whether
01414 another attribute fits into the remaining number of bytes or not.
01415 
01416 \code
01417 #include <netlink/attr.h>
01418 
01419 int nla_ok(const struct nlattr *attr, int remaining);
01420 \endcode
01421 
01422 A typical use of nla_ok() and nla_next() looks like this:
01423 
01424 \include nla_ok.c
01425 
01426 \b Note: nla_ok() only returns true if the \b complete attributes
01427          including the attribute payload fits into the remaining number
01428          of bytes.
01429 
01430 \subsubsection core_attr_payload 5.2.2 Accessing Attribute Header and Payload
01431 
01432 Once the individual attributes have been sorted out by either splitting
01433 the attributes stream or using another interface the attribute header
01434 and payload can be accessed.
01435 
01436 \code
01437                              <- nla_len(hdr) ->
01438     +-----------------+- - -+- - - - - - - - - +- - -+
01439     |  struct nlattr  | Pad |     Payload      | Pad |
01440     +-----------------+- - -+- - - - - - - - - +- - -+
01441 nla_data(hdr) ---------------^
01442 \endcode
01443 
01444 The functions nla_len() and nla_type() can be used to access the attribute
01445 header. nla_len() will return the length of the payload not including
01446 eventual padding bytes. nla_type returns the attribute type.
01447 
01448 \code
01449 #include <netlink/attr.h>
01450 
01451 int nla_len(const struct nlattr *hdr);
01452 int nla_type(const struct nlattr *hdr);
01453 \endcode
01454 
01455 The function nla_data() will return a pointer to the attribute payload.
01456 Please note that due to NLA_ALIGNTO being 4 bytes it may not be safe to
01457 cast and dereference the pointer for any datatype larger than 32 bit
01458 depending on the architecture the application is run on.
01459 
01460 \code
01461 #include <netlink/attr.h>
01462 
01463 void *nla_data(const struct nlattr *hdr);
01464 \endcode
01465 
01466 \b Note: Never rely on the size of a payload being what you expect it to
01467          be. \e Always verify the payload size and make sure that it
01468          matches your expectations. See \ref core_attr_validation.
01469 
01470 \subsubsection core_attr_validation 5.2.3 Attribute Validation
01471 
01472 When receiving netlink attributes, the receiver has certain expections
01473 on how the attributes should look like. These expectations must be
01474 defined to make sure the sending side meets our expecations. For this
01475 purpose, a attribute validation interface exists which must be used
01476 prior to accessing any payload.
01477 
01478 All functions providing attribute validation functionality are based
01479 on struct nla_policy:
01480 
01481 \code
01482 struct nla_policy {
01483         uint16_t        type;
01484         uint16_t        minlen;
01485         uint16_t        maxlen;
01486 };
01487 \endcode
01488 
01489 The \p type member specifies the datatype of the attribute, e.g.
01490 NLA_U32, NLA_STRING, NLA_FLAG. The default is NLA_UNSPEC. The \p minlen
01491 member defines the minmum payload length of an attribute to be
01492 considered a valid attribute. The value for \p minlen is implicit for
01493 most basic datatypes such as integers or flags. The \p maxlen member
01494 can be used to define a maximum payload length for an attribute to
01495 still be considered valid.
01496 
01497 \b Note: Specyfing a maximum payload length is not recommended when
01498 encoding structures in an attribute as it will prevent any extension of
01499 the structure in the future. Something that is frequently done in
01500 netlink protocols and does not break backwards compatibility.
01501 
01502 One of the functions which use struct nla_policy is nla_validate().
01503 The function expects an array of struct nla_policy and will access the
01504 array using the attribute type as index. If an attribute type is out
01505 of bounds the attribute is assumed to be valid. This is intentional
01506 behaviour to allow older applications not yet aware of recently
01507 introduced attributes to continue functioning.
01508 
01509 \code
01510 #include <netlink/attr.h>
01511 
01512 int nla_validate(struct nlattr *head, int len, int maxtype,
01513                  struct nla_policy *policy);
01514 \endcode
01515 
01516 The function nla_validate() returns 0 if all attributes are valid,
01517 otherwise a validation failure specific error code is returned.
01518 
01519 Most applications will rarely use nla_validate() directly but use
01520 nla_parse() instead which takes care of validation in the same way but
01521 also parses the the attributes in the same step. See
01522 \ref core_attr_nla_parse for an example and more information.
01523 
01524 The validation process in detail:
01525 -# If attribute type is 0 or exceeds \p maxtype attribute is 
01526    considered valid, 0 is returned.
01527 -# If payload length is < \p minlen, -NLE_ERANGE is returned.
01528 -# If \p maxlen is defined and payload exceeds it, NLE_ERANGE
01529    is returned.
01530 -# Datatype specific requirements rules, see \ref core_attr_data_type.
01531 -# If all is ok, 0 is returned.
01532 
01533 \subsubsection core_attr_nla_parse 5.2.4 Parsing Attributes the Easy Way
01534 
01535 Most applications will not want to deal with splitting attribute streams
01536 themselves as described in \ref core_attr_parse_split. A much easier
01537 method is to use nla_parse().
01538 
01539 \code
01540 #include <netlink/attr.h>
01541 
01542 int nla_parse(struct nlattr **attrs, int maxtype, struct nlattr *head,
01543               int len, struct nla_policy *policy);
01544 \endcode
01545 
01546 The function nla_parse() will iterate over a stream of attributes,
01547 validate each attribute as described in \ref core_attr_validation.  If
01548 the validation of all attributes succeeds, a pointer to each attribute
01549 is stored in the \p attrs array at \c attrs[nla_type(attr)].
01550 
01551 As an alernative to nla_parse() the function nlmsg_parse() can be used
01552 to parse the message and its attributes in one step. See
01553 \ref core_nlmsg_parse for information on how to use these functions.
01554 
01555 \b Example:
01556 
01557 The following example demonstrates how to parse a netlink message sent
01558 over a netlink protocol which does not use protocol headers. The example
01559 does enforce a attribute policy however, the attribute MY_ATTR_FOO must
01560 be a 32 bit integer, and the attribute MY_ATTR_BAR must be a string with
01561 a maximum length of 16 characters.
01562 
01563 \include nlmsg_parse.c
01564 
01565 \subsubsection core_attr_find 5.2.5 Locating a Single Attribute
01566 
01567 An application only interested in a single attribute can use one of the
01568 functions nla_find() or  nlmsg_find_attr(). These function will iterate
01569 over all attributes, search for a matching attribute and return a pointer
01570 to the corresponding attribute header.
01571 
01572 \code
01573 #include <netlink/attr.h>
01574 
01575 struct nlattr *nla_find(struct nlattr *head, int len, int attrtype);
01576 \endcode
01577 
01578 \code
01579 #include <netlink/msg.h>
01580 
01581 struct nlattr *nlmsg_find_attr(struct nlmsghdr *hdr, int hdrlen, int attrtype);
01582 \endcode
01583 
01584 \b Note: nla_find() and nlmsg_find_attr() will \b not search in nested
01585          attributes recursively, see \ref core_attr_nested.
01586 
01587 \subsubsection core_attr_iterate 5.2.6 Iterating over a Stream of Attributes
01588 
01589 In some situations it does not make sense to assign a unique attribute
01590 type to each attribute in the attribute stream. For example a list may
01591 be transferd using a stream of attributes and even if the attribute type
01592 is incremented for each attribute it may not make sense to use the
01593 nlmsg_parse() or nla_parse() function to fill an array.
01594 
01595 Therefore methods exist to iterate over a stream of attributes:
01596 
01597 \code
01598 #include <netlink/attr.h>
01599 
01600 nla_for_each_attr(attr, head, len, remaining)
01601 \endcode
01602 
01603 nla_for_each_attr() is a macro which can be used in front of a code
01604 block:
01605 
01606 \include nla_for_each_attr.c
01607 
01608 \subsection core_attr_constr 5.3 Attribute Construction
01609 
01610 The interface to add attributes to a netlink message is based on the
01611 regular message construction interface. It assumes that the message
01612 header and an eventual protocol header has been added to the message
01613 already.
01614 
01615 \code
01616 struct nlattr *nla_reserve(struct nl_msg *msg, int attrtype, int len);
01617 \endcode
01618 
01619 The function nla_reserve() adds an attribute header at the end of the
01620 message and reserves room for \p len bytes of payload. The function
01621 returns a pointer to the attribute payload section inside the message.
01622 Padding is added at the end of the attribute to ensure the next
01623 attribute is properly aligned.
01624 
01625 \code
01626 int nla_put(struct nl_msg *msg, int attrtype, int attrlen, const void *data);
01627 \endcode
01628 
01629 The function nla_put() is base don nla_reserve() but takes an additional
01630 pointer \p data pointing to a buffer containing the attribute payload.
01631 It will copy the buffer into the message automatically.
01632 
01633 \b Example:
01634 
01635 \include nla_put.c
01636 
01637 See \ref core_attr_data_type for datatype specific attribute construction
01638 functions.
01639 
01640 \subsubsection core_attr_exception 5.3.1 Exception Based Attribute Construction
01641 
01642 Like in the kernel API an exception based construction interface is
01643 provided. The behaviour of the macros is identical to their regular
01644 function counterparts except that in case of an error, the target
01645 \c nla_put_failure is jumped.
01646 
01647 \b Example:
01648 
01649 \include NLA_PUT.c
01650 
01651 See \ref core_attr_data_type for more information on the datatype
01652 specific exception based variants.
01653 
01654 \subsection core_attr_data_type 5.4 Attribute Data Types
01655 
01656 A number of basic data types have been defined to simplify access and
01657 validation of attributes. The datatype is not encoded in the attribute,
01658 therefore bthe sender and receiver are required to use the same
01659 definition on what attribute is of what type.
01660 
01661 Besides simplified access to the payload of such datatypes, the major
01662 advantage is the automatic validation of each attribute based on a
01663 policy. The validation ensures safe access to the payload by checking
01664 for minimal payload size and can also be used to enforce maximum
01665 payload size for some datatypes.
01666 
01667 \subsubsection core_attr_int 5.4.1 Integer Attributes
01668 
01669 The most frequently used datatypes are integers. Integers come in four
01670 different sizes:
01671 - \c NLA_U8 - 8bit integer
01672 - \c NLA_U16 - 16bit integer
01673 - \c NLA_U32 - 32bit integer
01674 - \c NLA_U64 - 64bit integer
01675 
01676 Note that due to the alignment requirements of attributes the integer
01677 attribtue \c NLA_u8 and \c NLA_U16 will not result in space savings in
01678 the netlink message. Their use is intended to limit the range of values.
01679 
01680 <b>Parsing Integer Attributes</b>
01681 
01682 \code
01683 #include <netlink/attr.h>
01684 
01685 uint8_t  nla_get_u8(struct nlattr *hdr);
01686 uint16_t nla_get_u16(struct nlattr *hdr);
01687 uint32_t nla_get_u32(struct nlattr *hdr);
01688 uint64_t nla_get_u64(struct nlattr *hdr);
01689 \endcode
01690 
01691 Example:
01692 
01693 \code
01694 if (attrs[MY_ATTR_FOO])
01695         uint32_t val = nla_get_u32(attrs[MY_ATTR_FOO]);
01696 \endcode
01697 
01698 <b>Constructing Integer Attributes</b>
01699 
01700 \code
01701 #include <netlink/attr.h>
01702 
01703 int nla_put_u8(struct nl_msg *msg, int attrtype, uint8_t value);
01704 int nla_put_u16(struct nl_msg *msg, int attrtype, uint16_t value);
01705 int nla_put_u32(struct nl_msg *msg, int attrtype, uint32_t value);
01706 int nla_put_u64(struct nl_msg *msg, int attrtype, uint64_t value);
01707 \endcode
01708 
01709 Exception based:
01710 
01711 \code
01712 NLA_PUT_U8(msg, attrtype, value)
01713 NLA_PUT_U16(msg, attrtype, value)
01714 NLA_PUT_U32(msg, attrtype, value)
01715 NLA_PUT_U64(msg, attrtype, value)
01716 \endcode
01717 
01718 <b>Validation</b>
01719 
01720 Use \p NLA_U8, \p NLA_U16, \p NLA_U32, or \p NLA_U64 to define the type
01721 of integer when filling out a struct nla_policy array. It will
01722 automatically enforce the correct minimum payload length policy.
01723 
01724 Validation does not differ between signed and unsigned integers, only
01725 the size matters. If the appliaction wishes to enforce particular value
01726 ranges it must do so itself.
01727 
01728 \code
01729 static struct nla_policy my_policy[ATTR_MAX+1] = {
01730         [ATTR_FOO] = { .type = NLA_U32 },
01731         [ATTR_BAR] = { .type = NLA_U8 },
01732 };
01733 \endcode
01734 
01735 The above is equivalent to:
01736 \code
01737 static struct nla_policy my_policy[ATTR_MAX+1] = {
01738         [ATTR_FOO] = { .minlen = sizeof(uint32_t) },
01739         [ATTR_BAR] = { .minlen = sizeof(uint8_t) },
01740 };
01741 \endcode
01742 
01743 \subsubsection core_attr_string 5.4.2 String Attributes
01744 
01745 The string datatype represents a NUL termianted character string of
01746 variable length. It is not intended for binary data streams.
01747 
01748 The payload of string attributes can be accessed with the function
01749 nla_get_string(). nla_strdup() calls strdup() on the payload and returns
01750 the newly allocated string.
01751 
01752 \code
01753 #include <netlink/attr.h>
01754 
01755 char *nla_get_string(struct nlattr *hdr);
01756 char *nla_strdup(struct nlattr *hdr);
01757 \endcode
01758 
01759 String attributes are constructed with the function nla_put_string()
01760 respectively NLA_PUT_STRING(). The length of the payload will be strlen()+1,
01761 the trailing NUL byte is included.
01762 
01763 \code
01764 int nla_put_string(struct nl_msg *msg, int attrtype, const char *data);
01765 
01766 NLA_PUT_STRING(msg, attrtype, data)
01767 \endcode
01768 
01769 For validation purposes the type \p NLA_STRING can be used in
01770 struct nla_policy definitions. It implies a minimum payload length of 1
01771 byte and checks for a trailing NUL byte. Optionally the \p maxlen member
01772 defines the maximum length of a character string (including the trailing
01773 NUL byte).
01774 
01775 \code
01776 static struct nla_policy my_policy[] = {
01777         [ATTR_FOO] = { .type = NLA_STRING,
01778                        .maxlen = IFNAMSIZ },
01779 };
01780 \endcode
01781 
01782 \subsubsection core_attr_flag 5.4.3 Flag Attributes
01783 
01784 The flag attribute represents a boolean datatype. The presence of the
01785 attribute implies a value of \p true, the absence of the attribute
01786 implies the value \p false. Therefore the payload length of flag
01787 attributes is always 0.
01788 
01789 \code
01790 int nla_get_flag(struct nlattr *hdr);
01791 int nla_put_flag(struct nl_msg *msg, int attrtype);
01792 \endcode
01793 
01794 The type \p NLA_FLAG is used for validation purposes. It implies a 
01795 \p maxlen value of 0 and thus enforces a maximum payload length of 0.
01796 
01797 \b Example:
01798 
01799 \include nla_flag.c
01800 
01801 \subsubsection core_attr_nested 5.4.4 Nested Attributes
01802 
01803 As described in \ref core_attr, attributes can be nested allowing for
01804 complex tree structures of attributes. It is commonly used to delegate
01805 the responsibility of a subsection of the message to a subsystem.
01806 Nested attributes are also commonly used for transmitting list of
01807 objects.
01808 
01809 When nesting attributes, the nested attributes are included as payload
01810 of a container attribute.
01811 
01812 <b>IMPORTANT NOTICE:</b> When validating the attributes using
01813 nlmsg_validate(), nlmsg_parse(), nla_validate(), or nla_parse() only
01814 the attributes on the first level are being validated. None of these
01815 functions will validate attributes recursively. Therefore you must
01816 explicitely call nla_validate() or use nla_parse_nested() for each
01817 level of nested attributes.
01818 
01819 The type \p NLA_NESTED should be used when defining nested attributes
01820 in a struct nla_policy definition. It will not enforce any minimum
01821 payload length unless \p minlen is specified explicitely. This is
01822 because some netlink protocols implicitely allow empty container
01823 attributes.
01824 
01825 \code
01826 static struct nla_policy my_policy[] = {
01827         [ATTR_OPTS] = { .type = NLA_NESTED },
01828 };
01829 \endcode
01830 
01831 <b>Parsing of Nested Attributes</b>
01832 
01833 The function nla_parse_nested() is used to parse nested attributes.
01834 Its behaviour is identical to nla_parse() except that it takes a
01835 struct nlattr as argument and will use the payload as stream of
01836 attributes.
01837 
01838 \include nla_parse_nested.c
01839 
01840 <b>Construction of Nested Attributes</b>
01841 
01842 Attributes are nested by surrounding them with calls to nla_nest_start()
01843 and nla_nest_end(). nla_nest_start() will add a attribute header to
01844 the message but no actual payload. All data added to the message from
01845 this point on will be part of the container attribute until nla_nest_end()
01846 is called which "closes" the attribute, correcting its payload length to
01847 include all data length.
01848 
01849 \include nla_nest_start.c
01850 
01851 \subsubsection core_attr_unspec 5.4.5 Unspecified Attribute
01852 
01853 This is the default attribute type and used when none of the basic
01854 datatypes is suitable. It represents data of arbitary type and length.
01855 
01856 See \ref core_abstract_addr_alloc for a more information on a special
01857 interface allowing the allocation of abstract address object based on
01858 netlink attributes which carry some form of network address.
01859 
01860 See \ref core_abstract_data_alloc for more information on how to
01861 allocate abstract data objects based on netlink attributes.
01862 
01863 Use the function nla_get() and nla_put() to access the payload and
01864 construct attributes. See \ref core_attr_constr for an example.
01865 
01866 \subsection core_attr_examples 5.5 Examples
01867 
01868 \subsubsection core_attr_example_constr 5.5.1 Constructing a Netlink Message with Attributes
01869 
01870 \include msg_constr_attr.c
01871 
01872 \subsubsection core_attr_example_parse 5.5.2 Parsing a Netlink Message with Attributes
01873 
01874 \include msg_parse_attr.c
01875 
01876 \section core_cb 6. Callback Configurations
01877 
01878 Callback hooks and overwriting capabilities are provided in various places
01879 inside library to control the behaviour of several functions. All the
01880 callback and overwrite functions are packed together in struct nl_cb which
01881 is attached to a netlink socket or passed on to functions directly.
01882 
01883 \subsection core_cb_hooks 6.1 Callback Hooks
01884 
01885 Callback hooks are spread across the library to provide entry points for
01886 message processing and to take action upon certain events.
01887 
01888 Callback functions may return the following return codes:
01889 \code
01890 Return Code      | Description
01891 -------------------------------------------------------------------------
01892 NL_OK            | Proceed.
01893 NL_SKIP          | Skip message currently being processed and continue
01894                  | parsing the receive buffer.
01895 NL_STOP          | Stop parsing and discard all remaining data in the
01896                  | receive buffer.
01897 \endcode
01898 
01899 \subsubsection core_cb_default 6.1.1 Default Callback Implementations
01900 
01901 The library provides three sets of default callback implementations:
01902 - \b NL_CB_DEFAULT This is the default set. It implets the default behaviour.
01903      See the table below for more information on the return codes of each
01904      function.
01905 - \b NL_CB_VERBOSE This set is based on the default set but will cause an
01906      error message to be printed to stderr for error messages, invalid
01907      messages, message overruns and unhandled valid messages. The \p arg
01908      pointer in nl_cb_set() and nl_cb_err() can be used to provide a FILE *
01909      which overwrites stderr.
01910 - \b NL_CB_DEBUG This set is intended for debugging purposes. It is based
01911      on the verbose set but will decode and dump each message sent or
01912      received to the console.
01913 
01914 \subsubsection core_cb_msg_proc 6.1.2 Message Processing Callbacks
01915 
01916 nl_sendmsg() callback hooks:
01917 \code
01918 Callback ID        | Description                       | Default Return Value
01919 -----------------------------------------------------------------------------
01920 NL_CB_MSG_OUT      | Each message sent                 | NL_OK
01921 \endcode
01922 
01923 Any function called by NL_CB_MSG_OUT may return a negative error code to
01924 prevent the message from being sent and the error code being returned.
01925 
01926 nl_recvmsgs() callback hooks (ordered by priority):
01927 \code
01928 Callback ID        | Description                       | Default Return Value
01929 -----------------------------------------------------------------------------
01930 NL_CB_MSG_IN       | Each message received             | NL_OK
01931 NL_CB_SEQ_CHECK    | May overwrite sequence check algo | NL_OK
01932 NL_CB_INVALID      | Invalid messages                  | NL_STOP
01933 NL_CB_SEND_ACK     | Messages with NLM_F_ACK flag set  | NL_OK
01934 NL_CB_FINISH       | Messages of type NLMSG_DONE       | NL_STOP
01935 NL_CB_SKIPPED      | Messages of type NLMSG_NOOP       | NL_SKIP
01936 NL_CB_OVERRUN      | Messages of type NLMSG_OVERRUN    | NL_STOP
01937 NL_CB_ACK          | ACK Messages                      | NL_STOP
01938 NL_CB_VALID        | Each valid message                | NL_OK
01939 \endcode
01940 
01941 Any of these functions may return NL_OK, NL_SKIP, or NL_STOP.
01942 
01943 Message processing callback functions are set with nl_cb_set():
01944 \code
01945 #include <netlink/handlers.h>
01946 
01947 int nl_cb_set(struct nl_cb *cb, enum nl_cb_type type, enum nl_cb_kind kind,
01948               nl_recvmsg_msg_cb_t func, void *cb);
01949 
01950 typedef int (*nl_recvmsg_msg_cb_t)(struct nl_msg *msg, void *arg);
01951 \endcode
01952 
01953 \subsubsection core_cb_errmsg 6.1.4 Callback for Error Messages
01954 
01955 A special function prototype is used for the error message callback hook:
01956 
01957 \code
01958 #include <netlink/handlers.h>
01959 
01960 int nl_cb_err(struct nl_cb *cb, enum nl_cb_kind kind, nl_recvmsg_err_cb_t func, void * arg);
01961 
01962 typedef int(* nl_recvmsg_err_cb_t)(struct sockaddr_nl *nla, struct nlmsgerr *nlerr, void *arg);
01963 \endcode
01964 
01965 \subsubsection core_cb_example 6.1.4 Example: Setting up a callback set
01966 \include nl_cb_set.c
01967 
01968 \subsection core_cb_overwrite 6.2 Overwriting of Internal Functions
01969 
01970 When the library needs to send or receive netlink messages in high level
01971 interfaces it does so by calling its own low level API. In the case the
01972 default characteristics are not sufficient for the application, it may
01973 overwrite several internal function calls with own implementations.
01974 
01975 \subsubsection core_cb_ow_recvmsgs 6.2.1 Overwriting recvmsgs()
01976 
01977 See \ref core_recv for more information on how and when recvmsgs() is
01978 called internally.
01979 
01980 \code
01981 #include <netlink/handlers.h>
01982 
01983 void nl_cb_overwrite_recvmsgs(struct nl_cb *cb,
01984                               int (*func)(struct nl_sock *sk, struct nl_cb *cb));
01985 \endcode
01986 
01987 The following criteras must be met if a recvmsgs() implementation is
01988 supposed to work with high level interfaces:
01989 - MUST respect the callback configuration in \c cb, therefore:
01990   - MUST call NL_CB_VALID for all valid messages, passing on 
01991   - MUST call NL_CB_ACK for all ACK messages
01992   - MUST correctly handle multipart messages, calling NL_CB_VALID for
01993     each message until a NLMSG_DONE message is received.
01994 - MUST report error code if a NLMSG_ERROR or NLMSG_OVERRUN mesasge is
01995   received.
01996 
01997 \subsubsection core_cb_ow_recv 6.2.2 Overwriting nl_recv()
01998 
01999 Often it is sufficient to overwrite nl_recv() which is responsible from
02000 receiving the actual data from the socket instead of replacing the complete
02001 recvmsgs() logic.
02002 
02003 See \ref core_recvmsgs for more information on how and when nl_recv()
02004 is called internally.
02005 
02006 \code
02007 #include <netlink/handlers.h>
02008 
02009 void nl_cb_overwrite_recv(struct nl_cb *cb,
02010                           int (*func)(struct nl_sock * sk,
02011                                       struct sockaddr_nl *addr,
02012                                       unsigned char **buf,
02013                                       struct ucred **cred));
02014 \endcode
02015 
02016 The following criteras must be met for an own nl_recv() implementation:
02017 - MUST return the number of bytes read or a negative error code if an
02018   error occured. The function may also return 0 to indicate that no
02019   data has been read.
02020 - MUST set \c *buf to a buffer containing the data read. It must be safe
02021   for the caller to access the number of bytes read returned as return code.
02022 - MAY fill out \c *addr with the netlink address of the peer the data
02023   has been received from.
02024 - MAY set \c *cred to a newly allocated struct ucred containg credentials.
02025 
02026 \subsubsection core_cb_ow_send 6.2.3 Overwriting nl_send()
02027 
02028 See \ref core_send for more information on how and when nl_send() is
02029 called internally.
02030 
02031 \code
02032 #include <netlink/handlers.h>
02033 
02034 void nl_cb_overwrite_send(struct nl_cb *cb, int (*func)(struct nl_sock *sk,
02035                                                         struct nl_msg *msg));
02036 \endcode
02037 
02038 Own implementations must send the netlink message and return 0 on success
02039 or a negative error code.
02040 
02041 \section core_cache 7. Cache System
02042 
02043 \subsection cache_alloc 7.1 Allocation of Caches
02044 
02045 Almost all subsystem provide a function to allocate a new cache
02046 of some form. The function usually looks like this:
02047 \code
02048 struct nl_cache *<object name>_alloc_cache(struct nl_sock *sk);
02049 \endcode
02050 
02051 These functions allocate a new cache for the own object type,
02052 initializes it properly and updates it to represent the current
02053 state of their master, e.g. a link cache would include all
02054 links currently configured in the kernel.
02055 
02056 Some of the allocation functions may take additional arguments
02057 to further specify what will be part of the cache.
02058 
02059 All such functions return a newly allocated cache or NULL
02060 in case of an error.
02061 
02062 \section core_abstract_types 8. Abstract Data Types
02063 
02064 A few high level abstract data types which are used by a majority netlink
02065 protocols are implemented in the core library. More may be added in the
02066 future if the need arises.
02067 
02068 \subsection core_abstract_addr 8.1 Abstract Address
02069 
02070 Most netlink protocols deal with networking related topics and thus
02071 dealing with network addresses is a common task.
02072 
02073 Currently the following address families are supported:
02074 - AF_INET
02075 - AF_INET6
02076 - AF_LLC
02077 - AF_DECnet
02078 - AF_UNSPEC
02079 
02080 \subsubsection core_abstract_addr_alloc 8.1.1 Address Allocation
02081 
02082 The function nl_addr_alloc() allocates a new empty address. The
02083 \p maxsize argument defines the maximum length of an address in bytes.
02084 The size of an address is address family specific. If the address
02085 family and address data are known at allocation time the function
02086 nl_addr_build() can be used alternatively. You may also clone
02087 an address by calling nl_addr_clone()
02088 
02089 \code
02090 #include <netlink/addr.h>
02091 
02092 struct nl_addr *nl_addr_alloc(size_t maxsize);
02093 struct nl_addr *nl_addr_clone(struct nl_addr *addr);
02094 struct nl_addr *nl_addr_build(int family, void *addr, size_t size);
02095 \endcode
02096 
02097 If the address is transported in a netlink attribute, the function
02098 nl_addr_alloc_attr() allocates a new address based on the payload
02099 of the attribute provided. The \p family argument is used to specify
02100 the address family of the address, set to \p AF_UNSPEC if unknown.
02101 
02102 \code
02103 #include <netlink/addr.h>
02104 
02105 struct nl_addr *nl_addr_alloc_attr(struct nlattr *attr, int family);
02106 \endcode
02107 
02108 If the address is provided by a user, it is usually stored in a human
02109 readable format. The function nl_addr_parse() parses a character
02110 string representing an address and allocates a new address based on
02111 it.
02112 
02113 \code
02114 #include <netlink/addr.h>
02115 
02116 int nl_addr_parse(const char *addr, int hint, struct nl_addr **result);
02117 \endcode
02118 
02119 If parsing succeeds the function returns 0 and the allocated address
02120 is stored in \p *result.
02121 
02122 \b Note: Make sure to return the reference to an address using
02123          nl_addr_put() after usage to allow memory being freed.
02124 
02125 \subsubsection core_abstract_addr_ref 8.1.2 Address References
02126 
02127 Abstract addresses use reference counting to account for all users of
02128 a particular address. After the last user has returned the reference
02129 the address is freed.
02130 
02131 If you pass on a address object to another function and you are not
02132 sure how long it will be used, make sure to call nl_addr_get() to
02133 acquire an additional reference and have that function or code path
02134 call nl_addr_put() as soon as it has finished using the address.
02135 
02136 \code
02137 #include <netlink/addr.h>
02138 
02139 struct nl_addr *nl_addr_get(struct nl_addr *addr);
02140 void nl_addr_put(struct nl_addr *addr);
02141 int nl_addr_shared(struct nl_addr *addr);
02142 \endcode
02143 
02144 You may call nl_addr_shared() at any time to check if you are the only
02145 user of an address.
02146 
02147 \subsubsection  core_abstract_addr_attr 8.1.3 Address Attributes
02148 
02149 The address is usually set at allocation time. If it was unknown at that
02150 time it can be specified later by calling nl_addr_set_family() and is
02151 accessed with the function nl_addr_get_family().
02152 
02153 \code
02154 #include <netlink/addr.h>
02155 
02156 void nl_addr_set_family(struct nl_addr *addr, int family);
02157 int nl_addr_get_family(struct nl_addr *addr);
02158 \endcode
02159 
02160 The same is true for the actual address data. It is typically present
02161 at allocation time. For exceptions it can be specified later or
02162 overwritten with the function nl_addr_set_binary_addr(). Beware that
02163 the length of the address may not exceed \p maxlen specified at
02164 allocation time. The address data is returned by the function
02165 nl_addr_get_binary_addr() and its length by the function
02166 nl_addr_get_len().
02167 
02168 \code
02169 #include <netlink/addr.h>
02170 
02171 int nl_addr_set_binary_addr(struct nl_addr *addr, void *data, size_t size);
02172 void *nl_addr_get_binary_addr(struct nl_addr *addr);
02173 unsigned int nl_addr_get_len(struct nl_addr *addr);
02174 \endcode
02175 
02176 If you only want to check if the address data consists of all zeros
02177 the function nl_addr_iszero() is a shortcut to that.
02178 
02179 \code
02180 #include <netlink/addr.h>
02181 
02182 int nl_addr_iszero(struct nl_addr *addr);
02183 \endcode
02184 
02185 \subsubsection core_abstract_addr_prefix 8.1.4 Address Prefix Length
02186 
02187 Although this functionality is somewhat specific to routing it has
02188 been implemented here. Addresses can have a prefix length assigned
02189 which implies that only the first n bits are of importance. This
02190 is f.e. used to implement subnets.
02191 
02192 Use set functions nl_addr_set_prefixlen() and nl_addr_get_prefixlen()
02193 to work with prefix lengths.
02194 
02195 \code
02196 #include <netlink/addr.h>
02197 
02198 void nl_addr_set_prefixlen(struct nl_addr *addr, int n);
02199 unsigned int nl_addr_get_prefixlen(struct nl_addr *addr);
02200 \endcode
02201 
02202 \b Note: The default prefix length is set to (address length * 8)
02203 
02204 \subsubsection core_abstract_addr_helpers 8.1.5 Address Helpers
02205 
02206 Several functions exist to help when dealing with addresses. The
02207 function nl_addr_cmp() compares two addresses and returns an integer
02208 less than, equal to or greater than zero without considering the prefix
02209 length at all. If you want to consider the prefix length, use the
02210 function nl_addr_cmp_prefix().
02211 
02212 \code
02213 #include <netlink/addr.h>
02214 
02215 int nl_addr_cmp(struct nl_addr *addr, struct nl_addr *addr);
02216 int nl_addr_cmp_prefix(struct nl_addr *addr, struct nl_addr *addr);
02217 \endcode
02218 
02219 If an abstract address needs to presented to the user it should be done
02220 in a human readable format which differs depending on the address
02221 family. The function nl_addr2str() takes care of this by calling the
02222 appropriate conversion functions internaly. It expects a \p buf of
02223 length \p size to write the character string into and returns a pointer
02224 to \p buf for easy printf() usage.
02225 
02226 \code
02227 #include <netlink/addr.h>
02228 
02229 char *nl_addr2str(struct nl_addr *addr, char *buf, size_t size);
02230 \endcode
02231 
02232 If the address family is unknown, the address data will be printed in
02233 hexadecimal format AA:BB:CC:DD:...
02234 
02235 Often the only way to figure out the address family is by looking at
02236 the length of the address. The function nl_addr_guess_family() does just
02237 this and returns the address family guessed based on the address size.
02238 
02239 \code
02240 #include <netlink/addr.h>
02241 
02242 int nl_addr_guess_family(struct nl_addr *addr);
02243 \endcode
02244 
02245 Before allocating an address you may want to check if the character
02246 string actually represents a valid address of the address family you are
02247 expecting. The function nl_addr_valid() can be used for that, it returns
02248 1 if the supplised \p addr is a valid address in the context of \p family.
02249 See inet_pton(3), dnet_pton(3) for more information on valid adddress
02250 formats.
02251 
02252 \code
02253 #include <netlink/addr.h>
02254 
02255 int nl_addr_valid(char *addr, int family);
02256 \endcode
02257 
02258 \subsection core_abstract_data 8.2 Abstract Data
02259 
02260 The abstract data type is a trivial datatype with the primary purpose
02261 to simplify usage of netlink attributes of arbitary length.
02262 
02263 \subsubsection core_abstract_data_alloc 8.2.1 Allocation of a Data Object
02264 
02265 The function nl_data_alloc() alloctes a new abstract data object and
02266 fill it with the provided data. nl_data_alloc_attr() does the same but
02267 bases the data on the payload of a netlink attribute. New data objects
02268 can also be allocated by cloning existing ones by using nl_data_clone().
02269 
02270 \code
02271 struct nl_data *nl_data_alloc(void *buf, size_t size);
02272 struct nl_data *nl_data_alloc_attr(struct nlattr *attr);
02273 struct nl_data *nl_data_clone(struct nl_data *data);
02274 void nl_data_free(struct nl_data *data);
02275 \endcode
02276 
02277 \subsubsection core_abstract_data_access 8.2.2 Access to Data
02278 
02279 The function nl_data_get() returns a pointer to the data, the size of
02280 data is returned by nl_data_get_size().
02281 
02282 \code
02283 void *nl_data_get(struct nl_data *data);
02284 size_t nl_data_get_size(struct nl_data *data);
02285 \endcode
02286 
02287 \subsubsection core_abstract_data_helpers 8.2.3 Data Helpers
02288 
02289 The function nl_data_append() reallocates the internal data buffers and
02290 appends the specified \p buf to the existing data.
02291 
02292 \code
02293 int nl_data_append(struct nl_data *data, void *buf, size_t size);
02294 \endcode
02295 
02296 \b Note: Call nl_data_append() invalidates all pointers returned by
02297          nl_data_get().
02298 
02299 \code
02300 int nl_data_cmp(struct nl_data *data, struct nl_data *data);
02301 \endcode
02302 
02303 */