forked from rdkcentral/networkmanager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NetworkManagerGnomeWIFI.cpp
1504 lines (1362 loc) · 65.5 KB
/
NetworkManagerGnomeWIFI.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
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
/*
* 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 <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <glib.h>
#include <NetworkManager.h>
#include <libnm/NetworkManager.h>
#include "NetworkManagerLogger.h"
#include "INetworkManager.h"
#include "NetworkManagerGnomeWIFI.h"
#include "NetworkManagerGnomeUtils.h"
#include "NetworkManagerImplementation.h"
using namespace std;
namespace WPEFramework
{
class Job : public Core::IDispatch {
public:
Job(function<void()> work)
: _work(work)
{
}
void Dispatch() override
{
_work();
}
private:
function<void()> _work;
};
namespace Plugin
{
extern NetworkManagerImplementation* _instance;
wifiManager::wifiManager() : m_client(nullptr), m_loop(nullptr), m_createNewConnection(false) {
NMLOG_INFO("wifiManager");
m_nmContext = g_main_context_new();
g_main_context_push_thread_default(m_nmContext);
m_loop = g_main_loop_new(m_nmContext, FALSE);
}
bool wifiManager::createClientNewConnection()
{
GError *error = NULL;
if(m_client != nullptr)
{
g_object_unref(m_client);
m_client = nullptr;
}
m_client = nm_client_new(NULL, &error);
if (!m_client || !m_loop) {
NMLOG_ERROR("Could not connect to NetworkManager: %s.", error->message);
g_error_free(error);
return false;
}
return true;
}
bool wifiManager::quit(NMDevice *wifiNMDevice)
{
if(!g_main_loop_is_running(m_loop)) {
NMLOG_ERROR("g_main_loop_is not running");
return false;
}
g_main_loop_quit(m_loop);
return false;
}
static gboolean gmainLoopTimoutCB(gpointer user_data)
{
wifiManager *_wifiManager = (static_cast<wifiManager*>(user_data));
NMLOG_WARNING("GmainLoop ERROR_TIMEDOUT");
_wifiManager->m_isSuccess = false;
g_main_loop_quit(_wifiManager->m_loop);
return true;
}
bool wifiManager::wait(GMainLoop *loop, int timeOutMs)
{
if(g_main_loop_is_running(loop)) {
NMLOG_WARNING("g_main_loop_is running");
return false;
}
m_source = g_timeout_source_new(timeOutMs); // 10000ms interval
g_source_set_callback(m_source, (GSourceFunc)gmainLoopTimoutCB, this, NULL);
g_source_attach(m_source, NULL);
g_main_loop_run(loop);
if(m_source != nullptr) {
if(g_source_is_destroyed(m_source)) {
NMLOG_WARNING("Source has been destroyed");
}
else {
g_source_destroy(m_source);
}
g_source_unref(m_source);
}
return true;
}
NMDevice* wifiManager::getWifiDevice()
{
NMDevice *wifiDevice = NULL;
GPtrArray *devices = const_cast<GPtrArray *>(nm_client_get_devices(m_client));
if (devices == NULL) {
NMLOG_ERROR("Failed to get device list.");
return wifiDevice;
}
for (guint j = 0; j < devices->len; j++)
{
NMDevice *device = NM_DEVICE(devices->pdata[j]);
const char* interface = nm_device_get_iface(device);
if(interface == nullptr)
continue;
std::string iface = interface;
if (iface == nmUtils::wlanIface())
{
wifiDevice = device;
//NMLOG_DEBUG("Wireless Device found ifce : %s !", nm_device_get_iface (wifiDevice));
break;
}
}
if (wifiDevice == NULL || !NM_IS_DEVICE_WIFI(wifiDevice))
{
NMLOG_ERROR("Wireless Device not found !");
return NULL;
}
NMDeviceState deviceState = NM_DEVICE_STATE_UNKNOWN;
deviceState = nm_device_get_state(wifiDevice);
switch (deviceState)
{
case NM_DEVICE_STATE_UNKNOWN:
case NM_DEVICE_STATE_UNMANAGED:
case NM_DEVICE_STATE_UNAVAILABLE:
NMLOG_WARNING("wifi device state is not vallied; state: (%d)", deviceState);
return NULL;
break;
default:
break;
}
return wifiDevice;
}
bool static getConnectedSSID(NMDevice *device, std::string& ssidin)
{
GBytes *ssid;
NMDeviceState device_state = nm_device_get_state(device);
if (device_state == NM_DEVICE_STATE_ACTIVATED)
{
NMAccessPoint *activeAP = nm_device_wifi_get_active_access_point(NM_DEVICE_WIFI(device));
ssid = nm_access_point_get_ssid(activeAP);
gsize size;
const guint8 *ssidData = static_cast<const guint8 *>(g_bytes_get_data(ssid, &size));
std::string ssidTmp(reinterpret_cast<const char *>(ssidData), size);
ssidin = ssidTmp;
NMLOG_INFO("connected ssid: %s", ssidin.c_str());
return true;
}
return false;
}
static void getApInfo(NMAccessPoint *AccessPoint, Exchange::INetworkManager::WiFiSSIDInfo &wifiInfo)
{
guint32 flags, wpaFlags, rsnFlags, freq, bitrate;
guint8 strength;
GBytes *ssid;
const char *hwaddr;
NM80211Mode mode;
/* Get AP properties */
flags = nm_access_point_get_flags(AccessPoint);
wpaFlags = nm_access_point_get_wpa_flags(AccessPoint);
rsnFlags = nm_access_point_get_rsn_flags(AccessPoint);
ssid = nm_access_point_get_ssid(AccessPoint);
hwaddr = nm_access_point_get_bssid(AccessPoint);
freq = nm_access_point_get_frequency(AccessPoint);
mode = nm_access_point_get_mode(AccessPoint);
bitrate = nm_access_point_get_max_bitrate(AccessPoint);
strength = nm_access_point_get_strength(AccessPoint);
/* Convert to strings */
if (ssid) {
gsize size;
const guint8 *ssidData = static_cast<const guint8 *>(g_bytes_get_data(ssid, &size));
if(size<=32)
{
std::string ssidTmp(reinterpret_cast<const char *>(ssidData), size);
wifiInfo.ssid = ssidTmp;
NMLOG_INFO("ssid: %s", wifiInfo.ssid.c_str());
}
else
{
NMLOG_ERROR("Invallied ssid length Error");
wifiInfo.ssid.clear();
return;
}
}
else
{
wifiInfo.ssid = "-----";
NMLOG_DEBUG("ssid: %s", wifiInfo.ssid.c_str());
}
wifiInfo.bssid = (hwaddr != nullptr) ? hwaddr : "-----";
NMLOG_DEBUG("bssid: %s", wifiInfo.bssid.c_str());
wifiInfo.frequency = std::to_string((double)freq/1000);
wifiInfo.rate = std::to_string(bitrate);
NMLOG_DEBUG("bitrate : %s kbit/s", wifiInfo.rate.c_str());
//TODO signal strenght to dBm
wifiInfo.strength = std::string(nmUtils::convertPercentageToSignalStrengtStr(strength));
NMLOG_DEBUG("sterngth: %s dbm", wifiInfo.strength.c_str());
wifiInfo.security = static_cast<Exchange::INetworkManager::WIFISecurityMode>(nmUtils::wifiSecurityModeFromAp(flags, wpaFlags, rsnFlags));
NMLOG_DEBUG("security %s", nmUtils::getSecurityModeString(flags, wpaFlags, rsnFlags).c_str());
NMLOG_DEBUG("Mode: %s", mode == NM_802_11_MODE_ADHOC ? "Ad-Hoc": mode == NM_802_11_MODE_INFRA ? "Infrastructure": "Unknown");
}
bool wifiManager::isWifiConnected()
{
if(!createClientNewConnection())
return false;
NMDeviceWifi *wifiDevice = NM_DEVICE_WIFI(getWifiDevice());
if(wifiDevice == NULL) {
NMLOG_FATAL("NMDeviceWifi * NULL !");
return false;
}
NMAccessPoint *activeAP = nm_device_wifi_get_active_access_point(wifiDevice);
if(activeAP == NULL) {
NMLOG_INFO("No active access point found !");
return false;
}
else
NMLOG_DEBUG("active access point found !");
return true;
}
bool wifiManager::wifiConnectedSSIDInfo(Exchange::INetworkManager::WiFiSSIDInfo &ssidinfo)
{
if(!createClientNewConnection())
return false;
NMDeviceWifi *wifiDevice = NM_DEVICE_WIFI(getWifiDevice());
if(wifiDevice == NULL) {
NMLOG_FATAL("NMDeviceWifi * NULL !");
return false;
}
NMAccessPoint *activeAP = nm_device_wifi_get_active_access_point(wifiDevice);
if(activeAP == NULL) {
NMLOG_DEBUG("No active access point found !");
return false;
}
else
NMLOG_DEBUG("active access point found !");
getApInfo(activeAP, ssidinfo);
return true;
}
static void disconnectCb(GObject *object, GAsyncResult *result, gpointer user_data)
{
NMDevice *device = NM_DEVICE(object);
GError *error = NULL;
wifiManager *_wifiManager = (static_cast<wifiManager*>(user_data));
NMLOG_DEBUG("Disconnecting... ");
_wifiManager->m_isSuccess = true;
if (!nm_device_disconnect_finish(device, result, &error)) {
if (g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
return;
NMLOG_ERROR("Device '%s' (%s) disconnecting failed: %s",
nm_device_get_iface(device),
nm_object_get_path(NM_OBJECT(device)),
error->message);
g_error_free(error);
_wifiManager->quit(device);
_wifiManager->m_isSuccess = false;
}
_wifiManager->quit(device);
}
bool wifiManager::wifiDisconnect()
{
if(!createClientNewConnection())
return false;
NMDevice *wifiNMDevice = getWifiDevice();
if(wifiNMDevice == NULL) {
NMLOG_WARNING("wifi state is unmanaged !");
return true;
}
nm_device_disconnect_async(wifiNMDevice, NULL, disconnectCb, this);
wait(m_loop);
return m_isSuccess;
}
static NMAccessPoint *checkSSIDAvailable(NMDevice *device, const char *ssid)
{
NMAccessPoint *AccessPoint = NULL;
const GPtrArray *aps = NULL;
if(ssid == NULL)
return NULL;
aps = nm_device_wifi_get_access_points(NM_DEVICE_WIFI(device));
for (guint i = 0; i < aps->len; i++)
{
NMAccessPoint *ap = static_cast<NMAccessPoint *>(g_ptr_array_index(aps, i));
GBytes *ssidGBytes;
ssidGBytes = nm_access_point_get_ssid(ap);
if (!ssidGBytes)
continue;
gsize size;
const guint8 *ssidData = static_cast<const guint8 *>(g_bytes_get_data(ssidGBytes, &size));
std::string ssidstr(reinterpret_cast<const char *>(ssidData), size);
//g_bytes_unref(ssidGBytes);
// NMLOG_DEBUG("ssid < %s >", ssidstr.c_str());
if (strcmp(ssid, ssidstr.c_str()) == 0)
{
AccessPoint = ap;
break;
}
}
return AccessPoint;
}
static void wifiConnectCb(GObject *client, GAsyncResult *result, gpointer user_data)
{
GError *error = NULL;
wifiManager *_wifiManager = (static_cast<wifiManager*>(user_data));
if (_wifiManager->m_createNewConnection) {
NMLOG_DEBUG("nm_client_add_and_activate_connection_finish");
nm_client_add_and_activate_connection_finish(NM_CLIENT(_wifiManager->m_client), result, &error);
_wifiManager->m_isSuccess = true;
}
else {
NMLOG_DEBUG("nm_client_activate_connection_finish ");
nm_client_activate_connection_finish(NM_CLIENT(_wifiManager->m_client), result, &error);
_wifiManager->m_isSuccess = true;
}
if (error) {
_wifiManager->m_isSuccess = false;
if (_wifiManager->m_createNewConnection) {
NMLOG_ERROR("Failed to add/activate new connection: %s", error->message);
} else {
NMLOG_ERROR("Failed to activate connection: %s", error->message);
}
}
g_main_loop_quit(_wifiManager->m_loop);
}
static void removeKnownSSIDCb(GObject *client, GAsyncResult *result, gpointer user_data)
{
GError *error = NULL;
wifiManager *_wifiManager = (static_cast<wifiManager*>(user_data));
NMRemoteConnection *connection = NM_REMOTE_CONNECTION(client);
if (!nm_remote_connection_delete_finish(connection, result, &error)) {
NMLOG_ERROR("RemoveKnownSSID failed %s", error->message);
_wifiManager->m_isSuccess = false;
}
else
{
NMLOG_INFO ("RemoveKnownSSID is success");
_wifiManager->m_isSuccess = true;
}
_wifiManager->quit(NULL);
}
static void wifiConnectionUpdate(GObject *rmObject, GAsyncResult *res, gpointer user_data)
{
NMRemoteConnection *remote_con = NM_REMOTE_CONNECTION(rmObject);
wifiManager *_wifiManager = (static_cast<wifiManager*>(user_data));
GVariant *ret = NULL;
GError *error = NULL;
ret = nm_remote_connection_update2_finish(remote_con, res, &error);
if (!ret) {
NMLOG_ERROR("Error: %s.", error->message);
g_error_free(error);
_wifiManager->m_isSuccess = false;
_wifiManager->quit(NULL);
return;
}
_wifiManager->m_createNewConnection = false; // no need to create new connection
nm_client_activate_connection_async(
_wifiManager->m_client, NM_CONNECTION(remote_con), _wifiManager->m_wifidevice, _wifiManager->m_objectPath, NULL, wifiConnectCb, _wifiManager);
}
static bool connectionBuilder(const Exchange::INetworkManager::WiFiConnectTo& ssidinfo, NMConnection *m_connection)
{
if(ssidinfo.ssid.empty() || ssidinfo.ssid.length() > 32)
{
NMLOG_WARNING("ssid name is missing or invalied");
return false;
}
/* Build up the 'connection' Setting */
NMSettingConnection *sConnection = (NMSettingConnection *) nm_setting_connection_new();
const char *uuid = nm_utils_uuid_generate();
g_object_set(G_OBJECT(sConnection), NM_SETTING_CONNECTION_UUID, uuid, NULL); // uuid
g_object_set(G_OBJECT(sConnection), NM_SETTING_CONNECTION_ID, ssidinfo.ssid.c_str(), NULL); // connection id = ssid
g_object_set(G_OBJECT(sConnection), NM_SETTING_CONNECTION_INTERFACE_NAME, "wlan0", NULL); // interface name
g_object_set(G_OBJECT(sConnection), NM_SETTING_CONNECTION_TYPE, "802-11-wireless", NULL); // type 802.11wireless
nm_connection_add_setting(m_connection, NM_SETTING(sConnection));
/* Build up the '802-11-wireless-security' settings */
NMSettingWireless *sWireless = NULL;
sWireless = (NMSettingWireless *)nm_setting_wireless_new();
nm_connection_add_setting(m_connection, NM_SETTING(sWireless));
GBytes *ssid = g_bytes_new(ssidinfo.ssid.c_str(), strlen(ssidinfo.ssid.c_str()));
g_object_set(G_OBJECT(sWireless), NM_SETTING_WIRELESS_SSID, ssid, NULL); // ssid in Gbyte
g_object_set(G_OBJECT(sWireless), NM_SETTING_WIRELESS_MODE, NM_SETTING_WIRELESS_MODE_INFRA, NULL); // infra mode
g_object_set(G_OBJECT(sWireless), NM_SETTING_WIRELESS_HIDDEN, true, NULL); // hidden = true
// 'bssid' parameter is used to restrict the connection only to the BSSID
// g_object_set(s_wifi, NM_SETTING_WIRELESS_BSSID, bssid, NULL);
NMSettingWirelessSecurity *sSecurity = NULL;
switch(ssidinfo.security)
{
case Exchange::INetworkManager::WIFISecurityMode::WIFI_SECURITY_WPA_PSK_AES:
case Exchange::INetworkManager::WIFISecurityMode::WIFI_SECURITY_WPA_WPA2_PSK:
case Exchange::INetworkManager::WIFISecurityMode::WIFI_SECURITY_WPA_PSK_TKIP:
case Exchange::INetworkManager::WIFISecurityMode::WIFI_SECURITY_WPA2_PSK_AES:
case Exchange::INetworkManager::WIFISecurityMode::WIFI_SECURITY_WPA2_PSK_TKIP:
case Exchange::INetworkManager::WIFISecurityMode::WIFI_SECURITY_WPA3_SAE:
{
if(ssidinfo.passphrase.empty() || ssidinfo.passphrase.length() < 8)
{
NMLOG_WARNING("password legth should be > 8");
return false;
}
sSecurity = (NMSettingWirelessSecurity *) nm_setting_wireless_security_new();
nm_connection_add_setting(m_connection, NM_SETTING(sSecurity));
if(Exchange::INetworkManager::WIFISecurityMode::WIFI_SECURITY_WPA3_SAE == ssidinfo.security)
{
NMLOG_INFO("key-mgmt: %s", "sae");
g_object_set(G_OBJECT(sSecurity), NM_SETTING_WIRELESS_SECURITY_KEY_MGMT,"sae", NULL);
}
else
{
NMLOG_INFO("key-mgmt: %s", "wpa-psk");
g_object_set(G_OBJECT(sSecurity), NM_SETTING_WIRELESS_SECURITY_KEY_MGMT,"wpa-psk", NULL);
}
g_object_set(G_OBJECT(sSecurity), NM_SETTING_WIRELESS_SECURITY_AUTH_ALG, "open", NULL);
g_object_set(G_OBJECT(sSecurity), NM_SETTING_WIRELESS_SECURITY_PSK, ssidinfo.passphrase.c_str(), NULL);
break;
}
case Exchange::INetworkManager::WIFISecurityMode::WIFI_SECURITY_WPA_ENTERPRISE_TKIP:
case Exchange::INetworkManager::WIFISecurityMode::WIFI_SECURITY_WPA_ENTERPRISE_AES:
case Exchange::INetworkManager::WIFISecurityMode::WIFI_SECURITY_WPA2_ENTERPRISE_TKIP:
case Exchange::INetworkManager::WIFISecurityMode::WIFI_SECURITY_WPA2_ENTERPRISE_AES:
case Exchange::INetworkManager::WIFISecurityMode::WIFI_SECURITY_WPA_WPA2_ENTERPRISE:
{
NMSetting8021x *s8021X = NULL;
GError *error = NULL;
NMLOG_INFO("key-mgmt: %s", "802.1X");
NMLOG_DEBUG("802.1x Identity : %s", ssidinfo.eap_identity.c_str());
NMLOG_DEBUG("802.1x CA cert path : %s", ssidinfo.ca_cert.c_str());
NMLOG_DEBUG("802.1x Client cert path : %s", ssidinfo.client_cert.c_str());
NMLOG_DEBUG("802.1x Private key path : %s", ssidinfo.private_key.c_str());
NMLOG_DEBUG("802.1x Private key psswd : %s", ssidinfo.private_key_passwd.c_str());
s8021X = (NMSetting8021x *) nm_setting_802_1x_new();
nm_connection_add_setting(m_connection, NM_SETTING(s8021X));
g_object_set(s8021X, NM_SETTING_802_1X_IDENTITY, ssidinfo.eap_identity.c_str(), NULL);
nm_setting_802_1x_add_eap_method(s8021X, "tls");
if(!ssidinfo.ca_cert.empty() && !nm_setting_802_1x_set_ca_cert(s8021X,
ssidinfo.ca_cert.c_str(),
NM_SETTING_802_1X_CK_SCHEME_PATH,
NULL,
&error))
{
NMLOG_ERROR("ca certificate add failed: %s", error->message);
g_error_free(error);
return false;
}
if(!ssidinfo.client_cert.empty() && !nm_setting_802_1x_set_client_cert(s8021X,
ssidinfo.client_cert.c_str(),
NM_SETTING_802_1X_CK_SCHEME_PATH,
NULL,
&error))
{
NMLOG_ERROR("client certificate add failed: %s", error->message);
g_error_free(error);
return false;
}
if(!ssidinfo.private_key.empty() && !nm_setting_802_1x_set_private_key(s8021X,
ssidinfo.private_key.c_str(),
ssidinfo.private_key_passwd.c_str(),
NM_SETTING_802_1X_CK_SCHEME_PATH,
NULL,
&error))
{
NMLOG_ERROR("client private key add failed: %s", error->message);
g_error_free(error);
return false;
}
sSecurity = (NMSettingWirelessSecurity *) nm_setting_wireless_security_new();
nm_connection_add_setting(m_connection, NM_SETTING(sSecurity));
g_object_set(G_OBJECT(sSecurity), NM_SETTING_WIRELESS_SECURITY_KEY_MGMT,"wpa-eap", NULL);
break;
}
case Exchange::INetworkManager::WIFI_SECURITY_NONE:
{
NMLOG_INFO("key-mgmt: %s", "none");
sSecurity = (NMSettingWirelessSecurity *) nm_setting_wireless_security_new();
nm_connection_add_setting(m_connection, NM_SETTING(sSecurity));
g_object_set(G_OBJECT(sSecurity), NM_SETTING_WIRELESS_SECURITY_KEY_MGMT,"none", NULL);
NMLOG_WARNING("open wifi network configuration");
break;
}
default:
{
NMLOG_ERROR("wifi securtity type not supported %d", ssidinfo.security);
return false;
}
}
/* Build up the 'ipv4' Setting */
NMSettingIP4Config *sIpv4Conf = (NMSettingIP4Config *) nm_setting_ip4_config_new();
g_object_set(G_OBJECT(sIpv4Conf), NM_SETTING_IP_CONFIG_METHOD, NM_SETTING_IP4_CONFIG_METHOD_AUTO, NULL); // autoconf = true
nm_connection_add_setting(m_connection, NM_SETTING(sIpv4Conf));
/* Build up the 'ipv6' Setting */
NMSettingIP6Config *sIpv6Conf = (NMSettingIP6Config *) nm_setting_ip6_config_new();
g_object_set(G_OBJECT(sIpv6Conf), NM_SETTING_IP_CONFIG_METHOD, NM_SETTING_IP6_CONFIG_METHOD_AUTO, NULL); // autoconf = true
nm_connection_add_setting(m_connection, NM_SETTING(sIpv6Conf));
return true;
}
bool wifiManager::wifiConnect(Exchange::INetworkManager::WiFiConnectTo ssidInfo)
{
NMAccessPoint *AccessPoint = NULL;
NMConnection *m_connection = NULL;
const GPtrArray *availableConnections;
bool SSIDmatch = false;
m_isSuccess = false;
if(!createClientNewConnection())
return false;
NMDevice *device = getWifiDevice();
if(device == NULL)
return false;
std::string activeSSID;
if(getConnectedSSID(device, activeSSID))
{
if(ssidInfo.ssid == activeSSID)
{
NMLOG_INFO("ssid already connected !");
return true;
}
else
NMLOG_DEBUG("wifi already connected with %s AP", activeSSID.c_str());
}
AccessPoint = checkSSIDAvailable(device, ssidInfo.ssid.c_str());
if(AccessPoint == NULL) {
NMLOG_WARNING("SSID '%s' not found !", ssidInfo.ssid.c_str());
if(_instance != nullptr)
_instance->ReportWiFiStateChange(Exchange::INetworkManager::WIFI_STATE_SSID_NOT_FOUND);
return false;
}
Exchange::INetworkManager::WiFiSSIDInfo apinfo;
getApInfo(AccessPoint, apinfo);
availableConnections = nm_device_get_available_connections(device);
for (guint i = 0; i < availableConnections->len; i++)
{
NMConnection *connection = static_cast<NMConnection*>(g_ptr_array_index(availableConnections, i));
const char *connId = nm_connection_get_id(NM_CONNECTION(connection));
if (connId != NULL && strcmp(connId, ssidInfo.ssid.c_str()) == 0)
{
if (nm_access_point_connection_valid(AccessPoint, NM_CONNECTION(connection))) {
m_connection = g_object_ref(connection);
NMLOG_DEBUG("connection '%s' exists !", ssidInfo.ssid.c_str());
if (m_connection == NULL)
{
NMLOG_ERROR("m_connection == NULL smothing went worng");
return false;
}
break;
}
else
{
if (NM_IS_REMOTE_CONNECTION(connection))
{
/*
* libnm reuses the existing connection if new settings match the AP properties;
* remove the old one because now only one connection per SSID is supported.
*/
NMLOG_WARNING(" '%s' connection exist but properties miss match; deleting...", ssidInfo.ssid.c_str());
nm_remote_connection_delete_async(NM_REMOTE_CONNECTION(connection),
NULL,
removeKnownSSIDCb,
this);
}
}
}
}
if (NM_IS_REMOTE_CONNECTION(m_connection))
{
if(!connectionBuilder(ssidInfo, m_connection))
{
NMLOG_ERROR("connection builder failed");
return false;
}
GVariant *connSettings = nm_connection_to_dbus(m_connection, NM_CONNECTION_SERIALIZE_ALL);
nm_remote_connection_update2(NM_REMOTE_CONNECTION(m_connection),
connSettings,
NM_SETTINGS_UPDATE2_FLAG_BLOCK_AUTOCONNECT, // block auto connect becuse manualy activate
NULL,
NULL,
wifiConnectionUpdate,
this);
}
else
{
NMLOG_DEBUG("creating new connection '%s' ", ssidInfo.ssid.c_str());
m_connection = nm_simple_connection_new();
m_objectPath = nm_object_get_path(NM_OBJECT(AccessPoint));
if(!connectionBuilder(ssidInfo, m_connection))
{
NMLOG_ERROR("connection builder failed");
return false;
}
m_createNewConnection = true;
nm_client_add_and_activate_connection_async(m_client, m_connection, device, m_objectPath, NULL, wifiConnectCb, this);
}
wait(m_loop);
return m_isSuccess;
}
static void addToKnownSSIDsUpdateCb(GObject *rmObject, GAsyncResult *res, gpointer user_data)
{
NMRemoteConnection *remote_con = NM_REMOTE_CONNECTION(rmObject);
wifiManager *_wifiManager = (static_cast<wifiManager*>(user_data));
GVariant *ret = NULL;
GError *error = NULL;
ret = nm_remote_connection_update2_finish(remote_con, res, &error);
if (!ret) {
NMLOG_ERROR("Error: %s.", error->message);
g_error_free(error);
_wifiManager->m_isSuccess = false;
NMLOG_ERROR("AddToKnownSSIDs failed");
}
else
{
_wifiManager->m_isSuccess = true;
NMLOG_INFO("AddToKnownSSIDs success");
}
_wifiManager->quit(NULL);
}
static void addToKnownSSIDsCb(GObject *client, GAsyncResult *result, gpointer user_data)
{
GError *error = NULL;
wifiManager *_wifiManager = (static_cast<wifiManager*>(user_data));
GVariant **outResult = NULL;
if (!nm_client_add_connection2_finish(NM_CLIENT(client), result, outResult, &error)) {
NMLOG_ERROR("AddToKnownSSIDs Failed");
_wifiManager->m_isSuccess = false;
}
else
{
NMLOG_INFO("AddToKnownSSIDs success");
_wifiManager->m_isSuccess = true;
}
g_main_loop_quit(_wifiManager->m_loop);
}
bool wifiManager::addToKnownSSIDs(const Exchange::INetworkManager::WiFiConnectTo ssidinfo)
{
m_isSuccess = false;
NMConnection *m_connection = NULL;
if(!createClientNewConnection())
return false;
NMDevice *device = getWifiDevice();
if(device == NULL)
return false;
const GPtrArray *availableConnections = nm_device_get_available_connections(device);
for (guint i = 0; i < availableConnections->len; i++)
{
NMConnection *connection = static_cast<NMConnection*>(g_ptr_array_index(availableConnections, i));
const char *connId = nm_connection_get_id(NM_CONNECTION(connection));
if (connId != NULL && strcmp(connId, ssidinfo.ssid.c_str()) == 0)
{
m_connection = g_object_ref(connection);
}
}
if (NM_IS_REMOTE_CONNECTION(m_connection))
{
if(!connectionBuilder(ssidinfo, m_connection))
{
NMLOG_ERROR("connection builder failed");
return false;
}
NMLOG_DEBUG("update exsisting connection '%s' ", ssidinfo.ssid.c_str());
GVariant *connSettings = nm_connection_to_dbus(m_connection, NM_CONNECTION_SERIALIZE_ALL);
nm_remote_connection_update2(NM_REMOTE_CONNECTION(m_connection),
connSettings,
NM_SETTINGS_UPDATE2_FLAG_TO_DISK,
NULL,
NULL,
addToKnownSSIDsUpdateCb,
this);
}
else
{
NMLOG_DEBUG("creating new connection '%s' ", ssidinfo.ssid.c_str());
m_connection = nm_simple_connection_new();
if(!connectionBuilder(ssidinfo, m_connection))
{
NMLOG_ERROR("connection builder failed");
return false;
}
m_createNewConnection = true;
GVariant *connSettings = nm_connection_to_dbus(m_connection, NM_CONNECTION_SERIALIZE_ALL);
nm_client_add_connection2(m_client,
connSettings,
NM_SETTINGS_ADD_CONNECTION2_FLAG_TO_DISK,
NULL, TRUE, NULL,
addToKnownSSIDsCb, this);
}
wait(m_loop);
return m_isSuccess;
}
bool wifiManager::removeKnownSSID(const string& ssid)
{
NMConnection *m_connection = NULL;
m_isSuccess = false;
if(!createClientNewConnection())
return false;
if(ssid.empty())
{
NMLOG_ERROR("ssid is empty");
return false;
}
const GPtrArray *allconnections = nm_client_get_connections(m_client);
for (guint i = 0; i < allconnections->len; i++)
{
NMConnection *connection = static_cast<NMConnection*>(g_ptr_array_index(allconnections, i));
if (!NM_IS_SETTING_WIRELESS(nm_connection_get_setting_wireless(connection)))
continue; // if not wireless connection skipt
const char *connId = nm_connection_get_id(NM_CONNECTION(connection));
if(connId == NULL)
continue;
NMLOG_DEBUG("wireless connection '%s'", connId);
if (strcmp(connId, ssid.c_str()) == 0)
{
m_connection = g_object_ref(connection);
if (NM_IS_REMOTE_CONNECTION(m_connection))
{
NMLOG_INFO("deleting '%s' connection...", ssid.c_str());
nm_remote_connection_delete_async(NM_REMOTE_CONNECTION(m_connection),
NULL,
removeKnownSSIDCb,
this);
}
wait(m_loop);
break; // multiple connection with same name not handiled
}
}
if(!m_connection)
NMLOG_INFO("'%s' no such connection profile", ssid.c_str());
return m_isSuccess;
}
bool wifiManager::getKnownSSIDs(std::list<string>& ssids)
{
if(!createClientNewConnection())
return false;
const GPtrArray *connections = nm_client_get_connections(m_client);
std::string ssidPrint;
for (guint i = 0; i < connections->len; i++)
{
NMConnection *connection = NM_CONNECTION(connections->pdata[i]);
if (NM_IS_SETTING_WIRELESS(nm_connection_get_setting_wireless(connection)))
{
GBytes *ssidBytes = nm_setting_wireless_get_ssid(nm_connection_get_setting_wireless(connection));
if (ssidBytes)
{
gsize ssidSize;
const guint8 *ssidData = static_cast<const guint8 *>(g_bytes_get_data(ssidBytes, &ssidSize));
std::string ssidstr(reinterpret_cast<const char *>(ssidData), ssidSize);
if (!ssidstr.empty())
{
ssids.push_back(ssidstr);
ssidPrint += ssidstr;
ssidPrint += ", ";
}
}
}
}
if (!ssids.empty())
{
NMLOG_DEBUG("known wifi connections are %s", ssidPrint.c_str());
return true;
}
return false;
}
static void wifiScanCb(GObject *object, GAsyncResult *result, gpointer user_data)
{
GError *error = NULL;
wifiManager *_wifiManager = (static_cast<wifiManager*>(user_data));
if(nm_device_wifi_request_scan_finish(NM_DEVICE_WIFI(object), result, &error)) {
NMLOG_DEBUG("Scanning success");
_wifiManager->m_isSuccess = true;
}
else
{
NMLOG_ERROR("Scanning Failed");
_wifiManager->m_isSuccess = false;
}
if (error) {
NMLOG_ERROR("Scanning Failed Error: %s.", error->message);
_wifiManager->m_isSuccess = false;
g_error_free(error);
}
g_main_loop_quit(_wifiManager->m_loop);
}
bool wifiManager::wifiScanRequest(std::string ssidReq)
{
if(!createClientNewConnection())
return false;
NMDeviceWifi *wifiDevice = NM_DEVICE_WIFI(getWifiDevice());
if(wifiDevice == NULL) {
NMLOG_FATAL("NMDeviceWifi * NULL !");
return false;
}
m_isSuccess = false;
if(!ssidReq.empty() && ssidReq != "null")
{
NMLOG_INFO("staring wifi scanning .. %s", ssidReq.c_str());
GVariantBuilder builder, array_builder;
GVariant *options;
g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT);
g_variant_builder_init(&array_builder, G_VARIANT_TYPE("aay"));
g_variant_builder_add(&array_builder, "@ay",
g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, (const guint8 *) ssidReq.c_str(), ssidReq.length(), 1)
);
g_variant_builder_add(&builder, "{sv}", "ssids", g_variant_builder_end(&array_builder));
options = g_variant_builder_end(&builder);
nm_device_wifi_request_scan_options_async(wifiDevice, options, NULL, wifiScanCb, this);
}
else {
NMLOG_DEBUG("staring normal wifi scanning");
nm_device_wifi_request_scan_async(wifiDevice, NULL, wifiScanCb, this);
}
wait(m_loop);
return m_isSuccess;
}
bool wifiManager::isWifiScannedRecently(int timelimitInSec)
{
if (!createClientNewConnection())
return false;
NMDeviceWifi *wifiDevice = NM_DEVICE_WIFI(getWifiDevice());
if (wifiDevice == NULL) {
NMLOG_ERROR("Invalid Wi-Fi device.");
return false;
}
gint64 last_scan_time = nm_device_wifi_get_last_scan(wifiDevice);
if (last_scan_time <= 0) {
NMLOG_INFO("No scan has been performed yet");
return false;
}
gint64 current_time_in_msec = nm_utils_get_timestamp_msec();
gint64 time_difference_in_seconds = (current_time_in_msec - last_scan_time) / 1000;
NMLOG_DEBUG("Current time in milliseconds: %" G_GINT64_FORMAT, current_time_in_msec);
NMLOG_DEBUG("Last scan time in milliseconds: %" G_GINT64_FORMAT, last_scan_time);
NMLOG_DEBUG("Time difference in seconds: %" G_GINT64_FORMAT, time_difference_in_seconds);
if (time_difference_in_seconds <= timelimitInSec) {
return true;
}
NMLOG_DEBUG("Last Wi-Fi scan exceeded time limit.");
return false;
}
std::string wifiManager::executeWpaCliCommand(const std::string& wpaCliCommand) {
std::array<char, 128> buffer;
std::string wpaCliResult;
FILE* fp = popen(wpaCliCommand.c_str(), "r");
if (fp == nullptr) {
NMLOG_ERROR("Failed to run command: %s", wpaCliCommand.c_str());
return "ERROR";
}
while (fgets(buffer.data(), buffer.size(), fp) != nullptr) {
wpaCliResult += buffer.data();
}
pclose(fp);
NMLOG_DEBUG("Command output: %s", wpaCliResult.c_str());
return wpaCliResult;
}
void wifiManager::wpsAction()
{
FILE *fp = nullptr;
std::string line = "";
std::string securityPattern = "key_mgmt=";
std::string ssidPattern = "ssid=";
std::string passphrasePattern = "psk=";
std::string security = "", ssid = "", passphrase = "";
std::string wpaCliResult = "";
gboolean wpsConnect = false;
struct timespec startTime = {}, endTime = {};
long timeDiff = 0;
long wpsPBCDuration = 0;
int count = 0;
bool scanResult = false;
const char* bssid = nullptr;
gboolean pbcFound = false;
const GPtrArray *aps;
wifi_wps_pbc_ap_t apList[MAX_WPS_AP_COUNT];
int wpsApCount = 0;
if (!m_wpsContext || !g_main_context_acquire(m_wpsContext))
{
NMLOG_ERROR("Failed to acquire wpsContext");
if (m_wpsContext) {
g_main_context_unref(m_wpsContext);
m_wpsContext = nullptr;
}
return;
}
g_main_context_push_thread_default(m_wpsContext);
clock_gettime(CLOCK_MONOTONIC, &startTime);
do{
sleep(10);
m_loop = g_main_loop_new(m_wpsContext, FALSE);
scanResult = wifiScanRequest("");
m_loop = g_main_loop_new(m_nmContext, FALSE);
NMLOG_DEBUG("Wifi scan result = %d", scanResult);
if(scanResult)