Home | History | Annotate | Download | only in doc
      1 ////
      2 	vim.syntax: asciidoc
      3 
      4 	Copyright (c) 2011 Thomas Graf <tgraf (a] suug.ch>
      5 ////
      6 
      7 Netlink Library (libnl)
      8 =======================
      9 Thomas Graf <tgraf (a] suug.ch>
     10 3.2, May 9 2011:
     11 :numbered:
     12 
     13 == Introduction
     14 
     15 The core library contains the fundamentals required to communicate
     16 over netlink sockets. It deals with connecting and disconnectng of
     17 sockets, sending and receiving of data, construction and parsing of
     18 messages, provides a customizeable receiving state machine, and
     19 provides a abstract data type framework which eases the implementation
     20 of object based netlink protocols where objects are added, removed, or
     21 modified using a netlink based protocol.
     22 
     23 .Library Hierarchy
     24 
     25 The suite is split into multiple libraries:
     26 
     27 image:library_overview.png["Library Hierarchy"]
     28 
     29 link:core.html[Netlink Library] (libnl)::
     30 Socket handling, sending and receiving, message construction and parsing, ...
     31 
     32 link:route.html[Routing Family Library] (libnl-route)::
     33 Adresses, links, neighbours, routing, traffic control, neighbour tables, ...
     34 
     35 Netfilter Library (libnl-nf)::
     36 Connection tracking, logging, queueing
     37 
     38 Generic Netlink Library (libnl-genl)::
     39 Controller API, family and command registration
     40 
     41 
     42 === How To Read This Documentation
     43 
     44 The libraries provide a broad set of APIs of which most applications only
     45 require a small subset of it. Depending on the type of application, some
     46 users may only be interested in the low level netlink messaging API while
     47 others wish to make heavy use of the high level API.
     48 
     49 In any case it is recommended to get familiar with the netlink protocol
     50 first.
     51 
     52 - <<core_netlink_fundamentals>>
     53 
     54 The low level APIs are described in:
     55 
     56 - <<core_sockets>>
     57 - <<core_send_recv>>
     58 
     59 
     60 === Linking to this Library
     61 
     62 .Checking the presence of the library using autoconf
     63 
     64 Projects using autoconf may use +PKG_CHECK_MODULES()+ to check if
     65 a specific version of libnl is available on the system. The example
     66 below also shows how to retrieve the +CFLAGS+ and linking dependencies
     67 required to link against the library.
     68 
     69 The following example shows how to check for a specific version of libnl. If
     70 found, it extends the `CFLAGS` and `LIBS` variable appropriately:
     71 
     72 [source]
     73 ----
     74 PKG_CHECK_MODULES(LIBNL3, libnl-3.0 >= 3.1, [have_libnl3=yes], [have_libnl3=no])
     75 if (test "${have_libnl3}" = "yes"); then
     76 	CFLAGS+="$LIBNL3_CFLAGS"
     77 	LIBS+="$LIBNL3_LIBS"
     78 fi
     79 ----
     80 
     81 NOTE: The pkgconfig file is named +libnl-3.0.pc+ for historic reasons, it also
     82       covers library versions >= 3.1.
     83 
     84 .Header Files
     85 
     86 The main header file is `<netlink/netlink.h>`. Additional headers may need to
     87 be included in your sources depending on the subsystems and components your
     88 program makes use of.
     89 
     90 [source,c]
     91 -----
     92 #include <netlink/netlink.h>
     93 #include <netlink/cache.h>
     94 #include <netlink/route/link.h>
     95 -----
     96 
     97 .Version Dependent Code
     98 
     99 If your code wishes to be capable to link against multiple versions of libnl
    100 you may have direct the compiler to only include portions on the code depending
    101 on the version of libnl that it is compiled against.
    102 
    103 [source,c]
    104 -----
    105 #include <netlink/version.h>
    106 
    107 #if LIBNL_VER_NUM >= LIBNL_VER(3,1)
    108 	/* include code if compiled with libnl version >= 3.1 */
    109 #endif
    110 -----
    111 
    112 .Linking
    113 -----
    114 $ gcc myprogram.c -o myprogram $(pkgconfig --cflags --libs libnl-3.0)
    115 -----
    116 
    117 === Debugging
    118 
    119 The library has been compiled with debugging statements enabled it will
    120 print debug information to +stderr+ if the environment variable +NLDBG+
    121 is set to > 0.
    122 
    123 -----
    124 $ NLDBG=2 ./myprogram
    125 -----
    126 
    127 .Debugging Levels
    128 [options="header", width="80%", cols="1,5", align="center"]
    129 |===============================================================
    130 | Level | Description
    131 | 0     | Debugging disabled (default)
    132 | 1     | Warnings, important events and notifications
    133 | 2     | More or less important debugging messages
    134 | 3     | Repetitive events causing a flood of debugging messages
    135 | 4     | Even less important messages
    136 |===============================================================
    137 
    138 .Debugging the Netlink Protocol
    139 
    140 It is often useful to peek into the stream of netlink messages exchanged
    141 with other sockets. Setting the environment variable +NLCB=debug+ will
    142 cause the debugging message handlers to be used which in turn print the
    143 netlink messages exchanged in a human readable format to to +stderr+:
    144 
    145 -----
    146 $ NLCB=debug ./myprogram
    147 -- Debug: Sent Message:
    148 --------------------------   BEGIN NETLINK MESSAGE ---------------------------
    149   [HEADER] 16 octets
    150     .nlmsg_len = 20
    151     .nlmsg_type = 18 <route/link::get>
    152     .nlmsg_flags = 773 <REQUEST,ACK,ROOT,MATCH>
    153     .nlmsg_seq = 1301410712
    154     .nlmsg_pid = 20014
    155   [PAYLOAD] 16 octets
    156     00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00       ................
    157 ---------------------------  END NETLINK MESSAGE   ---------------------------
    158 -- Debug: Received Message:
    159 --------------------------   BEGIN NETLINK MESSAGE ---------------------------
    160   [HEADER] 16 octets
    161     .nlmsg_len = 996
    162     .nlmsg_type = 16 <route/link::new>
    163     .nlmsg_flags = 2 <MULTI>
    164     .nlmsg_seq = 1301410712
    165     .nlmsg_pid = 20014
    166   [PAYLOAD] 16 octets
    167     00 00 04 03 01 00 00 00 49 00 01 00 00 00 00 00       ........I.......
    168   [ATTR 03] 3 octets
    169     6c 6f 00                                              lo.
    170   [PADDING] 1 octets
    171     00                                                    .
    172   [ATTR 13] 4 octets
    173     00 00 00 00                                           ....
    174   [ATTR 16] 1 octets
    175     00                                                    .
    176   [PADDING] 3 octets
    177     00 00 00                                              ...
    178   [ATTR 17] 1 octets
    179     00                                                    .
    180   [...]
    181 ---------------------------  END NETLINK MESSAGE   ---------------------------
    182 
    183 -----
    184 
    185 [[core_netlink_fundamentals]]
    186 == Netlink Protocol Fundamentals
    187 
    188 The netlink protocol is a socket based IPC mechanism used for
    189 communication between userspace processes and the kernel or between
    190 userspace processes themselves. The netlink protocol is based on BSD
    191 sockets and uses the +AF_NETLINK+ address family. Every netlink
    192 protocol uses its own protocol number (e.g. +NETLINK_ROUTE+,
    193 +NETLINK_NETFILTER+, etc). Its addressing schema is based on a 32 bit
    194 port number, formerly referred to as PID, which uniquely identifies
    195 each peer.
    196 
    197 [[core_addressing]]
    198 === Addressing
    199 
    200 The netlink address (port) consists of a 32bit integer. Port 0 (zero)
    201 is reserved for the kernel and refers to the kernel side socket of each
    202 netlink protocol family. Other port numbers usually refer to user space
    203 owned sockets, although this is not enforced.
    204 
    205 NOTE: In the beginning, it was common practice to use the process
    206       identifier (PID) as the local port number. This became unpractical
    207       with the introduction of threaded netlink applications and
    208       applications requiring multiple sockets. Therefore libnl generates
    209       unique port numbers based on the process identifier and adds an
    210       offset to it allowing for multiple sockets to be used. The initial
    211       socket will still equal to the process identifier for backwards
    212       compatibility reasons.
    213 
    214 image:addressing.png["Addressing Example"]
    215 
    216 The above figure illustrates three applications and the kernel side
    217 exposing two kernel side sockets. It shows the common netlink use
    218 cases:
    219 
    220   * User space to kernel
    221   * User space to user space
    222   * Listening to kernel multicast notifications
    223 
    224 .User Space to Kernel
    225 
    226 The most common form of netlink usage is for a user space application
    227 to send requests to the kernel and process the reply which is either
    228 an error message or a success notification.
    229 
    230 ["mscgen"]
    231 --------
    232 msc {
    233   App1,App2,Kernel;
    234   App1=>Kernel [label="request (src=11, dst=0)"];
    235   App1<=Kernel [label="reply (src=0, dst=11)"];
    236   ...;
    237   App2=>Kernel [label="request (src=21, dst=0)"];
    238   App2<=Kernel [label="reply (src=0, dst=21)"];
    239 }
    240 --------
    241 
    242 .User Space to User Space
    243 
    244 Netlink may also be used as an IPC mechanism to communicate between user
    245 space applications directly. Communication is not limited to two peers,
    246 any number of peers may communicate with each other and multicasting
    247 capabilities allow to reach multiple peers with a single message.
    248 
    249 In order for the sockets to be visible to each other, both sockets must
    250 be created for the same netlink protocol family.
    251 
    252 ["mscgen"]
    253 --------
    254 msc {
    255   App2,App3;
    256   App2=>App3 [label="request (src=22, dst=31)"];
    257   App2<=App3 [label="reply (src=31, dst=22)"];
    258   ...;
    259 }
    260 --------
    261 
    262 .User space listening to kernel notifications
    263 
    264 This form of netlink communication is typically found in user space
    265 daemons that need to act on certain kernel events. Such daemons will
    266 typically maintain a netlink socket subscribed to a multicast group that
    267 is used by the kernel to notify interested user space parties about
    268 specific events.
    269 
    270 ["mscgen"]
    271 --------
    272 msc {
    273   Kernel,App3;
    274   Kernel=>App3 [label="notification (src=0, group=foo)"];
    275   ...;
    276 }
    277 --------
    278 
    279 Use of multicasting is preferred over direct addressing due to the
    280 flexibility in exchanging the user space component at any time without
    281 the kernel noticing.
    282 
    283 [[core_msg_format]]
    284 === Message Format
    285 
    286 A netlink protocol is typically based on messages and consists of the
    287 netlink message header (+struct nlmsghdr+) plus the payload attached
    288 to it.  The payload can consist of arbitrary data but usually contains
    289 a fixed size protocol specific header followed by a stream of
    290 attributes.
    291 
    292 .Netlink message header (struct nlmsghdr)
    293 
    294 image:nlmsghdr.png[align="center", alt="Netlink Message Header"]
    295 
    296 Total Length (32bit)::
    297 Total length of the message in bytes including the netlink message header.
    298 
    299 Message Type (16bit)::
    300 The message type specifies the type of payload the message is carrying.
    301 Several standard message types are defined by the netlink protocol.
    302 Additional message types may be defined by each protocol family. See
    303 <<core_msg_types>> for additional information.
    304 
    305 Message Flags (16bit)::
    306 The message flags may be used to modify the behaviour of a message type.
    307 See section <<core_msg_flags>> for a list of standard message flags.
    308 
    309 Sequence Number (32bit)::
    310 The sequence number is optional and may be used to allow referring to
    311 a previous message, e.g. an error message can refer to the original
    312 request causing the error.
    313 
    314 Port Number (32bit)::
    315 The port number specifies the peer to which the message should be delivered
    316 to. If not specified, the message will be delivered to the first matching
    317 kernel side socket of the same protocol family.
    318 
    319 [[core_msg_types]]
    320 === Message Types
    321 
    322 Netlink differs between requests, notifications, and replies. Requests
    323 are messages which have the +NLM_F_REQUEST+ flag set and are meant to
    324 request an action from the receiver. A request is typically sent from
    325 a userspace process to the kernel. While not strictly enforced, requests
    326 should carry a sequence number incremented for each request sent.
    327 
    328 Depending on the nature of the request, the receiver may reply to the
    329 request with another netlink message. The sequence number of a reply
    330 must match the sequence number of the request it relates to.
    331 
    332 Notifications are of informal nature and no reply is expected, therefore
    333 the sequence number is typically set to 0.
    334 
    335 ["mscgen"]
    336 --------
    337 msc {
    338   A,B;
    339   A=>B [label="GET (seq=1, NLM_F_REQUEST)"];
    340   A<=B [label="PUT (seq=1)"];
    341   ...;
    342   A<=B [label="NOTIFY (seq=0)"];
    343 }
    344 --------
    345 
    346 
    347 The type of message is primarly identified by its 16 bit message type set
    348 in the message header. The following standard message types are defined:
    349 
    350 - +NLMSG_NOOP+ - No operation, message must be discarded
    351 - +NLMSG_ERROR+ - Error message or ACK, see <<core_errmsg>>
    352   respectively <<core_msg_ack>>
    353 - +NLMSG_DONE+ - End of multipart sequence, see <<core_multipart>>
    354 - +NLMSG_OVERRUN+ - Overrun notification (Error)
    355 
    356 Every netlink protocol is free to define own message types. Note that
    357 message type values  +< NLMSG_MIN_TYPE (0x10)+ are reserved and may
    358 not be used.
    359 
    360 It is common practice to use own message types to implement RPC schemas.
    361 Suppose the goal of the netlink protocol you are implementing is allow
    362 configuration of a particular network device, therefore you want to
    363 provide read/write access to various configuration options. The typical
    364 "netlink way" of doing this would be to define two message types
    365 +MSG_SETCFG+, +MSG_GETCFG+:
    366 
    367 [source,c]
    368 --------
    369 #define MSG_SETCFG	0x11
    370 #define MSG_GETCFG	0x12
    371 --------
    372 
    373 Sending a +MSG_GETCFG+ request message will typically trigger a reply
    374 with the message type +MSG_SETCFG+ containing the current configuration.
    375 In object oriented terms one would describe this as "the kernel sets
    376 the local copy of the configuration in userspace".
    377 
    378 ["mscgen"]
    379 --------
    380 msc {
    381   A,B;
    382   A=>B [label="MSG_GETCFG (seq=1, NLM_F_REQUEST)"];
    383   A<=B [label="MSG_SETCFG (seq=1)"];
    384 }
    385 --------
    386 
    387 The configuration may be changed by sending a +MSG_SETCFG+ which will
    388 be responded to with either a ACK (see <<core_msg_ack>>)
    389 or a error message (see <<core_errmsg>>).
    390 
    391 ["mscgen"]
    392 --------
    393 msc {
    394   A,B;
    395   A=>B [label="MSG_SETCFG (seq=1, NLM_F_REQUEST, NLM_F_ACK)"];
    396   A<=B [label="ACK (seq=1)"];
    397 }
    398 --------
    399 
    400 Optionally, the kernel may send out notifications for configuration
    401 changes allowing userspace to listen for changes instead of polling
    402 frequently. Notifications typically reuse an existing message type
    403 and rely on the application using a separate socket to differ between
    404 requests and notifications but you may also specify a separate message
    405 type.
    406 
    407 ["mscgen"]
    408 --------
    409 msc {
    410   A,B;
    411   A<=B [label="MSG_SETCFG (seq=0)"];
    412 }
    413 --------
    414 
    415 [[core_multipart]]
    416 ==== Multipart Messages
    417 
    418 Although in theory a netlink message can be up to 4GiB in size. The socket
    419 buffers are very likely not large enough to hold message of such sizes.
    420 Therefore it is common to limit messages to one page size (PAGE_SIZE) and
    421 use the multipart mechanism to split large pieces of data into several
    422 messages.  A multipart message has the flag +NLM_F_MULTI+ set and the
    423 receiver is expected to continue receiving and parsing until the special
    424 message type +NLMSG_DONE+ is received.
    425 
    426 Multipart messages unlike fragmented ip packets must not be reassmbled
    427 even though it is perfectly legal to do so if the protocols wishes to
    428 work this way. Often multipart message are used to send lists or trees
    429 of objects were each multipart message simply carries multiple objects
    430 allow for each message to be parsed independently.
    431 
    432 ["mscgen"]
    433 --------
    434 msc {
    435   A,B;
    436   A=>B [label="GET (seq=1, NLM_F_REQUEST)"];
    437   A<=B [label="PUT (seq=1, NLM_F_MULTI)"];
    438   ...;
    439   A<=B [label="PUT (seq=1, NLM_F_MULTI)"];
    440   A<=B [label="NLMSG_DONE (seq=1)"];
    441 }
    442 --------
    443 
    444 [[core_errmsg]]
    445 ==== Error Message
    446 
    447 Error messages can be sent in response to a request. Error messages must
    448 use the standard message type +NLMSG_ERROR+. The payload consists of a
    449 error code and the original netlink mesage header of the request. 
    450 
    451 image:nlmsgerr.png["Netlink Errror Message header"]
    452 
    453 Error messages should set the sequence number to the sequence number
    454 of the request which caused the error.
    455 
    456 ["mscgen"]
    457 --------
    458 msc {
    459   A,B;
    460   A=>B [label="GET (seq=1, NLM_F_REQUEST)"];
    461   A<=B [label="NLMSG_ERROR code=EINVAL (seq=1)"];
    462 }
    463 --------
    464 
    465 [[core_msg_ack]]
    466 ==== ACKs
    467 
    468 A sender can request an ACK message to be sent back for each request
    469 processed by setting the +NLM_F_ACK+ flag in the request. This is typically
    470 used to allow the sender to synchronize further processing until the
    471 request has been processed by the receiver.
    472 
    473 ["mscgen"]
    474 --------
    475 msc {
    476   A,B;
    477   A=>B [label="GET (seq=1, NLM_F_REQUEST | NLM_F_ACK)"];
    478   A<=B [label="ACK (seq=1)"];
    479 }
    480 --------
    481 
    482 ACK messages also use the message type +NLMSG_ERROR+ and payload
    483 format but the error code is set to 0.
    484 
    485 [[core_msg_flags]]
    486 ==== Message Flags
    487 
    488 The following standard flags are defined
    489 
    490 [source,c]
    491 --------
    492 #define NLM_F_REQUEST		1
    493 #define NLM_F_MULTI		2
    494 #define NLM_F_ACK		4
    495 #define NLM_F_ECHO		8
    496 --------
    497 
    498 - `NLM_F_REQUEST` - Message is a request, see <<core_msg_types>>.
    499 - `NLM_F_MULTI` - Multipart message, see <<core_multipart>>
    500 - `NLM_F_ACK` - ACK message requested, see <<core_msg_ack>>.
    501 - `NLM_F_ECHO` - Request to echo the request.
    502 
    503 The flag +NLM_F_ECHO+ is similar to the `NLM_F_ACK` flag. It can be
    504 used in combination with `NLM_F_REQUEST` and causes a notification
    505 which is sent as a result of a request to also be sent to the sender
    506 regardless of whether the sender has subscribed to the corresponding
    507 multicast group or not. See <<core_multicast>>
    508 
    509 Additional universal message flags are defined which only apply for
    510 +GET+ requests:
    511 
    512 [source,c]
    513 --------
    514 #define NLM_F_ROOT	0x100
    515 #define NLM_F_MATCH	0x200
    516 #define NLM_F_ATOMIC	0x400
    517 #define NLM_F_DUMP	(NLM_F_ROOT|NLM_F_MATCH)
    518 --------
    519 
    520 - `NLM_F_ROOT` - Return based on root of tree.
    521 - `NLM_F_MATCH` - Return all matching entries.
    522 - `NLM_F_ATOMIC` - Obsoleted, once used to request an atomic operation.
    523 - `NLM_F_DUMP` - Return a list of all objects
    524   (`NLM_F_ROOT`|`NLM_F_MATCH`).
    525 
    526 Use of these flags is completely optional and many netlink protocols only
    527 make use of the `NLM_F_DUMP` flag which typically requests the receiver
    528 to send a list of all objects in the context of the message type as a
    529 sequence of multipart messages (see <<core_multipart>>).
    530 
    531 Another set of flags exist related to `NEW` or `SET` requests. These
    532 flags are mutually exclusive to the `GET` flags:
    533 
    534 [source,c]
    535 --------
    536 #define NLM_F_REPLACE	0x100
    537 #define NLM_F_EXCL	0x200
    538 #define NLM_F_CREATE	0x400
    539 #define NLM_F_APPEND	0x800
    540 --------
    541 
    542 - `NLM_F_REPLACE` - Replace an existing object if it exists.
    543 - `NLM_F_EXCL` - Do not update object if it exists already.
    544 - `NLM_F_CREATE` - Create object if it does not exist yet.
    545 - `NLM_F_APPEND` - Add object at end of list.
    546 
    547 Behaviour of these flags may differ slightly between different netlink
    548 protocols.
    549 
    550 [[core_seq_num]]
    551 === Sequence Numbers
    552 
    553 Netlink allows the use of sequence numbers to help relate replies to
    554 requests. It should be noted that unlike in protocols such as TCP
    555 there is no strict enforcment of the sequence number. The sole purpose
    556 of sequence numbers is to assist a sender in relating replies to the
    557 corresponding requests. See <<core_msg_types>> for more information.
    558 
    559 Sequence numbers are managed on a per socket basis, see
    560 <<core_sk_seq_num>> for more information on how to use sequence numbers.
    561 
    562 [[core_multicast]]
    563 === Multicast Groups
    564 
    565 TODO
    566 
    567 See <<core_sk_multicast>>
    568 
    569 [[core_sockets]]
    570 == Netlink Sockets
    571 
    572 In order to use the netlink protocol, a netlink socket is required.
    573 Each socket defines an independent context for sending and receiving of
    574 messages. An application may make use multiple sockets, e.g. a socket to
    575 send requests and receive the replies and another socket subscribed to a
    576 multicast group to receive notifications.
    577 
    578 === Socket structure (struct nl_sock)
    579 
    580 The netlink socket and all related attributes including the actual file
    581 descriptor are represented by +struct nl_sock+.
    582 
    583 [source,c]
    584 --------
    585 #include <netlink/socket.h>
    586 
    587 struct nl_sock *nl_socket_alloc(void)
    588 void nl_socket_free(struct nl_sock *sk)
    589 --------
    590 
    591 The application must allocate an instance of +struct nl_sock+ for each
    592 netlink socket it wishes to use.
    593 
    594 [[core_sk_seq_num]]
    595 === Sequence Numbers
    596 
    597 The library will automatically take care of sequence number handling
    598 for the application. A sequence number counter is stored in the
    599 socket structure which is used and incremented automatically when a 
    600 message needs to be sent which is expected to generate a reply such as
    601 an error or any other message type that needs to be related to the
    602 original message.
    603 
    604 Alternatively, the counter can be used directly via the function
    605 nl_socket_use_seq(). It will return the current value of the counter
    606 and increment it by one afterwards.
    607 
    608 [source,c]
    609 --------
    610 #include <netlink/socket.h>
    611 
    612 unsigned int nl_socket_use_seq(struct nl_sock *sk);
    613 --------
    614 
    615 Most applications will not want to deal with sequence number handling
    616 themselves though. When using nl_send_auto() the sequence number is
    617 filled in automatically and matched again when a reply is received. See
    618 section <<core_send_recv>> for more information.
    619 
    620 This behaviour can and must be disabled if the netlink protocol
    621 implemented does not use a request/reply model, e.g. when a socket is
    622 used to receive notification messages.
    623 
    624 [source,c]
    625 --------
    626 #include <netlink/socket.h>
    627 
    628 void nl_socket_disable_seq_check(struct nl_sock *sk);
    629 --------
    630 
    631 For more information on the theory behind netlink sequence numbers,
    632 see section <<core_seq_num>>.
    633 
    634 [[core_sk_multicast]]
    635 === Multicast Group Subscriptions
    636 
    637 Each socket can subscribe to any number of multicast groups of the
    638 netlink protocol it is connected to. The socket will then receive a
    639 copy of each message sent to any of the groups. Multicast groups are
    640 commonly used to implement event notifications.
    641 
    642 Prior to kernel 2.6.14 the group subscription was performed using a
    643 bitmask which limited the number of groups per protocol family to 32.
    644 This outdated interface can still be accessed via the function
    645 nl_join_groups() even though it is not recommended for new code.
    646 
    647 [source,c]
    648 --------
    649 #include <netlink/socket.h>
    650 
    651 void nl_join_groups(struct nl_sock *sk, int bitmask);
    652 --------
    653 
    654 Starting with 2.6.14 a new method was introduced which supports subscribing
    655 to an almost infinite number of multicast groups.
    656 
    657 [source,c]
    658 --------
    659 #include <netlink/socket.h>
    660 
    661 int nl_socket_add_memberships(struct nl_sock *sk, int group, ...);
    662 int nl_socket_drop_memberships(struct nl_sock *sk, int group, ...);
    663 --------
    664 
    665 ==== Multicast Example
    666 
    667 [source,c]
    668 --------
    669 #include <netlink/netlink.h>
    670 #include <netlink/socket.h>
    671 #include <netlink/msg.h>
    672 
    673 /*
    674  * This function will be called for each valid netlink message received
    675  * in nl_recvmsgs_default()
    676  */
    677 static int my_func(struct nl_msg *msg, void *arg)
    678 {
    679 	return 0;
    680 }
    681 
    682 struct nl_sock *sk;
    683 
    684 /* Allocate a new socket */
    685 sk = nl_socket_alloc();
    686 
    687 /*
    688  * Notifications do not use sequence numbers, disable sequence number
    689  * checking.
    690  */
    691 nl_socket_disable_seq_check(sk);
    692 
    693 /*
    694  * Define a callback function, which will be called for each notification
    695  * received
    696  */
    697 nl_socket_modify_cb(sk, NL_CB_VALID, NL_CB_CUSTOM, my_func, NULL);
    698 
    699 /* Connect to routing netlink protocol */
    700 nl_connect(sk, NETLINK_ROUTE);
    701 
    702 /* Subscribe to link notifications group */
    703 nl_socket_add_memberships(sk, RTNLGRP_LINK, 0);
    704 
    705 /*
    706  * Start receiving messages. The function nl_recvmsgs_default() will block
    707  * until one or more netlink messages (notification) are received which
    708  * will be passed on to my_func().
    709  */
    710 while (1)
    711 	nl_recvmsgs_default(sock);
    712 --------
    713 
    714 [[core_sk_cb]]
    715 === Modifiying Socket Callback Configuration
    716 
    717 See <<core_cb>> for more information on
    718 callback hooks and overwriting capabilities.
    719 
    720 Each socket is assigned a callback configuration which controls the
    721 behaviour of the socket. This is f.e. required to have a separate
    722 message receive function per socket. It is perfectly legal to share
    723 callback configurations between sockets though.
    724 
    725 The following functions can be used to access and set the callback
    726 configuration of a socket:
    727 
    728 [source,c]
    729 --------
    730 #include <netlink/socket.h>
    731 
    732 struct nl_cb *nl_socket_get_cb(const struct nl_sock *sk);
    733 void nl_socket_set_cb(struct nl_sock *sk, struct nl_cb *cb);
    734 --------
    735 
    736 Additionaly a shortcut exists to modify the callback configuration
    737 assigned to a socket directly:
    738 
    739 [source,c]
    740 --------
    741 #include <netlink/socket.h>
    742 
    743 int nl_socket_modify_cb(struct nl_sock *sk, enum nl_cb_type type, enum nl_cb_kind kind,
    744                         nl_recvmsg_msg_cb_t func, void *arg);
    745 --------
    746 
    747 .Example:
    748 [source,c]
    749 --------
    750 #include <netlink/socket.h>
    751 
    752 // Call my_input() for all valid messages received in socket sk
    753 nl_socket_modify_cb(sk, NL_CB_VALID, NL_CB_CUSTOM, my_input, NULL);
    754 --------
    755 
    756 === Socket Attributes
    757 
    758 .Local Port
    759 
    760 The local port number uniquely identifies the socket and is used to
    761 address it. A unique local port is generated automatically when the
    762 socket is allocated. It will consist of the Process ID (22 bits) and a
    763 random number (10 bits) thus allowing up to 1024 sockets per process.
    764 
    765 [source,c]
    766 --------
    767 #include <netlink/socket.h>
    768 
    769 uint32_t nl_socket_get_local_port(const struct nl_sock *sk);
    770 void nl_socket_set_local_port(struct nl_sock *sk, uint32_t port);
    771 --------
    772 
    773 See section <<core_addressing>> for more information on port numbers.
    774 
    775 CAUTION: Overwriting the local port is possible but you have to ensure
    776 that the provided value is unique and no other socket in any other
    777 application is using the same value.
    778 
    779 .Peer Port
    780 
    781 A peer port can be assigned to the socket which will result in all
    782 unicast messages sent over the socket to be addresses to the peer. If
    783 no peer is specified, the message is sent to the kernel which will try
    784 to automatically bind the socket to a kernel side socket of the same
    785 netlink protocol family.  It is common practice not to bind the socket
    786 to a peer port as typically only one kernel side socket exists per
    787 netlink protocol family.
    788 
    789 [source,c]
    790 --------
    791 #include <netlink/socket.h>
    792 
    793 uint32_t nl_socket_get_peer_port(const struct nl_sock *sk);
    794 void nl_socket_set_peer_port(struct nl_sock *sk, uint32_t port);
    795 --------
    796 
    797 See section <<core_addressing>> for more information on port numbers.
    798 
    799 .File Descriptor
    800 
    801 Netlink uses the BSD socket interface, therefore a file descriptor is
    802 behind each socket and you may use it directly.
    803 
    804 [source,c]
    805 --------
    806 #include <netlink/socket.h>
    807 
    808 int nl_socket_get_fd(const struct nl_sock *sk);
    809 --------
    810 
    811 If a socket is used to only receive notifications it usually is best
    812 to put the socket in non-blocking mode and periodically poll for new
    813 notifications.
    814 
    815 [source,c]
    816 --------
    817 #include <netlink/socket.h>
    818 
    819 int nl_socket_set_nonblocking(const struct nl_sock *sk);
    820 --------
    821 
    822 .Send/Receive Buffer Size
    823 
    824 The socket buffer is used to queue netlink messages between sender and
    825 receiver. The size of these buffers specifies the maximum size you
    826 will be able to write() to a netlink socket, i.e. it will indirectly
    827 define the maximum message size. The default is 32KiB.
    828 
    829 [source,c]
    830 --------
    831 #include <netlink/socket.h>
    832 
    833 int nl_socket_set_buffer_size(struct nl_sock *sk, int rx, int tx);
    834 --------
    835 
    836 [[core_sk_cred]]
    837 .Enable/Disable Credentials
    838 
    839 TODO
    840 
    841 [source,c]
    842 --------
    843 #include <netlink/socket.h>
    844 
    845 int nl_socket_set_passcred(struct nl_sock *sk, int state);
    846 --------
    847 
    848 .Enable/Disable Auto-ACK Mode
    849 
    850 The following functions allow to enable/disable Auto-ACK mode on a socket.
    851 See <<core_auto_ack>> for more information on what implications that has.
    852 Auto-ACK mode is enabled by default.
    853 
    854 [source,c]
    855 --------
    856 #include <netlink/socket.h>
    857 
    858 void nl_socket_enable_auto_ack(struct nl_sock *sk);
    859 void nl_socket_disable_auto_ack(struct nl_sock *sk);
    860 --------
    861 
    862 .Enable/Disable Message Peeking
    863 
    864 If enabled, message peeking causes nl_recv() to try and use MSG_PEEK
    865 to retrieve the size of the next message received and allocate a
    866 buffer of that size. Message peeking is enabled by default but can be
    867 disabled using the following function:
    868 
    869 [source,c]
    870 --------
    871 #include <netlink/socket.h>
    872 
    873 void nl_socket_enable_msg_peek(struct nl_sock *sk);
    874 void nl_socket_disable_msg_peek(struct nl_sock *sk);
    875 --------
    876 
    877 .Enable/Disable Receival of Packet Information
    878 
    879 If enabled, each received netlink message from the kernel will include
    880 an additional struct nl_pktinfo in the control message. The following
    881 function can be used to enable/disable receival of packet information.
    882 
    883 [source,c]
    884 --------
    885 #include <netlink/socket.h>
    886 
    887 int nl_socket_recv_pktinfo(struct nl_sock *sk, int state);
    888 --------
    889 
    890 CAUTION: Processing of NETLINK_PKTINFO has not been implemented yet.
    891 
    892 [[core_send_recv]]
    893 == Sending and Receiving of Messages / Data
    894 
    895 [[core_send]]
    896 === Sending Messages
    897 
    898 The standard method of sending a netlink message over a netlink socket
    899 is to use the function nl_send_auto(). It will automatically complete
    900 the netlink message by filling the missing bits and pieces in the
    901 netlink message header and will deal with addressing based on the
    902 options and address set in the netlink socket. The message is then
    903 passed on to nl_send().
    904 
    905 If the default sending semantics implemented by nl_send() do not suit
    906 the application, it may overwrite the sending function nl_send() by
    907 specifying an own implementation using the function
    908 nl_cb_overwrite_send().
    909 
    910 [source,c]
    911 --------
    912    nl_send_auto(sk, msg)
    913          |
    914          |-----> nl_complete_msg(sk, msg)
    915          |
    916          |
    917          |              Own send function specified via nl_cb_overwrite_send()
    918          |- - - - - - - - - - - - - - - - - - - -
    919          v                                      v
    920    nl_send(sk, msg)                         send_func()
    921 --------
    922 
    923 .Using nl_send()
    924 
    925 If you do not require any of the automatic message completion
    926 functionality you may use nl_send() directly but beware that any
    927 internal calls to nl_send_auto() by the library to send netlink
    928 messages will still use nl_send(). Therefore if you wish to use any
    929 higher level interfaces and the behaviour of nl_send() is to your
    930 dislike then you must overwrite the nl_send() function via
    931 nl_cb_overwrite_send()
    932 
    933 The purpose of nl_send() is to embed the netlink message into a iovec
    934 structure and pass it on to nl_send_iovec().
    935 
    936 [source,c]
    937 --------
    938    nl_send(sk, msg)
    939          |
    940          v
    941    nl_send_iovec(sk, msg, iov, iovlen)
    942 --------
    943 
    944 .Using nl_send_iovec()
    945 
    946 nl_send_iovec() expects a finalized netlink message and fills out the
    947 struct msghdr used for addressing. It will first check if the struct
    948 nl_msg is addressed to a specific peer (see nlmsg_set_dst()). If not,
    949 it will try to fall back to the peer address specified in the socket
    950 (see nl_socket_set_peer_port(). Otherwise the message will be sent
    951 unaddressed and it is left to the kernel to find the correct peer.
    952 
    953 nl_send_iovec() also adds credentials if present and enabled
    954 (see <<core_sk_cred>>).
    955 
    956 The message is then passed on to nl_sendmsg().
    957 
    958 [source,c]
    959 --------
    960    nl_send_iovec(sk, msg, iov, iovlen)
    961          |
    962          v
    963    nl_sendmsg(sk, msg, msghdr)
    964 --------
    965 
    966 .Using nl_sendmsg()
    967 
    968 nl_sendmsg() expects a finalized netlink message and an optional
    969 struct msghdr containing the peer address. It will copy the local
    970 address as defined in the socket (see nl_socket_set_local_port()) into
    971 the netlink message header.
    972 
    973 At this point, construction of the message finished and it is ready to
    974 be sent.
    975 
    976 [source,c]
    977 --------
    978    nl_sendmsg(sk, msg, msghdr)
    979          |- - - - - - - - - - - - - - - - - - - - v
    980          |                                 NL_CB_MSG_OUT()
    981          |<- - - - - - - - - - - - - - - - - - - -+
    982          v
    983    sendmsg()
    984 --------
    985 
    986 Before sending the application has one last chance to modify the
    987 message.  It is passed to the NL_CB_MSG_OUT callback function which
    988 may inspect or modify the message and return an error code. If this
    989 error code is NL_OK the message is sent using sendmsg() resulting in
    990 the number of bytes written being returned. Otherwise the message
    991 sending process is aborted and the error code specified by the
    992 callback function is returned. See <<core_sk_cb>> for more information
    993 on how to set callbacks.
    994 
    995 .Sending Raw Data with nl_sendto()
    996 
    997 If you wish to send raw data over a netlink socket, the following
    998 function will pass on any buffer provided to it directly to sendto():
    999 
   1000 [source,c]
   1001 --------
   1002 #include <netlink/netlink.h>
   1003 
   1004 int nl_sendto(struct nl_sock *sk, void *buf, size_t size);
   1005 --------
   1006 
   1007 .Sending of Simple Messages
   1008 
   1009 A special interface exists for sending of trivial messages. The function
   1010 expects the netlink message type, optional netlink message flags, and an
   1011 optional data buffer and data length.  
   1012 [source,c]
   1013 --------
   1014 #include <netlink/netlink.h>
   1015 
   1016 int nl_send_simple(struct nl_sock *sk, int type, int flags,
   1017                    void *buf, size_t size);
   1018 --------
   1019 
   1020 The function will construct a netlink message header based on the message
   1021 type and flags provided and append the data buffer as message payload. The
   1022 newly constructed message is sent with nl_send_auto().
   1023 
   1024 The following example will send a netlink request message causing the
   1025 kernel to dump a list of all network links to userspace:
   1026 
   1027 [source,c]
   1028 --------
   1029 #include <netlink/netlink.h>
   1030 
   1031 struct nl_sock *sk;
   1032 struct rtgenmsg rt_hdr = {
   1033 	.rtgen_family = AF_UNSPEC,
   1034 };
   1035 
   1036 sk = nl_socket_alloc();
   1037 nl_connect(sk, NETLINK_ROUTE);
   1038 
   1039 nl_send_simple(sock, RTM_GETLINK, NLM_F_DUMP, &rt_hdr, sizeof(rt_hdr));
   1040 --------
   1041 
   1042 [[core_recv]]
   1043 === Receiving Messages
   1044 
   1045 The easiest method to receive netlink messages is to call nl_recvmsgs_default().
   1046 It will receive messages based on the semantics defined in the socket. The
   1047 application may customize these in detail although the default behaviour will
   1048 probably suit most applications.
   1049 
   1050 nl_recvmsgs_default() will also be called internally by the library whenever
   1051 it needs to receive and parse a netlink message.
   1052 
   1053 The function will fetch the callback configuration stored in the socket and
   1054 call nl_recvmsgs():
   1055 
   1056 [source,c]
   1057 --------
   1058    nl_recvmsgs_default(sk)
   1059          |
   1060          | cb = nl_socket_get_cb(sk)
   1061          v
   1062    nl_recvmsgs(sk, cb)
   1063 --------
   1064 
   1065 .Using nl_recvmsgs()
   1066 
   1067 nl_recvmsgs() implements the actual receiving loop, it blocks until a
   1068 netlink message has been received unless the socket has been put into
   1069 non-blocking mode.
   1070 
   1071 For the unlikely scenario that certain required receive characteristics
   1072 can not be achieved by fine tuning the internal recvmsgs function using
   1073 the callback configuration (see <<core_sk_cb>>) the application may provide
   1074 a complete own implementation of it and overwrite all calls to nl_recvmsgs()
   1075 with the function nl_cb_overwrite_recvmsgs().
   1076 
   1077 [source,c]
   1078 --------
   1079    nl_recvmsgs(sk, cb)
   1080          |
   1081          |     Own recvmsgs function specified via nl_cb_overwrite_recvmsgs()
   1082          |- - - - - - - - - - - - - - - - - - - -
   1083          v                                      v
   1084    internal_recvmsgs()                    my_recvmsgs()
   1085 --------
   1086 
   1087 [[core_recv_character]]
   1088 .Receive Characteristics
   1089 
   1090 If the application does not provide its own recvmsgs() implementation
   1091 with the function nl_cb_overwrite_recvmsgs() the following characteristics
   1092 apply while receiving data from a netlink socket:
   1093 
   1094 [source,c]
   1095 --------
   1096         internal_recvmsgs()
   1097                 |
   1098 +-------------->|     Own recv function specified with nl_cb_overwrite_recv()
   1099 |               |- - - - - - - - - - - - - - - -
   1100 |               v                              v
   1101 |           nl_recv()                      my_recv()
   1102 |               |<- - - - - - - - - - - - - - -+
   1103 |               |<-------------+
   1104 |               v              | More data to parse? (nlmsg_next())
   1105 |         Parse Message        | 
   1106 |               |--------------+
   1107 |               v
   1108 +------- NLM_F_MULTI set?
   1109                 |
   1110                 v
   1111             (SUCCESS)
   1112 --------
   1113 
   1114 The function nl_recv() is invoked first to receive data from the
   1115 netlink socket.  This function may be overwritten by the application
   1116 by an own implementation using the function nl_cb_overwrite_recv().
   1117 This may be useful if the netlink byte stream is in fact not received
   1118 from a socket directly but is read from a file or another source.
   1119 
   1120 If data has been read, it will be attemped to parse the data. This
   1121 will be done repeately until the parser returns NL_STOP, an error was
   1122 returned or all data has been parsed.
   1123 
   1124 In case the last message parsed successfully was a multipart message
   1125 (see <<core_multipart>>) and the parser did not
   1126 quit due to either an error or NL_STOP nl_recv() respectively the
   1127 applications own implementation will be called again and the parser
   1128 starts all over.
   1129 
   1130 See <<core_parse_character>> for information on how to extract valid
   1131 netlink messages from the parser and on how to control the behaviour
   1132 of it.
   1133 
   1134 [[core_parse_character]]
   1135 .Parsing Characteristics
   1136 
   1137 The internal parser is invoked for each netlink message received from
   1138 a netlink socket. It is typically fed by nl_recv() (see
   1139 <<core_recv_character>>).
   1140 
   1141 The parser will first ensure that the length of the data stream
   1142 provided is sufficient to contain a netlink message header and that
   1143 the message length as specified in the message header does not exceed
   1144 it.
   1145 
   1146 If this criteria is met, a new struct nl_msg is allocated and the
   1147 message is passed on to the the callback function NL_CB_MSG_IN if one
   1148 is set. Like any other callback function, it may return NL_SKIP to
   1149 skip the current message but continue parsing the next message or
   1150 NL_STOP to stop parsing completely.
   1151 
   1152 The next step is to check the sequence number of the message against
   1153 the currently expected sequence number. The application may provide
   1154 its own sequence number checking algorithm by setting the callback
   1155 function NL_CB_SEQ_CHECK to its own implementation. In fact, calling
   1156 nl_socket_disable_seq_check() to disable sequence number checking will
   1157 do nothing more than set the NL_CB_SEQ_CHECK hook to a function which
   1158 always returns NL_OK.
   1159 
   1160 Another callback hook NL_CB_SEND_ACK exists which is called if the
   1161 message has the NLM_F_ACK flag set. Although I am not aware of any
   1162 userspace netlink socket doing this, the application may want to send
   1163 an ACK message back to the sender (see <<core_msg_ack>>).
   1164 
   1165 [source,c]
   1166 --------
   1167         parse()
   1168           |
   1169           v
   1170       nlmsg_ok() --> Ignore
   1171           |
   1172           |- - - - - - - - - - - - - - - v
   1173           |                         NL_CB_MSG_IN()
   1174           |<- - - - - - - - - - - - - - -+
   1175           |
   1176           |- - - - - - - - - - - - - - - v
   1177      Sequence Check                NL_CB_SEQ_CHECK()
   1178           |<- - - - - - - - - - - - - - -+
   1179           |
   1180           |              Message has NLM_F_ACK set
   1181           |- - - - - - - - - - - - - - - v 
   1182           |                      NL_CB_SEND_ACK()
   1183           |<- - - - - - - - - - - - - - -+
   1184           |
   1185  Handle Message Type
   1186 --------
   1187 
   1188 [[core_auto_ack]]
   1189 === Auto-ACK Mode
   1190 
   1191 TODO
   1192 
   1193 == Message Parsing & Construction
   1194 
   1195 === Message Format
   1196 
   1197 See <<core_netlink_fundamentals>> for an introduction to the netlink
   1198 protocol and its message format.
   1199 
   1200 .Alignment
   1201 
   1202 Most netlink protocols enforce a strict alignment policy for all
   1203 boundries.  The alignment value is defined by NLMSG_ALIGNTO and is
   1204 fixed to 4 bytes.  Therefore all netlink message headers, begin of
   1205 payload sections, protocol specific headers, and attribute sections
   1206 must start at an offset which is a multiple of NLMSG_ALIGNTO.
   1207 
   1208 [source,c]
   1209 --------
   1210 #include <netlink/msg.h>
   1211 
   1212 int nlmsg_size(int payloadlen);
   1213 int nlmsg_total_size(int payloadlen);
   1214 --------
   1215 
   1216 The library provides a set of function to handle alignment
   1217 requirements automatically. The function nlmsg_total_size() returns
   1218 the total size of a netlink message including the padding to ensure
   1219 the next message header is aligned correctly.
   1220 
   1221 [source,c]
   1222 --------
   1223      <----------- nlmsg_total_size(len) ------------>
   1224      <----------- nlmsg_size(len) ------------>
   1225     +-------------------+- - -+- - - - - - - - +- - -+-------------------+- - -
   1226     |  struct nlmsghdr  | Pad |     Payload    | Pad |  struct nlsmghdr  |
   1227     +-------------------+- - -+- - - - - - - - +- - -+-------------------+- - -
   1228      <---- NLMSG_HDRLEN -----> <- NLMSG_ALIGN(len) -> <---- NLMSG_HDRLEN ---
   1229 --------
   1230 
   1231 If you need to know if padding needs to be added at the end of a
   1232 message, nlmsg_padlen() returns the number of padding bytes that need
   1233 to be added for a specific payload length.
   1234 
   1235 [source,c]
   1236 --------
   1237 #include <netlink/msg.h>
   1238 int nlmsg_padlen(int payloadlen);
   1239 --------
   1240 
   1241 === Parsing a Message
   1242 
   1243 The library offers two different methods of parsing netlink messages.
   1244 It offers a low level interface for applications which want to do all
   1245 the parsing manually. This method is described below. Alternatively
   1246 the library also offers an interface to implement a parser as part of
   1247 a cache operations set which is especially useful when your protocol
   1248 deals with objects of any sort such as network links, routes, etc.
   1249 This high level interface is described in <<core_cache>>.
   1250 
   1251 .Splitting a byte stream into separate messages
   1252 
   1253 What you receive from a netlink socket is typically a stream of
   1254 messages. You will be given a buffer and its length, the buffer may
   1255 contain any number of netlink messages.
   1256 
   1257 The first message header starts at the beginning of message stream.
   1258 Any subsequent message headers are access by calling nlmsg_next() on
   1259 the previous header.
   1260 
   1261 [source,c]
   1262 --------
   1263 #include <netlink/msg.h>
   1264 
   1265 struct nlmsghdr *nlmsg_next(struct nlmsghdr *hdr, int *remaining);
   1266 --------
   1267 
   1268 The function nlmsg_next() will automatically substract the size of the
   1269 previous message from the remaining number of bytes.
   1270 
   1271 Please note, there is no indication in the previous message whether
   1272 another message follows or not. You must assume that more messages
   1273 follow until all bytes of the message stream have been processed.
   1274 
   1275 To simplify this, the function nlmsg_ok() exists which returns true if
   1276 another message fits into the remaining number of bytes in the message
   1277 stream. nlmsg_valid_hdr() is similar, it checks whether a specific
   1278 netlink message contains at least a minimum of payload.
   1279 
   1280 [source,c]
   1281 --------
   1282 #include <netlink/msg.h>
   1283 
   1284 int nlmsg_valid_hdr(const struct nlmsghdr *hdr, int payloadlen);
   1285 int nlmsg_ok(const struct nlmsghdr *hdr, int remaining);
   1286 --------
   1287 
   1288 A typical use of these functions looks like this:
   1289 
   1290 [source,c]
   1291 --------
   1292 #include <netlink/msg.h>
   1293 
   1294 void my_parse(void *stream, int length)
   1295 {
   1296 	struct nlmsghdr *hdr = stream;
   1297 
   1298 	while (nlmsg_ok(hdr, length)) {
   1299 		// Parse message here
   1300 		hdr = nlmsg_next(hdr, &length);
   1301 	}
   1302 }
   1303 --------
   1304 
   1305 CAUTION: nlmsg_ok() only returns true if the *complete* message including
   1306          the message payload fits into the remaining buffer length. It will
   1307 	 return false if only a part of it fits.
   1308 
   1309 The above can also be written using the iterator nlmsg_for_each():
   1310 
   1311 [source,c]
   1312 --------
   1313 #include <netlink/msg.h>
   1314 
   1315 struct nlmsghdr *hdr;
   1316 
   1317 nlmsg_for_each(hdr, stream, length) {
   1318 	/* do something with message */
   1319 }
   1320 --------
   1321 
   1322 .Message Payload
   1323 
   1324 The message payload is appended to the message header and is guranteed
   1325 to start at a multiple of +NLMSG_ALIGNTO+. Padding at the end of the
   1326 message header is added if necessary to ensure this. The function
   1327 nlmsg_data() will calculate the necessary offset based on the message
   1328 and returns a pointer to the start of the message payload.
   1329 
   1330 [source,c]
   1331 --------
   1332 #include <netlink/msg.h>
   1333 
   1334 void *nlmsg_data(const struct nlmsghdr *nlh);
   1335 void *nlmsg_tail(const struct nlmsghdr *nlh);
   1336 int nlmsg_datalen(const struct nlmsghdr *nlh);
   1337 --------
   1338 
   1339 The length of the message payload is returned by nlmsg_datalen().
   1340 
   1341 [source,c]
   1342 --------
   1343                                <--- nlmsg_datalen(nlh) --->
   1344     +-------------------+- - -+----------------------------+- - -+
   1345     |  struct nlmsghdr  | Pad |           Payload          | Pad |
   1346     +-------------------+- - -+----------------------------+- - -+
   1347 nlmsg_data(nlh) ---------------^                                  ^
   1348 nlmsg_tail(nlh) --------------------------------------------------^
   1349 --------
   1350 
   1351 The payload may consist of arbitary data but may have strict alignment
   1352 and formatting rules depening on the actual netlink protocol.
   1353 
   1354 [[core_msg_attr]]
   1355 .Message Attributes
   1356 
   1357 Most netlink protocols use netlink attributes. It not only makes the
   1358 protocol self documenting but also gives flexibility in expanding the
   1359 protocol at a later point. New attributes can be added at any time and
   1360 older attributes can be obsoleted by newer ones without breaking
   1361 binary compatibility of the protocol.
   1362 
   1363 [source,c]
   1364 --------
   1365                                <---------------------- payload ------------------------->
   1366                                <----- hdrlen ---->       <- nlmsg_attrlen(nlh, hdrlen) ->
   1367     +-------------------+- - -+-----  ------------+- - -+--------------------------------+- - -+
   1368     |  struct nlmsghdr  | Pad |  Protocol Header  | Pad |           Attributes           | Pad |
   1369     +-------------------+- - -+-------------------+- - -+--------------------------------+- - -+
   1370 nlmsg_attrdata(nlh, hdrlen) -----------------------------^
   1371 --------
   1372 
   1373 The function nlmsg_attrdata() returns a pointer to the begin of the
   1374 attributes section. The length of the attributes section is returned
   1375 by the function nlmsg_attrlen().
   1376 
   1377 [source,c]
   1378 --------
   1379 #include <netlink/msg.h>
   1380 
   1381 struct nlattr *nlmsg_attrdata(const struct nlmsghdr *hdr, int hdrlen);
   1382 int nlmsg_attrlen(const struct nlmsghdr *hdr, int hdrlen);
   1383 --------
   1384 
   1385 See <<core_attr>> for more information on how to use netlink attributes.
   1386 
   1387 .Parsing a Message the Easy Way
   1388 
   1389 The function nlmsg_parse() validate a complete netlink message in one
   1390 step. If +hdrlen > 0+ it will first call nlmsg_valid_hdr() to check
   1391 if the protocol header fits into the message. If there is more payload
   1392 to parse, it will assume it to be attributes and parse the payload
   1393 accordingly. The function behaves exactly like nla_parse() when
   1394 parsing attributes, see <<core_attr_parse_easy>>.
   1395 
   1396 [source,c]
   1397 --------
   1398 int nlmsg_parse(struct nlmsghdr *hdr, int hdrlen, struct nlattr **attrs,
   1399                 int maxtype, struct nla_policy *policy);
   1400 --------
   1401 
   1402 The function nlmsg_validate() is based on nla_validate() and behaves
   1403 exactly the same as nlmsg_parse() except that it only validates and
   1404 will not fill a array with pointers to each attribute.
   1405 
   1406 [source,c]
   1407 --------
   1408 int nlmsg_validate(struct nlmsghdr *hdr, int hdrlen, intmaxtype,
   1409                    struct nla_policy *policy);
   1410 --------
   1411 
   1412 See <<core_attr_parse_easy>> for an example and more information on
   1413 attribute parsing.
   1414 
   1415 === Construction of a Message
   1416 
   1417 See <<core_msg_format>> for information on the netlink message format
   1418 and alignment requirements.
   1419 
   1420 Message construction is based on struct nl_msg which uses an internal
   1421 buffer to store the actual netlink message. struct nl_msg +does not+
   1422 point to the netlink message header. Use nlmsg_hdr() to retrieve a
   1423 pointer to the netlink message header.
   1424 
   1425 At allocation time, a maximum message size is specified. It defaults
   1426 to a page (PAGE_SIZE). The application constructing the message will
   1427 reserve space out of this maximum message size repeatedly for each
   1428 header or attribute added. This allows construction of messages across
   1429 various layers of code where lower layers do not need to know about
   1430 the space requirements of upper layers.
   1431 
   1432 +Why is setting the maximum message size necessary?+ This
   1433 question is often raised in combination with the proposed solution of
   1434 reallocating the message payload buffer on the fly using realloc().
   1435 While it is possible to reallocate the buffer during construction
   1436 using nlmsg_expand() it will make all pointers into the message buffer
   1437 become stale. This breaks usage of nlmsg_hdr(), nla_nest_start(), and
   1438 nla_nest_end() and is therefore not acceptable as default behaviour.
   1439 
   1440 .Allocating struct nl_msg
   1441 
   1442 The first step in constructing a new netlink message it to allocate a
   1443 `struct nl_msg` to hold the message header and payload. Several
   1444 functions exist to simplify various tasks.
   1445 
   1446 [source,c]
   1447 --------
   1448 #include <netlink/msg.h>
   1449 
   1450 struct nl_msg *nlmsg_alloc(void);
   1451 void nlmsg_free(struct nl_msg *msg);
   1452 --------
   1453 
   1454 The function nlmsg_alloc() is the default message allocation function.
   1455 It allocates a new message using the default maximum message size which
   1456 equals to one page (PAGE_SIZE). The application can change the default
   1457 size for messages by calling nlmsg_set_default_size():
   1458 
   1459 [source,c]
   1460 --------
   1461 void	  nlmsg_set_default_size(size_t);
   1462 --------
   1463 
   1464 CAUTION: Calling nlmsg_set_default_size() does not change the maximum
   1465          message size of already allocated messages.
   1466 
   1467 [source,c]
   1468 --------
   1469 struct nl_msg *nlmsg_alloc_size(size_t max);
   1470 --------
   1471 
   1472 Instead of changing the default message size, the function
   1473 nlmsg_alloc_size() can be used to allocate a message with a individual
   1474 maximum message size.
   1475 
   1476 
   1477 If the netlink message header is already known at allocation time, the
   1478 application may sue nlmsg_inherit(). It will allocate a message using
   1479 the default maximum message size and copy the header into the message.
   1480 Calling nlmsg_inherit with +set+ to NULL is equivalent to calling
   1481 nlmsg_alloc().
   1482 
   1483 [source,c]
   1484 --------
   1485 struct nl_msg *nlmsg_inherit(struct nlmsghdr *hdr);
   1486 --------
   1487 
   1488 Alternatively nlmsg_alloc_simple() takes a netlink message type and
   1489 netlink message flags. It is equivalent to nlmsg_inherit() except that it
   1490 takes the two common header fields as arguments instead of a complete
   1491 header.
   1492 
   1493 [source,c]
   1494 --------
   1495 #include <netlink/msg.h>
   1496 
   1497 struct nl_msg *nlmsg_alloc_simple(int nlmsg_type, int flags);
   1498 --------
   1499 
   1500 .Appending the netlink message header
   1501 
   1502 After allocating struct nl_msg, the netlink message header needs to be
   1503 added unless one of the function nlmsg_alloc_simple() or nlmsg_inherit()
   1504 have been used for allocation in which case this step will replace the
   1505 netlink message header already in place.
   1506 
   1507 [source,c]
   1508 --------
   1509 #include <netlink/msg.h>
   1510 
   1511 struct nlmsghdr *nlmsg_put(struct nl_msg *msg, uint32_t port, uint32_t seqnr,
   1512                            int nlmsg_type, int payload, int nlmsg_flags);
   1513 --------
   1514 
   1515 The function nlmsg_put() will build a netlink message header out of
   1516 +nlmsg_type+, +nlmsg_flags+, +seqnr+, and +port+ and copy it into the
   1517 netlink message. +seqnr+ can be set to +NL_AUTO_SEQ+ to indiciate
   1518 that the next possible sequence number should be used automatically.
   1519 To use this feature, the message must be sent using the function
   1520 nl_send_auto(). Like +port+, the argument +seqnr+ can be set to
   1521 +NL_AUTO_PORT+ indicating that the local port assigned to the socket
   1522 should be used as source port. This is generally a good idea unless
   1523 you are replying to a request. See <<core_netlink_fundamentals>>
   1524 for more information on how to fill the header.
   1525 
   1526 NOTE: The argument +payload+ can be used by the application to reserve
   1527       room for additional data after the header. A value of > 0 is
   1528       equivalent to calling +nlmsg_reserve(msg, payload, NLMSG_ALIGNTO)+.
   1529       See <<core_msg_reserve>> for more information on reserving room for
   1530       data.
   1531 
   1532 .Example
   1533 [source,c]
   1534 --------
   1535 #include <netlink/msg.h>
   1536 
   1537 struct nlmsghdr *hdr;
   1538 struct nl_msg *msg;
   1539 struct myhdr {
   1540 	uint32_t foo1, foo2;
   1541 } hdr = { 10, 20 };
   1542 
   1543 /* Allocate a message with the default maximum message size */
   1544 msg = nlmsg_alloc();
   1545 
   1546 /*
   1547  * Add header with message type MY_MSGTYPE, the flag NLM_F_CREATE,
   1548  * let library fill port and sequence number, and reserve room for
   1549  * struct myhdr
   1550  */
   1551 hdr = nlmsg_put(msg, NL_AUTO_PORT, NL_AUTO_SEQ, MY_MSGTYPE, sizeof(hdr), NLM_F_CREATE);
   1552 
   1553 /* Copy own header into newly reserved payload section */
   1554 memcpy(nlmsg_data(hdr), &hdr, sizeof(hdr));
   1555 
   1556 /*
   1557  * The message will now look like this:
   1558  *     +-------------------+- - -+----------------+- - -+
   1559  *     |  struct nlmsghdr  | Pad |  struct myhdr  | Pad |
   1560  *     +-------------------+-----+----------------+- - -+
   1561  * nlh -^                        /                \
   1562  *                              +--------+---------+
   1563  *                              |  foo1  |  foo2   |
   1564  *                              +--------+---------+
   1565  */
   1566 --------
   1567 
   1568 [[core_msg_reserve]]
   1569 .Reserving room at the end of the message
   1570 
   1571 Most functions described later on will automatically take care of
   1572 reserving room for the data that is added to the end of the netlink
   1573 message. In some situations it may be requried for the application
   1574 to reserve room directly though.
   1575 
   1576 [source,c]
   1577 --------
   1578 #include <netlink/msg.h>
   1579 
   1580 void *nlmsg_reserve(struct nl_msg *msg, size_t len, int pad);
   1581 --------
   1582 
   1583 The function nlmsg_reserve() reserves +len+ bytes at the end of the
   1584 netlink message and returns a pointer to the start of the reserved area.
   1585 The +pad+ argument can be used to request +len+ to be aligned to any
   1586 number of bytes prior to reservation.
   1587 
   1588 The following example requests to reserve a 17 bytes area at the end of
   1589 message aligned to 4 bytes. Therefore a total of 20 bytes will be
   1590 reserved.
   1591 
   1592 [source,c]
   1593 --------
   1594 #include <netlink/msg.h>
   1595 
   1596 void *buf = nlmsg_reserve(msg, 17, 4);
   1597 --------
   1598 
   1599 NOTE: `nlmsg_reserve()` will *not* align the start of the buffer. Any
   1600       alignment requirements must be provided by the owner of the
   1601       previous message section.
   1602 
   1603 .Appending data at the end of the message
   1604 
   1605 The function `nlmsg_append()` appends `len` bytes at the end of the
   1606 message, padding it if requested and necessary.
   1607 
   1608 [source,c]
   1609 --------
   1610 #include <netlink/msg.h>
   1611 
   1612 int nlmsg_append(struct nl_msg *msg, void *data, size_t len, int pad);
   1613 --------
   1614 
   1615 It is equivalent to calling `nlmsg_reserve()` and `memcpy()`ing the
   1616 data into the freshly reserved data section.
   1617 
   1618 NOTE: `nlmsg_append()` will *not* align the start of the data. Any
   1619       alignment requirements must be provided by the owner of the
   1620       previous message section.
   1621 
   1622 .Adding attribtues to a message
   1623 
   1624 Construction of attributes and addition of attribtues to the message is
   1625 covereted in section <<core_attr>>.
   1626 
   1627 [[core_attr]]
   1628 == Attributes
   1629 
   1630 Any form of payload should be encoded as netlink attributes whenever
   1631 possible. Use of attributes allows to extend any netlink protocol in
   1632 the future without breaking binary compatibility. F.e. Suppose your
   1633 device may currently be using 32 bit counters for statistics but years
   1634 later the device switches to maintaining 64 bit counters to account
   1635 for faster network hardware. If your protocol is using attributes the
   1636 move to 64 bit counters is trivial and only involves in sending an
   1637 additional attribute containing the 64 bit variants while still
   1638 providing the old legacy 32 bit counters. If your protocol is not using
   1639 attributes you will not be able to switch data types without breaking
   1640 all existing users of the protocol. 
   1641 
   1642 The concept of nested attributes also allows for subsystems of your
   1643 protocol to implement and maintain their own attribute schemas. Suppose
   1644 a new generation of network device is introduced which requires a
   1645 completely new set of configuration settings which was unthinkable when
   1646 the netlink protocol was initially designed. Using attributes the new
   1647 generation of devices may define a new attribute and fill it with its
   1648 own new structure of attributes which extend or even obsolete the old
   1649 attributes.
   1650 
   1651 Therefore, _always_ use attributes even if you are almost certain that
   1652 the message format will never ever change in the future.
   1653 
   1654 [[core_attr_format]]
   1655 === Attribute Format
   1656 
   1657 Netlink attributes allow for any number of data chunks of arbitary
   1658 length to be attached to a netlink message. See <<core_msg_attr>>
   1659 for more information on where attributes are stored in the message.
   1660 
   1661 The format of the attributes data returned by nlmsg_attrdata() is as
   1662 follows:
   1663 
   1664 [source,c]
   1665 --------
   1666      <----------- nla_total_size(payload) ----------->
   1667      <---------- nla_size(payload) ----------->
   1668     +-----------------+- - -+- - - - - - - - - +- - -+-----------------+- - -
   1669     |  struct nlattr  | Pad |     Payload      | Pad |  struct nlattr  |
   1670     +-----------------+- - -+- - - - - - - - - +- - -+-----------------+- - -
   1671      <---- NLA_HDRLEN -----> <--- NLA_ALIGN(len) ---> <---- NLA_HDRLEN ---
   1672 --------
   1673 
   1674 Every attribute must start at an offset which is a multiple of
   1675 +NLA_ALIGNTO+ (4 bytes). If you need to know whether an attribute needs
   1676 to be padded at the end, the function nla_padlen() returns the number
   1677 of padding bytes that will or need to be added.
   1678 
   1679 image:attribute_hdr.png["Netlink Attribute Header"]
   1680 
   1681 Every attribute is encoded with a type and length field, both 16 bits,
   1682 stored in the attribute header (struct nlattr) preceding the attribute
   1683 payload. The length of an attribute is used to calculate the offset to
   1684 the next attribute.
   1685 
   1686 [[core_attr_parse]]
   1687 === Parsing Attributes
   1688 
   1689 [[core_attr_parse_split]]
   1690 .Splitting an Attributes Stream into Attributes
   1691 
   1692 Although most applications will use one of the functions from the
   1693 nlmsg_parse() family (See <<core_attr_parse_easy>>) an interface exists
   1694 to split the attributes stream manually.
   1695 
   1696 As described in <<core_attr_format>> the attributes section contains a
   1697 infinite sequence or stream of attributes. The pointer returned by
   1698 nlmsg_attrdata() (See <<core_msg_attr>>) points to the first attribute
   1699 header. Any subsequent attribute is accessed with the function nla_next()
   1700 based on the previous header.
   1701 
   1702 [source,c]
   1703 --------
   1704 #include <netlink/attr.h>
   1705 
   1706 struct nlattr *nla_next(const struct nlattr *attr, int *remaining);
   1707 --------
   1708 
   1709 The semantics are equivalent to nlmsg_next() and thus nla_next() will also
   1710 subtract the size of the previous attribute from the remaining number of
   1711 bytes in the attributes stream.
   1712 
   1713 Like messages, attributes do not contain an indicator whether another
   1714 attribute follows or not. The only indication is the number of bytes left
   1715 in the attribute stream. The function nla_ok() exists to determine whether
   1716 another attribute fits into the remaining number of bytes or not.
   1717 
   1718 [source,c]
   1719 --------
   1720 #include <netlink/attr.h>
   1721 
   1722 int nla_ok(const struct nlattr *attr, int remaining);
   1723 --------
   1724 
   1725 A typical use of nla_ok() and nla_next() looks like this:
   1726 
   1727 .nla_ok()/nla_next() usage
   1728 [source,c]
   1729 --------
   1730 #include <netlink/msg.h>
   1731 #include <netlink/attr.h>
   1732 
   1733 struct nlattr *hdr = nlmsg_attrdata(msg, 0);
   1734 int remaining = nlmsg_attrlen(msg, 0);
   1735 
   1736 while (nla_ok(hdr, remaining)) {
   1737 	/* parse attribute here */
   1738 	hdr = nla_next(hdr, &remaining);
   1739 };
   1740 --------
   1741 
   1742 NOTE: `nla_ok()` only returns true if the *complete* attributes
   1743       including the attribute payload fits into the remaining number
   1744       of bytes.
   1745 
   1746 .Accessing Attribute Header and Payload
   1747 
   1748 Once the individual attributes have been sorted out by either splitting
   1749 the attributes stream or using another interface the attribute header
   1750 and payload can be accessed.
   1751 
   1752 [source,c]
   1753 --------
   1754                              <- nla_len(hdr) ->
   1755     +-----------------+- - -+- - - - - - - - - +- - -+
   1756     |  struct nlattr  | Pad |     Payload      | Pad |
   1757     +-----------------+- - -+- - - - - - - - - +- - -+
   1758 nla_data(hdr) ---------------^
   1759 --------
   1760 
   1761 The functions nla_len() and nla_type() can be used to access the attribute
   1762 header. nla_len() will return the length of the payload not including
   1763 eventual padding bytes. nla_type returns the attribute type.
   1764 
   1765 [source,c]
   1766 --------
   1767 #include <netlink/attr.h>
   1768 
   1769 int nla_len(const struct nlattr *hdr);
   1770 int nla_type(const struct nlattr *hdr);
   1771 --------
   1772 
   1773 The function nla_data() will return a pointer to the attribute
   1774 payload. Please note that due to +NLA_ALIGNTO+ being 4 bytes it may
   1775 not be safe to cast and dereference the pointer for any datatype
   1776 larger than 32 bit depending on the architecture the application is
   1777 run on.
   1778 
   1779 [source,c]
   1780 --------
   1781 #include <netlink/attr.h>
   1782 
   1783 void *nla_data(const struct nlattr *hdr);
   1784 --------
   1785 
   1786 [NOTE]
   1787 Never rely on the size of a payload being what you expect it to be.
   1788 _Always_ verify the payload size and make sure that it matches your
   1789 expectations. See <<core_attr_validation>>
   1790 
   1791 [[core_attr_validation]]
   1792 .Attribute Validation
   1793 
   1794 When receiving netlink attributes, the receiver has certain expections
   1795 on how the attributes should look like. These expectations must be
   1796 defined to make sure the sending side meets our expecations. For this
   1797 purpose, a attribute validation interface exists which must be used
   1798 prior to accessing any payload.
   1799 
   1800 All functions providing attribute validation functionality are based
   1801 on struct nla_policy:
   1802 
   1803 [source,c]
   1804 --------
   1805 struct nla_policy {
   1806 	uint16_t	type;
   1807 	uint16_t	minlen;
   1808 	uint16_t	maxlen;
   1809 };
   1810 --------
   1811 
   1812 The +type+ member specifies the datatype of the attribute, e.g.
   1813 +NLA_U32+, +NLA_STRING+, +NLA_FLAG+. The default is +NLA_UNSPEC+. The
   1814 +minlen+ member defines the minmum payload length of an attribute to
   1815 be considered a valid attribute. The value for +minlen+ is implicit
   1816 for most basic datatypes such as integers or flags. The +maxlen+
   1817 member can be used to define a maximum payload length for an
   1818 attribute to still be considered valid.
   1819 
   1820 NOTE: Specyfing a maximum payload length is not recommended when
   1821       encoding structures in an attribute as it will prevent any
   1822       extension of the structure in the future. Something that is
   1823       frequently done in netlink protocols and does not break
   1824       backwards compatibility.
   1825 
   1826 One of the functions which use struct nla_policy is nla_validate().
   1827 The function expects an array of struct nla_policy and will access the
   1828 array using the attribute type as index. If an attribute type is out
   1829 of bounds the attribute is assumed to be valid. This is intentional
   1830 behaviour to allow older applications not yet aware of recently
   1831 introduced attributes to continue functioning.
   1832 
   1833 [source,c]
   1834 --------
   1835 #include <netlink/attr.h>
   1836 
   1837 int nla_validate(struct nlattr *head, int len, int maxtype, struct nla_policy *policy);
   1838 --------
   1839 
   1840 The function nla_validate() returns 0 if all attributes are valid,
   1841 otherwise a validation failure specific error code is returned.
   1842 
   1843 Most applications will rarely use nla_validate() directly but use
   1844 nla_parse() instead which takes care of validation in the same way but
   1845 also parses the the attributes in the same step. See
   1846 <<core_attr_parse_easy>> for an example and more information.
   1847 
   1848 The validation process in detail:
   1849 
   1850 . If attribute type is 0 or exceeds +maxtype+ attribute is 
   1851   considered valid, 0 is returned.
   1852 . If payload length is < +minlen+, +-NLE_ERANGE+ is returned.
   1853 . If +maxlen+ is defined and payload exceeds it, +-NLE_ERANGE+
   1854   is returned.
   1855 . Datatype specific requirements rules, see <<core_attr_types>>
   1856 . If all is ok, 0 is returned.
   1857 
   1858 [[core_attr_parse_easy]]
   1859 .Parsing Attributes the Easy Way
   1860 
   1861 Most applications will not want to deal with splitting attribute
   1862 streams themselves as described in <<core_attr_parse_split>>
   1863 A much easier method is to use nla_parse().
   1864 
   1865 [source,c]
   1866 --------
   1867 #include <netlink/attr.h>
   1868 
   1869 int nla_parse(struct nlattr **attrs, int maxtype, struct nlattr *head,
   1870               int len, struct nla_policy *policy);
   1871 --------
   1872 
   1873 The function nla_parse() will iterate over a stream of attributes,
   1874 validate each attribute as described in <<core_attr_validation>>
   1875 If the validation of all attributes succeeds, a pointer to each attribute
   1876 is stored in the +attrs+ array at `attrs[nla_type(attr)]`.
   1877 
   1878 As an alernative to nla_parse() the function nlmsg_parse() can be used
   1879 to parse the message and its attributes in one step. See
   1880 <<core_attr_parse_easy>> for information on how to use these functions.
   1881 
   1882 .Example:
   1883 
   1884 The following example demonstrates how to parse a netlink message sent
   1885 over a netlink protocol which does not use protocol headers. The example
   1886 does enforce a attribute policy however, the attribute MY_ATTR_FOO must
   1887 be a 32 bit integer, and the attribute MY_ATTR_BAR must be a string with
   1888 a maximum length of 16 characters.
   1889 
   1890 [source,c]
   1891 ---------
   1892 #include <netlink/msg.h>
   1893 #include <netlink/attr.h>
   1894 
   1895 enum {
   1896 	MY_ATTR_FOO = 1,
   1897 	MY_ATTR_BAR,
   1898 	__MY_ATTR_MAX,
   1899 };
   1900 
   1901 #define MY_ATTR_MAX (__MY_ATTR_MAX - 1)
   1902 
   1903 static struct nla_policy my_policy[MY_ATTR_MAX+1] = {
   1904 	[MY_ATTR_FOO] = { .type = NLA_U32 },
   1905 	[MY_ATTR_BAR] = { .type = NLA_STRING,
   1906 			  .maxlen = 16 },
   1907 };
   1908 
   1909 void parse_msg(struct nlmsghdr *nlh)
   1910 {
   1911 	struct nlattr *attrs[MY_ATTR_MAX+1];
   1912 
   1913 	if (nlmsg_parse(nlh, 0, attrs, MY_ATTR_MAX, my_policy) < 0)
   1914 		/* error */
   1915 
   1916 	if (attrs[MY_ATTR_FOO]) {
   1917 		/* MY_ATTR_FOO is present in message */
   1918 		printf("value: %u\n", nla_get_u32(attrs[MY_ATTR_FOO]));
   1919 	}
   1920 }
   1921 ---------
   1922 
   1923 .Locating a Single Attribute
   1924 
   1925 An application only interested in a single attribute can use one of the
   1926 functions nla_find() or  nlmsg_find_attr(). These function will iterate
   1927 over all attributes, search for a matching attribute and return a pointer
   1928 to the corresponding attribute header.
   1929 
   1930 [source,c]
   1931 --------
   1932 #include <netlink/attr.h>
   1933 
   1934 struct nlattr *nla_find(struct nlattr *head, int len, int attrtype);
   1935 --------
   1936 
   1937 [source,c]
   1938 --------
   1939 #include <netlink/msg.h>
   1940 
   1941 struct nlattr *nlmsg_find_attr(struct nlmsghdr *hdr, int hdrlen, int attrtype);
   1942 --------
   1943 
   1944 NOTE: `nla_find()` and `nlmsg_find_attr()` will *not* search in nested
   1945       attributes recursively, see <<core_attr_nested>>.
   1946 
   1947 ==== Iterating over a Stream of Attributes
   1948 
   1949 In some situations it does not make sense to assign a unique attribute
   1950 type to each attribute in the attribute stream. For example a list may
   1951 be transferd using a stream of attributes and even if the attribute type
   1952 is incremented for each attribute it may not make sense to use the
   1953 nlmsg_parse() or nla_parse() function to fill an array.
   1954 
   1955 Therefore methods exist to iterate over a stream of attributes:
   1956 
   1957 [source,c]
   1958 --------
   1959 #include <netlink/attr.h>
   1960 
   1961 nla_for_each_attr(attr, head, len, remaining)
   1962 --------
   1963 
   1964 nla_for_each_attr() is a macro which can be used in front of a code
   1965 block:
   1966 
   1967 [source,c]
   1968 --------
   1969 #include <netlink/attr.h>
   1970 
   1971 struct nalttr *nla;
   1972 int rem;
   1973 
   1974 nla_for_each_attr(nla, attrstream, streamlen, rem) {
   1975 	/* validate & parse attribute */
   1976 }
   1977 
   1978 if (rem > 0)
   1979 	/* unparsed attribute data */
   1980 --------
   1981 
   1982 [[core_attr_constr]]
   1983 === Attribute Construction
   1984 
   1985 The interface to add attributes to a netlink message is based on the
   1986 regular message construction interface. It assumes that the message
   1987 header and an eventual protocol header has been added to the message
   1988 already.
   1989 
   1990 [source,c]
   1991 --------
   1992 struct nlattr *nla_reserve(struct nl_msg *msg, int attrtype, int len);
   1993 --------
   1994 
   1995 The function nla_reserve() adds an attribute header at the end of the
   1996 message and reserves room for +len+ bytes of payload. The function
   1997 returns a pointer to the attribute payload section inside the message.
   1998 Padding is added at the end of the attribute to ensure the next
   1999 attribute is properly aligned.
   2000 
   2001 [source,c]
   2002 --------
   2003 int nla_put(struct nl_msg *msg, int attrtype, int attrlen, const void *data);
   2004 --------
   2005 
   2006 The function nla_put() is base don nla_reserve() but takes an additional
   2007 pointer +data+ pointing to a buffer containing the attribute payload.
   2008 It will copy the buffer into the message automatically.
   2009 
   2010 .Example:
   2011 
   2012 [source,c]
   2013 --------
   2014 struct my_attr_struct {
   2015 	uint32_t a;
   2016 	uint32_t b;
   2017 };
   2018 
   2019 int my_put(struct nl_msg *msg)
   2020 {
   2021 	struct my_attr_struct obj = {
   2022 		.a = 10,
   2023 		.b = 20,
   2024 	};
   2025 
   2026 	return nla_put(msg, ATTR_MY_STRUCT, sizeof(obj), &obj);
   2027 }
   2028 --------
   2029 
   2030 See <<core_attr_types>> for datatype specific attribute construction
   2031 functions.
   2032 
   2033 .Exception Based Attribute Construction
   2034 
   2035 Like in the kernel API an exception based construction interface is
   2036 provided. The behaviour of the macros is identical to their regular
   2037 function counterparts except that in case of an error, the target
   2038 `nla_put_failure` is jumped.
   2039 
   2040 .Example:
   2041 [source,c]
   2042 --------
   2043 #include <netlink/msg.h>
   2044 #include <netlink/attr.h>
   2045 
   2046 void construct_attrs(struct nl_msg *msg)
   2047 {
   2048 	NLA_PUT_STRING(msg, MY_ATTR_FOO1, "some text");
   2049 	NLA_PUT_U32(msg, MY_ATTR_FOO1, 0x1010);
   2050 	NLA_PUT_FLAG(msg, MY_ATTR_FOO3, 1);
   2051 
   2052 	return 0;
   2053 
   2054 nla_put_failure:
   2055 	/* NLA_PUT* macros jump here in case of an error */
   2056 	return -EMSGSIZE;
   2057 }
   2058 --------
   2059 
   2060 See <<core_attr_types>> for more information on the datatype specific
   2061 exception based variants.
   2062 
   2063 [[core_attr_types]]
   2064 === Attribute Data Types
   2065 
   2066 A number of basic data types have been defined to simplify access and
   2067 validation of attributes. The datatype is not encoded in the
   2068 attribute, therefore bthe sender and receiver are required to use the
   2069 same definition on what attribute is of what type.
   2070 
   2071 [options="header", cols="1m,5"]
   2072 |================================================
   2073 | Type             | Description
   2074 | NLA_UNSPEC       | Unspecified attribute
   2075 | NLA_U{8\|16\|32} | Integers
   2076 | NLA_STRING       | String
   2077 | NLA_FLAG         | Flag
   2078 | NLA_NESTED       | Nested attribute
   2079 |================================================
   2080 
   2081 Besides simplified access to the payload of such datatypes, the major
   2082 advantage is the automatic validation of each attribute based on a
   2083 policy. The validation ensures safe access to the payload by checking
   2084 for minimal payload size and can also be used to enforce maximum
   2085 payload size for some datatypes.
   2086 
   2087 ==== Integer Attributes
   2088 
   2089 The most frequently used datatypes are integers. Integers come in four
   2090 different sizes:
   2091 [horizontal]
   2092 NLA_U8::  8bit integer
   2093 NLA_U16:: 16bit integer
   2094 NLA_U32:: 32bit integer
   2095 NLA_U64:: 64bit integer
   2096 
   2097 Note that due to the alignment requirements of attributes the integer
   2098 attribtue +NLA_u8+ and +NLA_U16+ will not result in space savings in
   2099 the netlink message. Their use is intended to limit the range of
   2100 values.
   2101 
   2102 .Parsing Integer Attributes
   2103 
   2104 [source,c]
   2105 --------
   2106 #include <netlink/attr.h>
   2107 
   2108 uint8_t  nla_get_u8(struct nlattr *hdr);
   2109 uint16_t nla_get_u16(struct nlattr *hdr);
   2110 uint32_t nla_get_u32(struct nlattr *hdr);
   2111 uint64_t nla_get_u64(struct nlattr *hdr);
   2112 --------
   2113 
   2114 Example:
   2115 
   2116 [source,c]
   2117 --------
   2118 if (attrs[MY_ATTR_FOO])
   2119 	uint32_t val = nla_get_u32(attrs[MY_ATTR_FOO]);
   2120 --------
   2121 
   2122 .Constructing Integer Attributes
   2123 
   2124 [source,c]
   2125 --------
   2126 #include <netlink/attr.h>
   2127 
   2128 int nla_put_u8(struct nl_msg *msg, int attrtype, uint8_t value);
   2129 int nla_put_u16(struct nl_msg *msg, int attrtype, uint16_t value);
   2130 int nla_put_u32(struct nl_msg *msg, int attrtype, uint32_t value);
   2131 int nla_put_u64(struct nl_msg *msg, int attrtype, uint64_t value);
   2132 --------
   2133 
   2134 Exception based:
   2135 
   2136 [source,c]
   2137 --------
   2138 NLA_PUT_U8(msg, attrtype, value)
   2139 NLA_PUT_U16(msg, attrtype, value)
   2140 NLA_PUT_U32(msg, attrtype, value)
   2141 NLA_PUT_U64(msg, attrtype, value)
   2142 --------
   2143 
   2144 .Validation
   2145 
   2146 Use +NLA_U8+, +NLA_U16+, +NLA_U32+, or +NLA_U64+ to define the type of
   2147 integer when filling out a struct nla_policy array. It will
   2148 automatically enforce the correct minimum payload length policy.
   2149 
   2150 Validation does not differ between signed and unsigned integers, only
   2151 the size matters. If the appliaction wishes to enforce particular value
   2152 ranges it must do so itself.
   2153 
   2154 [source,c]
   2155 --------
   2156 static struct nla_policy my_policy[ATTR_MAX+1] = {
   2157 	[ATTR_FOO] = { .type = NLA_U32 },
   2158 	[ATTR_BAR] = { .type = NLA_U8 },
   2159 };
   2160 --------
   2161 
   2162 The above is equivalent to:
   2163 [source,c]
   2164 --------
   2165 static struct nla_policy my_policy[ATTR_MAX+1] = {
   2166 	[ATTR_FOO] = { .minlen = sizeof(uint32_t) },
   2167 	[ATTR_BAR] = { .minlen = sizeof(uint8_t) },
   2168 };
   2169 --------
   2170 
   2171 ==== String Attributes
   2172 
   2173 The string datatype represents a NUL termianted character string of
   2174 variable length. It is not intended for binary data streams.
   2175 
   2176 The payload of string attributes can be accessed with the function
   2177 nla_get_string(). nla_strdup() calls strdup() on the payload and returns
   2178 the newly allocated string.
   2179 
   2180 [source,c]
   2181 --------
   2182 #include <netlink/attr.h>
   2183 
   2184 char *nla_get_string(struct nlattr *hdr);
   2185 char *nla_strdup(struct nlattr *hdr);
   2186 --------
   2187 
   2188 String attributes are constructed with the function +nla_put_string()+
   2189 respectively +NLA_PUT_STRING()+. The length of the payload will be
   2190 strlen()+1, the trailing NUL byte is included.
   2191 
   2192 [source,c]
   2193 --------
   2194 int nla_put_string(struct nl_msg *msg, int attrtype, const char *data);
   2195 
   2196 NLA_PUT_STRING(msg, attrtype, data)
   2197 --------
   2198 
   2199 For validation purposes the type +NLA_STRING+ can be used in
   2200 +struct nla_policy+ definitions. It implies a minimum payload length
   2201 of 1 byte and checks for a trailing NUL byte. Optionally the +maxlen+
   2202 member defines the maximum length of a character string (including the
   2203 trailing NUL byte).
   2204 
   2205 [source,c]
   2206 --------
   2207 static struct nla_policy my_policy[] = {
   2208 	[ATTR_FOO] = { .type = NLA_STRING,
   2209 		       .maxlen = IFNAMSIZ },
   2210 };
   2211 --------
   2212 
   2213 ==== Flag Attributes
   2214 
   2215 The flag attribute represents a boolean datatype. The presence of the
   2216 attribute implies a value of +true+, the absence of the attribute
   2217 implies the value +false+. Therefore the payload length of flag
   2218 attributes is always 0.
   2219 
   2220 [source,c]
   2221 --------
   2222 int nla_get_flag(struct nlattr *hdr);
   2223 int nla_put_flag(struct nl_msg *msg, int attrtype);
   2224 --------
   2225 
   2226 The type +NLA_FLAG+ is used for validation purposes. It implies a 
   2227 +maxlen+ value of 0 and thus enforces a maximum payload length of 0.
   2228 
   2229 .Example:
   2230 [source,c]
   2231 --------
   2232 /* nla_put_flag() appends a zero sized attribute to the message. */
   2233 nla_put_flag(msg, ATTR_FLAG);
   2234 
   2235 /* There is no need for a receival function, the presence is the value. */
   2236 if (attrs[ATTR_FLAG])
   2237 	/* flag is present */
   2238 --------
   2239 
   2240 [[core_attr_nested]]
   2241 ==== Nested Attributes
   2242 
   2243 As described in <<core_attr>>, attributes can be nested allowing for
   2244 complex tree structures of attributes. It is commonly used to delegate
   2245 the responsibility of a subsection of the message to a subsystem.
   2246 Nested attributes are also commonly used for transmitting list of objects.
   2247 
   2248 When nesting attributes, the nested attributes are included as payload
   2249 of a container attribute.
   2250 
   2251 NOTE: When validating the attributes using nlmsg_validate(),
   2252       nlmsg_parse(), nla_validate(), or nla_parse() only the
   2253       attributes on the first level are being validated. None of these
   2254       functions will validate attributes recursively. Therefore you
   2255       must explicitely call nla_validate() or use nla_parse_nested()
   2256       for each level of nested attributes.
   2257 
   2258 The type +NLA_NESTED+ should be used when defining nested attributes
   2259 in a struct nla_policy definition. It will not enforce any minimum
   2260 payload length unless +minlen+ is specified explicitely. This is
   2261 because some netlink protocols implicitely allow empty container
   2262 attributes.
   2263 
   2264 [source,c]
   2265 --------
   2266 static struct nla_policy my_policy[] = {
   2267 	[ATTR_OPTS] = { .type = NLA_NESTED },
   2268 };
   2269 --------
   2270 
   2271 .Parsing of Nested Attributes
   2272 
   2273 The function nla_parse_nested() is used to parse nested attributes.
   2274 Its behaviour is identical to nla_parse() except that it takes a
   2275 struct nlattr as argument and will use the payload as stream of
   2276 attributes.
   2277 
   2278 [source,c]
   2279 --------
   2280 if (attrs[ATTR_OPTS]) {
   2281 	struct nlattr *nested[NESTED_MAX+1];
   2282 	struct nla_policy nested_policy[] = {
   2283 		[NESTED_FOO] = { .type = NLA_U32 },
   2284 	};
   2285 
   2286 	if (nla_parse_nested(nested, NESTED_MAX, attrs[ATTR_OPTS], nested_policy) < 0)
   2287 		/* error */
   2288 	
   2289 	if (nested[NESTED_FOO])
   2290 		uint32_t val = nla_get_u32(nested[NESTED_FOO]);
   2291 }
   2292 --------
   2293 
   2294 .Construction of Nested Attributes
   2295 
   2296 Attributes are nested by surrounding them with calls to nla_nest_start()
   2297 and nla_nest_end(). nla_nest_start() will add a attribute header to
   2298 the message but no actual payload. All data added to the message from
   2299 this point on will be part of the container attribute until nla_nest_end()
   2300 is called which "closes" the attribute, correcting its payload length to
   2301 include all data length.
   2302 
   2303 [source,c]
   2304 --------
   2305 int put_opts(struct nl_msg *msg)
   2306 {
   2307 	struct nlattr *opts;
   2308 
   2309 	if (!(opts = nla_nest_start(msg, ATTR_OPTS)))
   2310 		goto nla_put_failure;
   2311 
   2312 	NLA_PUT_U32(msg, NESTED_FOO, 123);
   2313 	NLA_PUT_STRING(msg, NESTED_BAR, "some text");
   2314 
   2315 	nla_nest_end(msg, opts);
   2316 	return 0;
   2317 
   2318 nla_put_failure:
   2319 	nla_nest_cancel(msg, opts);
   2320 	return -EMSGSIZE;
   2321 }
   2322 --------
   2323 
   2324 ==== Unspecified Attribute
   2325 
   2326 This is the default attribute type and used when none of the basic
   2327 datatypes is suitable. It represents data of arbitary type and length.
   2328 
   2329 See <<core_addr_alloc, Address Allocation>> for a more information on
   2330 a special interface allowing the allocation of abstract address object
   2331 based on netlink attributes which carry some form of network address.
   2332 
   2333 See <<core_data_alloc, Abstract Data Allocation>> for more information
   2334 on how to allocate abstract data objects based on netlink attributes.
   2335 
   2336 Use the function nla_get() and nla_put() to access the payload and
   2337 construct attributes. See <<core_attr_constr, Attribute Construction>>
   2338 for an example.
   2339 
   2340 === Examples
   2341 
   2342 ==== Constructing a Netlink Message with Attributes
   2343 
   2344 [source,c]
   2345 --------
   2346 struct nl_msg *build_msg(int ifindex, struct nl_addr *lladdr, int mtu)
   2347 {
   2348 	struct nl_msg *msg;
   2349 	struct nlattr *info, *vlan;
   2350 	struct ifinfomsg ifi = {
   2351 		.ifi_family = AF_INET,
   2352 		.ifi_index = ifindex,
   2353 	};
   2354 
   2355 	/* Allocate a default sized netlink message */
   2356 	if (!(msg = nlmsg_alloc_simple(RTM_SETLINK, 0)))
   2357 		return NULL;
   2358 
   2359 	/* Append the protocol specific header (struct ifinfomsg)*/
   2360 	if (nlmsg_append(msg, &ifi, sizeof(ifi), NLMSG_ALIGNTO) < 0)
   2361 		goto nla_put_failure
   2362 
   2363 	/* Append a 32 bit integer attribute to carry the MTU */
   2364 	NLA_PUT_U32(msg, IFLA_MTU, mtu);
   2365 
   2366 	/* Append a unspecific attribute to carry the link layer address */
   2367 	NLA_PUT_ADDR(msg, IFLA_ADDRESS, lladdr);
   2368 
   2369 	/* Append a container for nested attributes to carry link information */
   2370 	if (!(info = nla_nest_start(msg, IFLA_LINKINFO)))
   2371 		goto nla_put_failure;
   2372 
   2373 	/* Put a string attribute into the container */
   2374 	NLA_PUT_STRING(msg, IFLA_INFO_KIND, "vlan");
   2375 
   2376 	/*
   2377 	 * Append another container inside the open container to carry
   2378 	 * vlan specific attributes
   2379 	 */
   2380 	if (!(vlan = nla_nest_start(msg, IFLA_INFO_DATA)))
   2381 		goto nla_put_failure;
   2382 
   2383 	/* add vlan specific info attributes here... */
   2384 
   2385 	/* Finish nesting the vlan attributes and close the second container. */
   2386 	nla_nest_end(msg, vlan);
   2387 
   2388 	/* Finish nesting the link info attribute and close the first container. */
   2389 	nla_nest_end(msg, info);
   2390 
   2391 	return msg;
   2392 
   2393 nla_put_failure:
   2394 	nlmsg_free(msg);
   2395 	return NULL;
   2396 }
   2397 ------
   2398 
   2399 ==== Parsing a Netlink Message with Attributes
   2400 
   2401 [source,c]
   2402 --------
   2403 int parse_message(struct nlmsghdr *hdr)
   2404 {
   2405 	/*
   2406 	 * The policy defines two attributes: a 32 bit integer and a container
   2407 	 * for nested attributes.
   2408 	 */
   2409 	struct nla_policy attr_policy[] = {
   2410 		[ATTR_FOO] = { .type = NLA_U32 },
   2411 		[ATTR_BAR] = { .type = NLA_NESTED },
   2412 	};
   2413 	struct nlattr *attrs[ATTR_MAX+1];
   2414 	int err;
   2415 
   2416 	/*
   2417 	 * The nlmsg_parse() function will make sure that the message contains
   2418 	 * enough payload to hold the header (struct my_hdr), validates any
   2419 	 * attributes attached to the messages and stores a pointer to each
   2420 	 * attribute in the attrs[] array accessable by attribute type.
   2421 	 */
   2422 	if ((err = nlmsg_parse(hdr, sizeof(struct my_hdr), attrs, ATTR_MAX,
   2423 			       attr_policy)) < 0)
   2424 		goto errout;
   2425 
   2426 	if (attrs[ATTR_FOO]) {
   2427 		/*
   2428 		 * It is safe to directly access the attribute payload without
   2429 		 * any further checks since nlmsg_parse() enforced the policy.
   2430 		 */
   2431 		uint32_t foo = nla_get_u32(attrs[ATTR_FOO]);
   2432 	}
   2433 
   2434 	if (attrs[ATTR_BAR]) {
   2435 		struct *nested[NESTED_MAX+1];
   2436 
   2437 		/*
   2438 		 * Attributes nested in a container can be parsed the same way
   2439 		 * as top level attributes.
   2440 		 */
   2441 		err = nla_parse_nested(nested, NESTED_MAX, attrs[ATTR_BAR],
   2442                 		       nested_policy);
   2443 		if (err < 0)
   2444 			goto errout;
   2445 
   2446 		// Process nested attributes here.
   2447 	}
   2448 
   2449 	err = 0;
   2450 errout:
   2451 	return err;
   2452 }
   2453 --------
   2454 
   2455 [[core_cb]]
   2456 == Callback Configurations
   2457 
   2458 Callback hooks and overwriting capabilities are provided in various places
   2459 inside library to control the behaviour of several functions. All the
   2460 callback and overwrite functions are packed together in struct nl_cb which
   2461 is attached to a netlink socket or passed on to functions directly.
   2462 
   2463 === Callback Hooks
   2464 
   2465 Callback hooks are spread across the library to provide entry points for
   2466 message processing and to take action upon certain events.
   2467 
   2468 Callback functions may return the following return codes:
   2469 [options="header", cols="1m,4"]
   2470 |========================================================================
   2471 | Return Code      | Description
   2472 | NL_OK            | Proceed.
   2473 | NL_SKIP          | Skip message currently being processed and continue
   2474                      parsing the receive buffer.
   2475 | NL_STOP          | Stop parsing and discard all remaining data in the
   2476                     receive buffer.
   2477 |========================================================================
   2478 
   2479 .Default Callback Implementations
   2480 
   2481 The library provides three sets of default callback implementations:
   2482 * +NL_CB_DEFAULT+ This is the default set. It implets the default behaviour.
   2483      See the table below for more information on the return codes of each
   2484      function.
   2485 * +NL_CB_VERBOSE+ This set is based on the default set but will cause an
   2486      error message to be printed to stderr for error messages, invalid
   2487      messages, message overruns and unhandled valid messages. The
   2488      +arg+ pointer in nl_cb_set() and nl_cb_err() can be used to
   2489      provide a FILE * which overwrites stderr.
   2490 * +NL_CB_DEBUG+ This set is intended for debugging purposes. It is
   2491   based on the verbose set but will decode and dump each message sent
   2492   or received to the console.
   2493 
   2494 .Message Processing Callbacks
   2495 
   2496 .nl_sendmsg() callback hooks:
   2497 [cols="2m,4e,1m", options="header"]
   2498 |============================================================================
   2499 | Callback ID        | Description                       | Default Return Value
   2500 | NL_CB_MSG_OUT      | Each message sent                 | NL_OK
   2501 |============================================================================
   2502 
   2503 Any function called by NL_CB_MSG_OUT may return a negative error code to
   2504 prevent the message from being sent and the error code being returned.
   2505 
   2506 nl_recvmsgs() callback hooks (ordered by priority):
   2507 [cols="2m,4e,1m", options="header"]
   2508 |============================================================================
   2509 | Callback ID        | Description                       | Default Return Value
   2510 | NL_CB_MSG_IN       | Each message received             | NL_OK
   2511 | NL_CB_SEQ_CHECK    | May overwrite sequence check algo | NL_OK
   2512 | NL_CB_INVALID      | Invalid messages                  | NL_STOP
   2513 | NL_CB_SEND_ACK     | Messages with NLM_F_ACK flag set  | NL_OK
   2514 | NL_CB_FINISH       | Messages of type NLMSG_DONE       | NL_STOP
   2515 | NL_CB_SKIPPED      | Messages of type NLMSG_NOOP       | NL_SKIP
   2516 | NL_CB_OVERRUN      | Messages of type NLMSG_OVERRUN    | NL_STOP
   2517 | NL_CB_ACK          | ACK Messages                      | NL_STOP
   2518 | NL_CB_VALID        | Each valid message                | NL_OK
   2519 |============================================================================
   2520 
   2521 Any of these functions may return NL_OK, NL_SKIP, or NL_STOP.
   2522 
   2523 Message processing callback functions are set with nl_cb_set():
   2524 [source,c]
   2525 --------
   2526 #include <netlink/handlers.h>
   2527 
   2528 int nl_cb_set(struct nl_cb *cb, enum nl_cb_type type, enum nl_cb_kind kind,
   2529               nl_recvmsg_msg_cb_t func, void *arg);
   2530 
   2531 typedef int (*nl_recvmsg_msg_cb_t)(struct nl_msg *msg, void *arg);
   2532 --------
   2533 
   2534 .Callback for Error Messages
   2535 
   2536 A special function prototype is used for the error message callback hook:
   2537 
   2538 [source,c]
   2539 --------
   2540 #include <netlink/handlers.h>
   2541 
   2542 int nl_cb_err(struct nl_cb *cb, enum nl_cb_kind kind, nl_recvmsg_err_cb_t func, void *arg);
   2543 
   2544 typedef int(* nl_recvmsg_err_cb_t)(struct sockaddr_nl *nla, struct nlmsgerr *nlerr, void *arg);
   2545 --------
   2546 
   2547 .Example: Setting up a callback set
   2548 [source,c]
   2549 --------
   2550 #include <netlink/handlers.h>
   2551 
   2552 /* Allocate a callback set and initialize it to the verbose default set */
   2553 struct nl_cb *cb = nl_cb_alloc(NL_CB_VERBOSE);
   2554 
   2555 /* Modify the set to call my_func() for all valid messages */
   2556 nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, my_func, NULL);
   2557 
   2558 /*
   2559  * Set the error message handler to the verbose default implementation
   2560  * and direct it to print all errors to the given file descriptor.
   2561  */
   2562 FILE *file = fopen(...);
   2563 nl_cb_err(cb, NL_CB_VERBOSE, NULL, file);
   2564 --------
   2565 
   2566 === Overwriting of Internal Functions
   2567 
   2568 When the library needs to send or receive netlink messages in high level
   2569 interfaces it does so by calling its own low level API. In the case the
   2570 default characteristics are not sufficient for the application, it may
   2571 overwrite several internal function calls with own implementations.
   2572 
   2573 .Overwriting recvmsgs()
   2574 
   2575 See <<core_recv, Receiving Netlink Messages>> for more information on
   2576 how and when recvmsgs() is called internally.
   2577 
   2578 [source,c]
   2579 --------
   2580 #include <netlink/handlers.h>
   2581 
   2582 void nl_cb_overwrite_recvmsgs(struct nl_cb *cb,
   2583                               int (*func)(struct nl_sock *sk, struct nl_cb *cb));
   2584 --------
   2585 
   2586 The following criteras must be met if a recvmsgs() implementation is
   2587 supposed to work with high level interfaces:
   2588 
   2589 - MUST respect the callback configuration +cb+, therefore:
   2590   - MUST call +NL_CB_VALID+ for all valid messages, passing on 
   2591   - MUST call +NL_CB_ACK+ for all ACK messages
   2592   - MUST correctly handle multipart messages, calling NL_CB_VALID for
   2593     each message until a NLMSG_DONE message is received.
   2594 - MUST report error code if a NLMSG_ERROR or NLMSG_OVERRUN mesasge is
   2595   received.
   2596 
   2597 .Overwriting nl_recv()
   2598 
   2599 Often it is sufficient to overwrite `nl_recv()` which is responsible
   2600 from receiving the actual data from the socket instead of replacing
   2601 the complete `recvmsgs()` logic.
   2602 
   2603 See <<core_recv_character, Receive Characteristics>> for more
   2604 information on how and when `nl_recv()` is called internally.
   2605 
   2606 [source,c]
   2607 --------
   2608 #include <netlink/handlers.h>
   2609 
   2610 void nl_cb_overwrite_recv(struct nl_cb *cb,
   2611                           int (*func)(struct nl_sock * sk,
   2612                                       struct sockaddr_nl *addr,
   2613                                       unsigned char **buf,
   2614                                       struct ucred **cred));
   2615 --------
   2616 
   2617 The following criteras must be met for an own `nl_recv()`
   2618 implementation:
   2619 
   2620  - *MUST* return the number of bytes read or a negative error code if
   2621    an error occured. The function may also return 0 to indicate that
   2622    no data has been read.
   2623  - *MUST* set `*buf` to a buffer containing the data read. It must be
   2624    safe for the caller to access the number of bytes read returned as
   2625    return code.
   2626  - *MAY* fill out `*addr` with the netlink address of the peer the
   2627    data has been received from.
   2628  - *MAY* set `*cred` to a newly allocated struct ucred containg
   2629    credentials.
   2630 
   2631 .Overwriting nl_send()
   2632 
   2633 See <<core_send, Sending Netlink Messages>> for more information on
   2634 how and when nl_send() is called internally.
   2635 
   2636 [source,c]
   2637 --------
   2638 #include <netlink/handlers.h>
   2639 
   2640 void nl_cb_overwrite_send(struct nl_cb *cb, int (*func)(struct nl_sock *sk,
   2641                                                         struct nl_msg *msg));
   2642 --------
   2643 
   2644 Own implementations must send the netlink message and return 0 on success
   2645 or a negative error code.
   2646 
   2647 [[core_cache]]
   2648 == Cache System
   2649 
   2650 === Allocation of Caches
   2651 
   2652 Almost all subsystem provide a function to allocate a new cache
   2653 of some form. The function usually looks like this:
   2654 [source,c]
   2655 --------
   2656 struct nl_cache *<object name>_alloc_cache(struct nl_sock *sk);
   2657 --------
   2658 
   2659 These functions allocate a new cache for the own object type,
   2660 initializes it properly and updates it to represent the current
   2661 state of their master, e.g. a link cache would include all
   2662 links currently configured in the kernel.
   2663 
   2664 Some of the allocation functions may take additional arguments
   2665 to further specify what will be part of the cache.
   2666 
   2667 All such functions return a newly allocated cache or NULL
   2668 in case of an error.
   2669 
   2670 === Cache Manager
   2671 
   2672 The purpose of a cache manager is to keep track of caches and
   2673 automatically receive event notifications to keep the caches
   2674 up to date with the kernel state. Each manager has exactly one
   2675 netlink socket assigned which limits the scope of each manager
   2676 to exactly one netlink family. Therefore all caches committed
   2677 to a manager must be part of the same netlink family. Due to the
   2678 nature of a manager, it is not possible to have a cache maintain
   2679 two instances of the same cache type. The socket is subscribed
   2680 to the event notification group of each cache and also put into
   2681 non-blocking mode. Functions exist to poll() on the socket to
   2682 wait for new events to be received.
   2683 
   2684 
   2685 ----
   2686  App       libnl                        Kernel
   2687         |                            |
   2688             +-----------------+        [ notification, link change ]
   2689         |   |  Cache Manager  |      | [   (IFF_UP | IFF_RUNNING)  ]
   2690             |                 |                |
   2691         |   |   +------------+|      |         |  [ notification, new addr ]
   2692     <-------|---| route/link |<-------(async)--+  [  10.0.1.1/32 dev eth1  ]
   2693         |   |   +------------+|      |                      |
   2694             |   +------------+|                             |
   2695     <---|---|---| route/addr |<------|-(async)--------------+
   2696             |   +------------+|
   2697         |   |   +------------+|      |
   2698     <-------|---| ...        ||
   2699         |   |   +------------+|      |
   2700             +-----------------+
   2701         |                            |
   2702 ----
   2703 
   2704 .Creating a new cache manager
   2705 
   2706 [source,c]
   2707 ----
   2708 struct nl_cache_mngr *mngr;
   2709 
   2710 // Allocate a new cache manager for RTNETLINK and automatically
   2711 // provide the caches added to the manager.
   2712 err = nl_cache_mngr_alloc(NULL, NETLINK_ROUTE, NL_AUTO_PROVIDE, &mngr);
   2713 ----
   2714 
   2715 .Keep track of a cache
   2716 
   2717 [source,c]
   2718 ----
   2719 struct nl_cache *cache;
   2720 
   2721 // Create a new cache for links/interfaces and ask the manager to
   2722 // keep it up to date for us. This will trigger a full dump request
   2723 // to initially fill the cache.
   2724 cache = nl_cache_mngr_add(mngr, "route/link");
   2725 -----
   2726 
   2727 .Make the manager receive updates
   2728 
   2729 [source,c]
   2730 ----
   2731 // Give the manager the ability to receive updates, will call poll()
   2732 // with a timeout of 5 seconds.
   2733 if (nl_cache_mngr_poll(mngr, 5000) > 0) {
   2734         // Manager received at least one update, dump cache?
   2735         nl_cache_dump(cache, ...);
   2736 }
   2737 ----
   2738 
   2739 .Release cache manager
   2740 
   2741 [source,c]
   2742 ----
   2743 nl_cache_mngr_free(mngr);
   2744 ----
   2745 
   2746 == Abstract Data Types
   2747 
   2748 A few high level abstract data types which are used by a majority netlink
   2749 protocols are implemented in the core library. More may be added in the
   2750 future if the need arises.
   2751 
   2752 === Abstract Address
   2753 
   2754 Most netlink protocols deal with networking related topics and thus
   2755 dealing with network addresses is a common task.
   2756 
   2757 Currently the following address families are supported:
   2758 
   2759 [options="compact"]
   2760  * `AF_INET`
   2761  * `AF_INET6`
   2762  * `AF_LLC`
   2763  * `AF_DECnet`
   2764  * `AF_UNSPEC`
   2765 
   2766 [[core_addr_alloc]]
   2767 .Address Allocation
   2768 
   2769 The function nl_addr_alloc() allocates a new empty address. The
   2770 +maxsize+ argument defines the maximum length of an address in bytes.
   2771 The size of an address is address family specific. If the address
   2772 family and address data are known at allocation time the function
   2773 nl_addr_build() can be used alternatively. You may also clone
   2774 an address by calling nl_addr_clone()
   2775 
   2776 [source,c]
   2777 --------
   2778 #include <netlink/addr.h>
   2779 
   2780 struct nl_addr *nl_addr_alloc(size_t maxsize);
   2781 struct nl_addr *nl_addr_clone(struct nl_addr *addr);
   2782 struct nl_addr *nl_addr_build(int family, void *addr, size_t size);
   2783 --------
   2784 
   2785 If the address is transported in a netlink attribute, the function
   2786 nl_addr_alloc_attr() allocates a new address based on the payload
   2787 of the attribute provided. The +family+ argument is used to specify
   2788 the address family of the address, set to +AF_UNSPEC+ if unknown.
   2789 
   2790 [source,c]
   2791 --------
   2792 #include <netlink/addr.h>
   2793 
   2794 struct nl_addr *nl_addr_alloc_attr(struct nlattr *attr, int family);
   2795 --------
   2796 
   2797 If the address is provided by a user, it is usually stored in a human
   2798 readable format. The function nl_addr_parse() parses a character
   2799 string representing an address and allocates a new address based on
   2800 it.
   2801 
   2802 [source,c]
   2803 --------
   2804 #include <netlink/addr.h>
   2805 
   2806 int nl_addr_parse(const char *addr, int hint, struct nl_addr **result);
   2807 --------
   2808 
   2809 If parsing succeeds the function returns 0 and the allocated address
   2810 is stored in +*result+.
   2811 
   2812 NOTE: Make sure to return the reference to an address using
   2813       `nl_addr_put()` after usage to allow memory being freed.
   2814 
   2815 .Example: Transform character string to abstract address
   2816 [source,c]
   2817 -----
   2818 struct nl_addr *a = nl_addr_parse("::1", AF_UNSPEC);
   2819 printf("Address family: %s\n", nl_af2str(nl_addr_get_family(a)));
   2820 nl_addr_put(a);
   2821 a = nl_addr_parse("11:22:33:44:55:66", AF_UNSPEC);
   2822 printf("Address family: %s\n", nl_af2str(nl_addr_get_family(a)));
   2823 nl_addr_put(a);
   2824 -----
   2825 
   2826 .Address References
   2827 
   2828 Abstract addresses use reference counting to account for all users of
   2829 a particular address. After the last user has returned the reference
   2830 the address is freed.
   2831 
   2832 If you pass on a address object to another function and you are not
   2833 sure how long it will be used, make sure to call nl_addr_get() to
   2834 acquire an additional reference and have that function or code path
   2835 call nl_addr_put() as soon as it has finished using the address.
   2836 
   2837 [source,c]
   2838 --------
   2839 #include <netlink/addr.h>
   2840 
   2841 struct nl_addr *nl_addr_get(struct nl_addr *addr);
   2842 void nl_addr_put(struct nl_addr *addr);
   2843 int nl_addr_shared(struct nl_addr *addr);
   2844 --------
   2845 
   2846 You may call nl_addr_shared() at any time to check if you are the only
   2847 user of an address.
   2848 
   2849 .Address Attributes
   2850 
   2851 The address is usually set at allocation time. If it was unknown at that
   2852 time it can be specified later by calling nl_addr_set_family() and is
   2853 accessed with the function nl_addr_get_family().
   2854 
   2855 [source,c]
   2856 --------
   2857 #include <netlink/addr.h>
   2858 
   2859 void nl_addr_set_family(struct nl_addr *addr, int family);
   2860 int nl_addr_get_family(struct nl_addr *addr);
   2861 --------
   2862 
   2863 The same is true for the actual address data. It is typically present
   2864 at allocation time. For exceptions it can be specified later or
   2865 overwritten with the function `nl_addr_set_binary_addr()`. Beware that
   2866 the length of the address may not exceed `maxlen` specified at
   2867 allocation time. The address data is returned by the function
   2868 `nl_addr_get_binary_addr()` and its length by the function
   2869 `nl_addr_get_len()`.
   2870 
   2871 [source,c]
   2872 --------
   2873 #include <netlink/addr.h>
   2874 
   2875 int nl_addr_set_binary_addr(struct nl_addr *addr, void *data, size_t size);
   2876 void *nl_addr_get_binary_addr(struct nl_addr *addr);
   2877 unsigned int nl_addr_get_len(struct nl_addr *addr);
   2878 --------
   2879 
   2880 If you only want to check if the address data consists of all zeros
   2881 the function `nl_addr_iszero()` is a shortcut to that.
   2882 
   2883 [source,c]
   2884 --------
   2885 #include <netlink/addr.h>
   2886 
   2887 int nl_addr_iszero(struct nl_addr *addr);
   2888 --------
   2889 
   2890 ==== Address Prefix Length
   2891 
   2892 Although this functionality is somewhat specific to routing it has
   2893 been implemented here. Addresses can have a prefix length assigned
   2894 which implies that only the first n bits are of importance. This is
   2895 f.e. used to implement subnets.
   2896 
   2897 Use set functions `nl_addr_set_prefixlen()` and
   2898 `nl_addr_get_prefixlen()` to work with prefix lengths.
   2899 
   2900 [source,c]
   2901 --------
   2902 #include <netlink/addr.h>
   2903 
   2904 void nl_addr_set_prefixlen(struct nl_addr *addr, int n);
   2905 unsigned int nl_addr_get_prefixlen(struct nl_addr *addr);
   2906 --------
   2907 
   2908 NOTE: The default prefix length is set to (address length * 8)
   2909 
   2910 .Address Helpers
   2911 
   2912 Several functions exist to help when dealing with addresses. The
   2913 function `nl_addr_cmp()` compares two addresses and returns an integer
   2914 less than, equal to or greater than zero without considering the
   2915 prefix length at all. If you want to consider the prefix length, use
   2916 the function `nl_addr_cmp_prefix()`.
   2917 
   2918 [source,c]
   2919 --------
   2920 #include <netlink/addr.h>
   2921 
   2922 int nl_addr_cmp(struct nl_addr *addr, struct nl_addr *addr);
   2923 int nl_addr_cmp_prefix(struct nl_addr *addr, struct nl_addr *addr);
   2924 --------
   2925 
   2926 If an abstract address needs to presented to the user it should be
   2927 done in a human readable format which differs depending on the address
   2928 family. The function `nl_addr2str()` takes care of this by calling the
   2929 appropriate conversion functions internaly. It expects a `buf` of
   2930 length `size` to write the character string into and returns a pointer
   2931 to `buf` for easy `printf()` usage.
   2932 
   2933 [source,c]
   2934 --------
   2935 #include <netlink/addr.h>
   2936 
   2937 char *nl_addr2str(struct nl_addr *addr, char *buf, size_t size);
   2938 --------
   2939 
   2940 If the address family is unknown, the address data will be printed in
   2941 hexadecimal format `AA:BB:CC:DD:...`
   2942 
   2943 Often the only way to figure out the address family is by looking at
   2944 the length of the address. The function `nl_addr_guess_family()` does
   2945 just this and returns the address family guessed based on the address
   2946 size.
   2947 
   2948 [source,c]
   2949 --------
   2950 #include <netlink/addr.h>
   2951 
   2952 int nl_addr_guess_family(struct nl_addr *addr);
   2953 --------
   2954 
   2955 Before allocating an address you may want to check if the character
   2956 string actually represents a valid address of the address family you
   2957 are expecting. The function `nl_addr_valid()` can be used for that, it
   2958 returns 1 if the supplised `addr` is a valid address in the context of
   2959 `family`.  See `inet_pton(3)`, `dnet_pton(3)` for more information on
   2960 valid adddress formats.
   2961 
   2962 [source,c]
   2963 --------
   2964 #include <netlink/addr.h>
   2965 
   2966 int nl_addr_valid(char *addr, int family);
   2967 --------
   2968 
   2969 === Abstract Data
   2970 
   2971 The abstract data type is a trivial datatype with the primary purpose
   2972 to simplify usage of netlink attributes of arbitary length.
   2973 
   2974 [[core_data_alloc]]
   2975 .Allocation of a Data Object
   2976 The function `nl_data_alloc()` alloctes a new abstract data object and
   2977 fill it with the provided data. `nl_data_alloc_attr()` does the same
   2978 but bases the data on the payload of a netlink attribute. New data
   2979 objects can also be allocated by cloning existing ones by using
   2980 `nl_data_clone()`.
   2981 
   2982 [source,c]
   2983 --------
   2984 struct nl_data *nl_data_alloc(void *buf, size_t size);
   2985 struct nl_data *nl_data_alloc_attr(struct nlattr *attr);
   2986 struct nl_data *nl_data_clone(struct nl_data *data);
   2987 void nl_data_free(struct nl_data *data);
   2988 --------
   2989 
   2990 .Access to Data
   2991 
   2992 The function `nl_data_get()` returns a pointer to the data, the size
   2993 of data is returned by `nl_data_get_size()`.
   2994 
   2995 [source,c]
   2996 --------
   2997 void *nl_data_get(struct nl_data *data);
   2998 size_t nl_data_get_size(struct nl_data *data);
   2999 --------
   3000 
   3001 .Data Helpers
   3002 
   3003 The function nl_data_append() reallocates the internal data buffers
   3004 and appends the specified `buf` to the existing data.
   3005 
   3006 [source,c]
   3007 --------
   3008 int nl_data_append(struct nl_data *data, void *buf, size_t size);
   3009 --------
   3010 
   3011 CAUTION: Any call to `nl_data_append()` invalidates all pointers
   3012          returned by `nl_data_get()` of the same data object.
   3013 
   3014 [source,c]
   3015 --------
   3016 int nl_data_cmp(struct nl_data *data, struct nl_data *data);
   3017 --------
   3018