forked from rdkcentral/networkmanager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NetworkManagerConnectivity.cpp
740 lines (664 loc) · 29.5 KB
/
NetworkManagerConnectivity.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
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
/*
* If not stated otherwise in this file or this component's LICENSE file the
* following copyright and licenses apply:
*
* Copyright 2020 RDK Management
*
* 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 <curl/curl.h>
#include <resolv.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <stdbool.h>
#include <curl/curl.h>
#include <thread>
#include <algorithm>
#include "NetworkManagerImplementation.h"
#include "NetworkManagerConnectivity.h"
#include "NetworkManagerLogger.h"
namespace WPEFramework
{
namespace Plugin
{
extern NetworkManagerImplementation* _instance;
static const char* getInternetStateString(nsm_internetState state)
{
switch(state)
{
case NO_INTERNET: return "NO_INTERNET";
case LIMITED_INTERNET: return "LIMITED_INTERNET";
case CAPTIVE_PORTAL: return "CAPTIVE_PORTAL";
case FULLY_CONNECTED: return "FULLY_CONNECTED";
default: return "UNKNOWN";
}
}
void EndpointManager::writeEndpointsToFile(const std::vector<std::string>& endpoints)
{
std::ofstream outputFile(m_CachefilePath);
if (outputFile.is_open())
{
for (const std::string& str : endpoints)
{
outputFile << str << '\n';
}
outputFile.close();
}
else
{
NMLOG_ERROR("Connectivity endpoints file write error");
}
}
std::vector<std::string> EndpointManager::readEndpointsFromFile()
{
std::vector<std::string> readStrings;
std::ifstream inputFile(m_CachefilePath);
if (inputFile.is_open())
{
std::string line;
while (std::getline(inputFile, line))
{
readStrings.push_back(line);
}
inputFile.close();
}
else
{
NMLOG_ERROR("Failed to open connectivity endpoint cache file");
}
return readStrings;
}
void EndpointManager::setConnectivityMonitorEndpoints(const std::vector<std::string>& endpoints)
{
const std::lock_guard<std::mutex> lock(m_endpointMutex);
if(endpoints.empty())
{
NMLOG_ERROR("Empty endpoints");
return;
}
m_Endpoints.clear();
for (auto endpoint : endpoints) {
if(!endpoint.empty() && endpoint.size() > 3)
m_Endpoints.push_back(endpoint.c_str());
else
NMLOG_ERROR("endpoint not vallied = %s", endpoint.c_str());
}
// write the endpoints to a file
writeEndpointsToFile(m_Endpoints);
std::string endpointsStr;
for (const auto& endpoint : m_Endpoints)
endpointsStr.append(endpoint).append(" ");
NMLOG_INFO("Connectivity monitor endpoints updated -: %d :- %s", static_cast<int>(m_Endpoints.size()), endpointsStr.c_str());
}
EndpointManager::EndpointManager()
{
m_CachefilePath = NMCONNECTIVITY_MONITOR_CACHE_FILE;
m_Endpoints.clear(); // default value will be loaded from NetworkManagerImplementation configuration
std::ifstream inputFile(m_CachefilePath);
if (inputFile.is_open())
{
std::string line;
std::vector<std::string> endpoints{};
while (std::getline(inputFile, line))
{
if(!line.empty() && line.size() > 3)
endpoints.push_back(line);
}
NMLOG_WARNING("cached connectivity endpoints loaded ..");
setConnectivityMonitorEndpoints(endpoints);
inputFile.close();
}
else
{
NMLOG_ERROR("no endpoint cache file found");
}
}
std::vector<std::string> EndpointManager::getConnectivityMonitorEndpoints()
{
const std::lock_guard<std::mutex> lock(m_endpointMutex);
return m_Endpoints;
}
bool DnsResolver::resolveIP(std::string& uri, nsm_ipversion ipversion)
{
struct addrinfo sockAddrProps, *resultAddr= NULL;
char ipStr[INET6_ADDRSTRLEN] = {0};
if(ipversion == NSM_IPRESOLVE_V4)
sockAddrProps.ai_family = AF_INET;
else if(ipversion == NSM_IPRESOLVE_V6)
sockAddrProps.ai_family = AF_INET6;
else
sockAddrProps.ai_family = AF_UNSPEC;
sockAddrProps.ai_socktype = SOCK_STREAM;
sockAddrProps.ai_flags = 0;
sockAddrProps.ai_protocol = 0;
int ret = getaddrinfo(uri.c_str(), NULL, &sockAddrProps, &resultAddr);
if (ret != 0) {
NMLOG_WARNING("Resolved IP Failed getaddrinfo: %s", gai_strerror(ret));
return false;
}
NMLOG_DEBUG("Resolved IP addresses for %s", uri.c_str());
for (struct addrinfo * resutIP = resultAddr; resutIP != NULL; resutIP = resutIP->ai_next)
{
void *addr= NULL;
if (resutIP->ai_family == AF_INET) {
struct sockaddr_in *ipv4 = (struct sockaddr_in *)resutIP->ai_addr;
addr = &(ipv4->sin_addr);
ipv4Resolved = true;
} else if (resutIP->ai_family == AF_INET6) {
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)resutIP->ai_addr;
addr = &(ipv6->sin6_addr);
ipv6Resolved = true;
} else {
continue;
}
inet_ntop(resutIP->ai_family, addr, ipStr, sizeof(ipStr));
NMLOG_DEBUG("Resolved IP --> %s", ipStr);
}
freeaddrinfo(resultAddr);
return true;
}
std::string DnsResolver::convertUrIToDomainName(std::string& url)
{
size_t domainStart = 0;
size_t protocolEnd = url.find("://");
if (protocolEnd != std::string::npos) {
domainStart = protocolEnd + 3;
}
size_t domainEnd = url.find('/', domainStart);
if (domainEnd != std::string::npos)
return url.substr(domainStart, domainEnd - domainStart);
else
return url.substr(domainStart);
}
DnsResolver::DnsResolver(std::string url, nsm_ipversion ipversion)
{
NMLOG_DEBUG("DnsResolver constructor %s - %d", url.c_str(), ipversion);
if(url.empty()) {
NMLOG_ERROR("URI/hostname missing");
return;
}
m_domain = convertUrIToDomainName(url);
resolveIP(m_domain, ipversion);
}
TestConnectivity::TestConnectivity(const std::vector<std::string>& endpoints, long timeout_ms, bool headReq, nsm_ipversion ipversion)
{
internetSate = UNKNOWN;
if(endpoints.size() < 1) {
NMLOG_ERROR("Endpoints size error ! curl check not possible");
return;
}
internetSate = checkCurlResponse(endpoints, timeout_ms, headReq, ipversion);
}
static bool curlVerboseEnabled() {
std::ifstream fileStream("/tmp/nm.plugin.debug");
return fileStream.is_open();
}
static long current_time ()
{
struct timespec ts;
clock_gettime (CLOCK_MONOTONIC, &ts);
return (ts.tv_sec * 1000) + (ts.tv_nsec / 1000000);
}
static size_t writeFunction(void* ptr, size_t size, size_t nmemb, std::string* data) {
#ifdef DBG_CURL_GET_RESPONSE
LOG_DBG("%s",(char*)ptr);
#endif
return size * nmemb;
}
nsm_internetState TestConnectivity::checkCurlResponse(const std::vector<std::string>& endpoints, long timeout_ms, bool headReq, nsm_ipversion ipversion)
{
long deadline = current_time() + timeout_ms, time_now = 0, time_earlier = 0;
CURLM *curl_multi_handle = curl_multi_init();
if (!curl_multi_handle)
{
NMLOG_ERROR("curl_multi_init returned NULL");
return NO_INTERNET;
}
CURLMcode mc;
std::vector<CURL*> curl_easy_handles;
std::vector<int> http_responses;
struct curl_slist *chunk = NULL;
chunk = curl_slist_append(chunk, "Cache-Control: no-cache, no-store");
chunk = curl_slist_append(chunk, "Connection: close");
for (const auto& endpoint : endpoints)
{
CURL *curl_easy_handle = curl_easy_init();
if (!curl_easy_handle)
{
NMLOG_ERROR("endpoint = <%s> curl_easy_init returned NULL", endpoint.c_str());
continue;
}
curl_easy_setopt(curl_easy_handle, CURLOPT_URL, endpoint.c_str());
curl_easy_setopt(curl_easy_handle, CURLOPT_PRIVATE, endpoint.c_str());
/* set our custom set of headers */
curl_easy_setopt(curl_easy_handle, CURLOPT_HTTPHEADER, chunk);
curl_easy_setopt(curl_easy_handle, CURLOPT_USERAGENT, "RDKCaptiveCheck/1.0");
if(!headReq)
{
/* HTTPGET request added insted of HTTPHEAD request fix for DELIA-61526 */
curl_easy_setopt(curl_easy_handle, CURLOPT_HTTPGET, 1L);
}
curl_easy_setopt(curl_easy_handle, CURLOPT_WRITEFUNCTION, writeFunction);
curl_easy_setopt(curl_easy_handle, CURLOPT_TIMEOUT_MS, deadline - current_time());
if ((ipversion == CURL_IPRESOLVE_V4) || (ipversion == CURL_IPRESOLVE_V6))
{
NMLOG_DEBUG("curlopt ipversion = %s reqtyp = %s", ipversion == CURL_IPRESOLVE_V4?"IPv4":"IPv6", headReq? "HEAD":"GET");
curl_easy_setopt(curl_easy_handle, CURLOPT_IPRESOLVE, ipversion);
}
else
{
NMLOG_DEBUG("curlopt ipversion = whatever reqtyp = %s", headReq? "HEAD":"GET");
}
if(curlVerboseEnabled())
curl_easy_setopt(curl_easy_handle, CURLOPT_VERBOSE, 1L);
if (CURLM_OK != (mc = curl_multi_add_handle(curl_multi_handle, curl_easy_handle)))
{
NMLOG_ERROR("endpoint = <%s> curl_multi_add_handle returned %d (%s)", endpoint.c_str(), mc, curl_multi_strerror(mc));
curl_easy_cleanup(curl_easy_handle);
continue;
}
curl_easy_handles.push_back(curl_easy_handle);
}
int handles, msgs_left;
char *url = nullptr;
#if LIBCURL_VERSION_NUM < 0x074200
int numfds, repeats = 0;
#endif
char *endpoint = nullptr;
while (1)
{
if (CURLM_OK != (mc = curl_multi_perform(curl_multi_handle, &handles)))
{
NMLOG_ERROR("curl_multi_perform returned %d (%s)", mc, curl_multi_strerror(mc));
break;
}
for (CURLMsg *msg; NULL != (msg = curl_multi_info_read(curl_multi_handle, &msgs_left)); )
{
long response_code = -1;
if (msg->msg != CURLMSG_DONE)
continue;
curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &endpoint);
if (CURLE_OK == msg->data.result) {
if (curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &response_code) == CURLE_OK)
{
if (HttpStatus_302_Found == response_code) {
if ( (curl_easy_getinfo(msg->easy_handle, CURLINFO_REDIRECT_URL, &url) == CURLE_OK) && url != nullptr) {
NMLOG_INFO("captive portal found !!!");
captivePortalURI = url;
}
}
}
}
else
NMLOG_ERROR("endpoint = <%s> curl error = %d (%s)", endpoint, msg->data.result, curl_easy_strerror(msg->data.result));
http_responses.push_back(response_code);
}
time_earlier = time_now;
time_now = current_time();
if (handles == 0 || time_now >= deadline)
break;
#if LIBCURL_VERSION_NUM < 0x074200
if (CURLM_OK != (mc = curl_multi_wait(curl_multi_handle, NULL, 0, deadline - time_now, &numfds)))
{
LOGERR("curl_multi_wait returned %d (%s)", mc, curl_multi_strerror(mc));
break;
}
if (numfds == 0)
{
repeats++;
if (repeats > 1)
usleep(10*1000); /* sleep 10 ms */
}
else
repeats = 0;
#else
if (CURLM_OK != (mc = curl_multi_poll(curl_multi_handle, NULL, 0, deadline - time_now, NULL)))
{
NMLOG_ERROR("curl_multi_poll returned %d (%s)", mc, curl_multi_strerror(mc));
break;
}
#endif
}
if(curlVerboseEnabled()) {
NMLOG_DEBUG("endpoints count = %d response count %d, handles = %d, deadline = %ld, time_now = %ld, time_earlier = %ld",
static_cast<int>(endpoints.size()), static_cast<int>(http_responses.size()), handles, deadline, time_now, time_earlier);
}
for (const auto& curl_easy_handle : curl_easy_handles)
{
curl_easy_getinfo(curl_easy_handle, CURLINFO_PRIVATE, &endpoint);
//LOG_DBG("endpoint = <%s> terminating attempt", endpoint);
curl_multi_remove_handle(curl_multi_handle, curl_easy_handle);
curl_easy_cleanup(curl_easy_handle);
}
curl_multi_cleanup(curl_multi_handle);
/* free the custom headers */
curl_slist_free_all(chunk);
return checkInternetStateFromResponseCode(http_responses);
}
/*
* verifying Most occurred response code is 50 % or more
* Example 1 :
* if we have 5 endpoints so response also 5 ( 204 302 204 204 200 ) . Here count is 204 :- 3, 302 :- 1, 200 :- 1
* Return Internet State: FULLY_CONNECTED - 60 %
* Example 2 :
* if we have 4 endpoints so response also 4 ( 204 204 200 200 ) . Here count is 204 :- 2, 200 :- 2
* Return Internet State: FULLY_CONNECTED - 50 %
*/
nsm_internetState TestConnectivity::checkInternetStateFromResponseCode(const std::vector<int>& responses)
{
nsm_internetState InternetConnectionState = NO_INTERNET;
nsm_connectivity_httpcode http_response_code = HttpStatus_response_error;
int max_count = 0;
for (int element : responses)
{
int element_count = count(responses.begin(), responses.end(), element);
if (element_count > max_count)
{
http_response_code = static_cast<nsm_connectivity_httpcode>(element);
max_count = element_count;
}
}
/* Calculate the percentage of the most frequent code occurrences */
float percentage = (static_cast<float>(max_count) / responses.size());
/* 50 % connectivity check */
if (percentage >= 0.5)
{
switch (http_response_code)
{
case HttpStatus_204_No_Content:
InternetConnectionState = FULLY_CONNECTED;
NMLOG_INFO("Internet State: FULLY_CONNECTED - %.1f%%", (percentage*100));
break;
case HttpStatus_200_OK:
InternetConnectionState = LIMITED_INTERNET;
NMLOG_INFO("Internet State: LIMITED_INTERNET - %.1f%%", (percentage*100));
break;
case HttpStatus_511_Authentication_Required:
case HttpStatus_302_Found:
InternetConnectionState = CAPTIVE_PORTAL;
NMLOG_INFO("Internet State: CAPTIVE_PORTAL - %.1f%%", (percentage*100));
break;
default:
InternetConnectionState = NO_INTERNET;
if(http_response_code == -1)
NMLOG_ERROR("Internet State: NO_INTERNET (curl error)");
else
NMLOG_WARNING("Internet State: NO_INTERNET (http code: %d - %.1f%%)", static_cast<int>(http_response_code), percentage * 100);
break;
}
}
return InternetConnectionState;
}
ConnectivityMonitor::ConnectivityMonitor()
{
m_cmRunning = false;
m_notify = true;
m_InternetState = nsm_internetState::UNKNOWN;
m_Ipv4InternetState = nsm_internetState::UNKNOWN;
m_Ipv6InternetState = nsm_internetState::UNKNOWN;
}
ConnectivityMonitor::~ConnectivityMonitor()
{
NMLOG_WARNING("~ConnectivityMonitor");
stopConnectivityMonitor();
}
std::vector<std::string> ConnectivityMonitor::getConnectivityMonitorEndpoints()
{
return m_endpoint.getConnectivityMonitorEndpoints();
}
void ConnectivityMonitor::setConnectivityMonitorEndpoints(const std::vector<std::string> &endpoints)
{
m_endpoint.setConnectivityMonitorEndpoints(endpoints);
}
bool ConnectivityMonitor::isConnectedToInternet(nsm_ipversion ipversion)
{
if (nsm_internetState::FULLY_CONNECTED == getInternetState(ipversion))
{
NMLOG_INFO("isConnectedToInternet %s = true", (ipversion == nsm_ipversion::NSM_IPRESOLVE_WHATEVER)?"":(ipversion == nsm_ipversion::NSM_IPRESOLVE_V4? "IPv4":"IPv6"));
return true;
}
NMLOG_WARNING("isConnectedToInternet %s = false",(ipversion == nsm_ipversion::NSM_IPRESOLVE_WHATEVER)?"":(ipversion == nsm_ipversion::NSM_IPRESOLVE_V4? "IPv4":"IPv6") );
return false;
}
nsm_internetState ConnectivityMonitor::getInternetState(nsm_ipversion& ipversion)
{
nsm_internetState internetState = nsm_internetState::UNKNOWN;
switch (ipversion)
{
case NSM_IPRESOLVE_V4:
internetState = m_Ipv4InternetState;
break;
case NSM_IPRESOLVE_V6:
internetState = m_Ipv6InternetState;
break;
case NSM_IPRESOLVE_WHATEVER:
internetState = m_InternetState;
break;
default:
NMLOG_ERROR("Unknown IP version");
return internetState;
}
return internetState;
}
std::string ConnectivityMonitor::getCaptivePortalURI()
{
if(m_Ipv4InternetState == nsm_internetState::CAPTIVE_PORTAL || m_Ipv6InternetState == nsm_internetState::CAPTIVE_PORTAL)
{
NMLOG_INFO("captive portal URI = %s", m_captiveURI.c_str());
return m_captiveURI;
}
NMLOG_WARNING("No captive portal found !");
return std::string("");
}
bool ConnectivityMonitor::startConnectivityMonitor()
{
if (m_cmRunning)
{
m_cmCv.notify_one();
NMLOG_DEBUG("connectivity monitor is already running");
return true;
}
m_cmRunning = true;
m_cmThrdID = std::thread(&ConnectivityMonitor::connectivityMonitorFunction, this);
m_cmThrdID.detach();
if(_instance != nullptr) {
NMLOG_INFO("connectivity monitor started - eth %s - wlan %s",
_instance->m_ethConnected? "up":"down", _instance->m_wlanConnected? "up":"down");
}
return true;
}
bool ConnectivityMonitor::stopConnectivityMonitor()
{
m_cmRunning = false;
m_cmCv.notify_one();
NMLOG_INFO("connectivity monitor stopping ...");
return true;
}
bool ConnectivityMonitor::switchToInitialCheck()
{
m_switchToInitial = true;
m_notify = true; // m_notify internet state because some network state change may happen
m_cmCv.notify_one();
NMLOG_INFO("switching to initial check");
return true;
}
void ConnectivityMonitor::notifyInternetStatusChangedEvent(nsm_internetState newInternetState)
{
static Exchange::INetworkManager::InternetStatus oldState = Exchange::INetworkManager::InternetStatus::INTERNET_UNKNOWN;
if(_instance != nullptr)
{
NMLOG_INFO("notifying internet state %s", getInternetStateString(newInternetState));
Exchange::INetworkManager::InternetStatus newState = static_cast<Exchange::INetworkManager::InternetStatus>(newInternetState);
_instance->ReportInternetStatusChange(oldState , newState);
m_InternetState = newInternetState;
oldState = newState; // 'm_InternetState' not exactly previous state, it may change to unknow when interface changed
}
else
NMLOG_FATAL("NetworkManagerImplementation Instance NULL notifyInternetStatusChange failed.");
}
void ConnectivityMonitor::connectivityMonitorFunction()
{
int timeoutInSec = NMCONNECTIVITY_MONITOR_MIN_INTERVAL;
nsm_ipversion ipVersion = NSM_IPRESOLVE_WHATEVER;
nsm_internetState currentInternetState = NO_INTERNET;
int InitialRetryCount = 0;
int IdealRetryCount = 0;
m_switchToInitial = true;
m_InternetState = UNKNOWN;
m_Ipv4InternetState = UNKNOWN;
m_Ipv6InternetState = UNKNOWN;
m_notify = true;
while (m_cmRunning) {
// Check if no interfaces are connected
if (_instance != nullptr && !_instance->m_ethConnected && !_instance->m_wlanConnected) {
NMLOG_DEBUG("no interface connected, no ccm check");
timeoutInSec = NMCONNECTIVITY_MONITOR_MIN_INTERVAL;
m_InternetState = NO_INTERNET;
m_Ipv4InternetState = NO_INTERNET;
m_Ipv6InternetState = NO_INTERNET;
currentInternetState = NO_INTERNET;
if (InitialRetryCount == 0)
m_notify = true;
InitialRetryCount = 1;
}
// Initial case monitoring
else if (m_switchToInitial) {
NMLOG_INFO("Initial cm check - retry count %d - %s", InitialRetryCount, getInternetStateString(m_InternetState));
timeoutInSec = NMCONNECTIVITY_MONITOR_MIN_INTERVAL;
// Lambda functions to check connectivity for IPv4 and IPv6
auto curlCheckThrdIpv4 = [&]() {
TestConnectivity testInternet(m_endpoint(), NMCONNECTIVITY_CURL_REQUEST_TIMEOUT_MS,
NMCONNECTIVITY_CURL_HEAD_REQUEST, NSM_IPRESOLVE_V4);
m_Ipv4InternetState = testInternet.getInternetState();
if(m_Ipv6InternetState == CAPTIVE_PORTAL)
m_captiveURI = testInternet.getCaptivePortal();
};
auto curlCheckThrdIpv6 = [&]() {
TestConnectivity testInternet(m_endpoint(), NMCONNECTIVITY_CURL_REQUEST_TIMEOUT_MS,
NMCONNECTIVITY_CURL_HEAD_REQUEST, NSM_IPRESOLVE_V6);
m_Ipv6InternetState = testInternet.getInternetState();
if(m_Ipv6InternetState == CAPTIVE_PORTAL)
m_captiveURI = testInternet.getCaptivePortal();
};
// Start threads for IPv4 and IPv6 checks
std::thread ipv4thread(curlCheckThrdIpv4);
std::thread ipv6thread(curlCheckThrdIpv6);
// Wait for both threads to finish
ipv4thread.join();
ipv6thread.join();
// Determine the current internet state based on the results
if (m_Ipv4InternetState == NO_INTERNET && m_Ipv6InternetState == NO_INTERNET) {
currentInternetState = NO_INTERNET;
if (InitialRetryCount == 0)
m_notify = true;
InitialRetryCount = 1; // continue same check for 5 sec
} else {
if (m_Ipv4InternetState == FULLY_CONNECTED || m_Ipv6InternetState == FULLY_CONNECTED) {
currentInternetState = FULLY_CONNECTED;
ipVersion = (m_Ipv4InternetState == FULLY_CONNECTED) ? NSM_IPRESOLVE_V4 : NSM_IPRESOLVE_V6;
} else if (m_Ipv4InternetState == CAPTIVE_PORTAL || m_Ipv6InternetState == CAPTIVE_PORTAL) {
currentInternetState = CAPTIVE_PORTAL;
ipVersion = (m_Ipv4InternetState == CAPTIVE_PORTAL) ? NSM_IPRESOLVE_V4 : NSM_IPRESOLVE_V6;
} else if (m_Ipv4InternetState == LIMITED_INTERNET || m_Ipv6InternetState == LIMITED_INTERNET) {
currentInternetState = LIMITED_INTERNET;
ipVersion = (m_Ipv4InternetState == LIMITED_INTERNET) ? NSM_IPRESOLVE_V4 : NSM_IPRESOLVE_V6;
} else {
currentInternetState = NO_INTERNET;
ipVersion = NSM_IPRESOLVE_WHATEVER;
}
if (InitialRetryCount == 0)
m_notify = true;
if (currentInternetState != m_InternetState) {
NMLOG_DEBUG("initial connectivity state change %s", getInternetStateString(m_InternetState));
m_InternetState = currentInternetState;
InitialRetryCount = 1; // reset retry count to get continuous 3 same state
}
InitialRetryCount++;
}
if (InitialRetryCount > NM_CONNECTIVITY_MONITOR_RETRY_COUNT) {
m_switchToInitial = false;
m_notify = true;
InitialRetryCount = 0;
IdealRetryCount = 0;
}
}
// Ideal case monitoring
else {
timeoutInSec = NMCONNECTIVITY_MONITOR_RETRY_INTERVAL;
InitialRetryCount = 0;
TestConnectivity testInternet(m_endpoint(), NMCONNECTIVITY_CURL_REQUEST_TIMEOUT_MS,
NMCONNECTIVITY_CURL_HEAD_REQUEST, ipVersion);
currentInternetState = testInternet.getInternetState();
if (currentInternetState == CAPTIVE_PORTAL) // if captive portal found copy the URL
m_captiveURI = testInternet.getCaptivePortal();
if (currentInternetState != m_InternetState)
{
if (currentInternetState == NO_INTERNET && m_InternetState == FULLY_CONNECTED)
{
DnsResolver dnsResolver(getConnectivityMonitorEndpoints()[0], ipVersion); // only first endpoint with specific ipversion
if (dnsResolver()) {
NMLOG_INFO("DNS resolved, success !!!");
IdealRetryCount = 0;
currentInternetState = FULLY_CONNECTED;
}
else
{
NMLOG_WARNING("DNS resolve failed !!!");
timeoutInSec = NMCONNECTIVITY_MONITOR_MIN_INTERVAL; // retry in 5 sec
IdealRetryCount++;
if (IdealRetryCount >= NM_CONNECTIVITY_MONITOR_RETRY_COUNT) {
IdealRetryCount = 0;
m_InternetState = NO_INTERNET;
m_Ipv4InternetState = NO_INTERNET;
m_Ipv6InternetState = NO_INTERNET; // reset all states to NO_INTERNET
m_switchToInitial = true; // switch to initial check after 3 retries
InitialRetryCount = 1; // reset initial retry count it will not post the event
m_notify = true;
NMLOG_DEBUG("No internet retrying completed notifying !!!");
} else {
NMLOG_INFO("No internet retrying connection check %d ...", IdealRetryCount);
}
}
} else {
// a state change happened but it is not fully connected to no internet
// switch to initial check to get the correct state
m_switchToInitial = true;
InitialRetryCount = 0;
IdealRetryCount = 0;
if (ipVersion == NSM_IPRESOLVE_V4)
m_Ipv4InternetState = currentInternetState;
else if (ipVersion == NSM_IPRESOLVE_V6)
m_Ipv6InternetState = currentInternetState;
else
m_InternetState = currentInternetState;
}
} else { // ideal case no change in network state
IdealRetryCount = 0;
}
}
if (m_notify) {
m_InternetState = currentInternetState;
notifyInternetStatusChangedEvent(m_InternetState);
m_notify = false;
}
if (!m_cmRunning)
break;
// Wait for next interval
std::unique_lock<std::mutex> lock(m_cmMutex);
if (m_cmCv.wait_for(lock, std::chrono::seconds(timeoutInSec)) != std::cv_status::timeout) {
NMLOG_INFO("connectivity monitor received signal. skipping %d sec interval", timeoutInSec);
}
}
}
} // namespace Plugin
} // namespace WPEFramework