forked from openvswitch/ovs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnetlink-socket.c
1808 lines (1613 loc) · 56.6 KB
/
netlink-socket.c
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
/*
* Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <config.h>
#include "netlink-socket.h"
#include <errno.h>
#include <inttypes.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include "coverage.h"
#include "dynamic-string.h"
#include "hash.h"
#include "hmap.h"
#include "netlink.h"
#include "netlink-protocol.h"
#include "odp-netlink.h"
#include "ofpbuf.h"
#include "ovs-thread.h"
#include "poll-loop.h"
#include "seq.h"
#include "socket-util.h"
#include "util.h"
#include "openvswitch/vlog.h"
VLOG_DEFINE_THIS_MODULE(netlink_socket);
COVERAGE_DEFINE(netlink_overflow);
COVERAGE_DEFINE(netlink_received);
COVERAGE_DEFINE(netlink_recv_jumbo);
COVERAGE_DEFINE(netlink_sent);
/* Linux header file confusion causes this to be undefined. */
#ifndef SOL_NETLINK
#define SOL_NETLINK 270
#endif
#ifdef _WIN32
static struct ovs_mutex portid_mutex = OVS_MUTEX_INITIALIZER;
static uint32_t g_last_portid = 0;
/* Port IDs must be unique! */
static uint32_t
portid_next(void)
OVS_GUARDED_BY(portid_mutex)
{
g_last_portid++;
return g_last_portid;
}
#endif /* _WIN32 */
/* A single (bad) Netlink message can in theory dump out many, many log
* messages, so the burst size is set quite high here to avoid missing useful
* information. Also, at high logging levels we log *all* Netlink messages. */
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 600);
static uint32_t nl_sock_allocate_seq(struct nl_sock *, unsigned int n);
static void log_nlmsg(const char *function, int error,
const void *message, size_t size, int protocol);
#ifdef _WIN32
static int get_sock_pid_from_kernel(struct nl_sock *sock);
#endif
/* Netlink sockets. */
struct nl_sock {
#ifdef _WIN32
HANDLE handle;
OVERLAPPED overlapped;
DWORD read_ioctl;
#else
int fd;
#endif
uint32_t next_seq;
uint32_t pid;
int protocol;
unsigned int rcvbuf; /* Receive buffer size (SO_RCVBUF). */
};
/* Compile-time limit on iovecs, so that we can allocate a maximum-size array
* of iovecs on the stack. */
#define MAX_IOVS 128
/* Maximum number of iovecs that may be passed to sendmsg, capped at a
* minimum of _XOPEN_IOV_MAX (16) and a maximum of MAX_IOVS.
*
* Initialized by nl_sock_create(). */
static int max_iovs;
static int nl_pool_alloc(int protocol, struct nl_sock **sockp);
static void nl_pool_release(struct nl_sock *);
/* Creates a new netlink socket for the given netlink 'protocol'
* (NETLINK_ROUTE, NETLINK_GENERIC, ...). Returns 0 and sets '*sockp' to the
* new socket if successful, otherwise returns a positive errno value. */
int
nl_sock_create(int protocol, struct nl_sock **sockp)
{
static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
struct nl_sock *sock;
#ifndef _WIN32
struct sockaddr_nl local, remote;
#endif
socklen_t local_size;
int rcvbuf;
int retval = 0;
if (ovsthread_once_start(&once)) {
int save_errno = errno;
errno = 0;
max_iovs = sysconf(_SC_UIO_MAXIOV);
if (max_iovs < _XOPEN_IOV_MAX) {
if (max_iovs == -1 && errno) {
VLOG_WARN("sysconf(_SC_UIO_MAXIOV): %s", ovs_strerror(errno));
}
max_iovs = _XOPEN_IOV_MAX;
} else if (max_iovs > MAX_IOVS) {
max_iovs = MAX_IOVS;
}
errno = save_errno;
ovsthread_once_done(&once);
}
*sockp = NULL;
sock = xmalloc(sizeof *sock);
#ifdef _WIN32
sock->handle = CreateFile(OVS_DEVICE_NAME_USER,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING,
FILE_FLAG_OVERLAPPED, NULL);
if (sock->handle == INVALID_HANDLE_VALUE) {
VLOG_ERR("fcntl: %s", ovs_lasterror_to_string());
goto error;
}
memset(&sock->overlapped, 0, sizeof sock->overlapped);
sock->overlapped.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (sock->overlapped.hEvent == NULL) {
VLOG_ERR("fcntl: %s", ovs_lasterror_to_string());
goto error;
}
/* Initialize the type/ioctl to Generic */
sock->read_ioctl = OVS_IOCTL_READ;
#else
sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
if (sock->fd < 0) {
VLOG_ERR("fcntl: %s", ovs_strerror(errno));
goto error;
}
#endif
sock->protocol = protocol;
sock->next_seq = 1;
rcvbuf = 1024 * 1024;
#ifdef _WIN32
sock->rcvbuf = rcvbuf;
retval = get_sock_pid_from_kernel(sock);
if (retval != 0) {
goto error;
}
#else
if (setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUFFORCE,
&rcvbuf, sizeof rcvbuf)) {
/* Only root can use SO_RCVBUFFORCE. Everyone else gets EPERM.
* Warn only if the failure is therefore unexpected. */
if (errno != EPERM) {
VLOG_WARN_RL(&rl, "setting %d-byte socket receive buffer failed "
"(%s)", rcvbuf, ovs_strerror(errno));
}
}
retval = get_socket_rcvbuf(sock->fd);
if (retval < 0) {
retval = -retval;
goto error;
}
sock->rcvbuf = retval;
/* Connect to kernel (pid 0) as remote address. */
memset(&remote, 0, sizeof remote);
remote.nl_family = AF_NETLINK;
remote.nl_pid = 0;
if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
VLOG_ERR("connect(0): %s", ovs_strerror(errno));
goto error;
}
/* Obtain pid assigned by kernel. */
local_size = sizeof local;
if (getsockname(sock->fd, (struct sockaddr *) &local, &local_size) < 0) {
VLOG_ERR("getsockname: %s", ovs_strerror(errno));
goto error;
}
if (local_size < sizeof local || local.nl_family != AF_NETLINK) {
VLOG_ERR("getsockname returned bad Netlink name");
retval = EINVAL;
goto error;
}
sock->pid = local.nl_pid;
#endif
*sockp = sock;
return 0;
error:
if (retval == 0) {
retval = errno;
if (retval == 0) {
retval = EINVAL;
}
}
#ifdef _WIN32
if (sock->overlapped.hEvent) {
CloseHandle(sock->overlapped.hEvent);
}
if (sock->handle != INVALID_HANDLE_VALUE) {
CloseHandle(sock->handle);
}
#else
if (sock->fd >= 0) {
close(sock->fd);
}
#endif
free(sock);
return retval;
}
/* Creates a new netlink socket for the same protocol as 'src'. Returns 0 and
* sets '*sockp' to the new socket if successful, otherwise returns a positive
* errno value. */
int
nl_sock_clone(const struct nl_sock *src, struct nl_sock **sockp)
{
return nl_sock_create(src->protocol, sockp);
}
/* Destroys netlink socket 'sock'. */
void
nl_sock_destroy(struct nl_sock *sock)
{
if (sock) {
#ifdef _WIN32
if (sock->overlapped.hEvent) {
CloseHandle(sock->overlapped.hEvent);
}
CloseHandle(sock->handle);
#else
close(sock->fd);
#endif
free(sock);
}
}
#ifdef _WIN32
/* Reads the pid for 'sock' generated in the kernel datapath. The function
* uses a separate IOCTL instead of a transaction semantic to avoid unnecessary
* message overhead. */
static int
get_sock_pid_from_kernel(struct nl_sock *sock)
{
uint32_t pid = 0;
int retval = 0;
DWORD bytes = 0;
if (!DeviceIoControl(sock->handle, OVS_IOCTL_GET_PID,
NULL, 0, &pid, sizeof(pid),
&bytes, NULL)) {
retval = EINVAL;
} else {
if (bytes < sizeof(pid)) {
retval = EINVAL;
} else {
sock->pid = pid;
}
}
return retval;
}
#endif /* _WIN32 */
#ifdef _WIN32
static int __inline
nl_sock_mcgroup(struct nl_sock *sock, unsigned int multicast_group, bool join)
{
struct ofpbuf request;
uint64_t request_stub[128];
struct ovs_header *ovs_header;
struct nlmsghdr *nlmsg;
int error;
ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
nl_msg_put_genlmsghdr(&request, 0, OVS_WIN_NL_CTRL_FAMILY_ID, 0,
OVS_CTRL_CMD_MC_SUBSCRIBE_REQ,
OVS_WIN_CONTROL_VERSION);
ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
ovs_header->dp_ifindex = 0;
nl_msg_put_u32(&request, OVS_NL_ATTR_MCAST_GRP, multicast_group);
nl_msg_put_u8(&request, OVS_NL_ATTR_MCAST_JOIN, join ? 1 : 0);
error = nl_sock_send(sock, &request, true);
ofpbuf_uninit(&request);
return error;
}
#endif
/* Tries to add 'sock' as a listener for 'multicast_group'. Returns 0 if
* successful, otherwise a positive errno value.
*
* A socket that is subscribed to a multicast group that receives asynchronous
* notifications must not be used for Netlink transactions or dumps, because
* transactions and dumps can cause notifications to be lost.
*
* Multicast group numbers are always positive.
*
* It is not an error to attempt to join a multicast group to which a socket
* already belongs. */
int
nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
{
#ifdef _WIN32
/* Set the socket type as a "multicast" socket */
sock->read_ioctl = OVS_IOCTL_READ_EVENT;
int error = nl_sock_mcgroup(sock, multicast_group, true);
if (error) {
sock->read_ioctl = OVS_IOCTL_READ;
VLOG_WARN("could not join multicast group %u (%s)",
multicast_group, ovs_strerror(error));
return error;
}
#else
if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
&multicast_group, sizeof multicast_group) < 0) {
VLOG_WARN("could not join multicast group %u (%s)",
multicast_group, ovs_strerror(errno));
return errno;
}
#endif
return 0;
}
#ifdef _WIN32
int
nl_sock_subscribe_packets(struct nl_sock *sock)
{
int error;
if (sock->read_ioctl != OVS_IOCTL_READ) {
return EINVAL;
}
error = nl_sock_subscribe_packet__(sock, true);
if (error) {
VLOG_WARN("could not unsubscribe packets (%s)",
ovs_strerror(errno));
return error;
}
sock->read_ioctl = OVS_IOCTL_READ_PACKET;
return 0;
}
int
nl_sock_unsubscribe_packets(struct nl_sock *sock)
{
ovs_assert(sock->read_ioctl == OVS_IOCTL_READ_PACKET);
int error = nl_sock_subscribe_packet__(sock, false);
if (error) {
VLOG_WARN("could not subscribe to packets (%s)",
ovs_strerror(errno));
return error;
}
sock->read_ioctl = OVS_IOCTL_READ;
return 0;
}
int
nl_sock_subscribe_packet__(struct nl_sock *sock, bool subscribe)
{
struct ofpbuf request;
uint64_t request_stub[128];
struct ovs_header *ovs_header;
struct nlmsghdr *nlmsg;
int error;
ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
nl_msg_put_genlmsghdr(&request, 0, OVS_WIN_NL_CTRL_FAMILY_ID, 0,
OVS_CTRL_CMD_PACKET_SUBSCRIBE_REQ,
OVS_WIN_CONTROL_VERSION);
ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
ovs_header->dp_ifindex = 0;
nl_msg_put_u8(&request, OVS_NL_ATTR_PACKET_SUBSCRIBE, subscribe ? 1 : 0);
nl_msg_put_u32(&request, OVS_NL_ATTR_PACKET_PID, sock->pid);
error = nl_sock_send(sock, &request, true);
ofpbuf_uninit(&request);
return error;
}
#endif
/* Tries to make 'sock' stop listening to 'multicast_group'. Returns 0 if
* successful, otherwise a positive errno value.
*
* Multicast group numbers are always positive.
*
* It is not an error to attempt to leave a multicast group to which a socket
* does not belong.
*
* On success, reading from 'sock' will still return any messages that were
* received on 'multicast_group' before the group was left. */
int
nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
{
#ifdef _WIN32
int error = nl_sock_mcgroup(sock, multicast_group, false);
if (error) {
VLOG_WARN("could not leave multicast group %u (%s)",
multicast_group, ovs_strerror(error));
return error;
}
sock->read_ioctl = OVS_IOCTL_READ;
#else
if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
&multicast_group, sizeof multicast_group) < 0) {
VLOG_WARN("could not leave multicast group %u (%s)",
multicast_group, ovs_strerror(errno));
return errno;
}
#endif
return 0;
}
static int
nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg,
uint32_t nlmsg_seq, bool wait)
{
struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
int error;
nlmsg->nlmsg_len = msg->size;
nlmsg->nlmsg_seq = nlmsg_seq;
nlmsg->nlmsg_pid = sock->pid;
do {
int retval;
#ifdef _WIN32
DWORD bytes;
if (!DeviceIoControl(sock->handle, OVS_IOCTL_WRITE,
msg->data, msg->size, NULL, 0,
&bytes, NULL)) {
retval = -1;
/* XXX: Map to a more appropriate error based on GetLastError(). */
errno = EINVAL;
VLOG_DBG_RL(&rl, "fatal driver failure in write: %s",
ovs_lasterror_to_string());
} else {
retval = msg->size;
}
#else
retval = send(sock->fd, msg->data, msg->size,
wait ? 0 : MSG_DONTWAIT);
#endif
error = retval < 0 ? errno : 0;
} while (error == EINTR);
log_nlmsg(__func__, error, msg->data, msg->size, sock->protocol);
if (!error) {
COVERAGE_INC(netlink_sent);
}
return error;
}
/* Tries to send 'msg', which must contain a Netlink message, to the kernel on
* 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size, nlmsg_pid
* will be set to 'sock''s pid, and nlmsg_seq will be initialized to a fresh
* sequence number, before the message is sent.
*
* Returns 0 if successful, otherwise a positive errno value. If
* 'wait' is true, then the send will wait until buffer space is ready;
* otherwise, returns EAGAIN if the 'sock' send buffer is full. */
int
nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
{
return nl_sock_send_seq(sock, msg, nl_sock_allocate_seq(sock, 1), wait);
}
/* Tries to send 'msg', which must contain a Netlink message, to the kernel on
* 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size, nlmsg_pid
* will be set to 'sock''s pid, and nlmsg_seq will be initialized to
* 'nlmsg_seq', before the message is sent.
*
* Returns 0 if successful, otherwise a positive errno value. If
* 'wait' is true, then the send will wait until buffer space is ready;
* otherwise, returns EAGAIN if the 'sock' send buffer is full.
*
* This function is suitable for sending a reply to a request that was received
* with sequence number 'nlmsg_seq'. Otherwise, use nl_sock_send() instead. */
int
nl_sock_send_seq(struct nl_sock *sock, const struct ofpbuf *msg,
uint32_t nlmsg_seq, bool wait)
{
return nl_sock_send__(sock, msg, nlmsg_seq, wait);
}
static int
nl_sock_recv__(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
{
/* We can't accurately predict the size of the data to be received. The
* caller is supposed to have allocated enough space in 'buf' to handle the
* "typical" case. To handle exceptions, we make available enough space in
* 'tail' to allow Netlink messages to be up to 64 kB long (a reasonable
* figure since that's the maximum length of a Netlink attribute). */
struct nlmsghdr *nlmsghdr;
uint8_t tail[65536];
struct iovec iov[2];
struct msghdr msg;
ssize_t retval;
int error;
ovs_assert(buf->allocated >= sizeof *nlmsghdr);
ofpbuf_clear(buf);
iov[0].iov_base = buf->base;
iov[0].iov_len = buf->allocated;
iov[1].iov_base = tail;
iov[1].iov_len = sizeof tail;
memset(&msg, 0, sizeof msg);
msg.msg_iov = iov;
msg.msg_iovlen = 2;
/* Receive a Netlink message from the kernel.
*
* This works around a kernel bug in which the kernel returns an error code
* as if it were the number of bytes read. It doesn't actually modify
* anything in the receive buffer in that case, so we can initialize the
* Netlink header with an impossible message length and then, upon success,
* check whether it changed. */
nlmsghdr = buf->base;
do {
nlmsghdr->nlmsg_len = UINT32_MAX;
#ifdef _WIN32
DWORD bytes;
if (!DeviceIoControl(sock->handle, sock->read_ioctl,
NULL, 0, tail, sizeof tail, &bytes, NULL)) {
VLOG_DBG_RL(&rl, "fatal driver failure in transact: %s",
ovs_lasterror_to_string());
retval = -1;
/* XXX: Map to a more appropriate error. */
errno = EINVAL;
} else {
retval = bytes;
if (retval == 0) {
retval = -1;
errno = EAGAIN;
} else {
if (retval >= buf->allocated) {
ofpbuf_reinit(buf, retval);
nlmsghdr = buf->base;
nlmsghdr->nlmsg_len = UINT32_MAX;
}
memcpy(buf->data, tail, retval);
buf->size = retval;
}
}
#else
retval = recvmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
#endif
error = (retval < 0 ? errno
: retval == 0 ? ECONNRESET /* not possible? */
: nlmsghdr->nlmsg_len != UINT32_MAX ? 0
: retval);
} while (error == EINTR);
if (error) {
if (error == ENOBUFS) {
/* Socket receive buffer overflow dropped one or more messages that
* the kernel tried to send to us. */
COVERAGE_INC(netlink_overflow);
}
return error;
}
if (msg.msg_flags & MSG_TRUNC) {
VLOG_ERR_RL(&rl, "truncated message (longer than %"PRIuSIZE" bytes)",
sizeof tail);
return E2BIG;
}
if (retval < sizeof *nlmsghdr
|| nlmsghdr->nlmsg_len < sizeof *nlmsghdr
|| nlmsghdr->nlmsg_len > retval) {
VLOG_ERR_RL(&rl, "received invalid nlmsg (%"PRIuSIZE" bytes < %"PRIuSIZE")",
retval, sizeof *nlmsghdr);
return EPROTO;
}
#ifndef _WIN32
buf->size = MIN(retval, buf->allocated);
if (retval > buf->allocated) {
COVERAGE_INC(netlink_recv_jumbo);
ofpbuf_put(buf, tail, retval - buf->allocated);
}
#endif
log_nlmsg(__func__, 0, buf->data, buf->size, sock->protocol);
COVERAGE_INC(netlink_received);
return 0;
}
/* Tries to receive a Netlink message from the kernel on 'sock' into 'buf'. If
* 'wait' is true, waits for a message to be ready. Otherwise, fails with
* EAGAIN if the 'sock' receive buffer is empty.
*
* The caller must have initialized 'buf' with an allocation of at least
* NLMSG_HDRLEN bytes. For best performance, the caller should allocate enough
* space for a "typical" message.
*
* On success, returns 0 and replaces 'buf''s previous content by the received
* message. This function expands 'buf''s allocated memory, as necessary, to
* hold the actual size of the received message.
*
* On failure, returns a positive errno value and clears 'buf' to zero length.
* 'buf' retains its previous memory allocation.
*
* Regardless of success or failure, this function resets 'buf''s headroom to
* 0. */
int
nl_sock_recv(struct nl_sock *sock, struct ofpbuf *buf, bool wait)
{
return nl_sock_recv__(sock, buf, wait);
}
static void
nl_sock_record_errors__(struct nl_transaction **transactions, size_t n,
int error)
{
size_t i;
for (i = 0; i < n; i++) {
struct nl_transaction *txn = transactions[i];
txn->error = error;
if (txn->reply) {
ofpbuf_clear(txn->reply);
}
}
}
static int
nl_sock_transact_multiple__(struct nl_sock *sock,
struct nl_transaction **transactions, size_t n,
size_t *done)
{
uint64_t tmp_reply_stub[1024 / 8];
struct nl_transaction tmp_txn;
struct ofpbuf tmp_reply;
uint32_t base_seq;
struct iovec iovs[MAX_IOVS];
struct msghdr msg;
int error;
int i;
base_seq = nl_sock_allocate_seq(sock, n);
*done = 0;
for (i = 0; i < n; i++) {
struct nl_transaction *txn = transactions[i];
struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(txn->request);
nlmsg->nlmsg_len = txn->request->size;
nlmsg->nlmsg_seq = base_seq + i;
nlmsg->nlmsg_pid = sock->pid;
iovs[i].iov_base = txn->request->data;
iovs[i].iov_len = txn->request->size;
}
#ifndef _WIN32
memset(&msg, 0, sizeof msg);
msg.msg_iov = iovs;
msg.msg_iovlen = n;
do {
error = sendmsg(sock->fd, &msg, 0) < 0 ? errno : 0;
} while (error == EINTR);
for (i = 0; i < n; i++) {
struct nl_transaction *txn = transactions[i];
log_nlmsg(__func__, error, txn->request->data,
txn->request->size, sock->protocol);
}
if (!error) {
COVERAGE_ADD(netlink_sent, n);
}
if (error) {
return error;
}
ofpbuf_use_stub(&tmp_reply, tmp_reply_stub, sizeof tmp_reply_stub);
tmp_txn.request = NULL;
tmp_txn.reply = &tmp_reply;
tmp_txn.error = 0;
while (n > 0) {
struct nl_transaction *buf_txn, *txn;
uint32_t seq;
/* Find a transaction whose buffer we can use for receiving a reply.
* If no such transaction is left, use tmp_txn. */
buf_txn = &tmp_txn;
for (i = 0; i < n; i++) {
if (transactions[i]->reply) {
buf_txn = transactions[i];
break;
}
}
/* Receive a reply. */
error = nl_sock_recv__(sock, buf_txn->reply, false);
if (error) {
if (error == EAGAIN) {
nl_sock_record_errors__(transactions, n, 0);
*done += n;
error = 0;
}
break;
}
/* Match the reply up with a transaction. */
seq = nl_msg_nlmsghdr(buf_txn->reply)->nlmsg_seq;
if (seq < base_seq || seq >= base_seq + n) {
VLOG_DBG_RL(&rl, "ignoring unexpected seq %#"PRIx32, seq);
continue;
}
i = seq - base_seq;
txn = transactions[i];
/* Fill in the results for 'txn'. */
if (nl_msg_nlmsgerr(buf_txn->reply, &txn->error)) {
if (txn->reply) {
ofpbuf_clear(txn->reply);
}
if (txn->error) {
VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
error, ovs_strerror(txn->error));
}
} else {
txn->error = 0;
if (txn->reply && txn != buf_txn) {
/* Swap buffers. */
struct ofpbuf *reply = buf_txn->reply;
buf_txn->reply = txn->reply;
txn->reply = reply;
}
}
/* Fill in the results for transactions before 'txn'. (We have to do
* this after the results for 'txn' itself because of the buffer swap
* above.) */
nl_sock_record_errors__(transactions, i, 0);
/* Advance. */
*done += i + 1;
transactions += i + 1;
n -= i + 1;
base_seq += i + 1;
}
ofpbuf_uninit(&tmp_reply);
#else
error = 0;
uint8_t reply_buf[65536];
for (i = 0; i < n; i++) {
DWORD reply_len;
bool ret;
struct nl_transaction *txn = transactions[i];
struct nlmsghdr *request_nlmsg, *reply_nlmsg;
ret = DeviceIoControl(sock->handle, OVS_IOCTL_TRANSACT,
txn->request->data,
txn->request->size,
reply_buf, sizeof reply_buf,
&reply_len, NULL);
if (ret && reply_len == 0) {
/*
* The current transaction did not produce any data to read and that
* is not an error as such. Continue with the remainder of the
* transactions.
*/
txn->error = 0;
if (txn->reply) {
ofpbuf_clear(txn->reply);
}
} else if (!ret) {
/* XXX: Map to a more appropriate error. */
error = EINVAL;
VLOG_DBG_RL(&rl, "fatal driver failure: %s",
ovs_lasterror_to_string());
break;
}
if (reply_len != 0) {
if (reply_len < sizeof *reply_nlmsg) {
nl_sock_record_errors__(transactions, n, 0);
VLOG_DBG_RL(&rl, "insufficient length of reply %#"PRIu32
" for seq: %#"PRIx32, reply_len, request_nlmsg->nlmsg_seq);
break;
}
/* Validate the sequence number in the reply. */
request_nlmsg = nl_msg_nlmsghdr(txn->request);
reply_nlmsg = (struct nlmsghdr *)reply_buf;
if (request_nlmsg->nlmsg_seq != reply_nlmsg->nlmsg_seq) {
ovs_assert(request_nlmsg->nlmsg_seq == reply_nlmsg->nlmsg_seq);
VLOG_DBG_RL(&rl, "mismatched seq request %#"PRIx32
", reply %#"PRIx32, request_nlmsg->nlmsg_seq,
reply_nlmsg->nlmsg_seq);
break;
}
/* Handle errors embedded within the netlink message. */
ofpbuf_use_stub(&tmp_reply, reply_buf, sizeof reply_buf);
tmp_reply.size = sizeof reply_buf;
if (nl_msg_nlmsgerr(&tmp_reply, &txn->error)) {
if (txn->reply) {
ofpbuf_clear(txn->reply);
}
if (txn->error) {
VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
error, ovs_strerror(txn->error));
}
} else {
txn->error = 0;
if (txn->reply) {
/* Copy the reply to the buffer specified by the caller. */
if (reply_len > txn->reply->allocated) {
ofpbuf_reinit(txn->reply, reply_len);
}
memcpy(txn->reply->data, reply_buf, reply_len);
txn->reply->size = reply_len;
}
}
ofpbuf_uninit(&tmp_reply);
}
/* Count the number of successful transactions. */
(*done)++;
}
if (!error) {
COVERAGE_ADD(netlink_sent, n);
}
#endif
return error;
}
static void
nl_sock_transact_multiple(struct nl_sock *sock,
struct nl_transaction **transactions, size_t n)
{
int max_batch_count;
int error;
if (!n) {
return;
}
/* In theory, every request could have a 64 kB reply. But the default and
* maximum socket rcvbuf size with typical Dom0 memory sizes both tend to
* be a bit below 128 kB, so that would only allow a single message in a
* "batch". So we assume that replies average (at most) 4 kB, which allows
* a good deal of batching.
*
* In practice, most of the requests that we batch either have no reply at
* all or a brief reply. */
max_batch_count = MAX(sock->rcvbuf / 4096, 1);
max_batch_count = MIN(max_batch_count, max_iovs);
while (n > 0) {
size_t count, bytes;
size_t done;
/* Batch up to 'max_batch_count' transactions. But cap it at about a
* page of requests total because big skbuffs are expensive to
* allocate in the kernel. */
#if defined(PAGESIZE)
enum { MAX_BATCH_BYTES = MAX(1, PAGESIZE - 512) };
#else
enum { MAX_BATCH_BYTES = 4096 - 512 };
#endif
bytes = transactions[0]->request->size;
for (count = 1; count < n && count < max_batch_count; count++) {
if (bytes + transactions[count]->request->size > MAX_BATCH_BYTES) {
break;
}
bytes += transactions[count]->request->size;
}
error = nl_sock_transact_multiple__(sock, transactions, count, &done);
transactions += done;
n -= done;
if (error == ENOBUFS) {
VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
} else if (error) {
VLOG_ERR_RL(&rl, "transaction error (%s)", ovs_strerror(error));
nl_sock_record_errors__(transactions, n, error);
if (error != EAGAIN) {
/* A fatal error has occurred. Abort the rest of
* transactions. */
break;
}
}
}
}
static int
nl_sock_transact(struct nl_sock *sock, const struct ofpbuf *request,
struct ofpbuf **replyp)
{
struct nl_transaction *transactionp;
struct nl_transaction transaction;
transaction.request = CONST_CAST(struct ofpbuf *, request);
transaction.reply = replyp ? ofpbuf_new(1024) : NULL;
transactionp = &transaction;
nl_sock_transact_multiple(sock, &transactionp, 1);
if (replyp) {
if (transaction.error) {
ofpbuf_delete(transaction.reply);
*replyp = NULL;
} else {
*replyp = transaction.reply;
}
}
return transaction.error;
}
/* Drain all the messages currently in 'sock''s receive queue. */
int
nl_sock_drain(struct nl_sock *sock)
{
#ifdef _WIN32
return 0;
#else
return drain_rcvbuf(sock->fd);
#endif
}
/* Starts a Netlink "dump" operation, by sending 'request' to the kernel on a
* Netlink socket created with the given 'protocol', and initializes 'dump' to
* reflect the state of the operation.
*
* 'request' must contain a Netlink message. Before sending the message,
* nlmsg_len will be finalized to match request->size, and nlmsg_pid will be
* set to the Netlink socket's pid. NLM_F_DUMP and NLM_F_ACK will be set in
* nlmsg_flags.
*
* The design of this Netlink socket library ensures that the dump is reliable.
*
* This function provides no status indication. nl_dump_done() provides an
* error status for the entire dump operation.
*
* The caller must eventually destroy 'request'.
*/
void
nl_dump_start(struct nl_dump *dump, int protocol, const struct ofpbuf *request)
{
nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
ovs_mutex_init(&dump->mutex);