forked from rdkcentral/networkmanager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNetworkManagerImplementation.cpp
857 lines (740 loc) · 35.8 KB
/
NetworkManagerImplementation.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
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
/**
* If not stated otherwise in this file or this component's LICENSE
* file the following copyright and licenses apply:
*
* Copyright 2023 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 <thread>
#include <chrono>
#include "NetworkManagerImplementation.h"
using namespace WPEFramework;
using namespace WPEFramework::Plugin;
using namespace NetworkManagerLogger;
#define CIDR_NETMASK_IP_LEN 32
#define RSSID_COMMAND "wpa_cli signal_poll"
#define SSID_COMMAND "wpa_cli status"
namespace WPEFramework
{
namespace Plugin
{
SERVICE_REGISTRATION(NetworkManagerImplementation, NETWORKMANAGER_MAJOR_VERSION, NETWORKMANAGER_MINOR_VERSION, NETWORKMANAGER_PATCH_VERSION);
NetworkManagerImplementation::NetworkManagerImplementation()
: _notificationCallbacks({})
{
/* Initialize STUN Endpoints */
m_stunEndpoint = "stun.l.google.com";
m_stunPort = 19302;
m_stunBindTimeout = 30;
m_stunCacheTimeout = 0;
m_defaultInterface = "";
m_publicIP = "";
m_ethConnected = false;
m_wlanConnected = false;
/* Initialize Network Manager */
NetworkManagerLogger::Init();
LOG_ENTRY_FUNCTION();
}
NetworkManagerImplementation::~NetworkManagerImplementation()
{
LOG_ENTRY_FUNCTION();
if(m_registrationThread.joinable())
{
m_registrationThread.join();
}
stopWiFiSignalStrengthMonitor();
}
/**
* Register a notification callback
*/
uint32_t NetworkManagerImplementation::Register(INetworkManager::INotification *notification)
{
LOG_ENTRY_FUNCTION();
_notificationLock.Lock();
// Make sure we can't register the same notification callback multiple times
if (std::find(_notificationCallbacks.begin(), _notificationCallbacks.end(), notification) == _notificationCallbacks.end()) {
_notificationCallbacks.push_back(notification);
notification->AddRef();
}
_notificationLock.Unlock();
return Core::ERROR_NONE;
}
/**
* Unregister a notification callback
*/
uint32_t NetworkManagerImplementation::Unregister(INetworkManager::INotification *notification)
{
LOG_ENTRY_FUNCTION();
_notificationLock.Lock();
// Make sure we can't register the same notification callback multiple times
auto itr = std::find(_notificationCallbacks.begin(), _notificationCallbacks.end(), notification);
if (itr != _notificationCallbacks.end()) {
(*itr)->Release();
_notificationCallbacks.erase(itr);
}
_notificationLock.Unlock();
return Core::ERROR_NONE;
}
uint32_t NetworkManagerImplementation::Configure(PluginHost::IShell* service)
{
LOG_ENTRY_FUNCTION();
Configuration config;
if (service)
{
string configLine = service->ConfigLine();
if(configLine.empty())
{
NMLOG_FATAL("config line : is empty !");
return Core::ERROR_GENERAL;
}
else
{
NMLOG_INFO("Loading the incoming configuration : %s", configLine.c_str());
config.FromString(configLine);
}
}
else
{
NMLOG_FATAL("Service is NULL!");
return Core::ERROR_GENERAL;
}
NetworkManagerLogger::SetLevel(static_cast <NetworkManagerLogger::LogLevel>(config.loglevel.Value()));
NMLOG_DEBUG("loglevel %d", config.loglevel.Value());
/* STUN configuration copy */
m_stunEndpoint = config.stun.stunEndpoint.Value();
m_stunPort = config.stun.port.Value();
m_stunBindTimeout = config.stun.interval.Value();
NMLOG_INFO("stun endpoint %s", m_stunEndpoint.c_str());
NMLOG_DEBUG("stun port %d", m_stunPort);
NMLOG_DEBUG("stun interval %d", m_stunBindTimeout);
/* Connectivity monitor endpoints configuration */
std::vector<std::string> connectEndpts;
if(!config.connectivityConf.endpoint_1.Value().empty()) {
NMLOG_INFO("connectivity endpoint 1 %s", config.connectivityConf.endpoint_1.Value().c_str());
connectEndpts.push_back(config.connectivityConf.endpoint_1.Value().c_str());
}
if(!config.connectivityConf.endpoint_2.Value().empty()) {
NMLOG_DEBUG("connectivity endpoint 2 %s", config.connectivityConf.endpoint_2.Value().c_str());
connectEndpts.push_back(config.connectivityConf.endpoint_2.Value().c_str());
}
if(!config.connectivityConf.endpoint_3.Value().empty()) {
NMLOG_DEBUG("connectivity endpoint 3 %s", config.connectivityConf.endpoint_3.Value().c_str());
connectEndpts.push_back(config.connectivityConf.endpoint_3.Value().c_str());
}
if(!config.connectivityConf.endpoint_4.Value().empty()) {
NMLOG_DEBUG("connectivity endpoint 4 %s", config.connectivityConf.endpoint_4.Value().c_str());
connectEndpts.push_back(config.connectivityConf.endpoint_4.Value().c_str());
}
if(!config.connectivityConf.endpoint_5.Value().empty()) {
NMLOG_DEBUG("connectivity endpoint 5 %s", config.connectivityConf.endpoint_5.Value().c_str());
connectEndpts.push_back(config.connectivityConf.endpoint_5.Value().c_str());
}
/* check whether the endpoint is already loaded from Cache; if Yes, do not use the one from configuration */
if (connectivityMonitor.getConnectivityMonitorEndpoints().size() < 1)
{
NMLOG_INFO("Use the connectivity endpoint from config");
connectivityMonitor.setConnectivityMonitorEndpoints(connectEndpts);
}
else if (connectEndpts.size() < 1)
{
std::vector<std::string> backup;
NMLOG_INFO("Connectivity endpoints are empty in config; use the default");
backup.push_back("http://clients3.google.com/generate_204");
connectivityMonitor.setConnectivityMonitorEndpoints(backup);
}
/* As all the configuration is set, lets instantiate platform */
NetworkManagerImplementation::platform_init();
return(Core::ERROR_NONE);
}
/* @brief Get STUN Endpoint to be used for identifying Public IP */
uint32_t NetworkManagerImplementation::GetStunEndpoint (string &endpoint /* @out */, uint32_t& port /* @out */, uint32_t& bindTimeout /* @out */, uint32_t& cacheTimeout /* @out */) const
{
LOG_ENTRY_FUNCTION();
endpoint = m_stunEndpoint;
port = m_stunPort;
bindTimeout = m_stunBindTimeout;
cacheTimeout = m_stunCacheTimeout;
return Core::ERROR_NONE;
}
/* @brief Set STUN Endpoint to be used to identify Public IP */
uint32_t NetworkManagerImplementation::SetStunEndpoint (string const endpoint /* @in */, const uint32_t port /* @in */, const uint32_t bindTimeout /* @in */, const uint32_t cacheTimeout /* @in */)
{
LOG_ENTRY_FUNCTION();
if (!endpoint.empty())
m_stunEndpoint = endpoint;
if (0 != port)
m_stunPort = port;
if (0 != bindTimeout)
m_stunBindTimeout = bindTimeout;
if (0 != cacheTimeout)
m_stunCacheTimeout = cacheTimeout;
return Core::ERROR_NONE;
}
/* @brief Get ConnectivityTest Endpoints */
uint32_t NetworkManagerImplementation::GetConnectivityTestEndpoints(IStringIterator*& endpoints/* @out */) const
{
LOG_ENTRY_FUNCTION();
std::vector<std::string> tmpEndpoints = connectivityMonitor.getConnectivityMonitorEndpoints();
endpoints = (Core::Service<RPC::StringIterator>::Create<RPC::IStringIterator>(tmpEndpoints));
return Core::ERROR_NONE;
}
/* @brief Set ConnectivityTest Endpoints */
uint32_t NetworkManagerImplementation::SetConnectivityTestEndpoints(IStringIterator* const endpoints /* @in */)
{
LOG_ENTRY_FUNCTION();
std::vector<std::string> tmpEndpoints;
if(endpoints && (endpoints->Count() >= 1))
{
string endpoint{};
while(endpoints->Next(endpoint))
{
/* The url must be atleast 7 letters to be a valid `http://` url */
if(!endpoint.empty() && endpoint.size() > 7)
{
tmpEndpoints.push_back(endpoint);
}
}
connectivityMonitor.setConnectivityMonitorEndpoints(tmpEndpoints);
}
return Core::ERROR_NONE;
}
/* @brief Get Internet Connectivty Status */
uint32_t NetworkManagerImplementation::IsConnectedToInternet(string &ipversion /* @inout */, InternetStatus &result /* @out */)
{
LOG_ENTRY_FUNCTION();
Exchange::INetworkManager::IPVersion curlIPversion = Exchange::INetworkManager::IP_ADDRESS_V4;
bool ipVersionNotSpecified = false;
if(0 == strcasecmp("IPv4", ipversion.c_str()))
curlIPversion = Exchange::INetworkManager::IP_ADDRESS_V4;
else if(0 == strcasecmp("IPv6", ipversion.c_str()))
curlIPversion = Exchange::INetworkManager::IP_ADDRESS_V6;
else
ipVersionNotSpecified = true;
result = connectivityMonitor.getInternetState(curlIPversion, ipVersionNotSpecified);
if (Exchange::INetworkManager::IP_ADDRESS_V6 == curlIPversion)
ipversion = "IPv6";
else
ipversion = "IPv4";
return Core::ERROR_NONE;
}
/* @brief Get Authentication URL if the device is behind Captive Portal */
uint32_t NetworkManagerImplementation::GetCaptivePortalURI(string &uri /* @out */) const
{
LOG_ENTRY_FUNCTION();
uri = connectivityMonitor.getCaptivePortalURI();
return Core::ERROR_NONE;
}
/* @brief Get the Public IP used for external world communication */
uint32_t NetworkManagerImplementation::GetPublicIP (string& interface /* @inout */, string &ipversion /* @inout */, string& ipaddress /* @out */)
{
LOG_ENTRY_FUNCTION();
stun::bind_result result;
bool isIPv6 = (ipversion == "IPv6");
// Either Interface must be connected to get the public IP
if (!(m_ethConnected | m_wlanConnected))
{
NMLOG_WARNING("No interface Connected");
return Core::ERROR_GENERAL;
}
stun::protocol proto (isIPv6 ? stun::protocol::af_inet6 : stun::protocol::af_inet);
if(stunClient.bind(m_stunEndpoint, m_stunPort, interface, proto, m_stunBindTimeout, m_stunCacheTimeout, result))
{
if (isIPv6)
ipversion = "IPv6";
else
ipversion = "IPv4";
if (interface.empty())
interface = m_defaultInterface;
ipaddress = result.public_ip;
return Core::ERROR_NONE;
}
else
{
return Core::ERROR_GENERAL;
}
}
/* @brief Set the network manager plugin log level */
uint32_t NetworkManagerImplementation::SetLogLevel(const Logging& level /* @in */)
{
NetworkManagerLogger::SetLevel((LogLevel)level);
return Core::ERROR_NONE;
}
/* @brief Get the network manager plugin log level */
uint32_t NetworkManagerImplementation::GetLogLevel(Logging& level /* @out */)
{
LogLevel inLevel;
NetworkManagerLogger::GetLevel(inLevel);
level = static_cast<Logging>(inLevel);
return Core::ERROR_NONE;
}
/* @brief Request for ping and get the response in as event. The GUID used in the request will be returned in the event. */
uint32_t NetworkManagerImplementation::Ping (const string ipversion /* @in */, const string endpoint /* @in */, const uint32_t noOfRequest /* @in */, const uint16_t timeOutInSeconds /* @in */, const string guid /* @in */, string& response /* @out */)
{
char cmd[100] = "";
string tempResult = "";
if(0 == strcasecmp("IPv6", ipversion.c_str()))
{
snprintf(cmd, sizeof(cmd), "ping6 -c %d -W %d '%s' 2>&1", noOfRequest, timeOutInSeconds, endpoint.c_str());
}
else
{
snprintf(cmd, sizeof(cmd), "ping -c %d -W %d '%s' 2>&1", noOfRequest, timeOutInSeconds, endpoint.c_str());
}
NMLOG_DEBUG ("The Command is %s", cmd);
string commandToExecute(cmd);
executeExternally(NETMGR_PING, commandToExecute, tempResult);
JsonObject temp;
temp.FromString(tempResult);
temp["endpoint"] = endpoint;
temp.ToString(response);
return Core::ERROR_NONE;
}
/* @brief Request for trace get the response in as event. The GUID used in the request will be returned in the event. */
uint32_t NetworkManagerImplementation::Trace (const string ipversion /* @in */, const string endpoint /* @in */, const uint32_t noOfRequest /* @in */, const string guid /* @in */, string& response /* @out */)
{
char cmd[256] = "";
string tempResult = "";
if(0 == strcasecmp("IPv6", ipversion.c_str()))
{
snprintf(cmd, 256, "traceroute6 -w 3 -m 6 -q %d %s 64 2>&1", noOfRequest, endpoint.c_str());
}
else
{
snprintf(cmd, 256, "traceroute -w 3 -m 6 -q %d %s 52 2>&1", noOfRequest, endpoint.c_str());
}
NMLOG_DEBUG ("The Command is %s", cmd);
string commandToExecute(cmd);
executeExternally(NETMGR_TRACE, commandToExecute, tempResult);
JsonObject temp;
temp["endpoint"] = endpoint;
temp["results"] = tempResult;
temp.ToString(response);
return Core::ERROR_NONE;
}
void NetworkManagerImplementation::executeExternally(NetworkEvents event, const string commandToExecute, string& response)
{
FILE *pipe = NULL;
string output{};
char buffer[1024];
JsonObject pingResult;
int exitStatus;
pipe = popen(commandToExecute.c_str(), "r");
if (pipe == NULL)
{
NMLOG_INFO ("%s: failed to open file '%s' for read mode with result: %s", __FUNCTION__, commandToExecute.c_str(), strerror(errno));
return;
}
if (NETMGR_PING == event)
{
while (!feof(pipe) && fgets(buffer, 1024, pipe) != NULL)
{
// remove newline from buffer
buffer[strcspn(buffer, "\n")] = '\0';
string line(buffer);
if( line.find( "packet" ) != string::npos )
{
//Example: 10 packets transmitted, 10 packets received, 0% packet loss
stringstream ss( line );
int transCount;
ss >> transCount;
pingResult["packetsTransmitted"] = transCount;
string token;
getline( ss, token, ',' );
getline( ss, token, ',' );
stringstream ss2( token );
int rxCount;
ss2 >> rxCount;
pingResult["packetsReceived"] = rxCount;
getline( ss, token, ',' );
string prefix = token.substr(0, token.find("%"));
pingResult["packetLoss"] = prefix.c_str();
}
else if( line.find( "min/avg/max" ) != string::npos )
{
//Example: round-trip min/avg/max = 17.038/18.310/20.197 ms
stringstream ss( line );
string fullpath;
getline( ss, fullpath, '=' );
getline( ss, fullpath, '=' );
string prefix;
int index = fullpath.find("/");
if (index >= 0)
{
prefix = fullpath.substr(0, fullpath.find("/"));
pingResult["tripMin"] = prefix.c_str();
}
index = fullpath.find("/");
if (index >= 0)
{
fullpath = fullpath.substr(index + 1, fullpath.length());
prefix = fullpath.substr(0, fullpath.find("/"));
pingResult["tripAvg"] = prefix.c_str();
}
index = fullpath.find("/");
if (index >= 0)
{
fullpath = fullpath.substr(index + 1, fullpath.length());
prefix = fullpath.substr(0, fullpath.find("/"));
pingResult["tripMax"] = prefix.c_str();
}
index = fullpath.find("/");
if (index >= 0)
{
fullpath = fullpath.substr(index + 1, fullpath.length());
pingResult["tripStdDev"] = fullpath.c_str();
}
}
else if( line.find( "bad" ) != string::npos )
{
pingResult["success"] = false;
pingResult["error"] = "Bad Address";
}
}
exitStatus = pclose(pipe);
// Check the exit status to determine if the command was successful
if (WIFEXITED(exitStatus) && WEXITSTATUS(exitStatus) == 0) {
pingResult["success"] = true;
pingResult["error"] = "";
} else {
pingResult["success"] = false;
pingResult["error"] = "Could not ping endpoint";
}
pingResult.ToString(response);
NMLOG_INFO("Response is, %s", response.c_str());
}
else if (NETMGR_TRACE == event)
{
// We return the entire output of the trace command but since this contains newlines it is not valid as
// a json value so we will parse the output into an array of strings, one element for each line.
JsonArray list;
while (!feof(pipe) && fgets(buffer, 1024, pipe) != NULL)
{
// remove newline from buffer
buffer[strcspn(buffer, "\n")] = ' ';
string line(buffer);
list.Add(line);
}
pclose(pipe);
list.ToString(response);
NMLOG_INFO("Response is, %s", response.c_str());
}
return;
}
void NetworkManagerImplementation::filterScanResults(JsonArray &ssids)
{
JsonArray result;
double filterFreq = 0.0;
std::unordered_set<std::string> scanForSsidsSet(m_filterSsidslist.begin(), m_filterSsidslist.end());
// If neither SSID list nor frequency is provided, exit
if (m_filterSsidslist.empty() && m_filterfrequency.empty())
{
NMLOG_DEBUG("Neither SSID nor Frequency is provided. Exiting function.");
return;
}
if (!m_filterfrequency.empty())
{
filterFreq = std::stod(m_filterfrequency);
NMLOG_DEBUG("Frequency provided: %lf\n", filterFreq);
}
for (int i = 0; i < ssids.Length(); i++)
{
JsonObject object = ssids[i].Object();
string ssid = object["ssid"].String();
string frequency = object["frequency"].String();
NMLOG_DEBUG("Processing SSID: %s, Frequency: %s\n", ssid.c_str(), frequency.c_str());
double frequencyValue = std::stod(frequency);
//Debug to print log
NMLOG_DEBUG("Processing Frequency after double conversion: %lf\n", frequencyValue);
bool ssidMatches = scanForSsidsSet.empty() || scanForSsidsSet.find(ssid) != scanForSsidsSet.end();
bool freqMatches = m_filterfrequency.empty() || (filterFreq == frequencyValue);
if (ssidMatches && freqMatches)
{
result.Add(object);
NMLOG_DEBUG("Match found: SSID = %s, Frequency = %lf\n", ssid.c_str(), frequencyValue);
}
else
{
NMLOG_DEBUG("No match: SSID = %s, Frequency = %lf\n", ssid.c_str(), frequencyValue);
}
}
ssids = result;
NMLOG_DEBUG("After filtering, found %d SSIDs.", ssids.Length());
}
// WiFi Specific Methods
/* @brief Initiate a WIFI Scan; This is Async method and returns the scan results as Event */
uint32_t NetworkManagerImplementation::GetSupportedSecurityModes(ISecurityModeIterator*& securityModes /* @out */) const
{
LOG_ENTRY_FUNCTION();
std::vector<WIFISecurityModeInfo> modeInfo {
{WIFI_SECURITY_NONE, "NONE"},
{WIFI_SECURITY_WPA_PSK, "WPA_PSK"},
{WIFI_SECURITY_SAE, "SAE"},
{WIFI_SECURITY_EAP, "EAP"},
};
using Implementation = RPC::IteratorType<Exchange::INetworkManager::ISecurityModeIterator>;
securityModes = Core::Service<Implementation>::Create<Exchange::INetworkManager::ISecurityModeIterator>(modeInfo);
return Core::ERROR_NONE;
}
void NetworkManagerImplementation::ReportInterfaceStateChange(const Exchange::INetworkManager::InterfaceState state, const string interface)
{
LOG_ENTRY_FUNCTION();
if(Exchange::INetworkManager::INTERFACE_LINK_DOWN == state || Exchange::INetworkManager::INTERFACE_REMOVED == state)
{
if(interface == "eth0")
m_ethConnected = false;
else if(interface == "wlan0")
m_wlanConnected = false;
connectivityMonitor.switchToInitialCheck();
}
/* Only the Ethernet connection status is changing here. The WiFi status is updated in the WiFi state callback. */
if(Exchange::INetworkManager::INTERFACE_LINK_UP == state && interface == "eth0")
m_ethConnected = true;
_notificationLock.Lock();
NMLOG_INFO("Posting onInterfaceChange %s - %u", interface.c_str(), (unsigned)state);
for (const auto callback : _notificationCallbacks) {
callback->onInterfaceStateChange(state, interface);
}
_notificationLock.Unlock();
}
void NetworkManagerImplementation::ReportActiveInterfaceChange(const string prevActiveInterface, const string currentActiveinterface)
{
_notificationLock.Lock();
NMLOG_INFO("Posting onActiveInterfaceChange %s", currentActiveinterface.c_str());
if(currentActiveinterface == "eth0")
m_ethConnected = true;
else if (currentActiveinterface == "wlan0")
m_wlanConnected = true;
// FIXME : This could be the place to define `m_defaultInterface` to incoming `currentActiveinterface`.
// m_defaultInterface = currentActiveinterface;
for (const auto callback : _notificationCallbacks) {
callback->onActiveInterfaceChange(prevActiveInterface, currentActiveinterface);
}
_notificationLock.Unlock();
}
void NetworkManagerImplementation::ReportIPAddressChange(const string interface, const string ipversion, const string ipaddress, const Exchange::INetworkManager::IPStatus status)
{
LOG_ENTRY_FUNCTION();
if (Exchange::INetworkManager::IP_ACQUIRED == status) {
// Switch the connectivity monitor to initial check
// if ipaddress is aquired means there should be interface connected
if(interface == "eth0")
m_ethConnected = true;
else if(interface == "wlan0")
m_wlanConnected = true;
// FIXME : Availability of ip address for a given interface does not mean that its the default interface. This hardcoding will work for RDKProxy but not for Gnome.
if (m_ethConnected && m_wlanConnected)
m_defaultInterface = "eth0";
else
m_defaultInterface = interface;
connectivityMonitor.switchToInitialCheck();
}
_notificationLock.Lock();
NMLOG_INFO("Posting onIPAddressChange %s - %s", ipaddress.c_str(), interface.c_str());
for (const auto callback : _notificationCallbacks) {
callback->onIPAddressChange(interface, ipversion, ipaddress, status);
}
_notificationLock.Unlock();
}
void NetworkManagerImplementation::ReportInternetStatusChange(const Exchange::INetworkManager::InternetStatus prevState, const Exchange::INetworkManager::InternetStatus currState)
{
_notificationLock.Lock();
NMLOG_INFO("Posting onInternetStatusChange with current state as %u", (unsigned)currState);
for (const auto callback : _notificationCallbacks) {
callback->onInternetStatusChange(prevState, currState);
}
_notificationLock.Unlock();
}
void NetworkManagerImplementation::ReportAvailableSSIDs(const JsonArray &arrayofWiFiScanResults)
{
_notificationLock.Lock();
string jsonOfWiFiScanResults;
string jsonOfFilterScanResults;
JsonArray filterResult = arrayofWiFiScanResults;
arrayofWiFiScanResults.ToString(jsonOfWiFiScanResults);
NMLOG_DEBUG("onAvailableSSIDs Filtering is, %s", jsonOfWiFiScanResults.c_str());
filterScanResults(filterResult);
filterResult.ToString(jsonOfFilterScanResults);
NMLOG_INFO("Posting onAvailableSSIDs event as, %s", jsonOfFilterScanResults.c_str());
for (const auto callback : _notificationCallbacks) {
callback->onAvailableSSIDs(jsonOfFilterScanResults);
}
_notificationLock.Unlock();
}
void NetworkManagerImplementation::startWiFiSignalStrengthMonitor(int interval)
{
if (m_isRunning) {
NMLOG_INFO("WiFiSignalStrengthMonitor Thread is already running.");
return;
}
m_isRunning = true;
m_stopThread = false;
m_monitorThread = std::thread(&NetworkManagerImplementation::monitorThreadFunction, this, interval);
}
void NetworkManagerImplementation::stopWiFiSignalStrengthMonitor()
{
if (!m_isRunning) {
return; // No thread to stop
}
std::lock_guard<std::mutex> lock(m_condVariableMutex);
m_stopThread = true;
m_condVariable.notify_one();
if (m_monitorThread.joinable()) {
m_monitorThread.join();
}
m_isRunning = false;
}
/* The below implementation of GetWiFiSignalStrength is a temporary mitigation. Need to be revisited */
uint32_t NetworkManagerImplementation::GetWiFiSignalStrength(string& ssid /* @out */, string& strength /* @out */, WiFiSignalQuality& quality /* @out */)
{
uint32_t rc = Core::ERROR_RPC_CALL_FAILED;
uint16_t strengthOut = 0;
std::string key, value;
std::string noiseStr = "";
std::string rssiStr = "";
uint16_t rssi = 0;
uint16_t noise = 0;
char buff[512] = {'\0'};
FILE *fp = NULL;
fp = popen(RSSID_COMMAND, "r");
if (!fp)
{
NMLOG_ERROR("Failed in getting output from command %s",RSSID_COMMAND);
return Core::ERROR_RPC_CALL_FAILED;
}
while ((!feof(fp)) && (fgets(buff, sizeof (buff), fp) != NULL))
{
std::istringstream mystream(buff);
if(std::getline(std::getline(mystream, key, '=') >> std::ws, value))
if (key == "RSSI") {
rssiStr = value;
}
else if (key == "NOISE") {
noiseStr = value;
}
if (!rssiStr.empty() && !noiseStr.empty())
break;
}
pclose(fp);
fp = popen(SSID_COMMAND, "r");
if (!fp)
{
NMLOG_ERROR("Failed in getting output from command %s",SSID_COMMAND); return Core::ERROR_RPC_CALL_FAILED;
}
while ((!feof(fp)) && (fgets(buff, sizeof (buff), fp) != NULL)) {
std::istringstream mystream(buff);
if(std::getline(std::getline(mystream, key, '=') >> std::ws, value))
if (key == "ssid") {
ssid = value;
break;
}
}
pclose(fp);
rssi = std::stoi(rssiStr);
noise = std::stoi(noiseStr);
strengthOut = (rssi - noise);
NMLOG_INFO ("WiFiSignalStrength in dB = %u",strengthOut);
if (strengthOut == 0)
{
quality = WiFiSignalQuality::WIFI_SIGNAL_DISCONNECTED;
strength = "0";
}
else if (strengthOut > 0 && strengthOut < NM_WIFI_SNR_THRESHOLD_FAIR)
{
quality = WiFiSignalQuality::WIFI_SIGNAL_WEAK;
}
else if (strengthOut > NM_WIFI_SNR_THRESHOLD_FAIR && strengthOut < NM_WIFI_SNR_THRESHOLD_GOOD)
{
quality = WiFiSignalQuality::WIFI_SIGNAL_FAIR;
}
else if (strengthOut > NM_WIFI_SNR_THRESHOLD_GOOD && strengthOut < NM_WIFI_SNR_THRESHOLD_EXCELLENT)
{
quality = WiFiSignalQuality::WIFI_SIGNAL_GOOD;
}
else
{
quality = WiFiSignalQuality::WIFI_SIGNAL_EXCELLENT;
}
strength = std::to_string(strengthOut);
NMLOG_INFO ("GetWiFiSignalStrength success");
rc = Core::ERROR_NONE;
return rc;
}
void NetworkManagerImplementation::monitorThreadFunction(int interval)
{
static Exchange::INetworkManager::WiFiSignalQuality oldSignalQuality = Exchange::INetworkManager::WIFI_SIGNAL_DISCONNECTED;
NMLOG_INFO("WiFiSignalStrengthMonitor thread started ! (%d)", interval);
while (!m_stopThread) {
std::string ssid;
std::string strength;
std::unique_lock<std::mutex> lock(m_condVariableMutex);
Exchange::INetworkManager::WiFiSignalQuality newSignalQuality;
NMLOG_DEBUG("checking WiFi signal strength");
GetWiFiSignalStrength(ssid, strength, newSignalQuality);
if (oldSignalQuality != newSignalQuality) {
NMLOG_INFO("Notifying WiFiSignalStrengthChangedEvent %s", strength.c_str());
oldSignalQuality = newSignalQuality;
NetworkManagerImplementation::ReportWiFiSignalStrengthChange(ssid, strength, newSignalQuality);
}
if (newSignalQuality == Exchange::INetworkManager::WIFI_SIGNAL_DISCONNECTED) {
NMLOG_WARNING("WiFiSignalStrengthChanged to disconnect - WiFiSignalStrengthMonitor exiting");
m_stopThread = true; // Signal thread to stop
break; // Exit the loop
}
// Wait for the specified interval or until notified to stop
if (m_condVariable.wait_for(lock, std::chrono::seconds(interval), [this](){ return m_stopThread == true; }))
{
NMLOG_INFO("WiFiSignalStrengthMonitor received stop signal or timed out");
}
}
m_isRunning = false;
}
void NetworkManagerImplementation::ReportWiFiStateChange(const Exchange::INetworkManager::WiFiState state)
{
/* start signal strength monitor when wifi connected */
if(INetworkManager::WiFiState::WIFI_STATE_CONNECTED == state)
{
m_wlanConnected = true;
if (!m_monitoringStarted)
{
startWiFiSignalStrengthMonitor(DEFAULT_WIFI_SIGNAL_TEST_INTERVAL_SEC);
m_monitoringStarted = true;
}
}
else
{
if (m_monitoringStarted)
{
stopWiFiSignalStrengthMonitor();
m_monitoringStarted = false;
}
m_wlanConnected = false; /* Any other state is considered as WiFi not connected. */
}
_notificationLock.Lock();
NMLOG_INFO("Posting onWiFiStateChange (%d)", state);
for (const auto callback : _notificationCallbacks) {
callback->onWiFiStateChange(state);
}
_notificationLock.Unlock();
}
void NetworkManagerImplementation::ReportWiFiSignalStrengthChange(const string ssid, const string strength, const Exchange::INetworkManager::WiFiSignalQuality quality)
{
_notificationLock.Lock();
NMLOG_INFO("Posting onWiFiSignalStrengthChange %s", strength.c_str());
for (const auto callback : _notificationCallbacks) {
callback->onWiFiSignalStrengthChange(ssid, strength, quality);
}
_notificationLock.Unlock();
}
}
}