forked from thom311/libnl
/
core.txt
3017 lines (2341 loc) · 93.9 KB
/
core.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
////
vim.syntax: asciidoc
Copyright (c) 2011 Thomas Graf <tgraf@suug.ch>
////
Netlink Library (libnl)
=======================
Thomas Graf <tgraf@suug.ch>
3.2, May 9 2011:
:numbered:
== Introduction
The core library contains the fundamentals required to communicate
over netlink sockets. It deals with connecting and disconnectng of
sockets, sending and receiving of data, construction and parsing of
messages, provides a customizeable receiving state machine, and
provides a abstract data type framework which eases the implementation
of object based netlink protocols where objects are added, removed, or
modified using a netlink based protocol.
.Library Hierarchy
The suite is split into multiple libraries:
image:library_overview.png["Library Hierarchy"]
link:core.html[Netlink Library] (libnl)::
Socket handling, sending and receiving, message construction and parsing, ...
link:route.html[Routing Family Library] (libnl-route)::
Adresses, links, neighbours, routing, traffic control, neighbour tables, ...
Netfilter Library (libnl-nf)::
Connection tracking, logging, queueing
Generic Netlink Library (libnl-genl)::
Controller API, family and command registration
=== How To Read This Documentation
The libraries provide a broad set of APIs of which most applications only
require a small subset of it. Depending on the type of application, some
users may only be interested in the low level netlink messaging API while
others wish to make heavy use of the high level API.
In any case it is recommended to get familiar with the netlink protocol
first.
- <<core_netlink_fundamentals>>
The low level APIs are described in:
- <<core_sockets>>
- <<core_send_recv>>
=== Linking to this Library
.Checking the presence of the library using autoconf
Projects using autoconf may use +PKG_CHECK_MODULES()+ to check if
a specific version of libnl is available on the system. The example
below also shows how to retrieve the +CFLAGS+ and linking dependencies
required to link against the library.
The following example shows how to check for a specific version of libnl. If
found, it extends the `CFLAGS` and `LIBS` variable appropriately:
[source]
----
PKG_CHECK_MODULES(LIBNL3, libnl-3.0 >= 3.1, [have_libnl3=yes], [have_libnl3=no])
if (test "${have_libnl3}" = "yes"); then
CFLAGS+="$LIBNL3_CFLAGS"
LIBS+="$LIBNL3_LIBS"
fi
----
NOTE: The pkgconfig file is named +libnl-3.0.pc+ for historic reasons, it also
covers library versions >= 3.1.
.Header Files
The main header file is `<netlink/netlink.h>`. Additional headers may need to
be included in your sources depending on the subsystems and components your
program makes use of.
[source,c]
-----
#include <netlink/netlink.h>
#include <netlink/cache.h>
#include <netlink/route/link.h>
-----
.Version Dependent Code
If your code wishes to be capable to link against multiple versions of libnl
you may have direct the compiler to only include portions on the code depending
on the version of libnl that it is compiled against.
[source,c]
-----
#include <netlink/version.h>
#if LIBNL_VER_NUM >= LIBNL_VER(3,1)
/* include code if compiled with libnl version >= 3.1 */
#endif
-----
.Linking
-----
$ gcc myprogram.c -o myprogram $(pkgconfig --cflags --libs libnl-3.0)
-----
=== Debugging
The library has been compiled with debugging statements enabled it will
print debug information to +stderr+ if the environment variable +NLDBG+
is set to > 0.
-----
$ NLDBG=2 ./myprogram
-----
.Debugging Levels
[options="header", width="80%", cols="1,5", align="center"]
|===============================================================
| Level | Description
| 0 | Debugging disabled (default)
| 1 | Warnings, important events and notifications
| 2 | More or less important debugging messages
| 3 | Repetitive events causing a flood of debugging messages
| 4 | Even less important messages
|===============================================================
.Debugging the Netlink Protocol
It is often useful to peek into the stream of netlink messages exchanged
with other sockets. Setting the environment variable +NLCB=debug+ will
cause the debugging message handlers to be used which in turn print the
netlink messages exchanged in a human readable format to to +stderr+:
-----
$ NLCB=debug ./myprogram
-- Debug: Sent Message:
-------------------------- BEGIN NETLINK MESSAGE ---------------------------
[HEADER] 16 octets
.nlmsg_len = 20
.nlmsg_type = 18 <route/link::get>
.nlmsg_flags = 773 <REQUEST,ACK,ROOT,MATCH>
.nlmsg_seq = 1301410712
.nlmsg_pid = 20014
[PAYLOAD] 16 octets
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
--------------------------- END NETLINK MESSAGE ---------------------------
-- Debug: Received Message:
-------------------------- BEGIN NETLINK MESSAGE ---------------------------
[HEADER] 16 octets
.nlmsg_len = 996
.nlmsg_type = 16 <route/link::new>
.nlmsg_flags = 2 <MULTI>
.nlmsg_seq = 1301410712
.nlmsg_pid = 20014
[PAYLOAD] 16 octets
00 00 04 03 01 00 00 00 49 00 01 00 00 00 00 00 ........I.......
[ATTR 03] 3 octets
6c 6f 00 lo.
[PADDING] 1 octets
00 .
[ATTR 13] 4 octets
00 00 00 00 ....
[ATTR 16] 1 octets
00 .
[PADDING] 3 octets
00 00 00 ...
[ATTR 17] 1 octets
00 .
[...]
--------------------------- END NETLINK MESSAGE ---------------------------
-----
[[core_netlink_fundamentals]]
== Netlink Protocol Fundamentals
The netlink protocol is a socket based IPC mechanism used for
communication between userspace processes and the kernel or between
userspace processes themselves. The netlink protocol is based on BSD
sockets and uses the +AF_NETLINK+ address family. Every netlink
protocol uses its own protocol number (e.g. +NETLINK_ROUTE+,
+NETLINK_NETFILTER+, etc). Its addressing schema is based on a 32 bit
port number, formerly referred to as PID, which uniquely identifies
each peer.
[[core_addressing]]
=== Addressing
The netlink address (port) consists of a 32bit integer. Port 0 (zero)
is reserved for the kernel and refers to the kernel side socket of each
netlink protocol family. Other port numbers usually refer to user space
owned sockets, although this is not enforced.
NOTE: In the beginning, it was common practice to use the process
identifier (PID) as the local port number. This became unpractical
with the introduction of threaded netlink applications and
applications requiring multiple sockets. Therefore libnl generates
unique port numbers based on the process identifier and adds an
offset to it allowing for multiple sockets to be used. The initial
socket will still equal to the process identifier for backwards
compatibility reasons.
image:addressing.png["Addressing Example"]
The above figure illustrates three applications and the kernel side
exposing two kernel side sockets. It shows the common netlink use
cases:
* User space to kernel
* User space to user space
* Listening to kernel multicast notifications
.User Space to Kernel
The most common form of netlink usage is for a user space application
to send requests to the kernel and process the reply which is either
an error message or a success notification.
["mscgen"]
--------
msc {
App1,App2,Kernel;
App1=>Kernel [label="request (src=11, dst=0)"];
Kernel<=App1 [label="reply (src=0, dst=11)"];
...;
App2=>Kernel [label="request (src=21, dst=0)"];
Kernel<=App2 [label="reply (src=0, dst=21)"];
}
--------
.User Space to User Space
Netlink may also be used as an IPC mechanism to communicate between user
space applications directly. Communication is not limited to two peers,
any number of peers may communicate with each other and multicasting
capabilities allow to reach multiple peers with a single message.
In order for the sockets to be visible to each other, both sockets must
be created for the same netlink protocol family.
["mscgen"]
--------
msc {
App2,App3;
App2=>App3 [label="request (src=22, dst=31)"];
App2<=App3 [label="reply (src=31, dst=22)"];
...;
}
--------
.User space listening to kernel notifications
This form of netlink communication is typically found in user space
daemons that need to act on certain kernel events. Such daemons will
typically maintain a netlink socket subscribed to a multicast group that
is used by the kernel to notify interested user space parties about
specific events.
["mscgen"]
--------
msc {
Kernel,App3;
Kernel=>App3 [label="notification (src=0, group=foo)"];
...;
}
--------
Use of multicasting is preferred over direct addressing due to the
flexibility in exchanging the user space component at any time without
the kernel noticing.
[[core_msg_format]]
=== Message Format
A netlink protocol is typically based on messages and consists of the
netlink message header (+struct nlmsghdr+) plus the payload attached
to it. The payload can consist of arbitrary data but usually contains
a fixed size protocol specific header followed by a stream of
attributes.
.Netlink message header (struct nlmsghdr)
image:nlmsghdr.png[align="center", alt="Netlink Message Header"]
Total Length (32bit)::
Total length of the message in bytes including the netlink message header.
Message Type (16bit)::
The message type specifies the type of payload the message is carrying.
Several standard message types are defined by the netlink protocol.
Additional message types may be defined by each protocol family. See
<<core_msg_types>> for additional information.
Message Flags (16bit)::
The message flags may be used to modify the behaviour of a message type.
See section <<core_msg_flags>> for a list of standard message flags.
Sequence Number (32bit)::
The sequence number is optional and may be used to allow referring to
a previous message, e.g. an error message can refer to the original
request causing the error.
Port Number (32bit)::
The port number specifies the peer to which the message should be delivered
to. If not specified, the message will be delivered to the first matching
kernel side socket of the same protocol family.
[[core_msg_types]]
=== Message Types
Netlink differs between requests, notifications, and replies. Requests
are messages which have the +NLM_F_REQUEST+ flag set and are meant to
request an action from the receiver. A request is typically sent from
a userspace process to the kernel. While not strictly enforced, requests
should carry a sequence number incremented for each request sent.
Depending on the nature of the request, the receiver may reply to the
request with another netlink message. The sequence number of a reply
must match the sequence number of the request it relates to.
Notifications are of informal nature and no reply is expected, therefore
the sequence number is typically set to 0.
["mscgen"]
--------
msc {
A,B;
A=>B [label="GET (seq=1, NLM_F_REQUEST)"];
A<=B [label="PUT (seq=1)"];
...;
A<=B [label="NOTIFY (seq=0)"];
}
--------
The type of message is primarly identified by its 16 bit message type set
in the message header. The following standard message types are defined:
- +NLMSG_NOOP+ - No operation, message must be discarded
- +NLMSG_ERROR+ - Error message or ACK, see <<core_errmsg>>
respectively <<core_msg_ack>>
- +NLMSG_DONE+ - End of multipart sequence, see <<core_multipart>>
- +NLMSG_OVERRUN+ - Overrun notification (Error)
Every netlink protocol is free to define own message types. Note that
message type values +< NLMSG_MIN_TYPE (0x10)+ are reserved and may
not be used.
It is common practice to use own message types to implement RPC schemas.
Suppose the goal of the netlink protocol you are implementing is allow
configuration of a particular network device, therefore you want to
provide read/write access to various configuration options. The typical
"netlink way" of doing this would be to define two message types
+MSG_SETCFG+, +MSG_GETCFG+:
[source,c]
--------
#define MSG_SETCFG 0x11
#define MSG_GETCFG 0x12
--------
Sending a +MSG_GETCFG+ request message will typically trigger a reply
with the message type +MSG_SETCFG+ containing the current configuration.
In object oriented terms one would describe this as "the kernel sets
the local copy of the configuration in userspace".
["mscgen"]
--------
msc {
A,B;
A=>B [label="MSG_GETCFG (seq=1, NLM_F_REQUEST)"];
A<=B [label="MSG_SETCFG (seq=1)"];
}
--------
The configuration may be changed by sending a +MSG_SETCFG+ which will
be responded to with either a ACK (see <<core_msg_ack>>)
or a error message (see <<core_errmsg>>).
["mscgen"]
--------
msc {
A,B;
A=>B [label="MSG_SETCFG (seq=1, NLM_F_REQUEST, NLM_F_ACK)"];
A<=B [label="ACK (seq=1)"];
}
--------
Optionally, the kernel may send out notifications for configuration
changes allowing userspace to listen for changes instead of polling
frequently. Notifications typically reuse an existing message type
and rely on the application using a separate socket to differ between
requests and notifications but you may also specify a separate message
type.
["mscgen"]
--------
msc {
A,B;
A<=B [label="MSG_SETCFG (seq=0)"];
}
--------
[[core_multipart]]
==== Multipart Messages
Although in theory a netlink message can be up to 4GiB in size. The socket
buffers are very likely not large enough to hold message of such sizes.
Therefore it is common to limit messages to one page size (PAGE_SIZE) and
use the multipart mechanism to split large pieces of data into several
messages. A multipart message has the flag +NLM_F_MULTI+ set and the
receiver is expected to continue receiving and parsing until the special
message type +NLMSG_DONE+ is received.
Multipart messages unlike fragmented ip packets must not be reassmbled
even though it is perfectly legal to do so if the protocols wishes to
work this way. Often multipart message are used to send lists or trees
of objects were each multipart message simply carries multiple objects
allow for each message to be parsed independently.
["mscgen"]
--------
msc {
A,B;
A=>B [label="GET (seq=1, NLM_F_REQUEST)"];
A<=B [label="PUT (seq=1, NLM_F_MULTI)"];
...;
A<=B [label="PUT (seq=1, NLM_F_MULTI)"];
A<=B [label="NLMSG_DONE (seq=1)"];
}
--------
[[core_errmsg]]
==== Error Message
Error messages can be sent in response to a request. Error messages must
use the standard message type +NLMSG_ERROR+. The payload consists of a
error code and the original netlink mesage header of the request.
image:nlmsgerr.png["Netlink Errror Message header"]
Error messages should set the sequence number to the sequence number
of the request which caused the error.
["mscgen"]
--------
msc {
A,B;
A=>B [label="GET (seq=1, NLM_F_REQUEST)"];
A<=B [label="NLMSG_ERROR code=EINVAL (seq=1)"];
}
--------
[[core_msg_ack]]
==== ACKs
A sender can request an ACK message to be sent back for each request
processed by setting the +NLM_F_ACK+ flag in the request. This is typically
used to allow the sender to synchronize further processing until the
request has been processed by the receiver.
["mscgen"]
--------
msc {
A,B;
A=>B [label="GET (seq=1, NLM_F_REQUEST | NLM_F_ACK)"];
A<=B [label="ACK (seq=1)"];
}
--------
ACK messages also use the message type +NLMSG_ERROR+ and payload
format but the error code is set to 0.
[[core_msg_flags]]
==== Message Flags
The following standard flags are defined
[source,c]
--------
#define NLM_F_REQUEST 1
#define NLM_F_MULTI 2
#define NLM_F_ACK 4
#define NLM_F_ECHO 8
--------
- `NLM_F_REQUEST` - Message is a request, see <<core_msg_types>>.
- `NLM_F_MULTI` - Multipart message, see <<core_multipart>>
- `NLM_F_ACK` - ACK message requested, see <<core_msg_ack>>.
- `NLM_F_ECHO` - Request to echo the request.
The flag +NLM_F_ECHO+ is similar to the `NLM_F_ACK` flag. It can be
used in combination with `NLM_F_REQUEST` and causes a notification
which is sent as a result of a request to also be sent to the sender
regardless of whether the sender has subscribed to the corresponding
multicast group or not. See <<core_multicast>>
Additional universal message flags are defined which only apply for
+GET+ requests:
[source,c]
--------
#define NLM_F_ROOT 0x100
#define NLM_F_MATCH 0x200
#define NLM_F_ATOMIC 0x400
#define NLM_F_DUMP (NLM_F_ROOT|NLM_F_MATCH)
--------
- `NLM_F_ROOT` - Return based on root of tree.
- `NLM_F_MATCH` - Return all matching entries.
- `NLM_F_ATOMIC` - Obsoleted, once used to request an atomic operation.
- `NLM_F_DUMP` - Return a list of all objects
(`NLM_F_ROOT`|`NLM_F_MATCH`).
Use of these flags is completely optional and many netlink protocols only
make use of the `NLM_F_DUMP` flag which typically requests the receiver
to send a list of all objects in the context of the message type as a
sequence of multipart messages (see <<core_multipart>>).
Another set of flags exist related to `NEW` or `SET` requests. These
flags are mutually exclusive to the `GET` flags:
[source,c]
--------
#define NLM_F_REPLACE 0x100
#define NLM_F_EXCL 0x200
#define NLM_F_CREATE 0x400
#define NLM_F_APPEND 0x800
--------
- `NLM_F_REPLACE` - Replace an existing object if it exists.
- `NLM_F_EXCL` - Do not update object if it exists already.
- `NLM_F_CREATE` - Create object if it does not exist yet.
- `NLM_F_APPEND` - Add object at end of list.
Behaviour of these flags may differ slightly between different netlink
protocols.
[[core_seq_num]]
=== Sequence Numbers
Netlink allows the use of sequence numbers to help relate replies to
requests. It should be noted that unlike in protocols such as TCP
there is no strict enforcment of the sequence number. The sole purpose
of sequence numbers is to assist a sender in relating replies to the
corresponding requests. See <<core_msg_types>> for more information.
Sequence numbers are managed on a per socket basis, see
<<core_sk_seq_num>> for more information on how to use sequence numbers.
[[core_multicast]]
=== Multicast Groups
TODO
See <<core_sk_multicast>>
[[core_sockets]]
== Netlink Sockets
In order to use the netlink protocol, a netlink socket is required.
Each socket defines an independent context for sending and receiving of
messages. An application may make use multiple sockets, e.g. a socket to
send requests and receive the replies and another socket subscribed to a
multicast group to receive notifications.
=== Socket structure (struct nl_sock)
The netlink socket and all related attributes including the actual file
descriptor are represented by +struct nl_sock+.
[source,c]
--------
#include <netlink/socket.h>
struct nl_sock *nl_socket_alloc(void)
void nl_socket_free(struct nl_sock *sk)
--------
The application must allocate an instance of +struct nl_sock+ for each
netlink socket it wishes to use.
[[core_sk_seq_num]]
=== Sequence Numbers
The library will automatically take care of sequence number handling
for the application. A sequence number counter is stored in the
socket structure which is used and incremented automatically when a
message needs to be sent which is expected to generate a reply such as
an error or any other message type that needs to be related to the
original message.
Alternatively, the counter can be used directly via the function
nl_socket_use_seq(). It will return the current value of the counter
and increment it by one afterwards.
[source,c]
--------
#include <netlink/socket.h>
unsigned int nl_socket_use_seq(struct nl_sock *sk);
--------
Most applications will not want to deal with sequence number handling
themselves though. When using nl_send_auto() the sequence number is
filled in automatically and matched again when a reply is received. See
section <<core_send_recv>> for more information.
This behaviour can and must be disabled if the netlink protocol
implemented does not use a request/reply model, e.g. when a socket is
used to receive notification messages.
[source,c]
--------
#include <netlink/socket.h>
void nl_socket_disable_seq_check(struct nl_sock *sk);
--------
For more information on the theory behind netlink sequence numbers,
see section <<core_seq_num>>.
[[core_sk_multicast]]
=== Multicast Group Subscriptions
Each socket can subscribe to any number of multicast groups of the
netlink protocol it is connected to. The socket will then receive a
copy of each message sent to any of the groups. Multicast groups are
commonly used to implement event notifications.
Prior to kernel 2.6.14 the group subscription was performed using a
bitmask which limited the number of groups per protocol family to 32.
This outdated interface can still be accessed via the function
nl_join_groups() even though it is not recommended for new code.
[source,c]
--------
#include <netlink/socket.h>
void nl_join_groups(struct nl_sock *sk, int bitmask);
--------
Starting with 2.6.14 a new method was introduced which supports subscribing
to an almost infinite number of multicast groups.
[source,c]
--------
#include <netlink/socket.h>
int nl_socket_add_memberships(struct nl_sock *sk, int group, ...);
int nl_socket_drop_memberships(struct nl_sock *sk, int group, ...);
--------
==== Multicast Example
[source,c]
--------
#include <netlink/netlink.h>
#include <netlink/socket.h>
#include <netlink/msg.h>
/*
* This function will be called for each valid netlink message received
* in nl_recvmsgs_default()
*/
static int my_func(struct nl_msg *msg, void *arg)
{
return 0;
}
struct nl_sock *sk;
/* Allocate a new socket */
sk = nl_socket_alloc();
/*
* Notifications do not use sequence numbers, disable sequence number
* checking.
*/
nl_socket_disable_seq_check(sk);
/*
* Define a callback function, which will be called for each notification
* received
*/
nl_socket_modify_cb(sk, NL_CB_VALID, NL_CB_CUSTOM, my_func, NULL);
/* Connect to routing netlink protocol */
nl_connect(sk, NETLINK_ROUTE);
/* Subscribe to link notifications group */
nl_socket_add_memberships(sk, RTNLGRP_LINK, 0);
/*
* Start receiving messages. The function nl_recvmsgs_default() will block
* until one or more netlink messages (notification) are received which
* will be passed on to my_func().
*/
while (1)
nl_recvmsgs_default(sock);
--------
[[core_sk_cb]]
=== Modifiying Socket Callback Configuration
See <<core_cb>> for more information on
callback hooks and overwriting capabilities.
Each socket is assigned a callback configuration which controls the
behaviour of the socket. This is f.e. required to have a separate
message receive function per socket. It is perfectly legal to share
callback configurations between sockets though.
The following functions can be used to access and set the callback
configuration of a socket:
[source,c]
--------
#include <netlink/socket.h>
struct nl_cb *nl_socket_get_cb(const struct nl_sock *sk);
void nl_socket_set_cb(struct nl_sock *sk, struct nl_cb *cb);
--------
Additionaly a shortcut exists to modify the callback configuration
assigned to a socket directly:
[source,c]
--------
#include <netlink/socket.h>
int nl_socket_modify_cb(struct nl_sock *sk, enum nl_cb_type type, enum nl_cb_kind kind,
nl_recvmsg_msg_cb_t func, void *arg);
--------
.Example:
[source,c]
--------
#include <netlink/socket.h>
// Call my_input() for all valid messages received in socket sk
nl_socket_modify_cb(sk, NL_CB_VALID, NL_CB_CUSTOM, my_input, NULL);
--------
=== Socket Attributes
.Local Port
The local port number uniquely identifies the socket and is used to
address it. A unique local port is generated automatically when the
socket is allocated. It will consist of the Process ID (22 bits) and a
random number (10 bits) thus allowing up to 1024 sockets per process.
[source,c]
--------
#include <netlink/socket.h>
uint32_t nl_socket_get_local_port(const struct nl_sock *sk);
void nl_socket_set_local_port(struct nl_sock *sk, uint32_t port);
--------
See section <<core_addressing>> for more information on port numbers.
CAUTION: Overwriting the local port is possible but you have to ensure
that the provided value is unique and no other socket in any other
application is using the same value.
.Peer Port
A peer port can be assigned to the socket which will result in all
unicast messages sent over the socket to be addresses to the peer. If
no peer is specified, the message is sent to the kernel which will try
to automatically bind the socket to a kernel side socket of the same
netlink protocol family. It is common practice not to bind the socket
to a peer port as typically only one kernel side socket exists per
netlink protocol family.
[source,c]
--------
#include <netlink/socket.h>
uint32_t nl_socket_get_peer_port(const struct nl_sock *sk);
void nl_socket_set_peer_port(struct nl_sock *sk, uint32_t port);
--------
See section <<core_addressing>> for more information on port numbers.
.File Descriptor
Netlink uses the BSD socket interface, therefore a file descriptor is
behind each socket and you may use it directly.
[source,c]
--------
#include <netlink/socket.h>
int nl_socket_get_fd(const struct nl_sock *sk);
--------
If a socket is used to only receive notifications it usually is best
to put the socket in non-blocking mode and periodically poll for new
notifications.
[source,c]
--------
#include <netlink/socket.h>
int nl_socket_set_nonblocking(const struct nl_sock *sk);
--------
.Send/Receive Buffer Size
The socket buffer is used to queue netlink messages between sender and
receiver. The size of these buffers specifies the maximum size you
will be able to write() to a netlink socket, i.e. it will indirectly
define the maximum message size. The default is 32KiB.
[source,c]
--------
#include <netlink/socket.h>
int nl_socket_set_buffer_size(struct nl_sock *sk, int rx, int tx);
--------
[[core_sk_cred]]
.Enable/Disable Credentials
TODO
[source,c]
--------
#include <netlink/socket.h>
int nl_socket_set_passcred(struct nl_sock *sk, int state);
--------
.Enable/Disable Auto-ACK Mode
The following functions allow to enable/disable Auto-ACK mode on a socket.
See <<core_auto_ack>> for more information on what implications that has.
Auto-ACK mode is enabled by default.
[source,c]
--------
#include <netlink/socket.h>
void nl_socket_enable_auto_ack(struct nl_sock *sk);
void nl_socket_disable_auto_ack(struct nl_sock *sk);
--------
.Enable/Disable Message Peeking
If enabled, message peeking causes nl_recv() to try and use MSG_PEEK
to retrieve the size of the next message received and allocate a
buffer of that size. Message peeking is enabled by default but can be
disabled using the following function:
[source,c]
--------
#include <netlink/socket.h>
void nl_socket_enable_msg_peek(struct nl_sock *sk);
void nl_socket_disable_msg_peek(struct nl_sock *sk);
--------
.Enable/Disable Receival of Packet Information
If enabled, each received netlink message from the kernel will include
an additional struct nl_pktinfo in the control message. The following
function can be used to enable/disable receival of packet information.
[source,c]
--------
#include <netlink/socket.h>
int nl_socket_recv_pktinfo(struct nl_sock *sk, int state);
--------
CAUTION: Processing of NETLINK_PKTINFO has not been implemented yet.
[[core_send_recv]]
== Sending and Receiving of Messages / Data
[[core_send]]
=== Sending Messages
The standard method of sending a netlink message over a netlink socket
is to use the function nl_send_auto(). It will automatically complete
the netlink message by filling the missing bits and pieces in the
netlink message header and will deal with addressing based on the
options and address set in the netlink socket. The message is then
passed on to nl_send().
If the default sending semantics implemented by nl_send() do not suit
the application, it may overwrite the sending function nl_send() by
specifying an own implementation using the function
nl_cb_overwrite_send().
[source,c]
--------
nl_send_auto(sk, msg)
|
|-----> nl_complete_msg(sk, msg)
|
|
| Own send function specified via nl_cb_overwrite_send()
|- - - - - - - - - - - - - - - - - - - -
v v
nl_send(sk, msg) send_func()
--------
.Using nl_send()
If you do not require any of the automatic message completion
functionality you may use nl_send() directly but beware that any
internal calls to nl_send_auto() by the library to send netlink
messages will still use nl_send(). Therefore if you wish to use any
higher level interfaces and the behaviour of nl_send() is to your
dislike then you must overwrite the nl_send() function via
nl_cb_overwrite_send()
The purpose of nl_send() is to embed the netlink message into a iovec
structure and pass it on to nl_send_iovec().
[source,c]
--------
nl_send(sk, msg)
|
v
nl_send_iovec(sk, msg, iov, iovlen)
--------
.Using nl_send_iovec()
nl_send_iovec() expects a finalized netlink message and fills out the
struct msghdr used for addressing. It will first check if the struct
nl_msg is addressed to a specific peer (see nlmsg_set_dst()). If not,
it will try to fall back to the peer address specified in the socket
(see nl_socket_set_peer_port(). Otherwise the message will be sent
unaddressed and it is left to the kernel to find the correct peer.
nl_send_iovec() also adds credentials if present and enabled
(see <<core_sk_cred>>).
The message is then passed on to nl_sendmsg().
[source,c]
--------
nl_send_iovec(sk, msg, iov, iovlen)
|
v
nl_sendmsg(sk, msg, msghdr)
--------
.Using nl_sendmsg()
nl_sendmsg() expects a finalized netlink message and an optional
struct msghdr containing the peer address. It will copy the local
address as defined in the socket (see nl_socket_set_local_port()) into
the netlink message header.
At this point, construction of the message finished and it is ready to
be sent.
[source,c]
--------
nl_sendmsg(sk, msg, msghdr)
|- - - - - - - - - - - - - - - - - - - - v
| NL_CB_MSG_OUT()
|<- - - - - - - - - - - - - - - - - - - -+
v
sendmsg()
--------
Before sending the application has one last chance to modify the
message. It is passed to the NL_CB_MSG_OUT callback function which
may inspect or modify the message and return an error code. If this
error code is NL_OK the message is sent using sendmsg() resulting in
the number of bytes written being returned. Otherwise the message
sending process is aborted and the error code specified by the
callback function is returned. See <<core_sk_cb>> for more information
on how to set callbacks.
.Sending Raw Data with nl_sendto()
If you wish to send raw data over a netlink socket, the following
function will pass on any buffer provided to it directly to sendto():
[source,c]