• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1////
2	vim.syntax: asciidoc
3
4	Copyright (c) 2011 Thomas Graf <tgraf@suug.ch>
5////
6
7Netlink Library (libnl)
8=======================
9Thomas Graf <tgraf@suug.ch>
103.2, May 9 2011:
11:numbered:
12
13== Introduction
14
15The core library contains the fundamentals required to communicate
16over netlink sockets. It deals with connecting and disconnectng of
17sockets, sending and receiving of data, construction and parsing of
18messages, provides a customizeable receiving state machine, and
19provides a abstract data type framework which eases the implementation
20of object based netlink protocols where objects are added, removed, or
21modified using a netlink based protocol.
22
23.Library Hierarchy
24
25The suite is split into multiple libraries:
26
27image:library_overview.png["Library Hierarchy"]
28
29link:core.html[Netlink Library] (libnl)::
30Socket handling, sending and receiving, message construction and parsing, ...
31
32link:route.html[Routing Family Library] (libnl-route)::
33Adresses, links, neighbours, routing, traffic control, neighbour tables, ...
34
35Netfilter Library (libnl-nf)::
36Connection tracking, logging, queueing
37
38Generic Netlink Library (libnl-genl)::
39Controller API, family and command registration
40
41
42=== How To Read This Documentation
43
44The libraries provide a broad set of APIs of which most applications only
45require a small subset of it. Depending on the type of application, some
46users may only be interested in the low level netlink messaging API while
47others wish to make heavy use of the high level API.
48
49In any case it is recommended to get familiar with the netlink protocol
50first.
51
52- <<core_netlink_fundamentals>>
53
54The 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
64Projects using autoconf may use +PKG_CHECK_MODULES()+ to check if
65a specific version of libnl is available on the system. The example
66below also shows how to retrieve the +CFLAGS+ and linking dependencies
67required to link against the library.
68
69The following example shows how to check for a specific version of libnl. If
70found, it extends the `CFLAGS` and `LIBS` variable appropriately:
71
72[source]
73----
74PKG_CHECK_MODULES(LIBNL3, libnl-3.0 >= 3.1, [have_libnl3=yes], [have_libnl3=no])
75if (test "${have_libnl3}" = "yes"); then
76	CFLAGS+="$LIBNL3_CFLAGS"
77	LIBS+="$LIBNL3_LIBS"
78fi
79----
80
81NOTE: 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
86The main header file is `<netlink/netlink.h>`. Additional headers may need to
87be included in your sources depending on the subsystems and components your
88program 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
99If your code wishes to be capable to link against multiple versions of libnl
100you may have direct the compiler to only include portions on the code depending
101on 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
119The library has been compiled with debugging statements enabled it will
120print debug information to +stderr+ if the environment variable +NLDBG+
121is 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
140It is often useful to peek into the stream of netlink messages exchanged
141with other sockets. Setting the environment variable +NLCB=debug+ will
142cause the debugging message handlers to be used which in turn print the
143netlink 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
188The netlink protocol is a socket based IPC mechanism used for
189communication between userspace processes and the kernel or between
190userspace processes themselves. The netlink protocol is based on BSD
191sockets and uses the +AF_NETLINK+ address family. Every netlink
192protocol uses its own protocol number (e.g. +NETLINK_ROUTE+,
193+NETLINK_NETFILTER+, etc). Its addressing schema is based on a 32 bit
194port number, formerly referred to as PID, which uniquely identifies
195each peer.
196
197[[core_addressing]]
198=== Addressing
199
200The netlink address (port) consists of a 32bit integer. Port 0 (zero)
201is reserved for the kernel and refers to the kernel side socket of each
202netlink protocol family. Other port numbers usually refer to user space
203owned sockets, although this is not enforced.
204
205NOTE: 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
214image:addressing.png["Addressing Example"]
215
216The above figure illustrates three applications and the kernel side
217exposing two kernel side sockets. It shows the common netlink use
218cases:
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
226The most common form of netlink usage is for a user space application
227to send requests to the kernel and process the reply which is either
228an error message or a success notification.
229
230["mscgen"]
231--------
232msc {
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
244Netlink may also be used as an IPC mechanism to communicate between user
245space applications directly. Communication is not limited to two peers,
246any number of peers may communicate with each other and multicasting
247capabilities allow to reach multiple peers with a single message.
248
249In order for the sockets to be visible to each other, both sockets must
250be created for the same netlink protocol family.
251
252["mscgen"]
253--------
254msc {
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
264This form of netlink communication is typically found in user space
265daemons that need to act on certain kernel events. Such daemons will
266typically maintain a netlink socket subscribed to a multicast group that
267is used by the kernel to notify interested user space parties about
268specific events.
269
270["mscgen"]
271--------
272msc {
273  Kernel,App3;
274  Kernel=>App3 [label="notification (src=0, group=foo)"];
275  ...;
276}
277--------
278
279Use of multicasting is preferred over direct addressing due to the
280flexibility in exchanging the user space component at any time without
281the kernel noticing.
282
283[[core_msg_format]]
284=== Message Format
285
286A netlink protocol is typically based on messages and consists of the
287netlink message header (+struct nlmsghdr+) plus the payload attached
288to it.  The payload can consist of arbitrary data but usually contains
289a fixed size protocol specific header followed by a stream of
290attributes.
291
292.Netlink message header (struct nlmsghdr)
293
294image:nlmsghdr.png[align="center", alt="Netlink Message Header"]
295
296Total Length (32bit)::
297Total length of the message in bytes including the netlink message header.
298
299Message Type (16bit)::
300The message type specifies the type of payload the message is carrying.
301Several standard message types are defined by the netlink protocol.
302Additional message types may be defined by each protocol family. See
303<<core_msg_types>> for additional information.
304
305Message Flags (16bit)::
306The message flags may be used to modify the behaviour of a message type.
307See section <<core_msg_flags>> for a list of standard message flags.
308
309Sequence Number (32bit)::
310The sequence number is optional and may be used to allow referring to
311a previous message, e.g. an error message can refer to the original
312request causing the error.
313
314Port Number (32bit)::
315The port number specifies the peer to which the message should be delivered
316to. If not specified, the message will be delivered to the first matching
317kernel side socket of the same protocol family.
318
319[[core_msg_types]]
320=== Message Types
321
322Netlink differs between requests, notifications, and replies. Requests
323are messages which have the +NLM_F_REQUEST+ flag set and are meant to
324request an action from the receiver. A request is typically sent from
325a userspace process to the kernel. While not strictly enforced, requests
326should carry a sequence number incremented for each request sent.
327
328Depending on the nature of the request, the receiver may reply to the
329request with another netlink message. The sequence number of a reply
330must match the sequence number of the request it relates to.
331
332Notifications are of informal nature and no reply is expected, therefore
333the sequence number is typically set to 0.
334
335["mscgen"]
336--------
337msc {
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
347The type of message is primarly identified by its 16 bit message type set
348in 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
356Every netlink protocol is free to define own message types. Note that
357message type values  +< NLMSG_MIN_TYPE (0x10)+ are reserved and may
358not be used.
359
360It is common practice to use own message types to implement RPC schemas.
361Suppose the goal of the netlink protocol you are implementing is allow
362configuration of a particular network device, therefore you want to
363provide 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
373Sending a +MSG_GETCFG+ request message will typically trigger a reply
374with the message type +MSG_SETCFG+ containing the current configuration.
375In object oriented terms one would describe this as "the kernel sets
376the local copy of the configuration in userspace".
377
378["mscgen"]
379--------
380msc {
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
387The configuration may be changed by sending a +MSG_SETCFG+ which will
388be responded to with either a ACK (see <<core_msg_ack>>)
389or a error message (see <<core_errmsg>>).
390
391["mscgen"]
392--------
393msc {
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
400Optionally, the kernel may send out notifications for configuration
401changes allowing userspace to listen for changes instead of polling
402frequently. Notifications typically reuse an existing message type
403and rely on the application using a separate socket to differ between
404requests and notifications but you may also specify a separate message
405type.
406
407["mscgen"]
408--------
409msc {
410  A,B;
411  A<=B [label="MSG_SETCFG (seq=0)"];
412}
413--------
414
415[[core_multipart]]
416==== Multipart Messages
417
418Although in theory a netlink message can be up to 4GiB in size. The socket
419buffers are very likely not large enough to hold message of such sizes.
420Therefore it is common to limit messages to one page size (PAGE_SIZE) and
421use the multipart mechanism to split large pieces of data into several
422messages.  A multipart message has the flag +NLM_F_MULTI+ set and the
423receiver is expected to continue receiving and parsing until the special
424message type +NLMSG_DONE+ is received.
425
426Multipart messages unlike fragmented ip packets must not be reassmbled
427even though it is perfectly legal to do so if the protocols wishes to
428work this way. Often multipart message are used to send lists or trees
429of objects were each multipart message simply carries multiple objects
430allow for each message to be parsed independently.
431
432["mscgen"]
433--------
434msc {
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
447Error messages can be sent in response to a request. Error messages must
448use the standard message type +NLMSG_ERROR+. The payload consists of a
449error code and the original netlink mesage header of the request.
450
451image:nlmsgerr.png["Netlink Errror Message header"]
452
453Error messages should set the sequence number to the sequence number
454of the request which caused the error.
455
456["mscgen"]
457--------
458msc {
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
468A sender can request an ACK message to be sent back for each request
469processed by setting the +NLM_F_ACK+ flag in the request. This is typically
470used to allow the sender to synchronize further processing until the
471request has been processed by the receiver.
472
473["mscgen"]
474--------
475msc {
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
482ACK messages also use the message type +NLMSG_ERROR+ and payload
483format but the error code is set to 0.
484
485[[core_msg_flags]]
486==== Message Flags
487
488The 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
503The flag +NLM_F_ECHO+ is similar to the `NLM_F_ACK` flag. It can be
504used in combination with `NLM_F_REQUEST` and causes a notification
505which is sent as a result of a request to also be sent to the sender
506regardless of whether the sender has subscribed to the corresponding
507multicast group or not. See <<core_multicast>>
508
509Additional 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
526Use of these flags is completely optional and many netlink protocols only
527make use of the `NLM_F_DUMP` flag which typically requests the receiver
528to send a list of all objects in the context of the message type as a
529sequence of multipart messages (see <<core_multipart>>).
530
531Another set of flags exist related to `NEW` or `SET` requests. These
532flags 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
547Behaviour of these flags may differ slightly between different netlink
548protocols.
549
550[[core_seq_num]]
551=== Sequence Numbers
552
553Netlink allows the use of sequence numbers to help relate replies to
554requests. It should be noted that unlike in protocols such as TCP
555there is no strict enforcment of the sequence number. The sole purpose
556of sequence numbers is to assist a sender in relating replies to the
557corresponding requests. See <<core_msg_types>> for more information.
558
559Sequence 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
565TODO
566
567See <<core_sk_multicast>>
568
569[[core_sockets]]
570== Netlink Sockets
571
572In order to use the netlink protocol, a netlink socket is required.
573Each socket defines an independent context for sending and receiving of
574messages. An application may make use multiple sockets, e.g. a socket to
575send requests and receive the replies and another socket subscribed to a
576multicast group to receive notifications.
577
578=== Socket structure (struct nl_sock)
579
580The netlink socket and all related attributes including the actual file
581descriptor are represented by +struct nl_sock+.
582
583[source,c]
584--------
585#include <netlink/socket.h>
586
587struct nl_sock *nl_socket_alloc(void)
588void nl_socket_free(struct nl_sock *sk)
589--------
590
591The application must allocate an instance of +struct nl_sock+ for each
592netlink socket it wishes to use.
593
594[[core_sk_seq_num]]
595=== Sequence Numbers
596
597The library will automatically take care of sequence number handling
598for the application. A sequence number counter is stored in the
599socket structure which is used and incremented automatically when a
600message needs to be sent which is expected to generate a reply such as
601an error or any other message type that needs to be related to the
602original message.
603
604Alternatively, the counter can be used directly via the function
605nl_socket_use_seq(). It will return the current value of the counter
606and increment it by one afterwards.
607
608[source,c]
609--------
610#include <netlink/socket.h>
611
612unsigned int nl_socket_use_seq(struct nl_sock *sk);
613--------
614
615Most applications will not want to deal with sequence number handling
616themselves though. When using nl_send_auto() the sequence number is
617filled in automatically and matched again when a reply is received. See
618section <<core_send_recv>> for more information.
619
620This behaviour can and must be disabled if the netlink protocol
621implemented does not use a request/reply model, e.g. when a socket is
622used to receive notification messages.
623
624[source,c]
625--------
626#include <netlink/socket.h>
627
628void nl_socket_disable_seq_check(struct nl_sock *sk);
629--------
630
631For more information on the theory behind netlink sequence numbers,
632see section <<core_seq_num>>.
633
634[[core_sk_multicast]]
635=== Multicast Group Subscriptions
636
637Each socket can subscribe to any number of multicast groups of the
638netlink protocol it is connected to. The socket will then receive a
639copy of each message sent to any of the groups. Multicast groups are
640commonly used to implement event notifications.
641
642Prior to kernel 2.6.14 the group subscription was performed using a
643bitmask which limited the number of groups per protocol family to 32.
644This outdated interface can still be accessed via the function
645nl_join_groups() even though it is not recommended for new code.
646
647[source,c]
648--------
649#include <netlink/socket.h>
650
651void nl_join_groups(struct nl_sock *sk, int bitmask);
652--------
653
654Starting with 2.6.14 a new method was introduced which supports subscribing
655to an almost infinite number of multicast groups.
656
657[source,c]
658--------
659#include <netlink/socket.h>
660
661int nl_socket_add_memberships(struct nl_sock *sk, int group, ...);
662int 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 */
677static int my_func(struct nl_msg *msg, void *arg)
678{
679	return 0;
680}
681
682struct nl_sock *sk;
683
684/* Allocate a new socket */
685sk = nl_socket_alloc();
686
687/*
688 * Notifications do not use sequence numbers, disable sequence number
689 * checking.
690 */
691nl_socket_disable_seq_check(sk);
692
693/*
694 * Define a callback function, which will be called for each notification
695 * received
696 */
697nl_socket_modify_cb(sk, NL_CB_VALID, NL_CB_CUSTOM, my_func, NULL);
698
699/* Connect to routing netlink protocol */
700nl_connect(sk, NETLINK_ROUTE);
701
702/* Subscribe to link notifications group */
703nl_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 */
710while (1)
711	nl_recvmsgs_default(sock);
712--------
713
714[[core_sk_cb]]
715=== Modifiying Socket Callback Configuration
716
717See <<core_cb>> for more information on
718callback hooks and overwriting capabilities.
719
720Each socket is assigned a callback configuration which controls the
721behaviour of the socket. This is f.e. required to have a separate
722message receive function per socket. It is perfectly legal to share
723callback configurations between sockets though.
724
725The following functions can be used to access and set the callback
726configuration of a socket:
727
728[source,c]
729--------
730#include <netlink/socket.h>
731
732struct nl_cb *nl_socket_get_cb(const struct nl_sock *sk);
733void nl_socket_set_cb(struct nl_sock *sk, struct nl_cb *cb);
734--------
735
736Additionaly a shortcut exists to modify the callback configuration
737assigned to a socket directly:
738
739[source,c]
740--------
741#include <netlink/socket.h>
742
743int 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
753nl_socket_modify_cb(sk, NL_CB_VALID, NL_CB_CUSTOM, my_input, NULL);
754--------
755
756=== Socket Attributes
757
758.Local Port
759
760The local port number uniquely identifies the socket and is used to
761address it. A unique local port is generated automatically when the
762socket is allocated. It will consist of the Process ID (22 bits) and a
763random number (10 bits) thus allowing up to 1024 sockets per process.
764
765[source,c]
766--------
767#include <netlink/socket.h>
768
769uint32_t nl_socket_get_local_port(const struct nl_sock *sk);
770void nl_socket_set_local_port(struct nl_sock *sk, uint32_t port);
771--------
772
773See section <<core_addressing>> for more information on port numbers.
774
775CAUTION: Overwriting the local port is possible but you have to ensure
776that the provided value is unique and no other socket in any other
777application is using the same value.
778
779.Peer Port
780
781A peer port can be assigned to the socket which will result in all
782unicast messages sent over the socket to be addresses to the peer. If
783no peer is specified, the message is sent to the kernel which will try
784to automatically bind the socket to a kernel side socket of the same
785netlink protocol family.  It is common practice not to bind the socket
786to a peer port as typically only one kernel side socket exists per
787netlink protocol family.
788
789[source,c]
790--------
791#include <netlink/socket.h>
792
793uint32_t nl_socket_get_peer_port(const struct nl_sock *sk);
794void nl_socket_set_peer_port(struct nl_sock *sk, uint32_t port);
795--------
796
797See section <<core_addressing>> for more information on port numbers.
798
799.File Descriptor
800
801Netlink uses the BSD socket interface, therefore a file descriptor is
802behind each socket and you may use it directly.
803
804[source,c]
805--------
806#include <netlink/socket.h>
807
808int nl_socket_get_fd(const struct nl_sock *sk);
809--------
810
811If a socket is used to only receive notifications it usually is best
812to put the socket in non-blocking mode and periodically poll for new
813notifications.
814
815[source,c]
816--------
817#include <netlink/socket.h>
818
819int nl_socket_set_nonblocking(const struct nl_sock *sk);
820--------
821
822.Send/Receive Buffer Size
823
824The socket buffer is used to queue netlink messages between sender and
825receiver. The size of these buffers specifies the maximum size you
826will be able to write() to a netlink socket, i.e. it will indirectly
827define the maximum message size. The default is 32KiB.
828
829[source,c]
830--------
831#include <netlink/socket.h>
832
833int nl_socket_set_buffer_size(struct nl_sock *sk, int rx, int tx);
834--------
835
836[[core_sk_cred]]
837.Enable/Disable Credentials
838
839TODO
840
841[source,c]
842--------
843#include <netlink/socket.h>
844
845int nl_socket_set_passcred(struct nl_sock *sk, int state);
846--------
847
848.Enable/Disable Auto-ACK Mode
849
850The following functions allow to enable/disable Auto-ACK mode on a socket.
851See <<core_auto_ack>> for more information on what implications that has.
852Auto-ACK mode is enabled by default.
853
854[source,c]
855--------
856#include <netlink/socket.h>
857
858void nl_socket_enable_auto_ack(struct nl_sock *sk);
859void nl_socket_disable_auto_ack(struct nl_sock *sk);
860--------
861
862.Enable/Disable Message Peeking
863
864If enabled, message peeking causes nl_recv() to try and use MSG_PEEK
865to retrieve the size of the next message received and allocate a
866buffer of that size. Message peeking is enabled by default but can be
867disabled using the following function:
868
869[source,c]
870--------
871#include <netlink/socket.h>
872
873void nl_socket_enable_msg_peek(struct nl_sock *sk);
874void nl_socket_disable_msg_peek(struct nl_sock *sk);
875--------
876
877.Enable/Disable Receival of Packet Information
878
879If enabled, each received netlink message from the kernel will include
880an additional struct nl_pktinfo in the control message. The following
881function can be used to enable/disable receival of packet information.
882
883[source,c]
884--------
885#include <netlink/socket.h>
886
887int nl_socket_recv_pktinfo(struct nl_sock *sk, int state);
888--------
889
890CAUTION: 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
898The standard method of sending a netlink message over a netlink socket
899is to use the function nl_send_auto(). It will automatically complete
900the netlink message by filling the missing bits and pieces in the
901netlink message header and will deal with addressing based on the
902options and address set in the netlink socket. The message is then
903passed on to nl_send().
904
905If the default sending semantics implemented by nl_send() do not suit
906the application, it may overwrite the sending function nl_send() by
907specifying an own implementation using the function
908nl_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
925If you do not require any of the automatic message completion
926functionality you may use nl_send() directly but beware that any
927internal calls to nl_send_auto() by the library to send netlink
928messages will still use nl_send(). Therefore if you wish to use any
929higher level interfaces and the behaviour of nl_send() is to your
930dislike then you must overwrite the nl_send() function via
931nl_cb_overwrite_send()
932
933The purpose of nl_send() is to embed the netlink message into a iovec
934structure 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
946nl_send_iovec() expects a finalized netlink message and fills out the
947struct msghdr used for addressing. It will first check if the struct
948nl_msg is addressed to a specific peer (see nlmsg_set_dst()). If not,
949it 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
951unaddressed and it is left to the kernel to find the correct peer.
952
953nl_send_iovec() also adds credentials if present and enabled
954(see <<core_sk_cred>>).
955
956The 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
968nl_sendmsg() expects a finalized netlink message and an optional
969struct msghdr containing the peer address. It will copy the local
970address as defined in the socket (see nl_socket_set_local_port()) into
971the netlink message header.
972
973At this point, construction of the message finished and it is ready to
974be 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
986Before sending the application has one last chance to modify the
987message.  It is passed to the NL_CB_MSG_OUT callback function which
988may inspect or modify the message and return an error code. If this
989error code is NL_OK the message is sent using sendmsg() resulting in
990the number of bytes written being returned. Otherwise the message
991sending process is aborted and the error code specified by the
992callback function is returned. See <<core_sk_cb>> for more information
993on how to set callbacks.
994
995.Sending Raw Data with nl_sendto()
996
997If you wish to send raw data over a netlink socket, the following
998function will pass on any buffer provided to it directly to sendto():
999
1000[source,c]
1001--------
1002#include <netlink/netlink.h>
1003
1004int nl_sendto(struct nl_sock *sk, void *buf, size_t size);
1005--------
1006
1007.Sending of Simple Messages
1008
1009A special interface exists for sending of trivial messages. The function
1010expects the netlink message type, optional netlink message flags, and an
1011optional data buffer and data length.
1012[source,c]
1013--------
1014#include <netlink/netlink.h>
1015
1016int nl_send_simple(struct nl_sock *sk, int type, int flags,
1017                   void *buf, size_t size);
1018--------
1019
1020The function will construct a netlink message header based on the message
1021type and flags provided and append the data buffer as message payload. The
1022newly constructed message is sent with nl_send_auto().
1023
1024The following example will send a netlink request message causing the
1025kernel to dump a list of all network links to userspace:
1026
1027[source,c]
1028--------
1029#include <netlink/netlink.h>
1030
1031struct nl_sock *sk;
1032struct rtgenmsg rt_hdr = {
1033	.rtgen_family = AF_UNSPEC,
1034};
1035
1036sk = nl_socket_alloc();
1037nl_connect(sk, NETLINK_ROUTE);
1038
1039nl_send_simple(sock, RTM_GETLINK, NLM_F_DUMP, &rt_hdr, sizeof(rt_hdr));
1040--------
1041
1042[[core_recv]]
1043=== Receiving Messages
1044
1045The easiest method to receive netlink messages is to call nl_recvmsgs_default().
1046It will receive messages based on the semantics defined in the socket. The
1047application may customize these in detail although the default behaviour will
1048probably suit most applications.
1049
1050nl_recvmsgs_default() will also be called internally by the library whenever
1051it needs to receive and parse a netlink message.
1052
1053The function will fetch the callback configuration stored in the socket and
1054call 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
1067nl_recvmsgs() implements the actual receiving loop, it blocks until a
1068netlink message has been received unless the socket has been put into
1069non-blocking mode.
1070
1071For the unlikely scenario that certain required receive characteristics
1072can not be achieved by fine tuning the internal recvmsgs function using
1073the callback configuration (see <<core_sk_cb>>) the application may provide
1074a complete own implementation of it and overwrite all calls to nl_recvmsgs()
1075with 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
1090If the application does not provide its own recvmsgs() implementation
1091with the function nl_cb_overwrite_recvmsgs() the following characteristics
1092apply 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
1114The function nl_recv() is invoked first to receive data from the
1115netlink socket.  This function may be overwritten by the application
1116by an own implementation using the function nl_cb_overwrite_recv().
1117This may be useful if the netlink byte stream is in fact not received
1118from a socket directly but is read from a file or another source.
1119
1120If data has been read, it will be attemped to parse the data. This
1121will be done repeately until the parser returns NL_STOP, an error was
1122returned or all data has been parsed.
1123
1124In case the last message parsed successfully was a multipart message
1125(see <<core_multipart>>) and the parser did not
1126quit due to either an error or NL_STOP nl_recv() respectively the
1127applications own implementation will be called again and the parser
1128starts all over.
1129
1130See <<core_parse_character>> for information on how to extract valid
1131netlink messages from the parser and on how to control the behaviour
1132of it.
1133
1134[[core_parse_character]]
1135.Parsing Characteristics
1136
1137The internal parser is invoked for each netlink message received from
1138a netlink socket. It is typically fed by nl_recv() (see
1139<<core_recv_character>>).
1140
1141The parser will first ensure that the length of the data stream
1142provided is sufficient to contain a netlink message header and that
1143the message length as specified in the message header does not exceed
1144it.
1145
1146If this criteria is met, a new struct nl_msg is allocated and the
1147message is passed on to the the callback function NL_CB_MSG_IN if one
1148is set. Like any other callback function, it may return NL_SKIP to
1149skip the current message but continue parsing the next message or
1150NL_STOP to stop parsing completely.
1151
1152The next step is to check the sequence number of the message against
1153the currently expected sequence number. The application may provide
1154its own sequence number checking algorithm by setting the callback
1155function NL_CB_SEQ_CHECK to its own implementation. In fact, calling
1156nl_socket_disable_seq_check() to disable sequence number checking will
1157do nothing more than set the NL_CB_SEQ_CHECK hook to a function which
1158always returns NL_OK.
1159
1160Another callback hook NL_CB_SEND_ACK exists which is called if the
1161message has the NLM_F_ACK flag set. Although I am not aware of any
1162userspace netlink socket doing this, the application may want to send
1163an 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
1191TODO
1192
1193== Message Parsing & Construction
1194
1195=== Message Format
1196
1197See <<core_netlink_fundamentals>> for an introduction to the netlink
1198protocol and its message format.
1199
1200.Alignment
1201
1202Most netlink protocols enforce a strict alignment policy for all
1203boundries.  The alignment value is defined by NLMSG_ALIGNTO and is
1204fixed to 4 bytes.  Therefore all netlink message headers, begin of
1205payload sections, protocol specific headers, and attribute sections
1206must start at an offset which is a multiple of NLMSG_ALIGNTO.
1207
1208[source,c]
1209--------
1210#include <netlink/msg.h>
1211
1212int nlmsg_size(int payloadlen);
1213int nlmsg_total_size(int payloadlen);
1214--------
1215
1216The library provides a set of function to handle alignment
1217requirements automatically. The function nlmsg_total_size() returns
1218the total size of a netlink message including the padding to ensure
1219the 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
1231If you need to know if padding needs to be added at the end of a
1232message, nlmsg_padlen() returns the number of padding bytes that need
1233to be added for a specific payload length.
1234
1235[source,c]
1236--------
1237#include <netlink/msg.h>
1238int nlmsg_padlen(int payloadlen);
1239--------
1240
1241=== Parsing a Message
1242
1243The library offers two different methods of parsing netlink messages.
1244It offers a low level interface for applications which want to do all
1245the parsing manually. This method is described below. Alternatively
1246the library also offers an interface to implement a parser as part of
1247a cache operations set which is especially useful when your protocol
1248deals with objects of any sort such as network links, routes, etc.
1249This high level interface is described in <<core_cache>>.
1250
1251.Splitting a byte stream into separate messages
1252
1253What you receive from a netlink socket is typically a stream of
1254messages. You will be given a buffer and its length, the buffer may
1255contain any number of netlink messages.
1256
1257The first message header starts at the beginning of message stream.
1258Any subsequent message headers are access by calling nlmsg_next() on
1259the previous header.
1260
1261[source,c]
1262--------
1263#include <netlink/msg.h>
1264
1265struct nlmsghdr *nlmsg_next(struct nlmsghdr *hdr, int *remaining);
1266--------
1267
1268The function nlmsg_next() will automatically substract the size of the
1269previous message from the remaining number of bytes.
1270
1271Please note, there is no indication in the previous message whether
1272another message follows or not. You must assume that more messages
1273follow until all bytes of the message stream have been processed.
1274
1275To simplify this, the function nlmsg_ok() exists which returns true if
1276another message fits into the remaining number of bytes in the message
1277stream. nlmsg_valid_hdr() is similar, it checks whether a specific
1278netlink message contains at least a minimum of payload.
1279
1280[source,c]
1281--------
1282#include <netlink/msg.h>
1283
1284int nlmsg_valid_hdr(const struct nlmsghdr *hdr, int payloadlen);
1285int nlmsg_ok(const struct nlmsghdr *hdr, int remaining);
1286--------
1287
1288A typical use of these functions looks like this:
1289
1290[source,c]
1291--------
1292#include <netlink/msg.h>
1293
1294void 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
1305CAUTION: 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
1309The above can also be written using the iterator nlmsg_for_each():
1310
1311[source,c]
1312--------
1313#include <netlink/msg.h>
1314
1315struct nlmsghdr *hdr;
1316
1317nlmsg_for_each(hdr, stream, length) {
1318	/* do something with message */
1319}
1320--------
1321
1322.Message Payload
1323
1324The message payload is appended to the message header and is guranteed
1325to start at a multiple of +NLMSG_ALIGNTO+. Padding at the end of the
1326message header is added if necessary to ensure this. The function
1327nlmsg_data() will calculate the necessary offset based on the message
1328and returns a pointer to the start of the message payload.
1329
1330[source,c]
1331--------
1332#include <netlink/msg.h>
1333
1334void *nlmsg_data(const struct nlmsghdr *nlh);
1335void *nlmsg_tail(const struct nlmsghdr *nlh);
1336int nlmsg_datalen(const struct nlmsghdr *nlh);
1337--------
1338
1339The 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    +-------------------+- - -+----------------------------+- - -+
1347nlmsg_data(nlh) ---------------^                                  ^
1348nlmsg_tail(nlh) --------------------------------------------------^
1349--------
1350
1351The payload may consist of arbitary data but may have strict alignment
1352and formatting rules depening on the actual netlink protocol.
1353
1354[[core_msg_attr]]
1355.Message Attributes
1356
1357Most netlink protocols use netlink attributes. It not only makes the
1358protocol self documenting but also gives flexibility in expanding the
1359protocol at a later point. New attributes can be added at any time and
1360older attributes can be obsoleted by newer ones without breaking
1361binary 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    +-------------------+- - -+-------------------+- - -+--------------------------------+- - -+
1370nlmsg_attrdata(nlh, hdrlen) -----------------------------^
1371--------
1372
1373The function nlmsg_attrdata() returns a pointer to the begin of the
1374attributes section. The length of the attributes section is returned
1375by the function nlmsg_attrlen().
1376
1377[source,c]
1378--------
1379#include <netlink/msg.h>
1380
1381struct nlattr *nlmsg_attrdata(const struct nlmsghdr *hdr, int hdrlen);
1382int nlmsg_attrlen(const struct nlmsghdr *hdr, int hdrlen);
1383--------
1384
1385See <<core_attr>> for more information on how to use netlink attributes.
1386
1387.Parsing a Message the Easy Way
1388
1389The function nlmsg_parse() validate a complete netlink message in one
1390step. If +hdrlen > 0+ it will first call nlmsg_valid_hdr() to check
1391if the protocol header fits into the message. If there is more payload
1392to parse, it will assume it to be attributes and parse the payload
1393accordingly. The function behaves exactly like nla_parse() when
1394parsing attributes, see <<core_attr_parse_easy>>.
1395
1396[source,c]
1397--------
1398int nlmsg_parse(struct nlmsghdr *hdr, int hdrlen, struct nlattr **attrs,
1399                int maxtype, struct nla_policy *policy);
1400--------
1401
1402The function nlmsg_validate() is based on nla_validate() and behaves
1403exactly the same as nlmsg_parse() except that it only validates and
1404will not fill a array with pointers to each attribute.
1405
1406[source,c]
1407--------
1408int nlmsg_validate(struct nlmsghdr *hdr, int hdrlen, intmaxtype,
1409                   struct nla_policy *policy);
1410--------
1411
1412See <<core_attr_parse_easy>> for an example and more information on
1413attribute parsing.
1414
1415=== Construction of a Message
1416
1417See <<core_msg_format>> for information on the netlink message format
1418and alignment requirements.
1419
1420Message construction is based on struct nl_msg which uses an internal
1421buffer to store the actual netlink message. struct nl_msg +does not+
1422point to the netlink message header. Use nlmsg_hdr() to retrieve a
1423pointer to the netlink message header.
1424
1425At allocation time, a maximum message size is specified. It defaults
1426to a page (PAGE_SIZE). The application constructing the message will
1427reserve space out of this maximum message size repeatedly for each
1428header or attribute added. This allows construction of messages across
1429various layers of code where lower layers do not need to know about
1430the space requirements of upper layers.
1431
1432+Why is setting the maximum message size necessary?+ This
1433question is often raised in combination with the proposed solution of
1434reallocating the message payload buffer on the fly using realloc().
1435While it is possible to reallocate the buffer during construction
1436using nlmsg_expand() it will make all pointers into the message buffer
1437become stale. This breaks usage of nlmsg_hdr(), nla_nest_start(), and
1438nla_nest_end() and is therefore not acceptable as default behaviour.
1439
1440.Allocating struct nl_msg
1441
1442The first step in constructing a new netlink message it to allocate a
1443`struct nl_msg` to hold the message header and payload. Several
1444functions exist to simplify various tasks.
1445
1446[source,c]
1447--------
1448#include <netlink/msg.h>
1449
1450struct nl_msg *nlmsg_alloc(void);
1451void nlmsg_free(struct nl_msg *msg);
1452--------
1453
1454The function nlmsg_alloc() is the default message allocation function.
1455It allocates a new message using the default maximum message size which
1456equals to one page (PAGE_SIZE). The application can change the default
1457size for messages by calling nlmsg_set_default_size():
1458
1459[source,c]
1460--------
1461void	  nlmsg_set_default_size(size_t);
1462--------
1463
1464CAUTION: Calling nlmsg_set_default_size() does not change the maximum
1465         message size of already allocated messages.
1466
1467[source,c]
1468--------
1469struct nl_msg *nlmsg_alloc_size(size_t max);
1470--------
1471
1472Instead of changing the default message size, the function
1473nlmsg_alloc_size() can be used to allocate a message with a individual
1474maximum message size.
1475
1476
1477If the netlink message header is already known at allocation time, the
1478application may sue nlmsg_inherit(). It will allocate a message using
1479the default maximum message size and copy the header into the message.
1480Calling nlmsg_inherit with +set+ to NULL is equivalent to calling
1481nlmsg_alloc().
1482
1483[source,c]
1484--------
1485struct nl_msg *nlmsg_inherit(struct nlmsghdr *hdr);
1486--------
1487
1488Alternatively nlmsg_alloc_simple() takes a netlink message type and
1489netlink message flags. It is equivalent to nlmsg_inherit() except that it
1490takes the two common header fields as arguments instead of a complete
1491header.
1492
1493[source,c]
1494--------
1495#include <netlink/msg.h>
1496
1497struct nl_msg *nlmsg_alloc_simple(int nlmsg_type, int flags);
1498--------
1499
1500.Appending the netlink message header
1501
1502After allocating struct nl_msg, the netlink message header needs to be
1503added unless one of the function nlmsg_alloc_simple() or nlmsg_inherit()
1504have been used for allocation in which case this step will replace the
1505netlink message header already in place.
1506
1507[source,c]
1508--------
1509#include <netlink/msg.h>
1510
1511struct nlmsghdr *nlmsg_put(struct nl_msg *msg, uint32_t port, uint32_t seqnr,
1512                           int nlmsg_type, int payload, int nlmsg_flags);
1513--------
1514
1515The function nlmsg_put() will build a netlink message header out of
1516+nlmsg_type+, +nlmsg_flags+, +seqnr+, and +port+ and copy it into the
1517netlink message. +seqnr+ can be set to +NL_AUTO_SEQ+ to indiciate
1518that the next possible sequence number should be used automatically.
1519To use this feature, the message must be sent using the function
1520nl_send_auto(). Like +port+, the argument +seqnr+ can be set to
1521+NL_AUTO_PORT+ indicating that the local port assigned to the socket
1522should be used as source port. This is generally a good idea unless
1523you are replying to a request. See <<core_netlink_fundamentals>>
1524for more information on how to fill the header.
1525
1526NOTE: 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
1537struct nlmsghdr *hdr;
1538struct nl_msg *msg;
1539struct myhdr {
1540	uint32_t foo1, foo2;
1541} hdr = { 10, 20 };
1542
1543/* Allocate a message with the default maximum message size */
1544msg = 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 */
1551hdr = 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 */
1554memcpy(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
1571Most functions described later on will automatically take care of
1572reserving room for the data that is added to the end of the netlink
1573message. In some situations it may be requried for the application
1574to reserve room directly though.
1575
1576[source,c]
1577--------
1578#include <netlink/msg.h>
1579
1580void *nlmsg_reserve(struct nl_msg *msg, size_t len, int pad);
1581--------
1582
1583The function nlmsg_reserve() reserves +len+ bytes at the end of the
1584netlink message and returns a pointer to the start of the reserved area.
1585The +pad+ argument can be used to request +len+ to be aligned to any
1586number of bytes prior to reservation.
1587
1588The following example requests to reserve a 17 bytes area at the end of
1589message aligned to 4 bytes. Therefore a total of 20 bytes will be
1590reserved.
1591
1592[source,c]
1593--------
1594#include <netlink/msg.h>
1595
1596void *buf = nlmsg_reserve(msg, 17, 4);
1597--------
1598
1599NOTE: `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
1605The function `nlmsg_append()` appends `len` bytes at the end of the
1606message, padding it if requested and necessary.
1607
1608[source,c]
1609--------
1610#include <netlink/msg.h>
1611
1612int nlmsg_append(struct nl_msg *msg, void *data, size_t len, int pad);
1613--------
1614
1615It is equivalent to calling `nlmsg_reserve()` and `memcpy()`ing the
1616data into the freshly reserved data section.
1617
1618NOTE: `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
1624Construction of attributes and addition of attribtues to the message is
1625covereted in section <<core_attr>>.
1626
1627[[core_attr]]
1628== Attributes
1629
1630Any form of payload should be encoded as netlink attributes whenever
1631possible. Use of attributes allows to extend any netlink protocol in
1632the future without breaking binary compatibility. F.e. Suppose your
1633device may currently be using 32 bit counters for statistics but years
1634later the device switches to maintaining 64 bit counters to account
1635for faster network hardware. If your protocol is using attributes the
1636move to 64 bit counters is trivial and only involves in sending an
1637additional attribute containing the 64 bit variants while still
1638providing the old legacy 32 bit counters. If your protocol is not using
1639attributes you will not be able to switch data types without breaking
1640all existing users of the protocol.
1641
1642The concept of nested attributes also allows for subsystems of your
1643protocol to implement and maintain their own attribute schemas. Suppose
1644a new generation of network device is introduced which requires a
1645completely new set of configuration settings which was unthinkable when
1646the netlink protocol was initially designed. Using attributes the new
1647generation of devices may define a new attribute and fill it with its
1648own new structure of attributes which extend or even obsolete the old
1649attributes.
1650
1651Therefore, _always_ use attributes even if you are almost certain that
1652the message format will never ever change in the future.
1653
1654[[core_attr_format]]
1655=== Attribute Format
1656
1657Netlink attributes allow for any number of data chunks of arbitary
1658length to be attached to a netlink message. See <<core_msg_attr>>
1659for more information on where attributes are stored in the message.
1660
1661The format of the attributes data returned by nlmsg_attrdata() is as
1662follows:
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
1674Every 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
1676to be padded at the end, the function nla_padlen() returns the number
1677of padding bytes that will or need to be added.
1678
1679image:attribute_hdr.png["Netlink Attribute Header"]
1680
1681Every attribute is encoded with a type and length field, both 16 bits,
1682stored in the attribute header (struct nlattr) preceding the attribute
1683payload. The length of an attribute is used to calculate the offset to
1684the next attribute.
1685
1686[[core_attr_parse]]
1687=== Parsing Attributes
1688
1689[[core_attr_parse_split]]
1690.Splitting an Attributes Stream into Attributes
1691
1692Although most applications will use one of the functions from the
1693nlmsg_parse() family (See <<core_attr_parse_easy>>) an interface exists
1694to split the attributes stream manually.
1695
1696As described in <<core_attr_format>> the attributes section contains a
1697infinite sequence or stream of attributes. The pointer returned by
1698nlmsg_attrdata() (See <<core_msg_attr>>) points to the first attribute
1699header. Any subsequent attribute is accessed with the function nla_next()
1700based on the previous header.
1701
1702[source,c]
1703--------
1704#include <netlink/attr.h>
1705
1706struct nlattr *nla_next(const struct nlattr *attr, int *remaining);
1707--------
1708
1709The semantics are equivalent to nlmsg_next() and thus nla_next() will also
1710subtract the size of the previous attribute from the remaining number of
1711bytes in the attributes stream.
1712
1713Like messages, attributes do not contain an indicator whether another
1714attribute follows or not. The only indication is the number of bytes left
1715in the attribute stream. The function nla_ok() exists to determine whether
1716another attribute fits into the remaining number of bytes or not.
1717
1718[source,c]
1719--------
1720#include <netlink/attr.h>
1721
1722int nla_ok(const struct nlattr *attr, int remaining);
1723--------
1724
1725A 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
1733struct nlattr *hdr = nlmsg_attrdata(msg, 0);
1734int remaining = nlmsg_attrlen(msg, 0);
1735
1736while (nla_ok(hdr, remaining)) {
1737	/* parse attribute here */
1738	hdr = nla_next(hdr, &remaining);
1739};
1740--------
1741
1742NOTE: `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
1748Once the individual attributes have been sorted out by either splitting
1749the attributes stream or using another interface the attribute header
1750and payload can be accessed.
1751
1752[source,c]
1753--------
1754                             <- nla_len(hdr) ->
1755    +-----------------+- - -+- - - - - - - - - +- - -+
1756    |  struct nlattr  | Pad |     Payload      | Pad |
1757    +-----------------+- - -+- - - - - - - - - +- - -+
1758nla_data(hdr) ---------------^
1759--------
1760
1761The functions nla_len() and nla_type() can be used to access the attribute
1762header. nla_len() will return the length of the payload not including
1763eventual padding bytes. nla_type returns the attribute type.
1764
1765[source,c]
1766--------
1767#include <netlink/attr.h>
1768
1769int nla_len(const struct nlattr *hdr);
1770int nla_type(const struct nlattr *hdr);
1771--------
1772
1773The function nla_data() will return a pointer to the attribute
1774payload. Please note that due to +NLA_ALIGNTO+ being 4 bytes it may
1775not be safe to cast and dereference the pointer for any datatype
1776larger than 32 bit depending on the architecture the application is
1777run on.
1778
1779[source,c]
1780--------
1781#include <netlink/attr.h>
1782
1783void *nla_data(const struct nlattr *hdr);
1784--------
1785
1786[NOTE]
1787Never 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
1789expectations. See <<core_attr_validation>>
1790
1791[[core_attr_validation]]
1792.Attribute Validation
1793
1794When receiving netlink attributes, the receiver has certain expections
1795on how the attributes should look like. These expectations must be
1796defined to make sure the sending side meets our expecations. For this
1797purpose, a attribute validation interface exists which must be used
1798prior to accessing any payload.
1799
1800All functions providing attribute validation functionality are based
1801on struct nla_policy:
1802
1803[source,c]
1804--------
1805struct nla_policy {
1806	uint16_t	type;
1807	uint16_t	minlen;
1808	uint16_t	maxlen;
1809};
1810--------
1811
1812The +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
1815be considered a valid attribute. The value for +minlen+ is implicit
1816for most basic datatypes such as integers or flags. The +maxlen+
1817member can be used to define a maximum payload length for an
1818attribute to still be considered valid.
1819
1820NOTE: 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
1826One of the functions which use struct nla_policy is nla_validate().
1827The function expects an array of struct nla_policy and will access the
1828array using the attribute type as index. If an attribute type is out
1829of bounds the attribute is assumed to be valid. This is intentional
1830behaviour to allow older applications not yet aware of recently
1831introduced attributes to continue functioning.
1832
1833[source,c]
1834--------
1835#include <netlink/attr.h>
1836
1837int nla_validate(struct nlattr *head, int len, int maxtype, struct nla_policy *policy);
1838--------
1839
1840The function nla_validate() returns 0 if all attributes are valid,
1841otherwise a validation failure specific error code is returned.
1842
1843Most applications will rarely use nla_validate() directly but use
1844nla_parse() instead which takes care of validation in the same way but
1845also parses the the attributes in the same step. See
1846<<core_attr_parse_easy>> for an example and more information.
1847
1848The 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
1861Most applications will not want to deal with splitting attribute
1862streams themselves as described in <<core_attr_parse_split>>
1863A much easier method is to use nla_parse().
1864
1865[source,c]
1866--------
1867#include <netlink/attr.h>
1868
1869int nla_parse(struct nlattr **attrs, int maxtype, struct nlattr *head,
1870              int len, struct nla_policy *policy);
1871--------
1872
1873The function nla_parse() will iterate over a stream of attributes,
1874validate each attribute as described in <<core_attr_validation>>
1875If the validation of all attributes succeeds, a pointer to each attribute
1876is stored in the +attrs+ array at `attrs[nla_type(attr)]`.
1877
1878As an alernative to nla_parse() the function nlmsg_parse() can be used
1879to 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
1884The following example demonstrates how to parse a netlink message sent
1885over a netlink protocol which does not use protocol headers. The example
1886does enforce a attribute policy however, the attribute MY_ATTR_FOO must
1887be a 32 bit integer, and the attribute MY_ATTR_BAR must be a string with
1888a maximum length of 16 characters.
1889
1890[source,c]
1891---------
1892#include <netlink/msg.h>
1893#include <netlink/attr.h>
1894
1895enum {
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
1903static 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
1909void 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
1925An application only interested in a single attribute can use one of the
1926functions nla_find() or  nlmsg_find_attr(). These function will iterate
1927over all attributes, search for a matching attribute and return a pointer
1928to the corresponding attribute header.
1929
1930[source,c]
1931--------
1932#include <netlink/attr.h>
1933
1934struct nlattr *nla_find(struct nlattr *head, int len, int attrtype);
1935--------
1936
1937[source,c]
1938--------
1939#include <netlink/msg.h>
1940
1941struct nlattr *nlmsg_find_attr(struct nlmsghdr *hdr, int hdrlen, int attrtype);
1942--------
1943
1944NOTE: `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
1949In some situations it does not make sense to assign a unique attribute
1950type to each attribute in the attribute stream. For example a list may
1951be transferd using a stream of attributes and even if the attribute type
1952is incremented for each attribute it may not make sense to use the
1953nlmsg_parse() or nla_parse() function to fill an array.
1954
1955Therefore methods exist to iterate over a stream of attributes:
1956
1957[source,c]
1958--------
1959#include <netlink/attr.h>
1960
1961nla_for_each_attr(attr, head, len, remaining)
1962--------
1963
1964nla_for_each_attr() is a macro which can be used in front of a code
1965block:
1966
1967[source,c]
1968--------
1969#include <netlink/attr.h>
1970
1971struct nalttr *nla;
1972int rem;
1973
1974nla_for_each_attr(nla, attrstream, streamlen, rem) {
1975	/* validate & parse attribute */
1976}
1977
1978if (rem > 0)
1979	/* unparsed attribute data */
1980--------
1981
1982[[core_attr_constr]]
1983=== Attribute Construction
1984
1985The interface to add attributes to a netlink message is based on the
1986regular message construction interface. It assumes that the message
1987header and an eventual protocol header has been added to the message
1988already.
1989
1990[source,c]
1991--------
1992struct nlattr *nla_reserve(struct nl_msg *msg, int attrtype, int len);
1993--------
1994
1995The function nla_reserve() adds an attribute header at the end of the
1996message and reserves room for +len+ bytes of payload. The function
1997returns a pointer to the attribute payload section inside the message.
1998Padding is added at the end of the attribute to ensure the next
1999attribute is properly aligned.
2000
2001[source,c]
2002--------
2003int nla_put(struct nl_msg *msg, int attrtype, int attrlen, const void *data);
2004--------
2005
2006The function nla_put() is base don nla_reserve() but takes an additional
2007pointer +data+ pointing to a buffer containing the attribute payload.
2008It will copy the buffer into the message automatically.
2009
2010.Example:
2011
2012[source,c]
2013--------
2014struct my_attr_struct {
2015	uint32_t a;
2016	uint32_t b;
2017};
2018
2019int 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
2030See <<core_attr_types>> for datatype specific attribute construction
2031functions.
2032
2033.Exception Based Attribute Construction
2034
2035Like in the kernel API an exception based construction interface is
2036provided. The behaviour of the macros is identical to their regular
2037function 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
2046void 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
2054nla_put_failure:
2055	/* NLA_PUT* macros jump here in case of an error */
2056	return -EMSGSIZE;
2057}
2058--------
2059
2060See <<core_attr_types>> for more information on the datatype specific
2061exception based variants.
2062
2063[[core_attr_types]]
2064=== Attribute Data Types
2065
2066A number of basic data types have been defined to simplify access and
2067validation of attributes. The datatype is not encoded in the
2068attribute, therefore bthe sender and receiver are required to use the
2069same 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
2081Besides simplified access to the payload of such datatypes, the major
2082advantage is the automatic validation of each attribute based on a
2083policy. The validation ensures safe access to the payload by checking
2084for minimal payload size and can also be used to enforce maximum
2085payload size for some datatypes.
2086
2087==== Integer Attributes
2088
2089The most frequently used datatypes are integers. Integers come in four
2090different sizes:
2091[horizontal]
2092NLA_U8::  8bit integer
2093NLA_U16:: 16bit integer
2094NLA_U32:: 32bit integer
2095NLA_U64:: 64bit integer
2096
2097Note that due to the alignment requirements of attributes the integer
2098attribtue +NLA_u8+ and +NLA_U16+ will not result in space savings in
2099the netlink message. Their use is intended to limit the range of
2100values.
2101
2102.Parsing Integer Attributes
2103
2104[source,c]
2105--------
2106#include <netlink/attr.h>
2107
2108uint8_t  nla_get_u8(struct nlattr *hdr);
2109uint16_t nla_get_u16(struct nlattr *hdr);
2110uint32_t nla_get_u32(struct nlattr *hdr);
2111uint64_t nla_get_u64(struct nlattr *hdr);
2112--------
2113
2114Example:
2115
2116[source,c]
2117--------
2118if (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
2128int nla_put_u8(struct nl_msg *msg, int attrtype, uint8_t value);
2129int nla_put_u16(struct nl_msg *msg, int attrtype, uint16_t value);
2130int nla_put_u32(struct nl_msg *msg, int attrtype, uint32_t value);
2131int nla_put_u64(struct nl_msg *msg, int attrtype, uint64_t value);
2132--------
2133
2134Exception based:
2135
2136[source,c]
2137--------
2138NLA_PUT_U8(msg, attrtype, value)
2139NLA_PUT_U16(msg, attrtype, value)
2140NLA_PUT_U32(msg, attrtype, value)
2141NLA_PUT_U64(msg, attrtype, value)
2142--------
2143
2144.Validation
2145
2146Use +NLA_U8+, +NLA_U16+, +NLA_U32+, or +NLA_U64+ to define the type of
2147integer when filling out a struct nla_policy array. It will
2148automatically enforce the correct minimum payload length policy.
2149
2150Validation does not differ between signed and unsigned integers, only
2151the size matters. If the appliaction wishes to enforce particular value
2152ranges it must do so itself.
2153
2154[source,c]
2155--------
2156static struct nla_policy my_policy[ATTR_MAX+1] = {
2157	[ATTR_FOO] = { .type = NLA_U32 },
2158	[ATTR_BAR] = { .type = NLA_U8 },
2159};
2160--------
2161
2162The above is equivalent to:
2163[source,c]
2164--------
2165static 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
2173The string datatype represents a NUL termianted character string of
2174variable length. It is not intended for binary data streams.
2175
2176The payload of string attributes can be accessed with the function
2177nla_get_string(). nla_strdup() calls strdup() on the payload and returns
2178the newly allocated string.
2179
2180[source,c]
2181--------
2182#include <netlink/attr.h>
2183
2184char *nla_get_string(struct nlattr *hdr);
2185char *nla_strdup(struct nlattr *hdr);
2186--------
2187
2188String attributes are constructed with the function +nla_put_string()+
2189respectively +NLA_PUT_STRING()+. The length of the payload will be
2190strlen()+1, the trailing NUL byte is included.
2191
2192[source,c]
2193--------
2194int nla_put_string(struct nl_msg *msg, int attrtype, const char *data);
2195
2196NLA_PUT_STRING(msg, attrtype, data)
2197--------
2198
2199For validation purposes the type +NLA_STRING+ can be used in
2200+struct nla_policy+ definitions. It implies a minimum payload length
2201of 1 byte and checks for a trailing NUL byte. Optionally the +maxlen+
2202member defines the maximum length of a character string (including the
2203trailing NUL byte).
2204
2205[source,c]
2206--------
2207static struct nla_policy my_policy[] = {
2208	[ATTR_FOO] = { .type = NLA_STRING,
2209		       .maxlen = IFNAMSIZ },
2210};
2211--------
2212
2213==== Flag Attributes
2214
2215The flag attribute represents a boolean datatype. The presence of the
2216attribute implies a value of +true+, the absence of the attribute
2217implies the value +false+. Therefore the payload length of flag
2218attributes is always 0.
2219
2220[source,c]
2221--------
2222int nla_get_flag(struct nlattr *hdr);
2223int nla_put_flag(struct nl_msg *msg, int attrtype);
2224--------
2225
2226The 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. */
2233nla_put_flag(msg, ATTR_FLAG);
2234
2235/* There is no need for a receival function, the presence is the value. */
2236if (attrs[ATTR_FLAG])
2237	/* flag is present */
2238--------
2239
2240[[core_attr_nested]]
2241==== Nested Attributes
2242
2243As described in <<core_attr>>, attributes can be nested allowing for
2244complex tree structures of attributes. It is commonly used to delegate
2245the responsibility of a subsection of the message to a subsystem.
2246Nested attributes are also commonly used for transmitting list of objects.
2247
2248When nesting attributes, the nested attributes are included as payload
2249of a container attribute.
2250
2251NOTE: 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
2258The type +NLA_NESTED+ should be used when defining nested attributes
2259in a struct nla_policy definition. It will not enforce any minimum
2260payload length unless +minlen+ is specified explicitely. This is
2261because some netlink protocols implicitely allow empty container
2262attributes.
2263
2264[source,c]
2265--------
2266static struct nla_policy my_policy[] = {
2267	[ATTR_OPTS] = { .type = NLA_NESTED },
2268};
2269--------
2270
2271.Parsing of Nested Attributes
2272
2273The function nla_parse_nested() is used to parse nested attributes.
2274Its behaviour is identical to nla_parse() except that it takes a
2275struct nlattr as argument and will use the payload as stream of
2276attributes.
2277
2278[source,c]
2279--------
2280if (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
2296Attributes are nested by surrounding them with calls to nla_nest_start()
2297and nla_nest_end(). nla_nest_start() will add a attribute header to
2298the message but no actual payload. All data added to the message from
2299this point on will be part of the container attribute until nla_nest_end()
2300is called which "closes" the attribute, correcting its payload length to
2301include all data length.
2302
2303[source,c]
2304--------
2305int 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
2318nla_put_failure:
2319	nla_nest_cancel(msg, opts);
2320	return -EMSGSIZE;
2321}
2322--------
2323
2324==== Unspecified Attribute
2325
2326This is the default attribute type and used when none of the basic
2327datatypes is suitable. It represents data of arbitary type and length.
2328
2329See <<core_addr_alloc, Address Allocation>> for a more information on
2330a special interface allowing the allocation of abstract address object
2331based on netlink attributes which carry some form of network address.
2332
2333See <<core_data_alloc, Abstract Data Allocation>> for more information
2334on how to allocate abstract data objects based on netlink attributes.
2335
2336Use the function nla_get() and nla_put() to access the payload and
2337construct attributes. See <<core_attr_constr, Attribute Construction>>
2338for an example.
2339
2340=== Examples
2341
2342==== Constructing a Netlink Message with Attributes
2343
2344[source,c]
2345--------
2346struct 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
2393nla_put_failure:
2394	nlmsg_free(msg);
2395	return NULL;
2396}
2397------
2398
2399==== Parsing a Netlink Message with Attributes
2400
2401[source,c]
2402--------
2403int 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;
2450errout:
2451	return err;
2452}
2453--------
2454
2455[[core_cb]]
2456== Callback Configurations
2457
2458Callback hooks and overwriting capabilities are provided in various places
2459inside library to control the behaviour of several functions. All the
2460callback and overwrite functions are packed together in struct nl_cb which
2461is attached to a netlink socket or passed on to functions directly.
2462
2463=== Callback Hooks
2464
2465Callback hooks are spread across the library to provide entry points for
2466message processing and to take action upon certain events.
2467
2468Callback 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
2481The 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
2503Any function called by NL_CB_MSG_OUT may return a negative error code to
2504prevent the message from being sent and the error code being returned.
2505
2506nl_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
2521Any of these functions may return NL_OK, NL_SKIP, or NL_STOP.
2522
2523Message processing callback functions are set with nl_cb_set():
2524[source,c]
2525--------
2526#include <netlink/handlers.h>
2527
2528int 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
2531typedef int (*nl_recvmsg_msg_cb_t)(struct nl_msg *msg, void *arg);
2532--------
2533
2534.Callback for Error Messages
2535
2536A special function prototype is used for the error message callback hook:
2537
2538[source,c]
2539--------
2540#include <netlink/handlers.h>
2541
2542int nl_cb_err(struct nl_cb *cb, enum nl_cb_kind kind, nl_recvmsg_err_cb_t func, void *arg);
2543
2544typedef 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 */
2553struct nl_cb *cb = nl_cb_alloc(NL_CB_VERBOSE);
2554
2555/* Modify the set to call my_func() for all valid messages */
2556nl_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 */
2562FILE *file = fopen(...);
2563nl_cb_err(cb, NL_CB_VERBOSE, NULL, file);
2564--------
2565
2566=== Overwriting of Internal Functions
2567
2568When the library needs to send or receive netlink messages in high level
2569interfaces it does so by calling its own low level API. In the case the
2570default characteristics are not sufficient for the application, it may
2571overwrite several internal function calls with own implementations.
2572
2573.Overwriting recvmsgs()
2574
2575See <<core_recv, Receiving Netlink Messages>> for more information on
2576how and when recvmsgs() is called internally.
2577
2578[source,c]
2579--------
2580#include <netlink/handlers.h>
2581
2582void nl_cb_overwrite_recvmsgs(struct nl_cb *cb,
2583                              int (*func)(struct nl_sock *sk, struct nl_cb *cb));
2584--------
2585
2586The following criteras must be met if a recvmsgs() implementation is
2587supposed 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
2599Often it is sufficient to overwrite `nl_recv()` which is responsible
2600from receiving the actual data from the socket instead of replacing
2601the complete `recvmsgs()` logic.
2602
2603See <<core_recv_character, Receive Characteristics>> for more
2604information on how and when `nl_recv()` is called internally.
2605
2606[source,c]
2607--------
2608#include <netlink/handlers.h>
2609
2610void 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
2617The following criteras must be met for an own `nl_recv()`
2618implementation:
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
2633See <<core_send, Sending Netlink Messages>> for more information on
2634how and when nl_send() is called internally.
2635
2636[source,c]
2637--------
2638#include <netlink/handlers.h>
2639
2640void nl_cb_overwrite_send(struct nl_cb *cb, int (*func)(struct nl_sock *sk,
2641                                                        struct nl_msg *msg));
2642--------
2643
2644Own implementations must send the netlink message and return 0 on success
2645or a negative error code.
2646
2647[[core_cache]]
2648== Cache System
2649
2650=== Allocation of Caches
2651
2652Almost all subsystem provide a function to allocate a new cache
2653of some form. The function usually looks like this:
2654[source,c]
2655--------
2656struct nl_cache *<object name>_alloc_cache(struct nl_sock *sk);
2657--------
2658
2659These functions allocate a new cache for the own object type,
2660initializes it properly and updates it to represent the current
2661state of their master, e.g. a link cache would include all
2662links currently configured in the kernel.
2663
2664Some of the allocation functions may take additional arguments
2665to further specify what will be part of the cache.
2666
2667All such functions return a newly allocated cache or NULL
2668in case of an error.
2669
2670=== Cache Manager
2671
2672The purpose of a cache manager is to keep track of caches and
2673automatically receive event notifications to keep the caches
2674up to date with the kernel state. Each manager has exactly one
2675netlink socket assigned which limits the scope of each manager
2676to exactly one netlink family. Therefore all caches committed
2677to a manager must be part of the same netlink family. Due to the
2678nature of a manager, it is not possible to have a cache maintain
2679two instances of the same cache type. The socket is subscribed
2680to the event notification group of each cache and also put into
2681non-blocking mode. Functions exist to poll() on the socket to
2682wait 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----
2708struct nl_cache_mngr *mngr;
2709
2710// Allocate a new cache manager for RTNETLINK and automatically
2711// provide the caches added to the manager.
2712err = nl_cache_mngr_alloc(NULL, NETLINK_ROUTE, NL_AUTO_PROVIDE, &mngr);
2713----
2714
2715.Keep track of a cache
2716
2717[source,c]
2718----
2719struct 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.
2724cache = 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.
2733if (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----
2743nl_cache_mngr_free(mngr);
2744----
2745
2746== Abstract Data Types
2747
2748A few high level abstract data types which are used by a majority netlink
2749protocols are implemented in the core library. More may be added in the
2750future if the need arises.
2751
2752=== Abstract Address
2753
2754Most netlink protocols deal with networking related topics and thus
2755dealing with network addresses is a common task.
2756
2757Currently 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
2769The function nl_addr_alloc() allocates a new empty address. The
2770+maxsize+ argument defines the maximum length of an address in bytes.
2771The size of an address is address family specific. If the address
2772family and address data are known at allocation time the function
2773nl_addr_build() can be used alternatively. You may also clone
2774an address by calling nl_addr_clone()
2775
2776[source,c]
2777--------
2778#include <netlink/addr.h>
2779
2780struct nl_addr *nl_addr_alloc(size_t maxsize);
2781struct nl_addr *nl_addr_clone(struct nl_addr *addr);
2782struct nl_addr *nl_addr_build(int family, void *addr, size_t size);
2783--------
2784
2785If the address is transported in a netlink attribute, the function
2786nl_addr_alloc_attr() allocates a new address based on the payload
2787of the attribute provided. The +family+ argument is used to specify
2788the address family of the address, set to +AF_UNSPEC+ if unknown.
2789
2790[source,c]
2791--------
2792#include <netlink/addr.h>
2793
2794struct nl_addr *nl_addr_alloc_attr(struct nlattr *attr, int family);
2795--------
2796
2797If the address is provided by a user, it is usually stored in a human
2798readable format. The function nl_addr_parse() parses a character
2799string representing an address and allocates a new address based on
2800it.
2801
2802[source,c]
2803--------
2804#include <netlink/addr.h>
2805
2806int nl_addr_parse(const char *addr, int hint, struct nl_addr **result);
2807--------
2808
2809If parsing succeeds the function returns 0 and the allocated address
2810is stored in +*result+.
2811
2812NOTE: 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-----
2818struct nl_addr *a = nl_addr_parse("::1", AF_UNSPEC);
2819printf("Address family: %s\n", nl_af2str(nl_addr_get_family(a)));
2820nl_addr_put(a);
2821a = nl_addr_parse("11:22:33:44:55:66", AF_UNSPEC);
2822printf("Address family: %s\n", nl_af2str(nl_addr_get_family(a)));
2823nl_addr_put(a);
2824-----
2825
2826.Address References
2827
2828Abstract addresses use reference counting to account for all users of
2829a particular address. After the last user has returned the reference
2830the address is freed.
2831
2832If you pass on a address object to another function and you are not
2833sure how long it will be used, make sure to call nl_addr_get() to
2834acquire an additional reference and have that function or code path
2835call nl_addr_put() as soon as it has finished using the address.
2836
2837[source,c]
2838--------
2839#include <netlink/addr.h>
2840
2841struct nl_addr *nl_addr_get(struct nl_addr *addr);
2842void nl_addr_put(struct nl_addr *addr);
2843int nl_addr_shared(struct nl_addr *addr);
2844--------
2845
2846You may call nl_addr_shared() at any time to check if you are the only
2847user of an address.
2848
2849.Address Attributes
2850
2851The address is usually set at allocation time. If it was unknown at that
2852time it can be specified later by calling nl_addr_set_family() and is
2853accessed with the function nl_addr_get_family().
2854
2855[source,c]
2856--------
2857#include <netlink/addr.h>
2858
2859void nl_addr_set_family(struct nl_addr *addr, int family);
2860int nl_addr_get_family(struct nl_addr *addr);
2861--------
2862
2863The same is true for the actual address data. It is typically present
2864at allocation time. For exceptions it can be specified later or
2865overwritten with the function `nl_addr_set_binary_addr()`. Beware that
2866the length of the address may not exceed `maxlen` specified at
2867allocation 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
2875int nl_addr_set_binary_addr(struct nl_addr *addr, void *data, size_t size);
2876void *nl_addr_get_binary_addr(struct nl_addr *addr);
2877unsigned int nl_addr_get_len(struct nl_addr *addr);
2878--------
2879
2880If you only want to check if the address data consists of all zeros
2881the function `nl_addr_iszero()` is a shortcut to that.
2882
2883[source,c]
2884--------
2885#include <netlink/addr.h>
2886
2887int nl_addr_iszero(struct nl_addr *addr);
2888--------
2889
2890==== Address Prefix Length
2891
2892Although this functionality is somewhat specific to routing it has
2893been implemented here. Addresses can have a prefix length assigned
2894which implies that only the first n bits are of importance. This is
2895f.e. used to implement subnets.
2896
2897Use 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
2904void nl_addr_set_prefixlen(struct nl_addr *addr, int n);
2905unsigned int nl_addr_get_prefixlen(struct nl_addr *addr);
2906--------
2907
2908NOTE: The default prefix length is set to (address length * 8)
2909
2910.Address Helpers
2911
2912Several functions exist to help when dealing with addresses. The
2913function `nl_addr_cmp()` compares two addresses and returns an integer
2914less than, equal to or greater than zero without considering the
2915prefix length at all. If you want to consider the prefix length, use
2916the function `nl_addr_cmp_prefix()`.
2917
2918[source,c]
2919--------
2920#include <netlink/addr.h>
2921
2922int nl_addr_cmp(struct nl_addr *addr, struct nl_addr *addr);
2923int nl_addr_cmp_prefix(struct nl_addr *addr, struct nl_addr *addr);
2924--------
2925
2926If an abstract address needs to presented to the user it should be
2927done in a human readable format which differs depending on the address
2928family. The function `nl_addr2str()` takes care of this by calling the
2929appropriate conversion functions internaly. It expects a `buf` of
2930length `size` to write the character string into and returns a pointer
2931to `buf` for easy `printf()` usage.
2932
2933[source,c]
2934--------
2935#include <netlink/addr.h>
2936
2937char *nl_addr2str(struct nl_addr *addr, char *buf, size_t size);
2938--------
2939
2940If the address family is unknown, the address data will be printed in
2941hexadecimal format `AA:BB:CC:DD:...`
2942
2943Often the only way to figure out the address family is by looking at
2944the length of the address. The function `nl_addr_guess_family()` does
2945just this and returns the address family guessed based on the address
2946size.
2947
2948[source,c]
2949--------
2950#include <netlink/addr.h>
2951
2952int nl_addr_guess_family(struct nl_addr *addr);
2953--------
2954
2955Before allocating an address you may want to check if the character
2956string actually represents a valid address of the address family you
2957are expecting. The function `nl_addr_valid()` can be used for that, it
2958returns 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
2960valid adddress formats.
2961
2962[source,c]
2963--------
2964#include <netlink/addr.h>
2965
2966int nl_addr_valid(char *addr, int family);
2967--------
2968
2969=== Abstract Data
2970
2971The abstract data type is a trivial datatype with the primary purpose
2972to simplify usage of netlink attributes of arbitary length.
2973
2974[[core_data_alloc]]
2975.Allocation of a Data Object
2976The function `nl_data_alloc()` alloctes a new abstract data object and
2977fill it with the provided data. `nl_data_alloc_attr()` does the same
2978but bases the data on the payload of a netlink attribute. New data
2979objects can also be allocated by cloning existing ones by using
2980`nl_data_clone()`.
2981
2982[source,c]
2983--------
2984struct nl_data *nl_data_alloc(void *buf, size_t size);
2985struct nl_data *nl_data_alloc_attr(struct nlattr *attr);
2986struct nl_data *nl_data_clone(struct nl_data *data);
2987void nl_data_free(struct nl_data *data);
2988--------
2989
2990.Access to Data
2991
2992The function `nl_data_get()` returns a pointer to the data, the size
2993of data is returned by `nl_data_get_size()`.
2994
2995[source,c]
2996--------
2997void *nl_data_get(struct nl_data *data);
2998size_t nl_data_get_size(struct nl_data *data);
2999--------
3000
3001.Data Helpers
3002
3003The function nl_data_append() reallocates the internal data buffers
3004and appends the specified `buf` to the existing data.
3005
3006[source,c]
3007--------
3008int nl_data_append(struct nl_data *data, void *buf, size_t size);
3009--------
3010
3011CAUTION: 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--------
3016int nl_data_cmp(struct nl_data *data, struct nl_data *data);
3017--------
3018