-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathTonkineseNAT.cpp
More file actions
1763 lines (1444 loc) · 51 KB
/
Copy pathTonkineseNAT.cpp
File metadata and controls
1763 lines (1444 loc) · 51 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
/** \file
\brief NAT Traversal using Internet Gateway Protocol
\copyright Copyright (c) 2018 Christopher A. Taylor. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Tonk nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "TonkineseNAT.h"
#ifdef _WIN32
#include <Iphlpapi.h>
#include <Ws2tcpip.h>
#pragma comment(lib, "Iphlpapi.lib")
#endif
#ifdef __linux__
#include <sys/types.h>
#include <ifaddrs.h>
#endif
#ifdef __APPLE__
#include <stdlib.h>
#include <sys/sysctl.h>
#include <sys/socket.h>
#include <net/route.h>
// FIXME: Port to OSX
#endif
namespace tonk {
namespace gateway {
static logger::Channel ModuleLogger("GatewayPortMapper", MinimumLogLevel);
//------------------------------------------------------------------------------
// Constants
/// IPv4 address at which to multicast SSDP requests
static const char* kUPnPMulticastAddress = "239.255.255.250";
/// Port for SSDP multicast
static const uint16_t kPortSSDP = 1900;
#define SSDP_REQUEST(ST) \
"M-SEARCH * HTTP/1.1\r\n" \
"HOST: 239.255.255.250:1900\r\n" \
"ST: " ST "\r\n" \
"MAN: \"ssdp:discover\"\r\n" \
"MX: 2\r\n" \
"\r\n"
/// List of SSDP requests to make for each multicast
static const char* const kSSDPRequestList[] = {
//SSDP_REQUEST("urn:schemas-upnp-org:device:InternetGatewayDevice:2"),
//SSDP_REQUEST("urn:schemas-upnp-org:service:WANIPConnection:2"),
SSDP_REQUEST("urn:schemas-upnp-org:device:InternetGatewayDevice:1"),
SSDP_REQUEST("urn:schemas-upnp-org:service:WANIPConnection:1"),
SSDP_REQUEST("urn:schemas-upnp-org:service:WANPPPConnection:1"),
//SSDP_REQUEST("upnp:rootdevice")
};
//------------------------------------------------------------------------------
// GatewayPortMapper : API
struct GatewayPortMapper
{
std::unique_ptr<AsioHost> Host;
std::unique_ptr<SSDPRequester> SSDP;
std::unique_ptr<StateMachine> State;
/// Initialize objects
Result Initialize(const char* interfaceAddress);
/// Clean up background thread
void Shutdown();
};
// Lock to guard singleton pattern and parallel requests
static std::mutex APILock;
// Number of API references outstanding before PortMapper is killed
static int API_References = 0;
// Singleton object instance
static GatewayPortMapper* m_PortMapper = nullptr;
static void Delete_PortMapper()
{
if (m_PortMapper != nullptr)
{
m_PortMapper->Shutdown();
delete m_PortMapper;
m_PortMapper = nullptr;
}
API_References = 0;
}
MappedPortLifetime::~MappedPortLifetime()
{
std::lock_guard<std::mutex> locker(APILock);
// If there are no more references:
TONK_DEBUG_ASSERT(API_References > 0);
if (--API_References <= 0)
{
Delete_PortMapper();
// TBD: Should we bother unmapping ports before termination?
// Currently not doing this because it would delay shutdown.
return;
}
// Otherwise take the time to request removing port mapping:
TONK_DEBUG_ASSERT(m_PortMapper);
if (m_PortMapper)
{
// Flip type to Remove
Request.Type = RequestType::Remove;
// Clear the lifetime pointer
Request.API_LifetimePtr = nullptr;
// Thread-safe API request from object
m_PortMapper->State->API_Request(Request);
}
}
std::shared_ptr<MappedPortLifetime> RequestPortMap(
uint16_t localPort,
const char* interfaceAddress)
{
std::lock_guard<std::mutex> locker(APILock);
// If initialization is needed:
TONK_DEBUG_ASSERT(API_References >= 0);
if (API_References <= 0)
{
TONK_DEBUG_ASSERT(m_PortMapper == nullptr);
Delete_PortMapper();
// Allocate port mapper
m_PortMapper = new(std::nothrow) GatewayPortMapper;
if (!m_PortMapper) {
return nullptr; // OOM
}
// Initialize background thread and Asio objects
Result result = m_PortMapper->Initialize(interfaceAddress);
if (result.IsFail())
{
ModuleLogger.Error("Unable to initialize port mapper: ", result.ToJson());
Delete_PortMapper();
return nullptr;
}
}
// Create a request lifetime object
std::shared_ptr<MappedPortLifetime> ref = MakeSharedNoThrow<MappedPortLifetime>();
if (!ref) {
return nullptr; // OOM
}
// Put in request
TONK_DEBUG_ASSERT(m_PortMapper);
if (m_PortMapper)
{
AppRequest request;
request.LocalPort = localPort;
request.Type = RequestType::Add;
request.API_LifetimePtr = ref.get();
ref->Request = request;
// Insert request
m_PortMapper->State->API_Request(request);
}
// Increment references to API
++API_References;
return ref;
}
Result GatewayPortMapper::Initialize(const char* interfaceAddress)
{
TONK_DEBUG_ASSERT(!Host);
Host = MakeUniqueNoThrow<AsioHost>();
SSDP = MakeUniqueNoThrow<SSDPRequester>();
State = MakeUniqueNoThrow<StateMachine>();
// TBD: If two sessions specify different interface addresses,
// we currently do not bind properly
if (interfaceAddress) {
State->InterfaceAddress = interfaceAddress;
}
SSDP->Host = Host.get();
SSDP->State = State.get();
State->Host = Host.get();
State->SSDP = SSDP.get();
Host->State = State.get();
Host->SSDP = SSDP.get();
// Start searching for gateways using SSDP
SSDP->BeginSearch();
// Initialize state
State->Initialize();
// Initialize Asio
return Host->Initialize();
}
void GatewayPortMapper::Shutdown()
{
Host->Shutdown();
SSDP = nullptr;
State = nullptr;
Host = nullptr;
}
//------------------------------------------------------------------------------
// OS-Specific Gateway Address Query
#ifdef _WIN32
// Windows version
Result GetLANInfo(LANInfo& info)
{
info.Gateway = asio::ip::address();
info.Localhost = asio::ip::address();
// Note: When the computer is offline this keeps returning the last valid
// route, so it is not useful for detecting when the computer goes offline.
// This function only fails if no route ever existed.
MIB_IPFORWARDROW row{};
const DWORD bestResult = ::GetBestRoute(
INADDR_ANY, // source address
INADDR_ANY, // dest address
&row); // result row
if (bestResult != NO_ERROR) {
return Result("UpdateLANInfo", "GetBestRoute failed", ErrorType::Asio, bestResult);
}
else {
info.Gateway = asio::ip::address_v4(htonl(row.dwForwardNextHop));
}
const ULONG kFamily = AF_INET; // IPv4 only
const ULONG kFlags = /*GAA_FLAG_SKIP_UNICAST |*/ GAA_FLAG_SKIP_ANYCAST | \
GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME;
ULONG size = 0;
const DWORD sizeResult = ::GetAdaptersAddresses(
kFamily,
kFlags,
nullptr, // reserved
nullptr, // addresses
&size);
if (sizeResult != ERROR_BUFFER_OVERFLOW || size >= 1000000) {
return Result("UpdateLANInfo", "GetAdaptersAddresses size check failed", ErrorType::Asio, sizeResult);
}
std::vector<uint8_t> data(size);
PIP_ADAPTER_ADDRESSES addrs = (PIP_ADAPTER_ADDRESSES)data.data();
const DWORD getResult = ::GetAdaptersAddresses(
kFamily,
kFlags,
nullptr, // reserved
addrs, // addresses
&size);
if (getResult != NO_ERROR) {
return Result("UpdateLANInfo", "GetAdaptersAddresses failed", ErrorType::Asio, getResult);
}
for (; addrs; addrs = addrs->Next)
{
if (addrs->IfIndex != row.dwForwardIfIndex) {
continue;
}
// If interface is up:
if (addrs->OperStatus == IfOperStatusUp)
{
const unsigned family = addrs->FirstUnicastAddress->Address.lpSockaddr->sa_family;
if (family == AF_INET)
{
sockaddr_in* sa_in4 = (sockaddr_in *)addrs->FirstUnicastAddress->Address.lpSockaddr;
auto bytesCast4 = (asio::ip::address_v4::bytes_type*)&sa_in4->sin_addr.S_un.S_un_b;
asio::ip::address_v4 addr4(*bytesCast4);
info.Localhost = addr4;
}
else if (family == AF_INET6)
{
sockaddr_in6* sa_in6 = (sockaddr_in6 *)addrs->FirstUnicastAddress->Address.lpSockaddr;
auto bytesCast6 = (asio::ip::address_v6::bytes_type*)sa_in6->sin6_addr.u.Byte;
asio::ip::address_v6 addr6(*bytesCast6, sa_in6->sin6_scope_id);
info.Localhost = addr6;
}
else {
return Result("UpdateLANInfo", "Invalid interface unicast family", ErrorType::Asio, family);
}
}
else
{
info.Gateway = asio::ip::address();
}
return Result::Success();
}
return Result("UpdateLANInfo", "Could not find the forwarding interface", ErrorType::Asio, row.dwForwardIfIndex);
}
#elif defined(__linux__)
// Linux version
static Result GetLANInfo(LANInfo& info)
{
TONK_UNUSED(info);
return Result::Success();
}
#else // Unsupported platform
static Result GetLANInfo(LANInfo& info)
{
TONK_UNUSED(info);
return Result::Success();
}
#endif
// Shared part of the update function
Result UpdateLANInfo(LANInfo& info, bool& updated)
{
LANInfo latest;
Result result = GetLANInfo(latest);
updated = (latest.Gateway != info.Gateway) ||
(latest.Localhost != info.Localhost);
info = latest;
return result;
}
//------------------------------------------------------------------------------
// Tools
static bool IsWANConnectionServiceType(const std::string& serviceType)
{
if (serviceType.size() <= 2) {
return false;
}
std::string noVersion = serviceType.substr(0, serviceType.size() - 2);
return (0 == StrCaseCompare(noVersion.c_str(), "urn:schemas-upnp-org:service:WANIPConnection") ||
0 == StrCaseCompare(noVersion.c_str(), "urn:schemas-upnp-org:service:WANPPPConnection"));
}
Result ParsedURL::Parse(const std::string& url)
{
FullURL = url;
size_t ipEnd, slash;
// Find port offset
size_t portStart = url.find(':');
if (portStart == std::string::npos) {
ipEnd = url.length();
slash = std::string::npos;
}
else {
ipEnd = portStart;
++portStart;
slash = portStart;
}
size_t portEnd;
std::string path;
int port;
// Find path offset relative to port
slash = url.find('/', slash);
if (slash == std::string::npos) {
portEnd = url.length();
path.clear();
}
else {
portEnd = slash;
if (ipEnd > slash) {
ipEnd = slash;
}
path = url.substr(slash + 1);
}
// Parse out port field
if (portStart == std::string::npos) {
port = 80; // Default HTTP port
}
else {
const std::string portStr = url.substr(portStart, portEnd - portStart);
port = atoi(portStr.c_str());
if (port <= 0) {
return Result("Port did not parse");
}
}
// Note that regardless of protocol we always connect on port 80 with
// HTTP (no SSL encryption) unless a port is specified in the URL
if (port == 443) {
// Force port 80 instead of HTTPS since we do not support encryption
port = 80;
}
// Parse out IP field
std::string ip = url.substr(0, ipEnd);
// Fill info
IP = ip;
Port = (uint16_t)port;
XMLPath = path;
asio::error_code ec;
// Convert IP string to IP address
IPAddr = asio::ip::make_address(ip, ec);
if (ec) {
return Result("retrieveDescription: Invalid IP string", ec.message(), ErrorType::Asio, ec.value());
}
TCPEndpoint = asio::ip::tcp::endpoint(IPAddr, Port);
return Result::Success();
}
Result ParsedXML::Parse(const char* data, unsigned bytes)
{
URLBase.clear();
ServiceType.clear();
ControlURL.clear();
unsigned tag_start = 0, data_start = 0;
bool inService = false;
std::string serviceType, controlURL;
for (unsigned i = 0; i < bytes; ++i)
{
char ch = data[i];
if (tag_start != 0)
{
if (ch == '>')
{
std::string tagData(data + tag_start, i - tag_start);
const char* tag = tagData.c_str();
bool end = (tag[0] == '/');
if (end)
{
++tag;
if (tag_start > data_start)
{
if (inService)
{
if (0 == StrCaseCompare(tag, "serviceType")) {
serviceType = std::string(data + data_start, tag_start - data_start - 1);
}
else if (0 == StrCaseCompare(tag, "controlURL")) {
controlURL = std::string(data + data_start, tag_start - data_start - 1);
}
}
else if (0 == StrCaseCompare(tag, "URLBase")) {
URLBase = std::string(data + data_start, tag_start - data_start - 1);
}
}
}
if (0 == StrCaseCompare(tag, "service"))
{
if (end && IsWANConnectionServiceType(serviceType))
{
ServiceType = serviceType;
ControlURL = controlURL;
}
inService = !end;
}
tag_start = 0;
data_start = i + 1;
}
}
else if (ch == '<') {
tag_start = i + 1;
}
}
if (ServiceType.empty()) {
return Result("Unable to find ServiceType");
}
if (ControlURL.empty()) {
return Result("Unable to find ControlURL");
}
return Result::Success();
}
//------------------------------------------------------------------------------
// AsioHost
Result AsioHost::Initialize()
{
Context = MakeUniqueNoThrow<asio::io_context>();
if (!Context) {
return Result::OutOfMemory();
}
Context->restart();
AsioEventStrand = MakeUniqueNoThrow<asio::io_context::strand>(*Context);
Ticker = MakeUniqueNoThrow<asio::steady_timer>(*Context);
if (!Ticker || !AsioEventStrand) {
return Result::OutOfMemory();
}
/*
Asio bug work-around: If we do not keep some work queued for Asio it
will internally call stop() for some reason and then use a ton of
CPU expecting us to end our worker threads. The best way I've found
to prevent the work-queue to go to 0 items is to keep a timer queued
from before the first worker starts running. The timer OnTick()
keeps re-queuing a timer tick so the work-queue is never empty.
*/
TickAndPostNextTimer();
Terminated = false;
AsioThread = MakeUniqueNoThrow<std::thread>(&AsioHost::WorkerLoop, this);
if (!AsioThread) {
return Result::OutOfMemory();
}
return Result::Success();
}
void AsioHost::WorkerLoop()
{
asio::error_code ec;
while (!Terminated)
{
Context->run(ec);
if (ec) {
ModuleLogger.Warning("Worker loop context error: ", ec.message());
}
}
}
void AsioHost::DispatchTick()
{
// Note: This is posted to a background thread and will execute after the
// current thread of execution retires.
AsioEventStrand->post([this]() {
TickAndPostNextTimer();
});
}
void AsioHost::TickAndPostNextTimer()
{
// Run OnTick function in StateMachine
State->OnTick();
// This resets the existing timer so that we do not get two ticks in a row
static const unsigned kTickIntervalUsec = 1000 * 1000; /// 1 second
Ticker->expires_after(std::chrono::microseconds(kTickIntervalUsec));
Ticker->async_wait(([this](const asio::error_code& error)
{
if (!error) {
TickAndPostNextTimer();
}
}));
}
void AsioHost::Shutdown()
{
if (Context) {
// Note there is no need to stop or cancel timer ticks or sockets
Context->stop();
}
// Note this has to be done after cancel/close of sockets above because
// otherwise Asio can hang waiting for any outstanding callbacks
Terminated = true;
if (AsioThread)
{
try {
if (AsioThread->joinable()) {
AsioThread->join();
}
}
catch (std::system_error& err) {
ModuleLogger.Warning("Exception while joining thread: ", err.what());
}
}
AsioThread = nullptr;
Ticker = nullptr;
AsioEventStrand = nullptr;
// Keep the context object alive a bit longer while the other parts go
// out of scope.
//Context = nullptr;
}
//------------------------------------------------------------------------------
// SSDPRequester
void SSDPRequester::OnTick()
{
// If initialization is needed:
if (NeedsInitialization)
{
NeedsInitialization = false;
// Attempt to initialize sockets
Result result = InitializeSockets();
// If attempt failed:
if (result.IsFail())
{
ModuleLogger.Error("Socket initialization failed: ", result.ToJson());
return;
}
}
// If poll timer has expired:
const uint64_t nowUsec = siamese::GetTimeUsec();
if (nowUsec - LastLANInfoRequestUsec > protocol::kLANInfoIntervalUsec)
{
LastLANInfoRequestUsec = siamese::GetTimeUsec();
// Check if LAN info changed
PollLANInfo();
}
// If there are no multicasts requested:
if (AttemptsRemaining <= 0) {
return;
}
AttemptsRemaining--;
// Request SSDP from gateway
RequestSSDP();
}
void SSDPRequester::PollLANInfo()
{
bool updated = false;
Result lanResult = UpdateLANInfo(LAN, updated);
if (lanResult.IsFail()) {
ModuleLogger.Warning("Could not get LAN info: ", lanResult.ToJson());
}
if (!updated) {
return;
}
HaveSeenAGatewayAddress |= !LAN.Gateway.is_unspecified();
ModuleLogger.Info("Detected new LAN configuration. Gateway: ", LAN.Gateway.to_string(),
" LocalIP: ", LAN.Localhost.to_string());
// If network is not possibly up
if (IsNetworkDefinitelyDown()) {
return;
}
// Convert IP string to IP address
asio::error_code ec;
const asio::ip::address multicastIP = \
asio::ip::make_address(kUPnPMulticastAddress, ec);
TONK_DEBUG_ASSERT(!ec); // Should never happen
// Send to multicast address
SSDPAddresses.clear();
SSDPAddresses.emplace_back(multicastIP, kPortSSDP);
// If we were able to get the LAN gateway address:
if (!LAN.Gateway.is_unspecified()) {
SSDPAddresses.emplace_back(LAN.Gateway, kPortSSDP);
}
// Restart SSDP scanning
BeginSearch();
// Allow state machine to react to LAN change
State->OnLANChange();
}
Result SSDPRequester::InitializeSockets()
{
asio::error_code ec;
Socket_UDP = MakeUniqueNoThrow<asio::ip::udp::socket>(*Host->Context);
if (!Socket_UDP) {
return Result::OutOfMemory();
}
UDPAddress bindAddress;
// If application specified an interface address:
if (State->InterfaceAddress.empty()) {
// Note: Asio default endpoint address is the any address e.g. INADDR_ANY
bindAddress = UDPAddress(asio::ip::udp::v4(), 0);
}
else
{
// Convert provided interface address to Asio address
const asio::ip::address bindAddr = asio::ip::make_address(State->InterfaceAddress, ec);
if (ec) {
return Result("Provided InterfaceAddress was invalid", ec.message(), ErrorType::Asio, ec.value());
}
// Bind to the provided interface address
bindAddress = UDPAddress(bindAddr, 0);
}
Socket_UDP->open(bindAddress.protocol(), ec);
if (ec) {
return Result("UDP socket open failed", ec.message(), ErrorType::Asio, ec.value());
}
Socket_UDP->set_option(asio::socket_base::reuse_address(true), ec);
if (ec) {
return Result("UDP socket set_option reuse_address failed", ec.message(), ErrorType::Asio, ec.value());
}
Socket_UDP->bind(bindAddress, ec);
if (ec) {
return Result("UDP bind failed", ec.message(), ErrorType::Asio, ec.value());
}
// Start listening
PostNextRead_UDP();
return Result::Success();
}
void SSDPRequester::RequestSSDP()
{
// If initialization failed:
if (!Socket_UDP) {
return;
}
// For each schema to try:
for (const char* schemaRequest : kSSDPRequestList)
{
const size_t requestBytes = strlen(schemaRequest);
for (const auto& addr : SSDPAddresses)
{
//ModuleLogger.Info("Requesting SSDP from ", addr.address().to_string());
// Send the canned request
Socket_UDP->async_send_to(
asio::buffer(schemaRequest, requestBytes),
addr,
[requestBytes](const asio::error_code& ec, std::size_t bytes)
{
// Warn about any funky results
if (ec) {
ModuleLogger.Warning("async_send_to returned with error: ", ec.message());
}
else if (bytes != requestBytes) {
ModuleLogger.Warning("async_send_to sent partial bytes = ", bytes);
}
});
}
}
}
void SSDPRequester::PostNextRead_UDP()
{
SourceAddress = UDPAddress();
// Launch an asynchronous recvfrom()
Socket_UDP->async_receive_from(
asio::buffer(ReadBuffer_UDP, kReadBufferBytes),
SourceAddress,
[this](const asio::error_code& ec, size_t bytes)
{
// If an error was reported:
if (ec)
{
// If it was not just an ICMP error:
if (SourceAddress.address().is_unspecified()) {
// Stop reading
return;
}
}
// If the socket was closed gracefully:
if (bytes <= 0) {
// Stop reading
return;
}
Result result = OnUDPDatagram((char*)ReadBuffer_UDP, (unsigned)bytes);
if (result.IsFail()) {
ModuleLogger.Warning("SSDP datagram rejected: ", result.ToJson());
}
PostNextRead_UDP();
});
}
struct membuf : std::streambuf
{
membuf(char* begin, char* end)
{
this->setg(begin, begin, end);
}
};
// trim from start (in place)
static inline void ltrim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(),
[](int ch)
{
return !std::isspace(ch);
}));
}
// trim from end (in place)
static inline void rtrim(std::string &s)
{
s.erase(std::find_if(s.rbegin(), s.rend(),
[](int ch)
{
return !std::isspace(ch);
}).base(), s.end());
}
// trim from both ends (in place)
static inline void trim(std::string &s)
{
ltrim(s);
rtrim(s);
}
Result SSDPRequester::OnUDPDatagram(char* data, unsigned bytes)
{
membuf sbuf(data, data + bytes);
std::istream is(&sbuf);
std::string line;
// Check if response starts with a success code
if (!std::getline(is, line)) {
return Result("Truncated UDP response");
}
if (line.find("200 OK") == std::string::npos) {
return Result("Ignoring malformed UDP response (No \"200 OK\")");
}
//ModuleLogger.Info("**** ", SourceAddress.address().to_string(), ":", SourceAddress.port());
// For each remaining line:
while (std::getline(is, line))
{
//ModuleLogger.Info("LINE: ", line);
const bool isLocation = (0 == StrCaseCompare(line.substr(0, 9).c_str(), "location:"));
if (!isLocation) {
continue;
}
// Parse out the first HTTP or HTTPS URL in the response.
const std::string::size_type begin = line.find("://");
if (begin == std::string::npos) {
return Result("Ignoring malformed UDP response (No protocol)");
}
std::string url(line, begin + 3);
trim(url);
ParsedURL parsed;
Result result = parsed.Parse(url);
if (result.IsFail()) {
return result;
}
State->OnSSDPResponse(parsed);
return Result::Success();
}
return Result("No location found");
}
//------------------------------------------------------------------------------
// StateMachine
void StateMachine::Initialize()
{
uint64_t seed[2];
Result result = SecureRandom_Next((uint8_t*)&seed[0], sizeof(seed));
if (result.IsFail()) {
ModuleLogger.Warning("SecureRandom failed to generate random seed");
}
Rand.Seed(seed[0], seed[1]);
}
void StateMachine::API_Request(const AppRequest& request)
{
TONK_DEBUG_ASSERT(request.LocalPort != 0);
// This will be called from the application
// Hold API lock while accessing the requests list
{
std::lock_guard<std::mutex> locker(API_Lock);
bool found = false;
for (auto& r : API_Requests)
{
// Note: Requests are uniquely identified by ports
if (r.LocalPort == request.LocalPort)
{
r = request;
found = true;
break;
}
}
if (!found) {
API_Requests.push_back(request);
}
// Set the dirty flag
API_Requests_Updated = true;
}
// Run OnTick() immediately
Host->DispatchTick();
}
void StateMachine::API_CopyRequests()
{
// This must be called from the background thread
if (!API_Requests_Updated) {
return;
}
std::lock_guard<std::mutex> locker(API_Lock);
// Copy API_Requests into Requests
const int requestCount = (int)API_Requests.size();
Requests.resize(requestCount);
memcpy(&Requests[0], &API_Requests[0], requestCount * sizeof(AppRequest));
// Clear the dirty flag
API_Requests_Updated = false;
}
void StateMachine::OnTick()
{
API_CopyRequests();
SSDP->OnTick();