This repository was archived by the owner on Dec 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathWeaveMessageLayer.cpp
More file actions
2632 lines (2273 loc) · 95.1 KB
/
Copy pathWeaveMessageLayer.cpp
File metadata and controls
2632 lines (2273 loc) · 95.1 KB
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) 2019-2020 Google LLC.
* Copyright (c) 2013-2017 Nest Labs, Inc.
* All rights reserved.
*
* 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.
*/
/**
* @file
* This file implements the WeaveMessageLayer class. It manages communication
* with other Weave nodes by employing one of several Inetlayer endpoints
* to establish a communication channel with other Weave nodes.
*
*/
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <Weave/Core/WeaveCore.h>
#include <Weave/Core/WeaveMessageLayer.h>
#include <Weave/Core/WeaveExchangeMgr.h>
#include <Weave/Core/WeaveEncoding.h>
#include <Weave/Support/crypto/WeaveCrypto.h>
#include <Weave/Support/crypto/HashAlgos.h>
#include <Weave/Support/crypto/HMAC.h>
#include <Weave/Support/crypto/AESBlockCipher.h>
#include <Weave/Support/crypto/CTRMode.h>
#include <Weave/Support/logging/WeaveLogging.h>
#include <Weave/Support/ErrorStr.h>
#include <Weave/Support/CodeUtils.h>
#include <Weave/Support/WeaveFaultInjection.h>
namespace nl {
namespace Weave {
using namespace nl::Weave::Crypto;
using namespace nl::Weave::Encoding;
/**
* @def WEAVE_BIND_DETAIL_LOGGING
*
* @brief
* Use Weave Bind detailed logging for Weave communication.
*
*/
#ifndef WEAVE_BIND_DETAIL_LOGGING
#define WEAVE_BIND_DETAIL_LOGGING 1
#endif
/**
* @def WeaveBindLog(MSG, ...)
*
* @brief
* Define WeaveBindLogic to be the same as WeaveLogProgress based on
* whether both #WEAVE_BIND_DETAIL_LOGGING and #WEAVE_DETAIL_LOGGING
* are set.
*
*/
#if WEAVE_BIND_DETAIL_LOGGING && WEAVE_DETAIL_LOGGING
#define WeaveBindLog(MSG, ...) WeaveLogProgress(MessageLayer, MSG, ## __VA_ARGS__ )
#else
#define WeaveBindLog(MSG, ...)
#endif
enum
{
kKeyIdLen = 2,
kMinPayloadLen = 1
};
/**
* The Weave Message layer constructor.
*
* @note
* The class must be initialized via WeaveMessageLayer::Init()
* prior to use.
*
*/
WeaveMessageLayer::WeaveMessageLayer()
{
State = kState_NotInitialized;
}
/**
* Initialize the Weave Message layer object.
*
* @param[in] context A pointer to the InitContext object.
*
* @retval #WEAVE_NO_ERROR on successful initialization.
* @retval #WEAVE_ERROR_INVALID_ARGUMENT if the passed InitContext object is NULL.
* @retval #WEAVE_ERROR_INCORRECT_STATE if the state of the WeaveMessageLayer object is incorrect.
* @retval other errors generated from the lower Inet layer during endpoint creation.
*
*/
WEAVE_ERROR WeaveMessageLayer::Init(InitContext *context)
{
WEAVE_ERROR err = WEAVE_NO_ERROR;
VerifyOrExit(State == kState_NotInitialized, err = WEAVE_ERROR_INCORRECT_STATE);
VerifyOrExit(context != NULL, err = WEAVE_ERROR_INVALID_ARGUMENT);
State = kState_Initializing;
SystemLayer = context->systemLayer;
Inet = context->inet;
#if CONFIG_NETWORK_LAYER_BLE
mBle = context->ble;
#endif
#if WEAVE_CONFIG_PROVIDE_OBSOLESCENT_INTERFACES
if (SystemLayer == NULL)
{
SystemLayer = Inet->SystemLayer();
}
#endif // WEAVE_CONFIG_PROVIDE_OBSOLESCENT_INTERFACES
FabricState = context->fabricState;
FabricState->MessageLayer = this;
OnMessageReceived = NULL;
OnReceiveError = NULL;
OnConnectionReceived = NULL;
OnUnsecuredConnectionReceived = NULL;
OnUnsecuredConnectionCallbacksRemoved = NULL;
OnAcceptError = NULL;
OnMessageLayerActivityChange = NULL;
memset(mConPool, 0, sizeof(mConPool));
memset(mTunnelPool, 0, sizeof(mTunnelPool));
AppState = NULL;
ExchangeMgr = NULL;
SecurityMgr = NULL;
IsListening = context->listenTCP || context->listenUDP;
IncomingConIdleTimeout = WEAVE_CONFIG_DEFAULT_INCOMING_CONNECTION_IDLE_TIMEOUT;
//Internal and for Debug Only; When set, Message Layer drops message and returns.
mDropMessage = false;
mFlags = 0;
SetTCPListenEnabled(context->listenTCP);
SetUDPListenEnabled(context->listenUDP);
#if WEAVE_CONFIG_ENABLE_EPHEMERAL_UDP_PORT
SetEphemeralUDPPortEnabled(context->enableEphemeralUDPPort);
#endif
mIPv6TCPListen = NULL;
mIPv6UDP = NULL;
#if INET_CONFIG_ENABLE_IPV4
mIPv4TCPListen = NULL;
mIPv4UDP = NULL;
#endif // INET_CONFIG_ENABLE_IPV4
#if WEAVE_CONFIG_ENABLE_TARGETED_LISTEN
mIPv6UDPMulticastRcv = NULL;
#if INET_CONFIG_ENABLE_IPV4
mIPv4UDPBroadcastRcv = NULL;
#endif // INET_CONFIG_ENABLE_IPV4
#endif //WEAVE_CONFIG_ENABLE_TARGETED_LISTEN
#if WEAVE_CONFIG_ENABLE_EPHEMERAL_UDP_PORT
mIPv6EphemeralUDP = NULL;
#if INET_CONFIG_ENABLE_IPV4
mIPv4EphemeralUDP = NULL;
#endif // INET_CONFIG_ENABLE_IPV4
#endif // WEAVE_CONFIG_ENABLE_EPHEMERAL_UDP_PORT
#if WEAVE_CONFIG_ENABLE_UNSECURED_TCP_LISTEN
mUnsecuredIPv6TCPListen = NULL;
#endif
err = RefreshEndpoints();
SuccessOrExit(err);
#if CONFIG_NETWORK_LAYER_BLE
if (context->listenBLE && mBle != NULL)
{
mBle->mAppState = this;
mBle->OnWeaveBleConnectReceived = HandleIncomingBleConnection;
WeaveLogProgress(MessageLayer, "Accepting WoBLE connections");
}
else
{
WeaveLogProgress(MessageLayer, "WoBLE disabled%s", (mBle != NULL) ? " by application" : " (BLE layer not initialized)");
}
#endif // CONFIG_NETWORK_LAYER_BLE
State = kState_Initialized;
exit:
if (err != WEAVE_NO_ERROR && State == kState_Initializing)
{
Shutdown();
}
return err;
}
/**
* Shutdown the WeaveMessageLayer.
*
* Close all open Inet layer endpoints, reset all
* higher layer callbacks, member variables and objects.
* A call to Shutdown() terminates the WeaveMessageLayer
* object.
*
*/
WEAVE_ERROR WeaveMessageLayer::Shutdown()
{
CloseEndpoints();
#if CONFIG_NETWORK_LAYER_BLE
if (mBle != NULL && mBle->mAppState == this)
{
mBle->mAppState = NULL;
mBle->OnWeaveBleConnectReceived = NULL;
}
#endif // CONFIG_NETWORK_LAYER_BLE
State = kState_NotInitialized;
IsListening = false;
FabricState = NULL;
OnMessageReceived = NULL;
OnReceiveError = NULL;
OnUnsecuredConnectionReceived = NULL;
OnConnectionReceived = NULL;
OnAcceptError = NULL;
OnMessageLayerActivityChange = NULL;
memset(mConPool, 0, sizeof(mConPool));
memset(mTunnelPool, 0, sizeof(mTunnelPool));
ExchangeMgr = NULL;
AppState = NULL;
mFlags = 0;
return WEAVE_NO_ERROR;
}
#if WEAVE_CONFIG_ENABLE_TUNNELING
/**
* Send a tunneled IPv6 data message over UDP.
*
* @param[in] msgInfo A pointer to a WeaveMessageInfo object.
*
* @param[in] destAddr IPAddress of the UDP tunnel destination.
*
* @param[in] msgBuf A pointer to the PacketBuffer object holding the packet to send.
*
* @retval #WEAVE_NO_ERROR on successfully sending the message down to the network
* layer.
* @retval #WEAVE_ERROR_INVALID_ADDRESS if the destAddr is not specified or cannot be determined
* from destination node id.
* @retval errors generated from the lower Inet layer UDP endpoint during sending.
*
*/
WEAVE_ERROR WeaveMessageLayer::SendUDPTunneledMessage(const IPAddress &destAddr, WeaveMessageInfo *msgInfo, PacketBuffer *msgBuf)
{
WEAVE_ERROR res = WEAVE_NO_ERROR;
//Set message version to V2
msgInfo->MessageVersion = kWeaveMessageVersion_V2;
//Set the tunneling flag
msgInfo->Flags |= kWeaveMessageFlag_TunneledData;
res = SendMessage(destAddr, msgInfo, msgBuf);
msgBuf = NULL;
return res;
}
#endif // WEAVE_CONFIG_ENABLE_TUNNELING
/**
* Encode a Weave Message layer header into an PacketBuffer.
*
* @param[in] destAddr The destination IP Address.
*
* @param[in] destPort The destination port.
*
* @param[in] sendIntId The interface on which to send the Weave message.
*
* @param[in] msgInfo A pointer to a WeaveMessageInfo object.
*
* @param[in] payload A pointer to the PacketBuffer object that would hold the Weave message.
*
* @retval #WEAVE_NO_ERROR on successful encoding of the Weave message.
* @retval #WEAVE_ERROR_UNSUPPORTED_MESSAGE_VERSION if the Weave Message version is not supported.
* @retval #WEAVE_ERROR_INVALID_MESSAGE_LENGTH if the payload length in the message buffer is zero.
* @retval #WEAVE_ERROR_UNSUPPORTED_ENCRYPTION_TYPE if the encryption type is not supported.
* @retval #WEAVE_ERROR_MESSAGE_TOO_LONG if the encoded message would be longer than the
* requested maximum.
* @retval #WEAVE_ERROR_BUFFER_TOO_SMALL if there is not enough space before or after the
* message payload.
* @retval other errors generated by the fabric state object when fetching the session state.
*
*/
WEAVE_ERROR WeaveMessageLayer::EncodeMessage(const IPAddress &destAddr, uint16_t destPort, InterfaceId sendIntId,
WeaveMessageInfo *msgInfo, PacketBuffer *payload)
{
WEAVE_ERROR res = WEAVE_NO_ERROR;
// Set the source node identifier in the message header.
if ((msgInfo->Flags & kWeaveMessageFlag_ReuseSourceId) == 0)
msgInfo->SourceNodeId = FabricState->LocalNodeId;
// Force inclusion of the source node identifier if the destination address is not a local fabric address.
//
// Technically it should be possible to omit the source node identifier in other situations beyond the
// ones allowed for here. However it is difficult to determine exactly what the source IP
// address will be when sending a UDP packet, so we err on the side of correctness and only omit
// the source identifier if we're part of a fabric and sending to another member of the same fabric.
if (!FabricState->IsFabricAddress(destAddr))
msgInfo->Flags |= kWeaveMessageFlag_SourceNodeId;
// Force the destination node identifier to be included if it doesn't match the interface identifier in
// the destination address.
if (!destAddr.IsIPv6ULA() || IPv6InterfaceIdToWeaveNodeId(destAddr.InterfaceId()) != msgInfo->DestNodeId)
msgInfo->Flags |= kWeaveMessageFlag_DestNodeId;
// Encode the Weave message. NOTE that this results in the payload buffer containing the entire encoded message.
res = EncodeMessage(msgInfo, payload, NULL, UINT16_MAX, 0);
return res;
}
/**
* Send a Weave message using the underlying Inetlayer UDP endpoint after encoding it.
*
* @note
* The destination port used is #WEAVE_PORT.
*
* @param[in] msgInfo A pointer to a WeaveMessageInfo object containing information
* about the message to be sent.
*
* @param[in] payload A pointer to the PacketBuffer object holding the
* encoded Weave message.
*
* @retval #WEAVE_NO_ERROR on successfully sending the message down to the network layer.
* @retval errors generated from the lower Inet layer UDP endpoint during sending.
*
*/
WEAVE_ERROR WeaveMessageLayer::SendMessage(WeaveMessageInfo *msgInfo, PacketBuffer *payload)
{
return SendMessage(IPAddress::Any, msgInfo, payload);
}
/**
* Send a Weave message using the underlying Inetlayer UDP endpoint after encoding it.
*
* @note
* -The destination port used is #WEAVE_PORT.
*
* -If the destination address has not been supplied, attempt to determine it from the node identifier in
* the message header. Fail if this can't be done.
*
* -If the destination address is a fabric address for the local fabric, and the caller
* didn't specify the destination node id, extract it from the destination address.
*
* @param[in] destAddr The destination IP Address.
*
* @param[in] msgInfo A pointer to a WeaveMessageInfo object containing information
* about the message to be sent.
*
* @param[in] payload A pointer to the PacketBuffer object holding the
* encoded Weave message.
*
* @retval #WEAVE_NO_ERROR on successfully sending the message down to the network layer.
* @retval errors generated from the lower Inet layer UDP endpoint during sending.
*
*/
WEAVE_ERROR WeaveMessageLayer::SendMessage(const IPAddress &destAddr, WeaveMessageInfo *msgInfo,
PacketBuffer *payload)
{
return SendMessage(destAddr, WEAVE_PORT, INET_NULL_INTERFACEID, msgInfo, payload);
}
/**
* Send a Weave message using the underlying Inetlayer UDP endpoint after encoding it.
*
* @note
* -If the destination address has not been supplied, attempt to determine it from the node identifier in
* the message header. Fail if this can't be done.
*
* -If the destination address is a fabric address for the local fabric, and the caller
* didn't specify the destination node id, extract it from the destination address.
*
* @param[in] aDestAddr The destination IP Address.
*
* @param[in] destPort The destination port.
*
* @param[in] sendIntfId The interface on which to send the Weave message.
*
* @param[in] msgInfo A pointer to a WeaveMessageInfo object containing information
* about the message to be sent.
*
* @param[in] payload A pointer to the PacketBuffer object holding the
* encoded Weave message.
*
* @retval #WEAVE_NO_ERROR on successfully sending the message down to the network
* layer.
* @retval #WEAVE_ERROR_INVALID_ADDRESS if the destAddr is not specified or cannot be determined
* from destination node id.
* @retval errors generated from the lower Inet layer UDP endpoint during sending.
*
*/
WEAVE_ERROR WeaveMessageLayer::SendMessage(const IPAddress &aDestAddr, uint16_t destPort, InterfaceId sendIntfId,
WeaveMessageInfo *msgInfo, PacketBuffer *payload)
{
WEAVE_ERROR res = WEAVE_NO_ERROR;
IPAddress destAddr = aDestAddr;
// Determine the message destination address based on the destination nodeId.
res = SelectDestNodeIdAndAddress(msgInfo->DestNodeId, destAddr);
SuccessOrExit(res);
res = EncodeMessage(destAddr, destPort, sendIntfId, msgInfo, payload);
SuccessOrExit(res);
// on delay send, we do everything except actually send the
// message. As a result, the payload will contain the entire
// state required for sending it a bit later
if (msgInfo->Flags & kWeaveMessageFlag_DelaySend)
return WEAVE_NO_ERROR;
// Copy msg to a right-sized buffer if applicable
payload = PacketBuffer::RightSize(payload);
// Send the message using the appropriate UDP endpoint(s).
return SendMessage(destAddr, destPort, sendIntfId, payload, msgInfo->Flags);
exit:
if ((res != WEAVE_NO_ERROR) &&
(payload != NULL) &&
((msgInfo->Flags & kWeaveMessageFlag_RetainBuffer) == 0))
{
PacketBuffer::Free(payload);
}
return res;
}
bool WeaveMessageLayer::IsIgnoredMulticastSendError(WEAVE_ERROR err)
{
return err == WEAVE_NO_ERROR ||
#if WEAVE_SYSTEM_CONFIG_USE_LWIP
err == System::MapErrorLwIP(ERR_RTE)
#else
err == System::MapErrorPOSIX(ENETUNREACH) || err == System::MapErrorPOSIX(EADDRNOTAVAIL)
#endif
;
}
WEAVE_ERROR WeaveMessageLayer::FilterUDPSendError(WEAVE_ERROR err, bool isMulticast)
{
// Don't report certain types of routing errors when they occur while sending multicast packets.
// These may indicate that the underlying interface doesn't support multicast (e.g. the loopback
// interface on linux) or that the selected interface doesn't have an appropriate source address.
if (isMulticast)
{
#if WEAVE_SYSTEM_CONFIG_USE_LWIP
if (err == System::MapErrorLwIP(ERR_RTE))
{
err = WEAVE_NO_ERROR;
}
#endif // WEAVE_SYSTEM_CONFIG_USE_LWIP
#if WEAVE_SYSTEM_CONFIG_USE_SOCKETS
if (err == System::MapErrorPOSIX(ENETUNREACH) || err == System::MapErrorPOSIX(EADDRNOTAVAIL))
{
err = WEAVE_NO_ERROR;
}
#endif
}
return err;
}
/**
* Checks if error, while sending, is critical enough to report to the application.
*
* @param[in] err The #WEAVE_ERROR being checked for criticality.
*
* @return true if the error is NOT critical; false otherwise.
*
*/
bool WeaveMessageLayer::IsSendErrorNonCritical(WEAVE_ERROR err)
{
return (err == INET_ERROR_NOT_IMPLEMENTED || err == INET_ERROR_OUTBOUND_MESSAGE_TRUNCATED ||
err == INET_ERROR_MESSAGE_TOO_LONG || err == INET_ERROR_NO_MEMORY ||
WEAVE_CONFIG_IsPlatformErrorNonCritical(err));
}
/**
* Set the 'ForceRefreshUDPEndpoints' flag if needed.
*
* Based on the error returned when sending a UDP message, set a flag in the WeaveMessageLayer
* that will force a complete refresh of all UDPEndPoints the next time \c RefreshEndPoints is
* called.
*/
void WeaveMessageLayer::CheckForceRefreshUDPEndPointsNeeded(WEAVE_ERROR err)
{
// On some sockets-based systems, the OS will invalidate bound UDP endpoints when certain
// network transitions occur. This is known to occur on Android, although the precise
// conditions are unclear. When that happens, set the ForceRefreshUDPEndPoints flag to
// force all UDPEndPoints to be closed and re-opened on the next call to RefreshEndPoints().
#if WEAVE_SYSTEM_CONFIG_USE_SOCKETS
if (err == System::MapErrorPOSIX(EPIPE))
{
SetFlag(mFlags, kFlag_ForceRefreshUDPEndPoints);
}
#endif // WEAVE_SYSTEM_CONFIG_USE_SOCKETS
}
/**
* Send an encoded Weave message using the appropriate underlying Inetlayer UDPEndPoint (or EndPoints).
*
* @param[in] destAddr The destination IP Address.
*
* @param[in] destPort The destination port.
*
* @param[in] sendIntfId The interface on which to send the Weave message.
*
* @param[in] payload A pointer to the PacketBuffer object holding the encoded Weave message.
*
* @param[in] msgSendFlags Send flags containing metadata about the message for the lower Inet layer.
*
* @retval #WEAVE_NO_ERROR on successfully sending the message down to the network layer.
* @retval errors generated from the lower Inet layer UDP endpoint during sending.
*
*/
WEAVE_ERROR WeaveMessageLayer::SendMessage(const IPAddress & destAddr, uint16_t destPort, InterfaceId sendIntfId,
PacketBuffer * payload, uint32_t msgFlags)
{
WEAVE_ERROR err = WEAVE_NO_ERROR;
UDPEndPoint * ep;
enum
{
kUnicast,
kMulticast_OneInterface,
kMulticast_AllInterfaces,
kMulticast_AllFabricAddrs,
} sendAction;
uint16_t udpSendFlags;
IPPacketInfo pktInfo;
pktInfo.Clear();
pktInfo.DestAddress = destAddr;
pktInfo.DestPort = destPort;
pktInfo.Interface = sendIntfId;
// Check if drop flag is set; If so, do not send message; return WEAVE_NO_ERROR;
VerifyOrExit(!mDropMessage, err = WEAVE_NO_ERROR);
// Drop the message and return. Free the buffer if it does not need to be
// retained(e.g., for WRM retransmissions).
WEAVE_FAULT_INJECT(FaultInjection::kFault_DropOutgoingUDPMsg,
ExitNow(err = WEAVE_NO_ERROR);
);
// Select a UDP endpoint object for sending a message based on the destination address type
// and the message send flags.
err = SelectOutboundUDPEndPoint(destAddr, msgFlags, ep);
SuccessOrExit(err);
// Select an appropriate send action for the message.
//
// For unicast messages, send the message once to the given address. If a target interface
// is given, the message will be sent over that interface.
//
// For multicast/broadcast messages...
//
// If the local node is bound to a specific address (IPv4 or IPv6) send the multicast
// message once over the bound interface.
//
// Otherwise, if the destination is an IPv6 multicast address, and the local node is
// a member of a Weave fabric, AND MulticastFromLinkLocal has NOT been specified, send
// the message once for each Weave Fabric ULA assigned to a local interface that supports
// multicast. If a target interface is given, only consider ULAs on that interface.
//
// Otherwise, if a target interface is given, send the multicast message over that
// interface only.
//
// Otherwise, send the message over each local interface that supports multicast.
//
if (!destAddr.IsMulticast() && !destAddr.IsIPv4Broadcast())
{
sendAction = kUnicast;
}
#if WEAVE_CONFIG_ENABLE_TARGETED_LISTEN
else if (destAddr.IsIPv4() ? IsBoundToLocalIPv4Address() : IsBoundToLocalIPv6Address())
{
sendAction = kMulticast_OneInterface;
}
#endif // WEAVE_CONFIG_ENABLE_TARGETED_LISTEN
else if (destAddr.IsIPv6() && FabricState->FabricId != kFabricIdNotSpecified &&
!GetFlag(msgFlags, kWeaveMessageFlag_DefaultMulticastSourceAddress))
{
sendAction = kMulticast_AllFabricAddrs;
}
else if (sendIntfId != INET_NULL_INTERFACEID)
{
sendAction = kMulticast_OneInterface;
}
else
{
sendAction = kMulticast_AllInterfaces;
}
// Send the message...
switch (sendAction)
{
case kUnicast:
case kMulticast_OneInterface:
// Send the message once. If requested by the caller, instruct the end point code to not free the
// message buffer. If a send interface was specified, the message is sent over that interface.
udpSendFlags = GetFlag(msgFlags, kWeaveMessageFlag_RetainBuffer) ? UDPEndPoint::kSendFlag_RetainBuffer : 0;
err = ep->SendMsg(&pktInfo, payload, udpSendFlags);
payload = NULL; // Prevent call to Free() in exit code
CheckForceRefreshUDPEndPointsNeeded(err);
err = FilterUDPSendError(err, sendAction == kMulticast_OneInterface);
break;
case kMulticast_AllInterfaces:
// Send the message over each local interface that supports multicast.
for (InterfaceIterator intfIter; intfIter.HasCurrent(); intfIter.Next())
{
if (intfIter.SupportsMulticast())
{
pktInfo.Interface = intfIter.GetInterface();
WEAVE_ERROR sendErr = ep->SendMsg(&pktInfo, payload, UDPEndPoint::kSendFlag_RetainBuffer);
CheckForceRefreshUDPEndPointsNeeded(sendErr);
if (err == WEAVE_NO_ERROR)
{
err = FilterUDPSendError(sendErr, true);
}
}
}
break;
case kMulticast_AllFabricAddrs:
// Send the message once for each Weave Fabric ULA assigned to a local interface that supports
// multicast/broadcast. If the caller has specified a particular interface, only send over the
// specified interface. For each message sent, arrange for the source address to be the Fabric ULA.
for (InterfaceAddressIterator addrIter; addrIter.HasCurrent(); addrIter.Next())
{
pktInfo.SrcAddress = addrIter.GetAddress();
pktInfo.Interface = addrIter.GetInterface();
if (addrIter.SupportsMulticast() &&
FabricState->IsLocalFabricAddress(pktInfo.SrcAddress) &&
(sendIntfId == INET_NULL_INTERFACEID || pktInfo.Interface == sendIntfId))
{
WEAVE_ERROR sendErr = ep->SendMsg(&pktInfo, payload, UDPEndPoint::kSendFlag_RetainBuffer);
CheckForceRefreshUDPEndPointsNeeded(sendErr);
if (err == WEAVE_NO_ERROR)
{
err = FilterUDPSendError(sendErr, true);
}
}
}
break;
}
exit:
if (payload != NULL && !GetFlag(msgFlags, kWeaveMessageFlag_RetainBuffer))
PacketBuffer::Free(payload);
return err;
}
/**
* Select an appropriate UDP endpoint for sending a Weave message.
*/
WEAVE_ERROR WeaveMessageLayer::SelectOutboundUDPEndPoint(const IPAddress & destAddr, uint32_t msgFlags, UDPEndPoint *& ep)
{
WEAVE_ERROR err = WEAVE_NO_ERROR;
// Select a UDP endpoint object for sending a message based on the destination address type
// and the message send flags.
//
// If the WEAVE_CONFIG_ENABLE_EPHEMERAL_UDP_PORT option is set, select the ephemeral UDP
// endpoint if the caller has specified the 'ViaEphemeralUDPPort' flag. This will result in
// the source port field of the UDP message being set to the currently active ephemeral
// port. Otherwise, select the Weave UDP endpoint. This will result in the source port
// field being set to the well-known Weave port.
//
switch (destAddr.Type())
{
#if INET_CONFIG_ENABLE_IPV4
case kIPAddressType_IPv4:
if (GetFlag(msgFlags, kWeaveMessageFlag_ViaEphemeralUDPPort))
{
#if WEAVE_CONFIG_ENABLE_EPHEMERAL_UDP_PORT
ep = mIPv4EphemeralUDP;
#else
ep = NULL;
#endif
}
else
{
ep = mIPv4UDP;
}
break;
#endif // INET_CONFIG_ENABLE_IPV4
case kIPAddressType_IPv6:
if (GetFlag(msgFlags, kWeaveMessageFlag_ViaEphemeralUDPPort))
{
#if WEAVE_CONFIG_ENABLE_EPHEMERAL_UDP_PORT
ep = mIPv6EphemeralUDP;
#else
ep = NULL;
#endif
}
else
{
ep = mIPv6UDP;
}
break;
default:
ExitNow(err = WEAVE_ERROR_INVALID_ARGUMENT);
}
VerifyOrExit(ep != NULL, err = WEAVE_ERROR_NO_ENDPOINT);
exit:
return err;
}
/**
* Resend an encoded Weave message using the underlying Inetlayer UDP endpoint.
*
* @param[in] msgInfo A pointer to the WeaveMessageInfo object.
*
* @param[in] payload A pointer to the PacketBuffer object holding the encoded Weave message.
*
* @retval #WEAVE_NO_ERROR on successfully sending the message down to the network layer.
* @retval errors generated from the lower Inet layer UDP endpoint during sending.
*
*/
WEAVE_ERROR WeaveMessageLayer::ResendMessage(WeaveMessageInfo *msgInfo, PacketBuffer *payload)
{
IPAddress destAddr = IPAddress::Any;
return ResendMessage(destAddr, msgInfo, payload);
}
/**
* Resend an encoded Weave message using the underlying Inetlayer UDP endpoint.
*
* @note
* The destination port used is #WEAVE_PORT.
*
* @param[in] destAddr The destination IP Address.
*
* @param[in] msgInfo A pointer to the WeaveMessageInfo object.
*
* @param[in] payload A pointer to the PacketBuffer object holding the encoded Weave message.
*
* @retval #WEAVE_NO_ERROR on successfully sending the message down to the network layer.
* @retval errors generated from the lower Inet layer UDP endpoint during sending.
*
*/
WEAVE_ERROR WeaveMessageLayer::ResendMessage(const IPAddress &destAddr, WeaveMessageInfo *msgInfo, PacketBuffer *payload)
{
return ResendMessage(destAddr, WEAVE_PORT, msgInfo, payload);
}
/**
* Resend an encoded Weave message using the underlying Inetlayer UDP endpoint.
*
* @param[in] destAddr The destination IP Address.
*
* @param[in] destPort The destination port.
*
* @param[in] msgInfo A pointer to the WeaveMessageInfo object.
*
* @param[in] payload A pointer to the PacketBuffer object holding the encoded Weave message.
*
* @retval #WEAVE_NO_ERROR on successfully sending the message down to the network layer.
* @retval errors generated from the lower Inet layer UDP endpoint during sending.
*
*/
WEAVE_ERROR WeaveMessageLayer::ResendMessage(const IPAddress &destAddr, uint16_t destPort, WeaveMessageInfo *msgInfo, PacketBuffer *payload)
{
return ResendMessage(destAddr, WEAVE_PORT, INET_NULL_INTERFACEID, msgInfo, payload);
}
/**
* Resend an encoded Weave message using the underlying Inetlayer UDP endpoint.
*
* @note
* -If the destination address has not been supplied, attempt to determine it from the node identifier in
* the message header. Fail if this can't be done.
*
* -If the destination address is a fabric address for the local fabric, and the caller
* didn't specify the destination node id, extract it from the destination address.
*
* @param[in] aDestAddr The destination IP Address.
*
* @param[in] destPort The destination port.
*
* @param[in] interfaceId The interface on which to send the Weave message.
*
* @param[in] msgInfo A pointer to the WeaveMessageInfo object.
*
* @param[in] payload A pointer to the PacketBuffer object holding the encoded Weave message.
*
* @retval #WEAVE_NO_ERROR on successfully sending the message down to the network layer.
* @retval errors generated from the lower Inet layer UDP endpoint during sending.
*
*/
WEAVE_ERROR WeaveMessageLayer::ResendMessage(const IPAddress &aDestAddr, uint16_t destPort, InterfaceId interfaceId,
WeaveMessageInfo *msgInfo, PacketBuffer *payload)
{
WEAVE_ERROR res = WEAVE_NO_ERROR;
IPAddress destAddr = aDestAddr;
res = SelectDestNodeIdAndAddress(msgInfo->DestNodeId, destAddr);
SuccessOrExit(res);
return SendMessage(destAddr, destPort, interfaceId, payload, msgInfo->Flags);
exit:
if ((res != WEAVE_NO_ERROR) &&
(payload != NULL) &&
((msgInfo->Flags & kWeaveMessageFlag_RetainBuffer) == 0))
{
PacketBuffer::Free(payload);
}
return res;
}
/**
* Get the number of WeaveConnections in use and the size of the pool
*
* @param[out] aOutInUse Reference to size_t, in which the number of
* connections in use is stored.
*
*/
void WeaveMessageLayer::GetConnectionPoolStats(nl::Weave::System::Stats::count_t &aOutInUse) const
{
aOutInUse = 0;
const WeaveConnection *con = (WeaveConnection *) mConPool;
for (int i = 0; i < WEAVE_CONFIG_MAX_CONNECTIONS; i++, con++)
{
if (con->mRefCount != 0)
{
aOutInUse++;
}
}
}
/**
* Create a new WeaveConnection object from a pool.
*
* @return a pointer to the newly created WeaveConnection object if successful, otherwise
* NULL.
*
*/
WeaveConnection *WeaveMessageLayer::NewConnection()
{
WeaveConnection *con = (WeaveConnection *) mConPool;
for (int i = 0; i < WEAVE_CONFIG_MAX_CONNECTIONS; i++, con++)
{
if (con->mRefCount == 0)
{
con->Init(this);
return con;
}
}
WeaveLogError(ExchangeManager, "New con FAILED");
return NULL;
}
void WeaveMessageLayer::GetIncomingTCPConCount(const IPAddress &peerAddr, uint16_t &count, uint16_t &countFromIP)
{
count = 0;
countFromIP = 0;
WeaveConnection *con = (WeaveConnection *) mConPool;
for (int i = 0; i < WEAVE_CONFIG_MAX_CONNECTIONS; i++, con++)
{
if (con->mRefCount > 0 &&
con->NetworkType == WeaveConnection::kNetworkType_IP &&
con->IsIncoming())
{
count++;
if (con->PeerAddr == peerAddr)
{
countFromIP++;
}
}
}
}
/**
* Create a new WeaveConnectionTunnel object from a pool.
*
* @return a pointer to the newly created WeaveConnectionTunnel object if successful,
* otherwise NULL.
*
*/
WeaveConnectionTunnel *WeaveMessageLayer::NewConnectionTunnel()
{
WeaveConnectionTunnel *tun = (WeaveConnectionTunnel *) mTunnelPool;
for (int i = 0; i < WEAVE_CONFIG_MAX_TUNNELS; i++, tun++)
{
if (tun->IsInUse() == false)
{
tun->Init(this);
return tun;
}
}
WeaveLogError(ExchangeManager, "New tun FAILED");
return NULL;
}
/**
* Create a WeaveConnectionTunnel by coupling together two specified WeaveConnections.
On successful creation, the TCPEndPoints corresponding to the component WeaveConnection
objects are handed over to the WeaveConnectionTunnel, otherwise the WeaveConnections are
closed.
*
* @param[out] tunPtr A pointer to pointer of a WeaveConnectionTunnel object.
*
* @param[in] conOne A reference to the first WeaveConnection object.
*
* @param[in] conTwo A reference to the second WeaveConnection object.
*
* @param[in] inactivityTimeoutMS The maximum time in milliseconds that the Weave
* connection tunnel could be idle.
*
* @retval #WEAVE_NO_ERROR on successful creation of the WeaveConnectionTunnel.
* @retval #WEAVE_ERROR_INCORRECT_STATE if the component WeaveConnection objects of the
* WeaveConnectionTunnel is not in the correct state.
* @retval #WEAVE_ERROR_NO_MEMORY if a new WeaveConnectionTunnel object cannot be created.
*
*/
WEAVE_ERROR WeaveMessageLayer::CreateTunnel(WeaveConnectionTunnel **tunPtr, WeaveConnection &conOne,
WeaveConnection &conTwo, uint32_t inactivityTimeoutMS)
{
WeaveLogDetail(ExchangeManager, "Entering CreateTunnel");
WEAVE_ERROR err = WEAVE_NO_ERROR;
VerifyOrExit(conOne.State == WeaveConnection::kState_Connected && conTwo.State ==
WeaveConnection::kState_Connected, err = WEAVE_ERROR_INCORRECT_STATE);
*tunPtr = NewConnectionTunnel();
VerifyOrExit(*tunPtr != NULL, err = WEAVE_ERROR_NO_MEMORY);
// Form WeaveConnectionTunnel from former WeaveConnections' TCPEndPoints.
err = (*tunPtr)->MakeTunnelConnected(conOne.mTcpEndPoint, conTwo.mTcpEndPoint);
SuccessOrExit(err);
WeaveLogProgress(ExchangeManager, "Created Weave tunnel from Cons (%04X, %04X) with EPs (%04X, %04X)",
conOne.LogId(), conTwo.LogId(), conOne.mTcpEndPoint->LogId(), conTwo.mTcpEndPoint->LogId());
if (inactivityTimeoutMS > 0)
{
// Set TCPEndPoint inactivity timeouts.
conOne.mTcpEndPoint->SetIdleTimeout(inactivityTimeoutMS);
conTwo.mTcpEndPoint->SetIdleTimeout(inactivityTimeoutMS);
}
// Remove TCPEndPoints from WeaveConnections now that we've handed the former to our new WeaveConnectionTunnel.
conOne.mTcpEndPoint = NULL;
conTwo.mTcpEndPoint = NULL;
exit:
WeaveLogDetail(ExchangeManager, "Exiting CreateTunnel");
// Close WeaveConnection args.
conOne.Close(true);
conTwo.Close(true);