forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTestInetCommonPosix.cpp
479 lines (402 loc) · 14.3 KB
/
TestInetCommonPosix.cpp
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
/*
*
* Copyright (c) 2020-2021 Project CHIP Authors
* Copyright (c) 2013-2018 Nest Labs, 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.
*/
/**
* @file
* This file implements constants, globals and interfaces common to
* and used by all CHP Inet layer library test applications and
* tools.
*
* NOTE: These do not comprise a public part of the CHIP API and
* are subject to change without notice.
*
*/
#include "TestInetCommon.h"
#include "TestInetCommonOptions.h"
#include <assert.h>
#include <errno.h>
#include <vector>
#include <inttypes.h>
#include <stdint.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <lib/core/ErrorStr.h>
#include <lib/support/CHIPMem.h>
#include <lib/support/ScopedBuffer.h>
#include <platform/PlatformManager.h>
#include <system/SystemClock.h>
#if CHIP_SYSTEM_CONFIG_USE_LWIP
#include <lwip/dns.h>
#if (LWIP_VERSION_MAJOR == 2) && (LWIP_VERSION_MINOR == 0)
#include <lwip/ip6_route_table.h>
#endif // (LWIP_VERSION_MAJOR == 2) && (LWIP_VERSION_MINOR == 0)
#include <lwip/init.h>
#include <lwip/netif.h>
#include <lwip/sys.h>
#include <lwip/tcpip.h>
#include <netif/etharp.h>
#if CHIP_TARGET_STYLE_UNIX
// NOTE: this used to be supported, so could theoretically be
// recovered, however the TAP/TUN was never actually used
// and the underlying files were never compiled in CHIP.
#error "Testing of LWIP on unix systems via TAP not supported."
#endif // CHIP_TARGET_STYLE_UNIX
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP
using namespace chip;
using namespace chip::Inet;
System::LayerImpl gSystemLayer;
#if INET_CONFIG_ENABLE_UDP_ENDPOINT
Inet::UDPEndPointManagerImpl gUDP;
#endif
#if INET_CONFIG_ENABLE_TCP_ENDPOINT
Inet::TCPEndPointManagerImpl gTCP;
#endif
#if CHIP_SYSTEM_CONFIG_USE_LWIP && !(CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT)
static sys_mbox_t * sLwIPEventQueue = NULL;
static unsigned int sLwIPAcquireCount = 0;
static void AcquireLwIP(void)
{
if (sLwIPAcquireCount++ == 0)
{
sys_mbox_new(sLwIPEventQueue, 100);
}
}
static void ReleaseLwIP(void)
{
#if (LWIP_VERSION_MAJOR == 2) && (LWIP_VERSION_MINOR == 0)
if (sLwIPAcquireCount > 0 && --sLwIPAcquireCount == 0)
{
#if defined(INCLUDE_vTaskDelete) && INCLUDE_vTaskDelete
// FreeRTOS need to delete the task not return from it.
tcpip_finish(reinterpret_cast<tcpip_will_finish_fn>(vTaskDelete), NULL);
#else // defined(INCLUDE_vTaskDelete) && INCLUDE_vTaskDelete
tcpip_finish(NULL, NULL);
#endif // defined(INCLUDE_vTaskDelete) && INCLUDE_vTaskDelete
}
#endif // (LWIP_VERSION_MAJOR == 2) && (LWIP_VERSION_MINOR == 0)
}
static std::vector<struct netif> sNetIFs; // interface to filter
static bool NetworkIsReady();
static void OnLwIPInitComplete(void * arg);
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP && !(CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT)
char gDefaultTapDeviceName[32];
bool gDone = false;
void InetFailError(CHIP_ERROR err, const char * msg)
{
if (err != CHIP_NO_ERROR)
{
fprintf(stderr, "%s: %s\n", msg, ErrorStr(err));
exit(-1);
}
}
static void UseStdoutLineBuffering()
{
// Set stdout to be line buffered with a buffer of 512 (will flush on new line
// or when the buffer of 512 is exceeded).
#if CHIP_CONFIG_MEMORY_MGMT_MALLOC
constexpr char * buf = nullptr;
#else
static char buf[512];
#endif // CHIP_CONFIG_MEMORY_MGMT_MALLOC
setvbuf(stdout, buf, _IOLBF, 512);
}
void InitTestInetCommon()
{
chip::Platform::MemoryInit();
UseStdoutLineBuffering();
}
void ShutdownTestInetCommon()
{
chip::Platform::MemoryShutdown();
}
void InitSystemLayer()
{
#if CHIP_SYSTEM_CONFIG_USE_LWIP
// LwIP implementation uses the event loop for servicing events.
// The CHIP stack initialization is required then.
chip::DeviceLayer::PlatformMgr().InitChipStack();
#ifndef CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT
AcquireLwIP();
#endif // !CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP
gSystemLayer.Init();
}
void ShutdownSystemLayer()
{
gSystemLayer.Shutdown();
#if CHIP_SYSTEM_CONFIG_USE_LWIP
// LwIP implementation uses the event loop for servicing events.
// The CHIP stack shutdown is required then.
chip::DeviceLayer::PlatformMgr().Shutdown();
#ifndef CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT
ReleaseLwIP();
#endif // !CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP
}
#if CHIP_SYSTEM_CONFIG_USE_LWIP && !(CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT)
static void PrintNetworkState()
{
char intfName[InterfaceId::kMaxIfNameLength];
for (size_t j = 0; j < gNetworkOptions.TapDeviceName.size(); j++)
{
struct netif * netIF = &(sNetIFs[j]);
InterfaceId(netIF).GetInterfaceName(intfName, sizeof(intfName));
printf("LwIP interface ready\n");
printf(" Interface Name: %s\n", intfName);
printf(" Tap Device: %s\n", gNetworkOptions.TapDeviceName[j]);
#if INET_CONFIG_ENABLE_IPV4
printf(" IPv4 Address: %s\n", ipaddr_ntoa(&(netIF->ip_addr)));
printf(" IPv4 Mask: %s\n", ipaddr_ntoa(&(netIF->netmask)));
printf(" IPv4 Gateway: %s\n", ipaddr_ntoa(&(netIF->gw)));
#endif // INET_CONFIG_ENABLE_IPV4
for (int i = 0; i < LWIP_IPV6_NUM_ADDRESSES; i++)
{
if (!ip6_addr_isany(netif_ip6_addr(netIF, i)))
{
printf(" IPv6 address: %s, 0x%02x\n", ip6addr_ntoa(netif_ip6_addr(netIF, i)), netif_ip6_addr_state(netIF, i));
}
}
}
}
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP && !(CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT)
void InitNetwork()
{
#if CHIP_SYSTEM_CONFIG_USE_LWIP && !(CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT)
// If an tap device name hasn't been specified, derive one from the IPv6 interface id.
if (gNetworkOptions.TapDeviceName.empty())
{
for (size_t j = 0; j < gNetworkOptions.LocalIPv6Addr.size(); j++)
{
uint64_t iid = gNetworkOptions.LocalIPv6Addr[j].InterfaceId();
char * tap_name = (char *) chip::Platform::MemoryAlloc(sizeof(gDefaultTapDeviceName));
assert(tap_name);
snprintf(tap_name, sizeof(gDefaultTapDeviceName), "chip-dev-%x", static_cast<uint16_t>(iid));
gNetworkOptions.TapDeviceName.push_back(tap_name);
}
}
sNetIFs.clear();
for (size_t j = 0; j < gNetworkOptions.TapDeviceName.size(); j++)
{
struct netif netIF;
sNetIFs.push_back(netIF);
}
tcpip_init(OnLwIPInitComplete, NULL);
// Lock LwIP stack
LOCK_TCPIP_CORE();
for (size_t j = 0; j < gNetworkOptions.TapDeviceName.size(); j++)
{
std::vector<char *> addrsVec;
addrsVec.clear();
#if INET_CONFIG_ENABLE_IPV4
IPAddress ip4Addr = (j < gNetworkOptions.LocalIPv4Addr.size()) ? gNetworkOptions.LocalIPv4Addr[j] : IPAddress::Any;
for (size_t n = 0; n < addrsVec.size(); n++)
{
IPAddress auto_addr;
if (IPAddress::FromString(addrsVec[n], auto_addr) && auto_addr.IsIPv4())
{
ip4Addr = auto_addr;
}
}
#endif // INET_CONFIG_ENABLE_IPV4
netif_create_ip6_linklocal_address(&(sNetIFs[j]), 1);
#if (LWIP_VERSION_MAJOR == 2) && (LWIP_VERSION_MINOR == 0)
if (j < gNetworkOptions.LocalIPv6Addr.size())
{
ip6_addr_t ip6addr = gNetworkOptions.LocalIPv6Addr[j].ToIPv6();
s8_t index;
netif_add_ip6_address_with_route(&(sNetIFs[j]), &ip6addr, 64, &index);
// add ipv6 route for ipv6 address
if (j < gNetworkOptions.IPv6GatewayAddr.size())
{
static ip6_addr_t br_ip6_addr = gNetworkOptions.IPv6GatewayAddr[j].ToIPv6();
struct ip6_prefix ip6_prefix;
ip6_prefix.addr = Inet::IPAddress::Any.ToIPv6();
ip6_prefix.prefix_len = 0;
ip6_add_route_entry(&ip6_prefix, &sNetIFs[j], &br_ip6_addr, NULL);
}
if (index >= 0)
{
netif_ip6_addr_set_state(&(sNetIFs[j]), index, IP6_ADDR_PREFERRED);
}
}
for (size_t n = 0; n < addrsVec.size(); n++)
{
IPAddress auto_addr;
if (IPAddress::FromString(addrsVec[n], auto_addr) && !auto_addr.IsIPv4())
{
ip6_addr_t ip6addr = auto_addr.ToIPv6();
s8_t index;
if (auto_addr.IsIPv6LinkLocal())
continue; // skip over the LLA addresses, LwIP is aready adding those
if (auto_addr.IsIPv6Multicast())
continue; // skip over the multicast addresses from host for now.
netif_add_ip6_address_with_route(&(sNetIFs[j]), &ip6addr, 64, &index);
if (index >= 0)
{
netif_ip6_addr_set_state(&(sNetIFs[j]), index, IP6_ADDR_PREFERRED);
}
}
}
#endif // (LWIP_VERSION_MAJOR == 2) && (LWIP_VERSION_MINOR == 0)
netif_set_up(&(sNetIFs[j]));
netif_set_link_up(&(sNetIFs[j]));
}
netif_set_default(&(sNetIFs[0]));
// UnLock LwIP stack
UNLOCK_TCPIP_CORE();
while (!NetworkIsReady())
{
constexpr uint32_t kSleepTimeMilliseconds = 100;
ServiceEvents(kSleepTimeMilliseconds);
}
// FIXME: this is kinda nasty :(
// Force new IP address to be ready, bypassing duplicate detection.
for (size_t j = 0; j < gNetworkOptions.TapDeviceName.size(); j++)
{
if (j < gNetworkOptions.LocalIPv6Addr.size())
{
netif_ip6_addr_set_state(&(sNetIFs[j]), 2, 0x30);
}
else
{
netif_ip6_addr_set_state(&(sNetIFs[j]), 1, 0x30);
}
}
PrintNetworkState();
AcquireLwIP();
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP && !(CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT)
#if INET_CONFIG_ENABLE_TCP_ENDPOINT
gTCP.Init(gSystemLayer);
#endif
#if INET_CONFIG_ENABLE_UDP_ENDPOINT
gUDP.Init(gSystemLayer);
#endif
}
void ServiceEvents(uint32_t aSleepTimeMilliseconds)
{
static bool printed = false;
if (!printed)
{
#if CHIP_SYSTEM_CONFIG_USE_LWIP && !(CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT)
if (NetworkIsReady())
#endif
{
printf("CHIP node ready to service events\n");
fflush(stdout);
printed = true;
}
}
// Start a timer (with a no-op callback) to ensure that WaitForEvents() does not block longer than aSleepTimeMilliseconds.
gSystemLayer.StartTimer(
System::Clock::Milliseconds32(aSleepTimeMilliseconds), [](System::Layer *, void *) -> void {}, nullptr);
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
gSystemLayer.PrepareEvents();
gSystemLayer.WaitForEvents();
gSystemLayer.HandleEvents();
#endif
#if CHIP_SYSTEM_CONFIG_USE_LWIP || CHIP_SYSTEM_CONFIG_USE_OPEN_THREAD_ENDPOINT
if (gSystemLayer.IsInitialized())
{
static uint32_t sRemainingSystemLayerEventDelay = 0;
if (sRemainingSystemLayerEventDelay == 0)
{
#if CHIP_DEVICE_LAYER_TARGET_OPEN_IOT_SDK || CHIP_SYSTEM_CONFIG_USE_OPEN_THREAD_ENDPOINT
// We need to terminate event loop after performance single step.
// Event loop processing work items until StopEventLoopTask is called.
// Scheduling StopEventLoop task guarantees correct operation of the loop.
chip::DeviceLayer::PlatformMgr().ScheduleWork(
[](intptr_t) -> void { chip::DeviceLayer::PlatformMgr().StopEventLoopTask(); }, (intptr_t) nullptr);
#endif // CHIP_DEVICE_LAYER_TARGET_OPEN_IOT_SDK
chip::DeviceLayer::PlatformMgr().RunEventLoop();
sRemainingSystemLayerEventDelay = gNetworkOptions.EventDelay;
}
else
sRemainingSystemLayerEventDelay--;
gSystemLayer.HandlePlatformTimer();
}
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP || CHIP_SYSTEM_CONFIG_USE_OPEN_THREAD_ENDPOINT
}
#if CHIP_SYSTEM_CONFIG_USE_LWIP && !(CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT)
static bool NetworkIsReady()
{
bool ready = true;
for (size_t j = 0; j < gNetworkOptions.TapDeviceName.size(); j++)
{
for (int i = 0; i < LWIP_IPV6_NUM_ADDRESSES; i++)
{
if (!ip6_addr_isany(netif_ip6_addr(&(sNetIFs[j]), i)) && ip6_addr_istentative(netif_ip6_addr_state(&(sNetIFs[j]), i)))
{
ready = false;
break;
}
}
}
return ready;
}
static void OnLwIPInitComplete(void * arg)
{
printf("Waiting for addresses assignment...\n");
}
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP && !(CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT)
void ShutdownNetwork()
{
#if INET_CONFIG_ENABLE_TCP_ENDPOINT
gTCP.ForEachEndPoint([](TCPEndPoint * lEndPoint) -> Loop {
gTCP.ReleaseEndPoint(lEndPoint);
return Loop::Continue;
});
gTCP.Shutdown();
#endif
#if INET_CONFIG_ENABLE_UDP_ENDPOINT
gUDP.ForEachEndPoint([](UDPEndPoint * lEndPoint) -> Loop {
gUDP.ReleaseEndPoint(lEndPoint);
return Loop::Continue;
});
gUDP.Shutdown();
#endif
#if CHIP_SYSTEM_CONFIG_USE_LWIP && !(CHIP_SYSTEM_CONFIG_LWIP_SKIP_INIT)
ReleaseLwIP();
#endif
}
void DumpMemory(const uint8_t * mem, uint32_t len, const char * prefix, uint32_t rowWidth)
{
int indexWidth = snprintf(nullptr, 0, "%" PRIX32, len);
if (indexWidth < 4)
indexWidth = 4;
for (uint32_t i = 0; i < len; i += rowWidth)
{
printf("%s%0*" PRIX32 ": ", prefix, indexWidth, i);
uint32_t rowEnd = i + rowWidth;
uint32_t j = i;
for (; j < rowEnd && j < len; j++)
printf("%02X ", mem[j]);
for (; j < rowEnd; j++)
printf(" ");
for (j = i; j < rowEnd && j < len; j++)
if (isprint(static_cast<char>(mem[j])))
printf("%c", mem[j]);
else
printf(".");
printf("\n");
}
}
void DumpMemory(const uint8_t * mem, uint32_t len, const char * prefix)
{
const uint32_t kRowWidth = 16;
DumpMemory(mem, len, prefix, kRowWidth);
}