diff --git a/.gitignore b/.gitignore deleted file mode 100755 index b9616cd3..00000000 --- a/.gitignore +++ /dev/null @@ -1,54 +0,0 @@ -# C++ objects and libs -*.slo -*.lo -*.o -*.a -*.la -*.lai -*.so -*.so.* -*.dll -*.dylib - -# Qt-es -object_script.*.Release -object_script.*.Debug -*_plugin_import.cpp -/.qmake.cache -/.qmake.stash -*.pro.user -*.pro.user.* -*.qbs.user -*.qbs.user.* -*.moc -moc_*.cpp -moc_*.h -qrc_*.cpp -ui_*.h -*.qmlc -*.jsc -Makefile* -*build-* -*.prl - -# Qt unit tests -target_wrapper.* - -# QtCreator -*.autosave - -# QtCreator Qml -*.qmlproject.user -*.qmlproject.user.* - -# QtCreator CMake -CMakeLists.txt.user* - -# QtCreator 4.8< compilation database -compile_commands.json - -# QtCreator local machine specific files for imported projects -*creator.user* - -# OS X extra file -.DS_Store diff --git a/AUTHORS b/AUTHORS deleted file mode 100644 index a8b57e7b..00000000 --- a/AUTHORS +++ /dev/null @@ -1 +0,0 @@ -shine diff --git a/kylin-nm-plugin/libnm-icon-kylin/kynetworkicon.h b/kylin-nm-plugin/libnm-icon-kylin/kynetworkicon.h index 3c592ffa..a699336b 100644 --- a/kylin-nm-plugin/libnm-icon-kylin/kynetworkicon.h +++ b/kylin-nm-plugin/libnm-icon-kylin/kynetworkicon.h @@ -3,7 +3,7 @@ #include "libnm-base-kylin_global.h" -#include +#include #include #include diff --git a/kylin-nm-plugin/libnm-icon-kylin/libnm-icon-kylin.pro b/kylin-nm-plugin/libnm-icon-kylin/libnm-icon-kylin.pro index 66afa9d0..52020245 100644 --- a/kylin-nm-plugin/libnm-icon-kylin/libnm-icon-kylin.pro +++ b/kylin-nm-plugin/libnm-icon-kylin/libnm-icon-kylin.pro @@ -11,7 +11,14 @@ CONFIG += c++14 qt link_pkgconfig no_keywords # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS -PKGCONFIG += kylin-nm-base +PKGCONFIG += gio-2.0 libnm + +INCLUDEPATH += /usr/include/KF5/NetworkManagerQt +LIBS += -L/usr/lib/ -lKF5NetworkManagerQt + +#PKGCONFIG += kylin-nm-base +INCLUDEPATH += $$PWD/../../libkylin-nm-base/libnm-kylin/libnm-base-kylin +LIBS += -L$$PWD/../../libkylin-nm-base/libnm-kylin/libnm-base-kylin/ -lkylin-nm-base #INCLUDEPATH += $$PWD/../libnm-base-kylin/ #INCLUDEPATH += /usr/include/KF5/NetworkManagerQt diff --git a/kylin-nm-plugin/plugins/netconnect/netconnect.h b/kylin-nm-plugin/plugins/netconnect/netconnect.h index e14be2fb..456a33de 100644 --- a/kylin-nm-plugin/plugins/netconnect/netconnect.h +++ b/kylin-nm-plugin/plugins/netconnect/netconnect.h @@ -44,8 +44,8 @@ using namespace kdk; #include #include -#include -#include +#include +#include #include "lanitem.h" #include "../component/DeviceFrame/deviceframe.h" #include "itemframe.h" diff --git a/kylin-nm-plugin/plugins/netconnect/netconnect.pro b/kylin-nm-plugin/plugins/netconnect/netconnect.pro index 3f673245..ed578979 100644 --- a/kylin-nm-plugin/plugins/netconnect/netconnect.pro +++ b/kylin-nm-plugin/plugins/netconnect/netconnect.pro @@ -2,12 +2,6 @@ QT += widgets network dbus gui core TEMPLATE = lib CONFIG += plugin -include(../component/infobutton.pri) -include(../component/divider.pri) -include(../component/deviceframe.pri) -include(../component/RadioItemButton.pri) -include(../component/fixlabel.pri) - TARGET = $$qtLibraryTarget(netconnect) DESTDIR = ../.. target.path = /usr/lib/kylin-nm @@ -16,18 +10,28 @@ INCLUDEPATH += \ $$PROJECT_COMPONENTSOURCE \ $$PROJECT_ROOTDIR \ -LIBS += -L$$[QT_INSTALL_LIBS] -lkylin-nm-base - -CONFIG += c++11 \ - link_pkgconfig \ - no_keywords +CONFIG += c++11 link_pkgconfig no_keywords qt warn_on no_install_prl ordered +#CONFIG += create_pc create_prl PKGCONFIG += gsettings-qt \ kysdk-qtwidgets \ - kylin-nm-base + libnm \ + gtk+-3.0 +# kylin-nm-base +INCLUDEPATH += /usr/include/KF5/NetworkManagerQt +LIBS += -L/usr/lib/ -lKF5NetworkManagerQt + +INCLUDEPATH += $$PWD/../../../libkylin-nm-base/libnm-kylin/libnm-base-kylin +LIBS += -L$$PWD/../../../libkylin-nm-base/libnm-kylin/libnm-base-kylin/ -lkylin-nm-base #DEFINES += QT_DEPRECATED_WARNINGS +include(../component/infobutton.pri) +include(../component/divider.pri) +include(../component/deviceframe.pri) +include(../component/RadioItemButton.pri) +include(../component/fixlabel.pri) + SOURCES += \ itemframe.cpp \ lanitem.cpp \ diff --git a/kylin-nm-plugin/plugins/wlanconnect/hiddenwifi/enterprisewlanpage.h b/kylin-nm-plugin/plugins/wlanconnect/hiddenwifi/enterprisewlanpage.h index 6c5b52b3..a06beb63 100644 --- a/kylin-nm-plugin/plugins/wlanconnect/hiddenwifi/enterprisewlanpage.h +++ b/kylin-nm-plugin/plugins/wlanconnect/hiddenwifi/enterprisewlanpage.h @@ -5,7 +5,7 @@ #include #include -#include +#include #include "entsecuritywidget.h" class EnterpriseWlanPage : public QWidget diff --git a/kylin-nm-plugin/plugins/wlanconnect/hiddenwifi/entsecuritywidget.h b/kylin-nm-plugin/plugins/wlanconnect/hiddenwifi/entsecuritywidget.h index 0ea1d1b2..1cb17d92 100644 --- a/kylin-nm-plugin/plugins/wlanconnect/hiddenwifi/entsecuritywidget.h +++ b/kylin-nm-plugin/plugins/wlanconnect/hiddenwifi/entsecuritywidget.h @@ -15,7 +15,7 @@ #include "kpasswordedit.h" #include "kdialog.h" #include "kballontip.h" -#include "kylin-nm/depend/kyenterpricesettinginfo.h" +#include "depend/kyenterpricesettinginfo.h" using namespace kdk; diff --git a/kylin-nm-plugin/plugins/wlanconnect/hiddenwifi/hiddenwifipage.h b/kylin-nm-plugin/plugins/wlanconnect/hiddenwifi/hiddenwifipage.h index 2cdc5f78..f7d48fe7 100644 --- a/kylin-nm-plugin/plugins/wlanconnect/hiddenwifi/hiddenwifipage.h +++ b/kylin-nm-plugin/plugins/wlanconnect/hiddenwifi/hiddenwifipage.h @@ -18,7 +18,7 @@ #include "kpasswordedit.h" #include "kborderlessbutton.h" #include "entsecuritywidget.h" -#include "kylin-nm/depend/kywirelessconnectoperation.h" +#include "depend/kywirelessconnectoperation.h" using namespace kdk; diff --git a/kylin-nm-plugin/plugins/wlanconnect/wlanconnect.h b/kylin-nm-plugin/plugins/wlanconnect/wlanconnect.h index cf49cda3..e6d9c6e1 100644 --- a/kylin-nm-plugin/plugins/wlanconnect/wlanconnect.h +++ b/kylin-nm-plugin/plugins/wlanconnect/wlanconnect.h @@ -43,9 +43,9 @@ using namespace kdk; #include #include -#include -#include -#include +#include +#include +#include #include "../component/DeviceFrame/deviceframe.h" #include "itemframe.h" #include "wlanitem.h" diff --git a/kylin-nm-plugin/plugins/wlanconnect/wlanconnect.pro b/kylin-nm-plugin/plugins/wlanconnect/wlanconnect.pro index 2f48f742..06baad4d 100644 --- a/kylin-nm-plugin/plugins/wlanconnect/wlanconnect.pro +++ b/kylin-nm-plugin/plugins/wlanconnect/wlanconnect.pro @@ -2,13 +2,6 @@ QT += widgets network dbus gui core TEMPLATE = lib CONFIG += plugin -include(../component/infobutton.pri) -include(../component/divider.pri) -include(../component/deviceframe.pri) -include(../component/RadioItemButton.pri) -include(../component/fixlabel.pri) -include(hiddenwifi/hiddenwifi.pri) - TARGET = $$qtLibraryTarget(wlanconnect) DESTDIR = ../.. target.path = /usr/lib/kylin-nm @@ -19,17 +12,35 @@ INCLUDEPATH += \ LIBS += -L$$[QT_INSTALL_LIBS] -lkylin-nm-base -lkylin-keyring -CONFIG += c++11 \ - link_pkgconfig \ - no_keywords +CONFIG += c++11 link_pkgconfig no_keywords qt warn_on no_install_prl ordered +#CONFIG += create_pc create_prl + PKGCONFIG += gsettings-qt \ kysdk-qtwidgets \ - kylin-nm-base \ +# kylin-nm-base \ + libnm \ + gtk+-3.0 \ libsecret-1 +INCLUDEPATH += /usr/include/KF5/NetworkManagerQt +LIBS += -L/usr/lib/ -lKF5NetworkManagerQt + +INCLUDEPATH += $$PWD/../../../libkylin-nm-base/libnm-kylin/libnm-base-kylin +LIBS += -L$$PWD/../../../libkylin-nm-base/libnm-kylin/libnm-base-kylin/ -lkylin-nm-base + +INCLUDEPATH += $$PWD/../../../libkylin-nm-base/kylin-keyring +LIBS += -L$$PWD/../../../libkylin-nm-base/kylin-keyring/ -lkylin-keyring + #DEFINES += QT_DEPRECATED_WARNINGS +include(../component/infobutton.pri) +include(../component/divider.pri) +include(../component/deviceframe.pri) +include(../component/RadioItemButton.pri) +include(../component/fixlabel.pri) +include(hiddenwifi/hiddenwifi.pri) + SOURCES += \ itemframe.cpp \ wlanconnect.cpp \ diff --git a/kylin-nm.pro b/kylin-nm.pro index dbb9eba3..42bd11b5 100644 --- a/kylin-nm.pro +++ b/kylin-nm.pro @@ -5,10 +5,11 @@ CONFIG += \ qt \ SUBDIRS = \ + libkylin-nm-base/libkylin-nm-base.pro \ plugins/plugin.pro \ src-vpn/src-vpn.pro \ src \ sys-dbus-register \ - kylin-nm-plugin/kylin-nm-plugin.pro \ + kylin-nm-plugin/kylin-nm-plugin.pro QT += widgets diff --git a/libkylin-nm-base/kylin-keyring/authorize.svg b/libkylin-nm-base/kylin-keyring/authorize.svg new file mode 100755 index 00000000..edf7e74a --- /dev/null +++ b/libkylin-nm-base/kylin-keyring/authorize.svg @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/libkylin-nm-base/kylin-keyring/kylin-agent/agentutils.h b/libkylin-nm-base/kylin-keyring/kylin-agent/agentutils.h new file mode 100644 index 00000000..5c5e8b6f --- /dev/null +++ b/libkylin-nm-base/kylin-keyring/kylin-agent/agentutils.h @@ -0,0 +1,113 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef AGENTUTILS_H +#define AGENTUTILS_H + +#define VPN_TYPE "vpn" +#define VPN_NAME "vpn" +#define VPN_SERVICE "service-type" +#define VPN_DATA "data" +#define VPN_SECRET "secrets" +#define VPN_FLAG "password-flags" + +#define CONNECTION_KEY "connection" +#define UUID_KEY "uuid" +#define SSID_KEY "ssid" +#define ID_KEY "id" +#define TYPE_KEY "type" + + +#define WIRELESS_SECURITY_NAME "802-11-wireless-security" +#define KEY_MGMT "key-mgmt" + +#define PSK_MGMT "wpa-psk" +#define SAE_MGMT "sae" +#define PSK_FLAG "psk-flags" +#define PSK_KEY "psk" + +#define WEP_MGMT "none" +#define WEP128_MGMT "passphrase" +#define WEP_FLAG_KEY "wep-key-flags" +#define WEP_ID_KEY "wep-tx-keyidx" +#define WEP_KEY0 "wep-key0" +#define WEP_KEY1 "wep-key1" +#define WEP_KEY2 "wep-key2" +#define WEP_KEY3 "wep-key3" + +#define LEAP_MGMT "ieee8021x" +#define LEAP_PASSWORD_FLAG "leap-password-flags" +#define LEAP_PASSWORD_KEY "leap-password" +#define LEAP_USER_KEY "leap-username" + +#define ENTERPRICE_NAME "802-1x" +#define EAP_KEY "eap" +#define PWD_EAP "pwd" +#define LEAP_EAP "leap" +#define FAST_EAP "fast" +#define PEAP_EAP "peap" +#define TTLS_EAP "ttls" +#define TLS_EAP "tls" + +#define IDENTITY_KEY "identity" + +#define PASSWORD_FLAG "password-flags" +#define PASSWORD_KEY "password" + +#define PIN_FLAG "pin-flags" +#define PIN_KEY "pin" + +#define PHASE2_PRIVATE_KEY_FLAG "phase2-private-key-password-flags" +#define PHASE2_PRIVATE_KEY "phase2-private-key-password" + +#define PRIVATE_KEY_FLAG "private-key-password-flags" +#define PRIVATE_KEY "private-key-password" +#define DOMAIN_KEY "domain-suffix-match" + +#define PHASE2_CLIENT_FLAG "phase2-client-cert-password-flags" +#define PHASE2_CLIENT "phase2-client-cert-password" + +#define PHASE2_CACERT_FLAG "phase2-ca-cert-password-flags" +#define PHASE2_CACERT "phase2-ca-cert-password" + +#define PHASE1_AUTH_FLAG "phase1-auth-flags" +#define PHASE1_AUTH "phase1-auth" + +#define CLIENT_CERT_FLAG "client-cert-password-flags" +#define CLIENT_CERT "client-cert-password" + +#define CACERT_FLAG "ca-cert-password-flags" +#define CACERT "ca-cert-password" + + + +enum SecretPolicyFlag{ + POLICY_NONE = 0, + POLICY_AGENT_OWNED = 0x01, + POLICY_NOT_SAVED = 0x02, + POLICY_NOT_REQUIRED = 0x04 +}; + +enum SecretWepKeyId{ + KEY_TYPE0 = 0, + KEY_TYPE1 = 1, + KEY_TYPE2 = 2, + KEY_TYPE3 = 3 +}; + + +#endif // AGENTUTILS_H diff --git a/libkylin-nm-base/kylin-keyring/kylin-agent/kylin-agent.pri b/libkylin-nm-base/kylin-keyring/kylin-agent/kylin-agent.pri new file mode 100644 index 00000000..3cfbae16 --- /dev/null +++ b/libkylin-nm-base/kylin-keyring/kylin-agent/kylin-agent.pri @@ -0,0 +1,14 @@ +INCLUDEPATH += $$PWD + +HEADERS += \ + $$PWD/agentutils.h \ + $$PWD/kylinagent.h \ + $$PWD/kylinagentobject.h \ + $$PWD/kylinpassworddialog.h \ + $$PWD/kylinsecretagent.h + +SOURCES += \ + $$PWD/kylinagent.cpp \ + $$PWD/kylinagentobject.cpp \ + $$PWD/kylinpassworddialog.cpp \ + $$PWD/kylinsecretagent.cpp diff --git a/libkylin-nm-base/kylin-keyring/kylin-agent/kylinagent.cpp b/libkylin-nm-base/kylin-keyring/kylin-agent/kylinagent.cpp new file mode 100644 index 00000000..1ea8c281 --- /dev/null +++ b/libkylin-nm-base/kylin-keyring/kylin-agent/kylinagent.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include "kylinagent.h" +#include +#include + +KylinAgent::KylinAgent(QObject *parent) : QObject(parent) +{ + QLocale local; + QString locale = /*QLocale::system().*/local.name(); + QTranslator* translator = new QTranslator(this); + if (translator->load(":/translations/kylin-keyring_"+ locale + ".qm")) { + QApplication::installTranslator(translator); + } else { +// qWarning() << "Translations load fail"; + } +} + +KylinAgent::~KylinAgent() +{ + +} + +void KylinAgent::startKylinAgent() +{ + m_secretAgnet = new KylinSecretAgent("kylinagent", pWidget, this); +} + +//void KylinAgent::stopKylinAgent() +//{ +// delete m_kylinAgnetObject; +// m_kylinAgnetObject = nullptr; +// return; +//} diff --git a/libkylin-nm-base/kylin-keyring/kylin-agent/kylinagent.h b/libkylin-nm-base/kylin-keyring/kylin-agent/kylinagent.h new file mode 100644 index 00000000..fa68bfcc --- /dev/null +++ b/libkylin-nm-base/kylin-keyring/kylin-agent/kylinagent.h @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYLINAGENT_H +#define KYLINAGENT_H + +#include "kylinsecretagent.h".h" + +#if defined(LIBKYLIN_KEYRING_LIBRARY) +# define LIBKYLIN_KEYRING_LIBRARY Q_DECL_EXPORT +#else +# define LIBKYLIN_KEYRING_LIBRARY Q_DECL_IMPORT +#endif + +class LIBKYLIN_KEYRING_LIBRARY KylinAgent : public QObject +{ +public: + explicit KylinAgent(QObject *parent = nullptr); + ~KylinAgent(); + void startKylinAgent(); + void setParentWidget(QWidget *widget){ + pWidget = widget; + } + +private: + KylinSecretAgent *m_secretAgnet; + QWidget* pWidget = nullptr; +}; + + +#endif // KYLINAGENT_H diff --git a/libkylin-nm-base/kylin-keyring/kylin-agent/kylinagentobject.cpp b/libkylin-nm-base/kylin-keyring/kylin-agent/kylinagentobject.cpp new file mode 100644 index 00000000..116bc9c2 --- /dev/null +++ b/libkylin-nm-base/kylin-keyring/kylin-agent/kylinagentobject.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include "kylinagentobject.h" + +KylinAgentObject::KylinAgentObject(QObject *parent) : QObject(parent) +{ + +} + +KylinAgentObject::~KylinAgentObject() +{ + if (nullptr != m_secretAgnet) { + delete m_secretAgnet; + m_secretAgnet = nullptr; + } +} + +void KylinAgentObject::onInitAgent() +{ + m_secretAgnet = new KylinSecretAgent("kylinagent"); + + return; +} diff --git a/libkylin-nm-base/kylin-keyring/kylin-agent/kylinagentobject.h b/libkylin-nm-base/kylin-keyring/kylin-agent/kylinagentobject.h new file mode 100644 index 00000000..2bd79e80 --- /dev/null +++ b/libkylin-nm-base/kylin-keyring/kylin-agent/kylinagentobject.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYLINAGENTOBJECT_H +#define KYLINAGENTOBJECT_H + +#include "kylinsecretagent.h" + +#include + +class KylinAgentObject : public QObject +{ + Q_OBJECT +public: + explicit KylinAgentObject(QObject *parent = nullptr); + ~KylinAgentObject(); + +public Q_SLOTS: + void onInitAgent(); + +private: + KylinSecretAgent *m_secretAgnet; + +}; + +#endif // KYLINAGENTOBJECT_H diff --git a/libkylin-nm-base/kylin-keyring/kylin-agent/kylinpassworddialog.cpp b/libkylin-nm-base/kylin-keyring/kylin-agent/kylinpassworddialog.cpp new file mode 100644 index 00000000..667bf6d2 --- /dev/null +++ b/libkylin-nm-base/kylin-keyring/kylin-agent/kylinpassworddialog.cpp @@ -0,0 +1,508 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include "kylinpassworddialog.h" +#include +#include +#include +#include +#include +#include +#include +#include + +#define CLOSE_TIME 30*1000 + + +static QPalette lightPalette(QWidget *widget) +{ + auto palette = widget->palette(); + //ukui-light palette UKUI3.1 + QColor windowText_at(38, 38, 38), + windowText_iat(38, 38, 38), + windowText_dis(166, 166, 166), + button_at(230, 230, 230), + button_iat(230, 230, 230), + button_dis(233, 233, 233), + light_at(255, 255, 255), + light_iat(255, 255, 255), + light_dis(242, 242, 242), + midlight_at(218, 218, 218), + midlight_iat(218, 218, 218), + midlight_dis(230, 230, 230), + dark_at(77, 77, 77), + dark_iat(77, 77, 77), + dark_dis(64, 64, 64), + mid_at(115, 115, 115), + mid_iat(115, 115, 115), + mid_dis(102, 102, 102), + text_at(38, 38, 38), + text_iat(38, 38, 38), + text_dis(140, 140, 140), + brightText_at(89, 89, 89), + brightText_iat(89, 89, 89), + brightText_dis(77, 77, 77), + buttonText_at(38, 38, 38), + buttonText_iat(38, 38, 38), + buttonText_dis(179, 179, 179), + base_at(255, 255, 255), + base_iat(245, 245, 245), + base_dis(237, 237, 237), + window_at(245, 245, 245), + window_iat(237, 237, 237), + window_dis(230, 230, 230), + shadow_at(0, 0, 0, 16), + shadow_iat(0, 0, 0, 16), + shadow_dis(0, 0, 0, 21), +// shadow_at(214, 214, 214), +// shadow_iat(214, 214, 214), +// shadow_dis(201, 201, 201), + highLight_at(55, 144, 250), + highLight_iat(55, 144, 250), + highLight_dis(233, 233, 233), + highLightText_at(255, 255, 255), + highLightText_iat(255, 255, 255), + highLightText_dis(179, 179, 179), + link_at(55, 144, 250), + link_iat(55, 144, 250), + link_dis(55, 144, 250), + linkVisited_at(114, 46, 209), + linkVisited_iat(114, 46, 209), + linkVisited_dis(114, 46, 209), + alternateBase_at(245, 245, 245), + alternateBase_iat(245, 245, 245), + alternateBase_dis(245, 245, 245), + noRale_at(240, 240, 240), + noRole_iat(240, 240, 240), + noRole_dis(217, 217, 217), + toolTipBase_at(255, 255, 255), + toolTipBase_iat(255, 255, 255), + toolTipBase_dis(255, 255, 255), + toolTipText_at(38, 38, 38), + toolTipText_iat(38, 38, 38), + toolTipText_dis(38, 38, 38), + placeholderText_at(38, 38, 38), + placeholderText_iat(38, 38, 38), + placeholderText_dis(38, 38, 38); + + + + palette.setColor(QPalette::Active, QPalette::WindowText, windowText_at); + palette.setColor(QPalette::Inactive, QPalette::WindowText, windowText_iat); + palette.setColor(QPalette::Disabled, QPalette::WindowText, windowText_dis); + + palette.setColor(QPalette::Active, QPalette::Button, button_at); + palette.setColor(QPalette::Inactive, QPalette::Button, button_iat); + palette.setColor(QPalette::Disabled, QPalette::Button, button_dis); + + palette.setColor(QPalette::Active, QPalette::Light, light_at); + palette.setColor(QPalette::Inactive, QPalette::Light, light_iat); + palette.setColor(QPalette::Disabled, QPalette::Light, light_dis); + + palette.setColor(QPalette::Active, QPalette::Midlight, midlight_at); + palette.setColor(QPalette::Inactive, QPalette::Midlight, midlight_iat); + palette.setColor(QPalette::Disabled, QPalette::Midlight, midlight_dis); + + palette.setColor(QPalette::Active, QPalette::Dark, dark_at); + palette.setColor(QPalette::Inactive, QPalette::Dark, dark_iat); + palette.setColor(QPalette::Disabled, QPalette::Dark, dark_dis); + + palette.setColor(QPalette::Active, QPalette::Mid, mid_at); + palette.setColor(QPalette::Inactive, QPalette::Mid, mid_iat); + palette.setColor(QPalette::Disabled, QPalette::Mid, mid_dis); + + palette.setColor(QPalette::Active, QPalette::Text, text_at); + palette.setColor(QPalette::Inactive, QPalette::Text, text_iat); + palette.setColor(QPalette::Disabled, QPalette::Text, text_dis); + + palette.setColor(QPalette::Active, QPalette::BrightText, brightText_at); + palette.setColor(QPalette::Inactive, QPalette::BrightText, brightText_iat); + palette.setColor(QPalette::Disabled, QPalette::BrightText, brightText_dis); + + palette.setColor(QPalette::Active, QPalette::ButtonText, buttonText_at); + palette.setColor(QPalette::Inactive, QPalette::ButtonText, buttonText_iat); + palette.setColor(QPalette::Disabled, QPalette::ButtonText, buttonText_dis); + + palette.setColor(QPalette::Active, QPalette::Base, base_at); + palette.setColor(QPalette::Inactive, QPalette::Base, base_iat); + palette.setColor(QPalette::Disabled, QPalette::Base, base_dis); + + palette.setColor(QPalette::Active, QPalette::Window, window_at); + palette.setColor(QPalette::Inactive, QPalette::Window, window_iat); + palette.setColor(QPalette::Disabled, QPalette::Window, window_dis); + + palette.setColor(QPalette::Active, QPalette::Shadow, shadow_at); + palette.setColor(QPalette::Inactive, QPalette::Shadow, shadow_iat); + palette.setColor(QPalette::Disabled, QPalette::Shadow, shadow_dis); + + palette.setColor(QPalette::Active, QPalette::Highlight, highLight_at); + palette.setColor(QPalette::Inactive, QPalette::Highlight, highLight_iat); + palette.setColor(QPalette::Disabled, QPalette::Highlight, highLight_dis); + + palette.setColor(QPalette::Active, QPalette::HighlightedText, highLightText_at); + palette.setColor(QPalette::Inactive, QPalette::HighlightedText, highLightText_iat); + palette.setColor(QPalette::Disabled, QPalette::HighlightedText, highLightText_dis); + + palette.setColor(QPalette::Active, QPalette::Link, link_at); + palette.setColor(QPalette::Inactive, QPalette::Link, link_iat); + palette.setColor(QPalette::Disabled, QPalette::Link, link_dis); + + palette.setColor(QPalette::Active, QPalette::LinkVisited, linkVisited_at); + palette.setColor(QPalette::Inactive, QPalette::LinkVisited, linkVisited_iat); + palette.setColor(QPalette::Disabled, QPalette::LinkVisited, linkVisited_dis); + + palette.setColor(QPalette::Active, QPalette::AlternateBase, alternateBase_at); + palette.setColor(QPalette::Inactive, QPalette::AlternateBase, alternateBase_iat); + palette.setColor(QPalette::Disabled, QPalette::AlternateBase, alternateBase_dis); + + palette.setColor(QPalette::Active, QPalette::NoRole, noRale_at); + palette.setColor(QPalette::Inactive, QPalette::NoRole, noRole_iat); + palette.setColor(QPalette::Disabled, QPalette::NoRole, noRole_dis); + + palette.setColor(QPalette::Active, QPalette::ToolTipBase, toolTipBase_at); + palette.setColor(QPalette::Inactive, QPalette::ToolTipBase, toolTipBase_iat); + palette.setColor(QPalette::Disabled, QPalette::ToolTipBase, toolTipBase_dis); + + palette.setColor(QPalette::Active, QPalette::ToolTipText, toolTipText_at); + palette.setColor(QPalette::Inactive, QPalette::ToolTipText, toolTipText_iat); + palette.setColor(QPalette::Disabled, QPalette::ToolTipText, toolTipText_dis); + +#if (QT_VERSION >= QT_VERSION_CHECK(5,12,0)) + palette.setColor(QPalette::Active, QPalette::PlaceholderText, placeholderText_at); + palette.setColor(QPalette::Inactive, QPalette::PlaceholderText, placeholderText_iat); + palette.setColor(QPalette::Disabled, QPalette::PlaceholderText, placeholderText_dis); +#endif + + return palette; + +} + +RowWidget::RowWidget(QWidget *widget, QWidget *parent) : valueWidget(widget), QWidget(parent) +{ + mainLayout = new QHBoxLayout(this); + mainLayout->setContentsMargins(0,0,0,0); + this->setLayout(mainLayout); + keyLabel = new QLabel(this); + keyLabel->setMaximumWidth(87); + valueWidget->setMinimumWidth(280); + mainLayout->addWidget(keyLabel); + mainLayout->addStretch(); + mainLayout->addWidget(valueWidget); +} + +RowWidget::~RowWidget() +{ + +} + +void RowWidget::setKey(QString text) +{ + this->keyLabel->setText(text); +} + +KyPasswordDialog::KyPasswordDialog(QString dialogType, QString connectionID, QWidget *parent) + :connectionID(connectionID),dialogType(dialogType),QDialog(parent) +{ + this->setAttribute(Qt::WA_QuitOnClose, false); +// this->setWindowFlags(Qt::Dialog); +// this->setWindowIcon(QIcon::fromTheme("kylin-network")); +// this->setWindowTitle(connectionID); + + initUI(dialogType); + m_sdkPasswdEdit->installEventFilter(this); + this->setWindowFlags(Qt::MSWindowsFixedSizeDialogHint); + + connect(qApp, &QApplication::paletteChanged, this, &KyPasswordDialog::onPaletteChanged); + onPaletteChanged(); +} + +void KyPasswordDialog::showDesktopNotify(const QString &message) +{ + QDBusInterface iface("org.freedesktop.Notifications", + "/org/freedesktop/Notifications", + "org.freedesktop.Notifications", + QDBusConnection::sessionBus()); + QList args; + args<<(tr("Kylin NM")) + <<((unsigned int) 0) + <setContentsMargins(MAIN_LAYOUT_MARGINS); + mainVBoxLayout->setSpacing(DEFAULT_LAYOUT_SPACE); + this->setLayout(mainVBoxLayout); + + //不包含按钮的横向布局 + QHBoxLayout *hBoxLayout = new QHBoxLayout(this); + hBoxLayout->setContentsMargins(DEFAULT_LAYOUT_MARGINS); + hBoxLayout->setSpacing(DEFAULT_LAYOUT_SPACE); + + //图标 + QLabel *picture = new QLabel(this); + picture->setContentsMargins(DEFAULT_LAYOUT_MARGINS); + picture->setFixedSize(DEFAULT_PICTURE_FIXSIZE); + picture->setPixmap(QPixmap(":/authorize.svg")); + + //标题 + QLabel *titleLabel = new QLabel(this); + titleLabel->setText(tr("Wi-Fi authentication required")); + titleLabel->setFont(fontTitle); + + //提示信息 + QLabel *tipLabel = new QLabel(this); + tipLabel->setFixedSize(328, DEFAULT_FIXHEIGHT); + tipLabel->setAlignment(Qt::AlignTop); + tipLabel->setWordWrap(true); + QString text = tr("Access wireless networks"); + text += " " + connectionID + " "; + text += tr("needs password or encryption key"); + tipLabel->setText(text); + tipLabel->setFont(fontNormal); + + //密码输入框 + QLabel *pwdLabel = new QLabel(this); + pwdLabel->setText(tr("password")); + pwdLabel->setFont(fontNormal); + m_sdkPasswdEdit = new KPasswordEdit(this); + if (dialogType != "") { + this->setFixedSize(WPA2_PAGE_SIZE); + m_sdkPasswdEdit->setFixedSize(WPA2_EDIT_SIZE); + } else { + this->setFixedSize(DEFAULT_PAGE_SIZE); + m_sdkPasswdEdit->setFixedSize(DEFAULT_EDIT_SIZE); + } + m_sdkPasswdEdit->setClearButtonEnabled(false); + m_sdkPasswdEdit->setState(LoginFailed); + m_sdkPasswdEdit->setAttribute(Qt::WA_InputMethodEnabled, true); + QRegExp rx("^[A-Za-z0-9`~!@#$%^&*()_-+=<>,.\\\/]+$"); + QRegExpValidator *latitude = new QRegExpValidator(rx, this); + m_sdkPasswdEdit->setValidator(latitude); + + //密码输入框布局 + QHBoxLayout *pwdLayout = new QHBoxLayout(this); + pwdLayout->setContentsMargins(DEFAULT_LAYOUT_MARGINS); + if (dialogType != "") { + pwdLayout->setSpacing(DEFAULT_LAYOUT_SPACE); + } else { + pwdLayout->setSpacing(LESS_LAYOUT_SPACE); + } + pwdLayout->addWidget(pwdLabel); + pwdLayout->addWidget(m_sdkPasswdEdit); + + //不包含图标的纵向布局 + QVBoxLayout *contentLayout = new QVBoxLayout(this); + contentLayout->setContentsMargins(DEFAULT_LAYOUT_MARGINS); + contentLayout->setSpacing(LESS_LAYOUT_SPACE); + contentLayout->setAlignment(Qt::AlignTop); + contentLayout->addWidget(titleLabel); + contentLayout->addWidget(tipLabel); + if (dialogType != "") { + //WPA2企业加密方式用户名输入框 + QLabel *userNameLabel = new QLabel(this); + userNameLabel->setText(tr("user name")); + userNameLabel->setFont(fontNormal); + m_usrLineEdit = new QLineEdit(this); + m_usrLineEdit->setFixedSize(WPA2_EDIT_SIZE); + + //用户名输入框布局 + QHBoxLayout *userNameLayout = new QHBoxLayout(this); + userNameLayout->setContentsMargins(DEFAULT_LAYOUT_MARGINS); + userNameLayout->setSpacing(8); + userNameLayout->addWidget(userNameLabel); + userNameLayout->addWidget(m_usrLineEdit); + contentLayout->addLayout(userNameLayout); + } + contentLayout->addLayout(pwdLayout); + + //连接按钮 + m_connectBtn = new QPushButton(this); + m_connectBtn->setText(tr("Connect")); + m_connectBtn->setFont(fontNormal); + m_connectBtn->setFixedSize(DEFAULT_BTN_FIXSIZE); + + //取消按钮 + m_exitBtn = new QPushButton(this); + m_exitBtn->setText(tr("Cancel")); + m_exitBtn->setFont(fontNormal); + m_exitBtn->setFixedSize(DEFAULT_BTN_FIXSIZE); + + //按钮布局 + QHBoxLayout *btnLayout = new QHBoxLayout(this); + btnLayout->setContentsMargins(DEFAULT_LAYOUT_MARGINS); + btnLayout->setSpacing(LESS_LAYOUT_SPACE); + btnLayout->addStretch(); + btnLayout->addWidget(m_exitBtn); + btnLayout->addWidget(m_connectBtn); + + hBoxLayout->addWidget(picture); + hBoxLayout->setAlignment(picture, Qt::AlignTop); + hBoxLayout->addLayout(contentLayout); + + mainVBoxLayout->addLayout(hBoxLayout); + mainVBoxLayout->addLayout(btnLayout); + + if (m_usrLineEdit == nullptr) { + showDesktopNotify(tr("password error!")); + } else { + showDesktopNotify(tr("username or password error!")); + } +} + +QString KyPasswordDialog::getPassword() +{ + return m_sdkPasswdEdit->text(); +} + +void KyPasswordDialog::setPassword(QString password) +{ + m_sdkPasswdEdit->setText(password); + m_sdkPasswdEdit->setFocus(); +} + +QString KyPasswordDialog::getUserName() +{ + return m_usrLineEdit->text(); +} + +void KyPasswordDialog::setUserName(QString name) +{ + m_usrLineEdit->setText(name); +} + +void KyPasswordDialog::login() +{ + qDebug() << "KyPasswordDialog login"; + if ((!m_sdkPasswdEdit->text().isEmpty()) && (m_usrLineEdit == nullptr? true : (!m_usrLineEdit->text().isEmpty()))) { + accept(); + } else { + m_sdkPasswdEdit->clear(); + if (m_usrLineEdit != nullptr) { + m_usrLineEdit->clear(); + m_usrLineEdit->setFocus(); + } + } +} + +void KyPasswordDialog::onTextChanged(const QString & text) +{ + qDebug() << "KyPasswordDialog onTextChanged"; + m_sdkPasswdEdit->setState(Ordinary); + if (text == "") { + //任何输入框为空,则不许按下连接按钮 + m_connectBtn->setEnabled(false); + return ; + } + + if (m_usrLineEdit != nullptr) { + //企业网修改密码页面 + if (!m_usrLineEdit->text().isEmpty() && !m_sdkPasswdEdit->text().isEmpty()) { + //用户名和密码均不为空,允许按下连接按钮 + m_connectBtn->setEnabled(true); + } else { + m_connectBtn->setEnabled(false); + } + return ; + } + + if (m_sdkPasswdEdit->text().isEmpty() || m_sdkPasswdEdit->text().length() < 8) { + //普通热点密码修改页面,若密码为空,或长度小于8位,不许按下连接按钮 + m_connectBtn->setEnabled(false); + return ; + } + + m_connectBtn->setEnabled(true); +} + + +void KyPasswordDialog::onPaletteChanged() +{ + QPalette pal = lightPalette(this); + + this->setPalette(pal); + m_sdkPasswdEdit->setPalette(pal); + if (nullptr != m_usrLineEdit) + m_usrLineEdit->setPalette(pal); + +// setFramePalette(this, pal); +} + +void KyPasswordDialog::paintEvent(QPaintEvent *event) +{ + QPalette pal = this->palette(); + + QPainter painter(this); + painter.setRenderHint(QPainter:: Antialiasing, true); //设置渲染,启动反锯齿 + painter.setPen(Qt::NoPen); + painter.setBrush(pal.color(QPalette::Base)); + + QRect rect = this->rect(); + painter.drawRoundedRect(rect, 12, 12); + + + QDialog::paintEvent(event); +} diff --git a/libkylin-nm-base/kylin-keyring/kylin-agent/kylinpassworddialog.h b/libkylin-nm-base/kylin-keyring/kylin-agent/kylinpassworddialog.h new file mode 100644 index 00000000..6892c5d6 --- /dev/null +++ b/libkylin-nm-base/kylin-keyring/kylin-agent/kylinpassworddialog.h @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYLINPASSWORDDIALOG_H +#define KYLINPASSWORDDIALOG_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "kpasswordedit.h" + +using namespace kdk; + +class RowWidget : public QWidget +{ + Q_OBJECT +public: + RowWidget(QWidget *widget, QWidget *parent = nullptr); + ~RowWidget(); + void setKey(QString text); + +private: + QHBoxLayout *mainLayout; + QLabel *keyLabel; + QWidget *valueWidget; +}; + +class KyPasswordDialog : public QDialog +{ + Q_OBJECT +public: + KyPasswordDialog(QString dialogType, QString connectionID = "", QWidget *parent = 0); + ~KyPasswordDialog(); + + void showDesktopNotify(const QString &message); + + void InitConnect(); +private: + QString dialogType; + QString connectionID; + + QLineEdit *m_usrLineEdit = nullptr; + QPushButton *m_connectBtn = nullptr; + QPushButton *m_exitBtn = nullptr; + + KPasswordEdit *m_sdkPasswdEdit = nullptr; + + void onPaletteChanged(); + +protected: + void paintEvent(QPaintEvent *event); + +public: + void initUI(QString dialogType); + + QString getPassword(); + void setPassword(QString password); + + QString getUserName(); + void setUserName(QString name); + +private Q_SLOTS: + void login(); + void onTextChanged(const QString &); + +Q_SIGNALS: + void signal_username(QString); +}; + +#endif // KYLINPASSWORDDIALOG_H diff --git a/libkylin-nm-base/kylin-keyring/kylin-agent/kylinsecretagent.cpp b/libkylin-nm-base/kylin-keyring/kylin-agent/kylinsecretagent.cpp new file mode 100644 index 00000000..938f4202 --- /dev/null +++ b/libkylin-nm-base/kylin-keyring/kylin-agent/kylinsecretagent.cpp @@ -0,0 +1,1248 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include + +#include "kylinsecretagent.h" +#include "kylinpassworddialog.h" + +#define LOG_FLAG "[KylinSecretAgent]" + +#define KEYRING_UUID_TAG "connection-uuid" +#define KEYRING_SN_TAG "setting-name" +#define KEYRING_SK_TAG "setting-key" + +static const SecretSchema network_manager_secret_schema = { + "org.freedesktop.NetworkManager.Connection", + SECRET_SCHEMA_DONT_MATCH_NAME, + { + { KEYRING_UUID_TAG, SECRET_SCHEMA_ATTRIBUTE_STRING }, + { KEYRING_SN_TAG, SECRET_SCHEMA_ATTRIBUTE_STRING }, + { KEYRING_SK_TAG, SECRET_SCHEMA_ATTRIBUTE_STRING }, + { NULL, SECRET_SCHEMA_ATTRIBUTE_STRING }, + } +}; + +/* +* 目前wpa3存在的问题: +* 1、所有用户可见的存储策略情况下,当密码错误的时候,networkmanager不会调用getSecret接口 +* 2、当选择仅用户可见时,存储错误密码,由于传递给getSecret的flag参数一直是13, +* 导致无法弹出修改密码的框, +* 正常情况下,flag第一次是5,从keyring获取密码 第二次是7,由于密码错误,弹框获取新密码 +* 3、每次询问密码正常。 +* +* wep的存在的问题: +* 1、所有用户可见时,当输入错误的密码的时候,networkmanager没有调用getSecret函数,弹出密码框 +* 2、仅用户可见的时候,正确的密码可以正常连接,当密码错误的时候,不调用getsecret,不会弹出密码框 +* 3、每次询问密码的时候,第一次可以弹出密码框,如果输入错误的密码,有时弹出密码框,有时不弹,取决于输入的密码位数 +* +* +* 企业wifi leap加密方式 +* 无法选择每次询问用户 +* +*/ + + +KylinSecretAgent::KylinSecretAgent(const QString &id, QWidget *pWidget, QObject *parent):SecretAgent(id, parent) +{ + parentWidget = pWidget; + enterpriceInfo[PASSWORD_FLAG] = PASSWORD_KEY; + enterpriceInfo[PIN_FLAG] = PIN_KEY; + enterpriceInfo[PHASE2_PRIVATE_KEY_FLAG] = PHASE2_PRIVATE_KEY; + enterpriceInfo[PRIVATE_KEY_FLAG] = PRIVATE_KEY; + enterpriceInfo[PHASE2_CLIENT_FLAG] = PHASE2_CLIENT; + enterpriceInfo[PHASE2_CACERT_FLAG] = PHASE2_CACERT; + enterpriceInfo[PHASE1_AUTH_FLAG] = PHASE1_AUTH; + enterpriceInfo[CLIENT_CERT_FLAG] = CLIENT_CERT; + enterpriceInfo[CACERT_FLAG] = CACERT; + + wirelessInfo[PSK_FLAG] = PSK_KEY; + wirelessInfo[LEAP_PASSWORD_FLAG] = LEAP_PASSWORD_KEY; +} + +KylinSecretAgent::~KylinSecretAgent() +{ + +} + +bool KylinSecretAgent::hintIsFind(GList *p_secretList, const QStringList &hints) +{ + GList *p_iter; + bool hintFind = false; + + if (hints.isEmpty()) { + return true; + } + + for (p_iter = p_secretList; p_iter != NULL; p_iter = g_list_next(p_iter)) { + SecretItem *p_item = (SecretItem *)p_iter->data; + SecretValue *p_secret; + const char *p_keyName; + GHashTable *p_attributes; + + p_secret = secret_item_get_secret(p_item); + if (p_secret) { + p_attributes = secret_item_get_attributes (p_item); + p_keyName = (char *)g_hash_table_lookup (p_attributes, KEYRING_SK_TAG); + if (!p_keyName) { + g_hash_table_unref (p_attributes); + secret_value_unref (p_secret); + continue; + } + + /* See if this property matches a given hint */ + for (int index = 0; index < hints.size(); ++index) { + QString hintValue = hints.at(index); + if (!g_strcmp0(hintValue.toUtf8().constData(), p_keyName)) { + hintFind = true; + } + } + + g_hash_table_unref (p_attributes); + secret_value_unref (p_secret); + break; + } + } + + return hintFind; +} + +void KylinSecretAgent::getSecretFromKeyring(GList *p_secretList, + const QString &settingName, + QString connectType, + NMVariantMapMap &secretMap) +{ + GList *p_iter = nullptr; + QVariantMap secretKeyMap; + + for (p_iter = p_secretList; p_iter != NULL; p_iter = g_list_next(p_iter)) { + SecretItem *p_item = (SecretItem *)p_iter->data; + SecretValue *p_secret; + const char *p_keyName; + GHashTable *p_attributes; + + p_secret = secret_item_get_secret(p_item); + if (p_secret) { + p_attributes = secret_item_get_attributes (p_item); + p_keyName = (char *)g_hash_table_lookup (p_attributes, KEYRING_SK_TAG); + if (!p_keyName) { + g_hash_table_unref (p_attributes); + secret_value_unref (p_secret); + continue; + } + + if (VPN_TYPE == connectType) { + /* + * 目前根据测试的情况vpn只会存储密码,涉及的字段 + * vpn.secrets: password = 123456 + * 注意的问题:不知道会不会出现多个密码的问题, + */ + QString vpnSecretValue = QString(p_keyName) + + "=" + QString(secret_value_get(p_secret, NULL)); + secretKeyMap[VPN_SECRET] = vpnSecretValue; + } else { + secretKeyMap[p_keyName] = QString(secret_value_get(p_secret, NULL)); + } + g_hash_table_unref (p_attributes); + secret_value_unref (p_secret); + break; + } + } + + secretMap[settingName] = secretKeyMap; + + return; +} + +/* +* 目前根据测试掌握的情况来看,该函数无用原因: +* 当每次都是询问的时候,keyring上面并不会存储密码,那么从keyring上面获取的密码为空 +* 程序根本无法走到此处 +* +* 注意事项: +* 后期根据测试遇到的情况在调整该函数。 +*/ +bool KylinSecretAgent::connectionIsAlwaysAsk(const NMVariantMapMap &connection) +{ + return false; +} + +/* +* +* 802-11-wireless-security.key-mgmt: sae/wpa-psk +* wpa-psk 是WPA/WPA2个人加密方式 +* sae 是WPA3个人加密方式 +* 涉及的字段: +* 802-11-wireless-security.key-mgmt: sae +* 802-11-wireless-security.psk: asdasd +* 802-11-wireless-security.psk-flags: 0(无) +* +* 该函数通过弹出密码框获取密码,并构建相应类型的密码 +*/ +void KylinSecretAgent::askSecretForPassword(QVariantMap &securityMap, + QString passwordKey, + const QString &settingName, + NMVariantMapMap &secretMap, QString connectionID) +{ + QString secretValue = ""; + + if (secretMap.contains(settingName)) { + QVariantMap secretKeyMap = secretMap.value(settingName); + if (!secretKeyMap.isEmpty()) { + secretValue = secretKeyMap.value(passwordKey).toString(); + } + } + + if (secretValue.isEmpty()) { + secretValue = securityMap.value(passwordKey).toString(); + } + + KyPasswordDialog pwdDialog(tr(""), connectionID, parentWidget); + pwdDialog.setPassword(secretValue); + pwdDialog.InitConnect(); + if (qgetenv("USER") == "lightdm") { + pwdDialog.show(); + pwdDialog.activateWindow(); + } + + if(pwdDialog.exec()==QDialog::Accepted){ + QString password = pwdDialog.getPassword(); + QVariantMap newSecretKeyMap = securityMap; + newSecretKeyMap[passwordKey] = password; + secretMap[settingName] = newSecretKeyMap; + + qDebug() << LOG_FLAG << "password:" << password; + } else { + secretMap.clear(); + } + + return; +} + +/* +* 802-11-wireless-security.wep-key-type: passphrase or key +* passphrase 是 WEP128位密码句 +* key 是WEP40/128位秘钥(十六进制 或 ASCII) +* 两者对应的相同的mgmt类型:802-11-wireless-security.key-mgmt: none +* 共用该函数,保存密码到秘钥环 +* 涉及的字段 +* 802-11-wireless-security.key-mgmt: none +* 802-11-wireless-security.wep-tx-keyidx: 2 +* 802-11-wireless-security.wep-key0: -- +* 802-11-wireless-security.wep-key1: -- +* 802-11-wireless-security.wep-key2: -- +* 802-11-wireless-security.wep-key3: -- +* 802-11-wireless-security.wep-key-flags: 1 +* 802-11-wireless-security.wep-key-type: passphrase +*/ + +QString KylinSecretAgent::getWepKeyFromId(uint wepId) +{ + QString wepKey = ""; + + switch(wepId) { + case KEY_TYPE0: + wepKey = WEP_KEY0; + break; + case KEY_TYPE1: + wepKey = WEP_KEY1; + break; + case KEY_TYPE2: + wepKey = WEP_KEY2; + break; + case KEY_TYPE3: + wepKey = WEP_KEY3; + break; + default: + qWarning() << LOG_FLAG + << "the wep key id" << wepId << "is undefined."; + } + + return wepKey; +} + +void KylinSecretAgent::askSecretForWep(QVariantMap &wirelessSecurityMap, + const QString &settingName, + NMVariantMapMap &secretMap, QString connectionID) +{ + QString wepKey = ""; + QString wepSecretValue = ""; + uint wepId = 0; + + if (wirelessSecurityMap.contains(WEP_ID_KEY)) { + wepId = wirelessSecurityMap.value(WEP_ID_KEY).toUInt(); + } + + wepKey = getWepKeyFromId(wepId); + if (wepKey.isEmpty()) { + QString errorMsg = "the wep key is invalide."; + qWarning() << LOG_FLAG << errorMsg; + //sendError(); + return; + } + + if (secretMap.contains(settingName)) { + QVariantMap secretKeyMap = secretMap.value(settingName); + if (!secretKeyMap.isEmpty()) { + wepSecretValue = secretKeyMap.value(wepKey).toString(); + } + } + + if (wepSecretValue.isEmpty()) { + wepSecretValue = wirelessSecurityMap.value(wepKey).toString(); + } + + KyPasswordDialog pwdDialog("", connectionID, parentWidget); + pwdDialog.setPassword(wepSecretValue); + pwdDialog.InitConnect(); + if (qgetenv("USER") == "lightdm") { + pwdDialog.show(); + pwdDialog.activateWindow(); + } + + if(pwdDialog.exec()==QDialog::Accepted){ + QString password = pwdDialog.getPassword(); + QVariantMap newSecretKeyMap = wirelessSecurityMap; + newSecretKeyMap[wepKey] = password; + secretMap[settingName] = newSecretKeyMap; + qDebug() << LOG_FLAG << "password:" << password; + } else { + secretMap.clear(); + } + + return; +} + +/* +* leap加密类型对应的mgmt值: +* 802-11-wireless-security.key-mgmt: ieee8021x +* 涉及的字段 +* 802-11-wireless-security.leap-username: sadasd +* 802-11-wireless-security.leap-password: sadasd +* 802-11-wireless-security.leap-password-flags:0 +* +* 该函数通过弹窗获取正确的密码和用户名,需要构建相应的secretmap +*/ + +void KylinSecretAgent::askSecretForLeap(QVariantMap &wirelessSecurityMap, + const QString &settingName, + NMVariantMapMap &secretMap, QString connectionID) +{ + uint leapPasswordFlag = 0; + QString leapPassword = ""; + QString leapUserName = ""; + + if (wirelessSecurityMap.contains(LEAP_USER_KEY)) { + leapUserName = wirelessSecurityMap.value(LEAP_USER_KEY).toString(); + } + + if (wirelessSecurityMap.contains(LEAP_PASSWORD_FLAG)) { + leapPasswordFlag = wirelessSecurityMap.value(LEAP_PASSWORD_FLAG).toUInt(); + } + + if (secretMap.contains(settingName)) { + QVariantMap secretKeyMap = secretMap.value(settingName); + if (!secretKeyMap.isEmpty()) { + leapPassword = secretKeyMap.value(LEAP_PASSWORD_KEY).toString(); + } + } + + if (leapPassword.isEmpty()) { + leapPassword = wirelessSecurityMap.value(LEAP_PASSWORD_KEY).toString(); + } + + KyPasswordDialog pwdDialog("userAndPwd", connectionID, parentWidget); + pwdDialog.setUserName(leapUserName); + pwdDialog.setPassword(leapPassword); + pwdDialog.InitConnect(); + if (qgetenv("USER") == "lightdm") { + pwdDialog.show(); + pwdDialog.activateWindow(); + } + + if(pwdDialog.exec()==QDialog::Accepted){ + QString password = pwdDialog.getPassword(); + QString userName = pwdDialog.getUserName(); + QVariantMap securityMap; + securityMap[LEAP_PASSWORD_KEY] = password; + securityMap[LEAP_PASSWORD_FLAG] = leapPasswordFlag; + securityMap[LEAP_USER_KEY] = userName; + secretMap[settingName] = securityMap; + + qDebug() << LOG_FLAG << "password:" << password << userName; + } else { + secretMap.clear(); + } + + return; +} + +/* +* 功能:获取普通wifi的密码,分为三类 +* 1)wpa/wpa2/wpa3 +* 2) leap +* 3) wep +*/ +void KylinSecretAgent::askSecretForWireless(const NMVariantMapMap &connection, + const QString settingName, + NMVariantMapMap &secretMap) +{ + qDebug() << LOG_FLAG <<"askSecretForWireless connection" << connection; + QString secretType = ""; + + QVariantMap wirelessSecurityMap = connection.value(settingName); + if (wirelessSecurityMap.contains(KEY_MGMT)) { + secretType = wirelessSecurityMap.value(KEY_MGMT).toString(); + } else { + QString errorMsg = "can not get wireless secret type."; + sendError(InvalidConnection, errorMsg); + qWarning()<< LOG_FLAG << errorMsg; + return; + } + + QVariantMap connectMap = connection.value(CONNECTION_KEY); + QString connectId = connectMap.value(ID_KEY).toString(); + + if (PSK_MGMT == secretType || SAE_MGMT == secretType) { + askSecretForPassword(wirelessSecurityMap, PSK_KEY, settingName, secretMap, connectId); + } else if (WEP_MGMT == secretType || WEP128_MGMT == secretType) { + askSecretForWep(wirelessSecurityMap, settingName, secretMap, connectId); + } else if (LEAP_MGMT == secretType) { + askSecretForLeap(wirelessSecurityMap, settingName, secretMap, connectId); + } else { + QString errorMsg = "the secret type" + secretType + "is undefined"; + sendError(InvalidConnection, errorMsg); + qWarning()<< LOG_FLAG << errorMsg; + return; + } + if (secretMap.isEmpty()) { + QString errorMsg = "user cancel get wireless secret"; + sendError(UserCanceled, errorMsg); + qWarning()<< LOG_FLAG << errorMsg; + return; + } + QVariantMap newSecurityMap = secretMap.value(WIRELESS_SECURITY_NAME); +// QVariantMap connectMap = connection.value(CONNECTION_KEY); + QString connectUuid = connectMap.value(UUID_KEY).toString(); +// QString connectId = connectMap.value(ID_KEY).toString(); + saveWirelessSecret(newSecurityMap, connectId, connectUuid); + + return; +} + +/* +功能:获取企业wifi类型为非tls的密码,涉及的字段 +802-11-wireless-security.key-mgmt: wpa-eap/ieee8021x +wpa-eap 是wpa/wpa2企业 +ieee8021x 是动态wep(802.1x)需要和普通wifi的leep作区分 +802-1x.eap: ttls/pwd/leap/fast/peap +802-1x.identity: steve +802-1x.password: 23445 +802-1x.password-flags: 1 +*/ +void KylinSecretAgent::askSecretWithIdentityAndPassword(QVariantMap securityMap, + QString userKey, + QString passwordKey, + const QString &settingName, + NMVariantMapMap &secretMap, QString connectionID) +{ + QString password = ""; + QString userName = ""; + + if (securityMap.contains(userKey)) { + userName = securityMap.value(userKey).toString(); + } + + if (secretMap.contains(settingName)) { + QVariantMap secretKeyMap = secretMap.value(settingName); + if (!secretKeyMap.isEmpty()) { + password = secretKeyMap.value(passwordKey).toString(); + } + } + + if (password.isEmpty()) { + password = securityMap.value(passwordKey).toString(); + } + + KyPasswordDialog pwdDialog(tr("userAndPwd"), connectionID, parentWidget); + pwdDialog.setUserName(userName); + pwdDialog.setPassword(password); + pwdDialog.InitConnect(); + if (qgetenv("USER") == "lightdm") { + pwdDialog.show(); + pwdDialog.activateWindow(); + } + + if(pwdDialog.exec()==QDialog::Accepted){ + QString newPassword = pwdDialog.getPassword(); + QString newUserName = pwdDialog.getUserName(); + QVariantMap newSecurityMap = securityMap; + newSecurityMap[userKey] = newUserName; + newSecurityMap[passwordKey] = newPassword; + secretMap[settingName] = newSecurityMap; + + qDebug() << LOG_FLAG << "password:" << newPassword << newUserName; + } else { + secretMap.clear(); + } + + return; +} + +/* +* 功能:获取tls类型的密码,涉及的字段 +802-1x.eap: tls +802-1x.domain-suffix-match: +802-1x.private-key-password: -- +802-1x.private-key-password-flags: 0(无) +802-1x.identity: steve +*/ +void KylinSecretAgent::askSecretForTls(QVariantMap securityMap, + const QString &settingName, + NMVariantMapMap &secretMap, QString connectionID) +{ + QString password = ""; + QString identity = ""; + QString domain = ""; + + qDebug() << LOG_FLAG << "tls security map" << securityMap; + if (securityMap.contains(IDENTITY_KEY)) { + identity = securityMap.value(IDENTITY_KEY).toString(); + } + + if (securityMap.contains(DOMAIN_KEY)) { + domain = securityMap.value(DOMAIN_KEY).toString(); + qDebug() << LOG_FLAG << "domain match" << domain; + } + + if (secretMap.contains(settingName)) { + QVariantMap secretKeyMap = secretMap.value(settingName); + if (!secretKeyMap.isEmpty()) { + password = secretKeyMap.value(PRIVATE_KEY).toString(); + } + } + + if (password.isEmpty()) { + password = securityMap.value(PRIVATE_KEY).toString(); + } + + KyPasswordDialog pwdDialog(tr("tls"), connectionID, parentWidget); + pwdDialog.setUserName(identity); + pwdDialog.setPassword(password); + pwdDialog.InitConnect(); + if (qgetenv("USER") == "lightdm") { + pwdDialog.show(); + pwdDialog.activateWindow(); + } + + if(pwdDialog.exec()==QDialog::Accepted){ + QString newPassword = pwdDialog.getPassword(); + QString newIdentity = pwdDialog.getUserName(); + QVariantMap newSecurityMap = securityMap; + newSecurityMap[IDENTITY_KEY] = newIdentity; + newSecurityMap[PRIVATE_KEY] = newPassword; + newSecurityMap[DOMAIN_KEY] = domain; + secretMap[settingName] = newSecurityMap; + + qDebug() << LOG_FLAG << "tls password:" << newPassword << newIdentity << domain; + } else { + secretMap.clear(); + } + + return; +} + +void KylinSecretAgent::askSecretForEnterpriceWireless(const NMVariantMapMap &connection, + const QString settingName, + NMVariantMapMap &secretMap) +{ + qDebug() << LOG_FLAG <<"askSecretForEnterpriceWireless connection" << connection; + QString secretType = ""; + + QVariantMap enterpriceSecurityMap = connection.value(settingName); + if (enterpriceSecurityMap.contains(EAP_KEY)) { + secretType = enterpriceSecurityMap.value(EAP_KEY).toString(); + } else { + QString errorStr = "can not get enterprice secret type."; + sendError(InvalidConnection, errorStr); + qWarning()<< LOG_FLAG << errorStr; + return; + } + QVariantMap connectMap = connection.value(CONNECTION_KEY); + QString connectId = connectMap.value(ID_KEY).toString(); + + if (TLS_EAP == secretType) { + askSecretForTls(enterpriceSecurityMap, settingName, secretMap, connectId); + } else { + askSecretWithIdentityAndPassword(enterpriceSecurityMap, + IDENTITY_KEY, PASSWORD_KEY, settingName, secretMap, connectId); + } + + if (secretMap.isEmpty()) { + QString errorStr = "user cancel get enterprice wireless secret"; + sendError(UserCanceled, errorStr); + qWarning()<< LOG_FLAG << errorStr; + } + + QVariantMap newSecurityMap = secretMap.value(settingName); +// QVariantMap connectMap = connection.value(CONNECTION_KEY); + QString connectUuid = connectMap.value(UUID_KEY).toString(); +// QString connectId = connectMap.value(ID_KEY).toString(); + saveEnterpriceSecret(newSecurityMap, connectId, connectUuid); + + return; +} + +void KylinSecretAgent::askSecretForVpn(const NMVariantMapMap &connection, + const QString settingName, + NMVariantMapMap &secretMap) +{ + QVariantMap newVpnSetingMap; + + QVariantMap vpnSetingMap = connection.value(VPN_NAME); + if (vpnSetingMap.isEmpty()) { + QString errorStr = "the VPN map of connection is invalide"; + sendError(InvalidConnection, errorStr); + qWarning() << LOG_FLAG << errorStr; + return; + } + + QVariantMap vpnSecretMap = secretMap.value(VPN_NAME); + QStringList vpnSecret = getVpnPassword(vpnSecretMap); + if (vpnSecret.isEmpty() || vpnSecret.size() < 2) { + vpnSecret = getVpnPassword(vpnSetingMap); + } + QString secretKey = vpnSecret.at(0); + QString secretValue= vpnSecret.at(1); + + KyPasswordDialog pwdDialog("","", parentWidget); + pwdDialog.setPassword(secretValue); + pwdDialog.InitConnect(); + if (qgetenv("USER") == "lightdm") { + pwdDialog.show(); + pwdDialog.activateWindow(); + } + + if(pwdDialog.exec()==QDialog::Accepted){ + QString newPassword = pwdDialog.getPassword(); + newVpnSetingMap = vpnSetingMap; + newVpnSetingMap[VPN_SECRET] = secretKey + "=" + newPassword; + secretMap[VPN_NAME] = newVpnSetingMap; + + QVariantMap connectMap = connection.value(CONNECTION_KEY); + QString connectUuid = connectMap.value(UUID_KEY).toString(); + QString connectId = connectMap.value(ID_KEY).toString(); + saveSecretForVpn(newVpnSetingMap, connectId, connectUuid); + + qDebug() << LOG_FLAG << "vpn password:" << newPassword ; + } else { + QString errorStr = "user canceled get vpn secret"; + sendError(UserCanceled, errorStr); + qWarning() << LOG_FLAG << errorStr; + } + + return; +} + +void KylinSecretAgent::askForSecret(const NMVariantMapMap &connection, + const QString &settingName, + QString connectType, + NMVariantMapMap &secretMap) +{ + if (VPN_TYPE == connectType) { + askSecretForVpn(connection, settingName, secretMap); + } else { + QVariantMap enterpriceSecurityMap = connection.value(ENTERPRICE_NAME); + if (!enterpriceSecurityMap.isEmpty()) { + askSecretForEnterpriceWireless(connection, settingName, secretMap); + } else { + QVariantMap wirelessSecurityMap = connection.value(WIRELESS_SECURITY_NAME); + if (!wirelessSecurityMap.isEmpty()) { + askSecretForWireless(connection, settingName, secretMap); + } else { + qWarning()<< LOG_FLAG << "can not ask secret for wireless"; + } + } + } + + return; +} + +NMVariantMapMap KylinSecretAgent::GetSecrets(const NMVariantMapMap &connection, + const QDBusObjectPath &connection_path, + const QString &settingName, + const QStringList &hints, + uint flags) +{ + //qDebug() << LOG_FLAG <<"GetSecrets connection" << connection; + + qDebug() << LOG_FLAG <<"GetSecrets setting name" << settingName; + qDebug() << LOG_FLAG <<"GetSecrets hints" << hints; + qDebug() << LOG_FLAG <<"GetSecrets flag" << flags; + + NMVariantMapMap secretMap; + + GHashTable *p_attributes = NULL; + GError *p_secretError = NULL; + GCancellable *p_cancellable = g_cancellable_new(); + + QVariantMap connectMap = connection.value(CONNECTION_KEY); + QString connectUuid = connectMap.value(UUID_KEY).toString(); + QString connectType = connectMap.value(TYPE_KEY).toString(); + + p_attributes = secret_attributes_build (&network_manager_secret_schema, + KEYRING_UUID_TAG, connectUuid.toLocal8Bit().data(), + KEYRING_SN_TAG, settingName.toLocal8Bit().data(), + NULL); + if (NULL == p_attributes) { + qWarning() << LOG_FLAG << "create secret arributes for getting secret failed."; + //sendError(); + return secretMap; + } + + GList *p_secretList = secret_service_search_sync(NULL, &network_manager_secret_schema, p_attributes, + (SecretSearchFlags)(SECRET_SEARCH_ALL | SECRET_SEARCH_UNLOCK | SECRET_SEARCH_LOAD_SECRETS), + p_cancellable, &p_secretError); + if (p_secretError) { + if ((flags & AllowInteraction) + && g_error_matches (p_secretError, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN)) { + /* If the connection always asks for secrets, tolerate + * keyring service not being present. */ + qWarning() << LOG_FLAG << "secret dbus failed"; + g_clear_error (&p_secretError); + } else { + QString errorStr = "read secret from keyring error msg: (" + QString(p_secretError->message) + ")"; + qWarning() << LOG_FLAG << errorStr; + sendError(InternalError, errorStr); + g_hash_table_unref (p_attributes); + g_error_free (p_secretError); + g_object_unref(p_cancellable); + return secretMap; + } + } + + if ((flags & AllowInteraction) && g_list_length (p_secretList) == 0) { + qDebug() << LOG_FLAG << "get secret list is empty"; + askForSecret(connection, settingName, connectType, secretMap); + } else { + getSecretFromKeyring(p_secretList, settingName, connectType, secretMap); + bool hintFind = hintIsFind(p_secretList, hints); + if (flags) { + if (!hintFind) { + qDebug() << LOG_FLAG << "can not find hints int keyring"; + askForSecret(connection, settingName, connectType, secretMap); + } else if (flags & RequestNew) { + qDebug() << LOG_FLAG <<"request new secret"; + askForSecret(connection, settingName, connectType, secretMap); + } else if ((flags & AllowInteraction) + && connectionIsAlwaysAsk (connection)) { + qDebug() << LOG_FLAG << "secret is asked always"; + askForSecret(connection, settingName, connectType, secretMap); + } + } + } + + g_hash_table_unref (p_attributes); + g_object_unref(p_cancellable); + + return secretMap; +} + +void KylinSecretAgent::CancelGetSecrets(const QDBusObjectPath &connection_path, const QString &setting_name) +{ + //qDebug() << LOG_FLAG <<"CancelGetSecrets setting name" << setting_name; + //qDebug() << LOG_FLAG <<"CancelGetSecrets path" << connection_path; + + return; +} + +void KylinSecretAgent::saveOneSecret(QString &connectUuid, + QString settingName, + QString secretKey, + QString &secretValue, + QString &displayName) +{ + qDebug()<< LOG_FLAG << "save one secret" + << "display name" << displayName + << "uuid" << connectUuid + << "setting name" << settingName + << "psk key" << secretKey + << "psk secret" << secretValue; + + GHashTable *attrs = NULL; + GError *secretError = NULL; + GCancellable *cancellable = g_cancellable_new(); + + attrs = secret_attributes_build(&network_manager_secret_schema, + KEYRING_UUID_TAG, connectUuid.toLocal8Bit().data(), + KEYRING_SN_TAG, settingName.toLocal8Bit().data(), + KEYRING_SK_TAG, secretKey.toLocal8Bit().data(), + NULL); + if (!attrs) { + QString errorStr = "create secret attri failed"; + qWarning() << LOG_FLAG << errorStr; + g_object_unref (cancellable); + sendError(InternalError, errorStr); + return; + } + + gboolean ret = secret_password_storev_sync(&network_manager_secret_schema, attrs, NULL, + displayName.toLocal8Bit().data(), + secretValue.toLocal8Bit().data(), + cancellable, &secretError); + if (!ret) { + qWarning() << LOG_FLAG << "save secret failed"; + if (secretError) { + QString errorStr = "secret password storev error msg: (" + + QString(secretError->message) + ")"; + qWarning() << LOG_FLAG << errorStr; + sendError(InternalError, errorStr); + g_object_unref(secretError); + } + } + + g_object_unref (cancellable); + g_hash_table_unref (attrs); + + return; +} + +void KylinSecretAgent::saveConnectSecret(QVariantMap &securityMap, + QString secretSettingName, + QString &secretKey, + QString &connectId, + QString &connectUuid) +{ + //to do and test this case + QString secretValue = ""; + + if (!securityMap.contains(secretKey)) { + qWarning() << LOG_FLAG << "the secret key" << secretKey + << "is not contain in security map."; + return; + } + + secretValue = securityMap.value(secretKey).toString(); + if (secretValue.isEmpty()) { + qWarning() << LOG_FLAG << "the leap password is invalid."; + return; + } + + QString displayName = "Network secret for " + connectId + + "/" + secretSettingName + "/" + secretKey; + saveOneSecret(connectUuid, secretSettingName, + secretKey, secretValue, displayName); + + return; +} + +/* +* 802-11-wireless-security.wep-key-type: passphrase or key +* passphrase 是 WEP128位密码句 +* key 是WEP40/128位秘钥(十六进制 或 ASCII) +* 两者对应的相同的mgmt类型:802-11-wireless-security.key-mgmt: none +* 共用该函数,保存密码到秘钥环 +* 涉及的字段 +* 802-11-wireless-security.key-mgmt: none +* 802-11-wireless-security.wep-tx-keyidx: 2 +* 802-11-wireless-security.wep-key0: -- +* 802-11-wireless-security.wep-key1: -- +* 802-11-wireless-security.wep-key2: -- +* 802-11-wireless-security.wep-key3: -- +* 802-11-wireless-security.wep-key-flags: 1 +* 802-11-wireless-security.wep-key-type: passphrase +*/ +void KylinSecretAgent::saveWepSecret(QVariantMap &wirelessSecurityMap, + QString &connectId, + QString &connectUuid) +{ + QString wepSecret = ""; + QString wepKey = ""; + + uint wepKeyId = wirelessSecurityMap.value(WEP_ID_KEY).toUInt(); + + wepKey = getWepKeyFromId(wepKeyId); + if (wepKey.isEmpty()) { + QString errorMsg = "save wep secret, but wep key is invalide."; + qWarning() << LOG_FLAG << errorMsg; + //sendError(); + return; + } + + if (!wirelessSecurityMap.contains(wepKey)) { + qWarning()<::iterator iter; + + iter = wirelessInfo.begin(); + while (iter != wirelessInfo.end()) { + QString flagName = iter.key(); + QString secretName = iter.value(); + if (wirelessSecurityMap.contains(flagName)) { + uint secretFlag = wirelessSecurityMap.value(flagName).toUInt(); + if (POLICY_AGENT_OWNED == secretFlag) { + saveConnectSecret(wirelessSecurityMap, WIRELESS_SECURITY_NAME, + secretName, connectId, connectUuid); + } + + return; + } + + iter ++; + } + + if (wirelessSecurityMap.contains(WEP_FLAG_KEY)) { + uint wepFLags = wirelessSecurityMap.value(WEP_FLAG_KEY).toUInt(); + if (POLICY_AGENT_OWNED == wepFLags) { + saveWepSecret(wirelessSecurityMap, connectId, connectUuid); + } + } + + return; +} + +/* +* 功能:保存企业级的wifi密码到keyring,涉及的主要字段: +* 802-1x.optional: 否 +802-1x.eap: peap +802-1x.identity: steve + +802-1x.ca-cert-password: -- +802-1x.ca-cert-password-flags: 0(无) + +802-1x.client-cert-password: -- +802-1x.client-cert-password-flags: 0(无) + +802-1x.phase2-ca-cert-password: -- +802-1x.phase2-ca-cert-password-flags: 0(无) + +802-1x.phase2-client-cert-password: -- +802-1x.phase2-client-cert-password-flags:0(无) + +802-1x.password: testing +802-1x.password-flags: 0(无) + +802-1x.private-key-password: -- +802-1x.private-key-password-flags: 0(无) + +802-1x.phase2-private-key-password: -- +802-1x.phase2-private-key-password-flags:0(无) + +802-1x.pin: -- +802-1x.pin-flags: 0(无) + +目前根据测试情况,企业wifi密码类型主要分为两类: +1) +802-11-wireless-security.key-mgmt: wpa-eap/ieee8021x +wpa-eap 是wpa/wpa2企业 +ieee8021x 是动态wep(802.1x)需要和普通wifi的leep作区分 +802-1x.eap: ttls/pwd/leap/fast/peap +802-1x.identity: steve +802-1x.password: 23445 +802-1x.password-flags: 1 + +2) +802-1x.eap: tls +802-1x.domain-suffix-match: +802-1x.private-key-password: -- +802-1x.private-key-password-flags: 0(无) +802-1x.identity: steve + +对于这种密码类型nm-applet的agnet没有保存,不处理 +802-1x.password-raw: -- +802-1x.password-raw-flags: 0(无) + +通过如下命令可以查看信息: +nmcli connection show [connection uuid] --show-secrets + +通过打印日志,将SaveSecrets函数的入参connection打印出,也可以查看这些信息, +*/ + +void KylinSecretAgent::saveEnterpriceSecret(QVariantMap &enterpriceSecurityMap, + QString &connectId, + QString &connectUuid) +{ + QMap::iterator iter; + + iter = enterpriceInfo.begin(); + while (iter != enterpriceInfo.end()) { + QString flagName = iter.key(); + QString secretName = iter.value(); + if (enterpriceSecurityMap.contains(flagName)) { + uint secretFlags = enterpriceSecurityMap.value(flagName).toUInt(); + if (POLICY_AGENT_OWNED == secretFlags) { + saveConnectSecret(enterpriceSecurityMap, + ENTERPRICE_NAME, secretName, connectId, connectUuid); + } + } + + iter++; + } + + return; +} + +/* +* 功能:将wifi的密码保存到keyring上面 +* 先判断有没有企业级wifi的安全字段,有的话就从其获取要保存到keyring的密码 +* 如果没有那就从普通wifi的安全字段获取要保存到keyring的密码 +* +* 注意事项: +* 目前的测试情况:企业wifi和普通wifi的安全字段只有一个起作用,即互斥关系, +* 不能排除共存的情况,如果出现需要另做调整 +*/ + +void KylinSecretAgent::saveSecretForWireless(const NMVariantMapMap &connection, + QString &connectId, + QString &connectUuid) +{ + QVariantMap enterpriceSecurityMap = connection.value(ENTERPRICE_NAME); + if (!enterpriceSecurityMap.isEmpty()) { + saveEnterpriceSecret(enterpriceSecurityMap, connectId, connectUuid); + } else { + QVariantMap wirelessSecurityMap = connection.value(WIRELESS_SECURITY_NAME); + if (!wirelessSecurityMap.isEmpty()) { + saveWirelessSecret(wirelessSecurityMap, connectId, connectUuid); + } else { + QString errorStr = "wireless is invalid, save secret failed."; + sendError(InvalidConnection, errorStr); + qWarning() << LOG_FLAG << errorStr; + } + } + + return; +} + +QString KylinSecretAgent::getVpnDataItemByKey(QVariantMap &vpnMap, QString key) +{ + QString value = ""; + + QString vpnData = vpnMap.value(VPN_DATA).toString(); + if (vpnData.isEmpty()) { + qWarning() << LOG_FLAG << "vpn data is empty"; + return value; + } + + QStringList vpnDataList = vpnData.split(","); + int index = vpnDataList.indexOf(key); + if (index < 0) { + qWarning() << LOG_FLAG << "it can not find key" << key << "from vpn data"; + return value; + } + + QString vpnDataItem = vpnDataList.at(index); + QStringList keyList = vpnDataItem.split("="); + if (keyList.isEmpty() || keyList.size() < 2) { + return value; + } + + value = keyList.at(1); + + return value; +} + +QStringList KylinSecretAgent::getVpnPassword(QVariantMap &vpnMap) +{ + QStringList vpnPassword; + QString vpnSecret; + + vpnSecret.clear(); + vpnPassword.clear(); + + vpnSecret = vpnMap.value(VPN_SECRET).toString(); + if (vpnSecret.contains("=")) { + vpnPassword = vpnSecret.split("="); + } + + return vpnPassword; +} +/* +* 功能:将vpn的密码保存到keyring上面,vpn涉及的字段如下: + +vpn.service-type: org.freedesktop.NetworkManager.pptp +vpn.user-name: -- +vpn.data: gateway = 127.2.2.2, password-flags = 1, user = admin +vpn.secrets: password = 123456 +vpn.persistent: 否 +vpn.timeout: 0 + +其中主要的字段: +1)vpn.data中的password-flags,检查是否存于keyring +2)vpn.secrets中的password 是要存于keyring的密码,存密码时的key为password + +注意事项: +vpn.secrets可能会有多个密码,目前没有遇到,等遇到的时候在调试,目前先按一个处理 + +通过如下命令可以查看信息: +nmcli connection show [connection uuid] --show-secrets + +通过打印日志,将SaveSecrets函数的入参connection打印出,也可以查看这些信息, +***/ +void KylinSecretAgent::saveSecretForVpn(QVariantMap &vpnSetingMap, + QString &connectId, + QString &connectUuid) +{ + if (vpnSetingMap.isEmpty()) { + QString errorStr = "VPN map is empty"; + sendError(InvalidConnection, errorStr); + qWarning() << LOG_FLAG << errorStr; + return; + } + + QString vpnFlag = getVpnDataItemByKey(vpnSetingMap, VPN_FLAG); + if (vpnFlag.isEmpty() || POLICY_AGENT_OWNED != vpnFlag.toInt()){ + return; + } + + QStringList vpnSecret = getVpnPassword(vpnSetingMap); + if (vpnSecret.isEmpty() || vpnSecret.size() < 2) { + QString errorStr = "the vpn secret is invalid"; + sendError(NoSecrets, errorStr); + qWarning() << LOG_FLAG << errorStr; + return; + } + + QString secretKey = vpnSecret.at(0); + QString secretValue= vpnSecret.at(1); + + QString vpnService = vpnSetingMap.value(VPN_SERVICE).toString(); + QString displayName = "VPN" + vpnSecret.at(0) + "secret for" + + connectId + vpnService + "/vpn"; + + + saveOneSecret(connectUuid, VPN_NAME, secretKey, secretValue, displayName); + + return; + +} + +void KylinSecretAgent::SaveSecrets(const NMVariantMapMap &connection, + const QDBusObjectPath &connection_path) +{ + qDebug() << LOG_FLAG <<"SaveSecrets connection" << connection; + + //GError *secretError = NULL; + GCancellable *cancellable = g_cancellable_new(); + + QVariantMap connectMap = connection.value(CONNECTION_KEY); + QString connectUuid = connectMap.value(UUID_KEY).toString(); + + secret_password_clear_sync(&network_manager_secret_schema, + cancellable, NULL, + KEYRING_UUID_TAG, + connectUuid.toLocal8Bit().data(), NULL); + if (g_cancellable_is_cancelled(cancellable)) { + qWarning() << LOG_FLAG << "save secret is canceled"; + g_object_unref(cancellable); + return; + } + + QString connectType = connectMap.value(TYPE_KEY).toString(); + QString connectId = connectMap.value(ID_KEY).toString(); + if (VPN_TYPE == connectType) { + QVariantMap vpnSetingMap = connection.value(VPN_NAME); + saveSecretForVpn(vpnSetingMap, connectId, connectUuid); + } else { + saveSecretForWireless(connection, connectId, connectUuid); + } + + return; +} + +void KylinSecretAgent::DeleteSecrets(const NMVariantMapMap &connection, + const QDBusObjectPath &connection_path) +{ + //qDebug() << LOG_FLAG <<"DeleteSecrets connection" << connection; + + GError *secretError = NULL; + GCancellable *cancellable = g_cancellable_new(); + + QVariantMap connectMap = connection.value(CONNECTION_KEY); + QString uuid = connectMap.value(UUID_KEY).toString(); + + secret_password_clear_sync(&network_manager_secret_schema, + cancellable, + &secretError, + KEYRING_UUID_TAG, + uuid.toLocal8Bit().data(), + NULL); + + if (g_cancellable_is_cancelled(cancellable)) { + qWarning() << LOG_FLAG << "delete secret is canceled"; + g_object_unref(cancellable); + return; + } + + if (secretError != NULL) { + QString errorStr = "The request could not be completed (" + + QString(secretError->message) + ")"; + sendError(InternalError, errorStr); + g_error_free(secretError); + } + + g_object_unref(cancellable); + return; +} diff --git a/libkylin-nm-base/kylin-keyring/kylin-agent/kylinsecretagent.h b/libkylin-nm-base/kylin-keyring/kylin-agent/kylinsecretagent.h new file mode 100644 index 00000000..c0b92764 --- /dev/null +++ b/libkylin-nm-base/kylin-keyring/kylin-agent/kylinsecretagent.h @@ -0,0 +1,129 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYLINSECRETAGENT_H +#define KYLINSECRETAGENT_H + +#include + +#include +//#include +#include "networkmanagerqt/secretagent.h" + +#include "agentutils.h" + +class KylinSecretAgent: public NetworkManager::SecretAgent +{ + Q_OBJECT + +public: + explicit KylinSecretAgent(const QString &id, QWidget *pWidget = nullptr, QObject *parent = nullptr); + ~KylinSecretAgent(); + +private: + QWidget *parentWidget = nullptr; + void saveOneSecret(QString &connectUuid, QString settingName, + QString secretKey, QString &secretValue, QString &displayNmae); + void saveConnectSecret(QVariantMap &securityMap, QString secretSettingName, + QString &secretKey, QString &connectId, QString &connectUuid); + + void saveWepSecret(QVariantMap &wirelessSecurityMap, + QString &connectId, QString &connectUuid); + void saveWirelessSecret(QVariantMap &wirelessSecurityMap, + QString &connectId, QString &connectUuid); + + void saveEnterpriceSecret(QVariantMap &enterpriceSecurityMap, + QString &connectId, QString &connectUuidd); + + void saveSecretForWireless(const NMVariantMapMap &connection, + QString &connectId, QString &connectUuid); + + QStringList getVpnPassword(QVariantMap &vpnSettingMap); + QString getVpnDataItemByKey(QVariantMap &vpnSettingMap, QString key); + void saveSecretForVpn(QVariantMap &vpnSetingMap, + QString &connectId, QString &connectUuid); + + void getSecretFromKeyring(GList *p_secretList, const QString &settingName, + QString connectType, NMVariantMapMap &secretMap); + bool hintIsFind(GList *p_secretList, const QStringList &hints); + bool connectionIsAlwaysAsk(const NMVariantMapMap &connection); + QString getWepKeyFromId(uint wepId); + + + void askSecretForLeap(QVariantMap &wirelessSecurityMap, + const QString &settingName, NMVariantMapMap &secretMap, QString connectionID); + void askSecretForWep(QVariantMap &wirelessSecurityMap, + const QString &settingName, NMVariantMapMap &secretMap, QString connectionID); + void askSecretForPassword(QVariantMap &securityMap, QString passwordKey, + const QString &settingName, NMVariantMapMap &secretMap, QString connectionID); + void askSecretForWireless(const NMVariantMapMap &connection, + const QString settingName, NMVariantMapMap &secretMap); + + void askSecretForTls(QVariantMap securityMap, + const QString &settingName, NMVariantMapMap &secretMap, QString connectionID); + void askSecretWithIdentityAndPassword(QVariantMap securityMap, QString userKey, + QString passwordKey, const QString &settingName, NMVariantMapMap &secretMap, QString connectionID); + void askSecretForEnterpriceWireless(const NMVariantMapMap &connection, + const QString settingName, NMVariantMapMap &secretMap); + void askSecretForVpn(const NMVariantMapMap &connection, + const QString settingName, NMVariantMapMap &secretMap); + void askForSecret(const NMVariantMapMap &connection, const QString &settingName, + QString connectType, NMVariantMapMap &secretMap); + +public Q_SLOTS: + + /* + * kylin-nm的agent功能主要是实现如下四个函数,这四个函数继承自父类NetworkManager::SecretAgent + * 当发生错误的时候,调用父类的sendError函数,给networkmanager返回结果 + * 调试方式 + * 根据kylin-nm移植的nm-applet的agent功能代码添加日志,进行流程调试梳理,完成了该代码的开发, + * 后续出了问题可以通过这种方式理顺流程调试解决问题。 + * 注意事项: + * 1)所有的函数keyring、的操作都是同步的,需要其单独的agent线程,否则容易阻塞 + * 2)目前代码只是对能够测试到的情况做了代码实现,有可能会有遗漏的地方,后续出现新情况,在完善。 + */ + + /* + * 该函数从秘钥环上面获取密码,并将获取到的密码组成安全的mapmap返回,失败后通过sendError返回错误, + * 函数的返回值将变得无效 + */ + NMVariantMapMap GetSecrets(const NMVariantMapMap &connection, const QDBusObjectPath &connection_path, + const QString &setting_name, const QStringList &hints, uint flags); + + /* + * 该函数用于取消agent的操作,从测试的情况来看,目前没有发现在什么时候会出现这种情况 + * 暂时未实现,后期注意观察,出现问题后根据具体情况实现, + * 返回值为空,如果出现错误,通过sendError返回错误 + */ + void CancelGetSecrets(const QDBusObjectPath &connection_path, const QString &setting_name); + + /* + * 该函数将密码保存到keyring上面,要保存的密码可以在connection参数中查找到, + * 返回值为空,如果出现错误,通过sendError返回错误 + */ + void SaveSecrets(const NMVariantMapMap &connection, const QDBusObjectPath &connection_path); + /* + * 该函数将密码从keyring上面删除,返回值为空,如果出现错误,通过sendError返回错误 + */ + void DeleteSecrets(const NMVariantMapMap &connection, const QDBusObjectPath &connection_path); + +private: + QMap enterpriceInfo; + QMap wirelessInfo; +}; + +#endif // KYLINSECRETAGENT_H diff --git a/libkylin-nm-base/kylin-keyring/kylin-keyring.pro b/libkylin-nm-base/kylin-keyring/kylin-keyring.pro new file mode 100644 index 00000000..509406c0 --- /dev/null +++ b/libkylin-nm-base/kylin-keyring/kylin-keyring.pro @@ -0,0 +1,75 @@ +QT += core gui x11extras dbus KWindowSystem svg concurrent network + +greaterThan(QT_MAJOR_VERSION, 4): QT += widgets + +TARGET = kylin-keyring +TEMPLATE = lib +DEFINES += LIBKYLIN_KEYRING_LIBRARY + +CONFIG += c++14 qt warn_on link_pkgconfig console +CONFIG += no_keywords + +PKGCONFIG +=gio-2.0 glib-2.0 gio-unix-2.0 libnm libnma libsecret-1 gsettings-qt libcap kysdk-qtwidgets +#gtk+-3.0 +INCLUDEPATH += /usr/include/KF5/NetworkManagerQt + +LIBS += -L/usr/lib/ -lKF5NetworkManagerQt + +# The following define makes your compiler emit warnings if you use +# any Qt feature that has been marked deprecated (the exact warnings +# depend on your compiler). Please consult the documentation of the +# deprecated API in order to know how to port your code away from it. +DEFINES += QT_DEPRECATED_WARNINGS + +# You can also make your code fail to compile if it uses deprecated APIs. +# In order to do so, uncomment the following line. +# You can also select to disable deprecated APIs only up to a certain version of Qt. +#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 + +# QMAKE_CXXFLAGS += -Wno-unused-parameter +QMAKE_CPPFLAGS *= $(shell dpkg-buildflags --get CPPFLAGS) +QMAKE_CFLAGS *= $(shell dpkg-buildflags --get CFLAGS) +QMAKE_CXXFLAGS *= $(shell dpkg-buildflags --get CXXFLAGS) +QMAKE_LFLAGS *= $(shell dpkg-buildflags --get LDFLAGS) + +#include(kylin-agent/kylin-agent.pri) +INCLUDEPATH += $$PWD +INCLUDEPATH += ./kylin-agent + +HEADERS += \ + ./kylin-agent/agentutils.h \ + ./kylin-agent/kylinagent.h \ +# ./kylin-agent/kylinagentobject.h \ + ./kylin-agent/kylinpassworddialog.h \ + ./kylin-agent/kylinsecretagent.h + +SOURCES += \ + ./kylin-agent/kylinagent.cpp \ +# ./kylin-agent/kylinagentobject.cpp \ + ./kylin-agent/kylinpassworddialog.cpp \ + ./kylin-agent/kylinsecretagent.cpp \ + +TRANSLATIONS += \ + ./translations/kylin-keyring_zh_CN.ts \ + ./translations/kylin-keyring_tr.ts \ + ./translations/kylin-keyring_bo.ts \ + ./translations/kylin-keyring_bo_CN.ts + +unix { + target.path = /usr/lib/ + + manager.path = /usr/include/kylin-nm/kylin-agent + manager.files = kylin-agent/agentutils.h \ + kylin-agent/kylinagent.h \ + kylin-agent/kylinagentobject.h \ + kylin-agent/kylinpassworddialog.h \ + kylin-agent/kylinsecretagent.h + + INSTALLS += manager \ + trans +} +!isEmpty(target.path): INSTALLS += target + + +RESOURCES += \ + svg.qrc diff --git a/libkylin-nm-base/kylin-keyring/main.cpp b/libkylin-nm-base/kylin-keyring/main.cpp new file mode 100644 index 00000000..5752abd1 --- /dev/null +++ b/libkylin-nm-base/kylin-keyring/main.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include +#include +#include +#include "kylinagent.h" +#include + +bool isAppRuning(); + +int main(int argc, char *argv[]) +{ + QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); + QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); + QApplication a(argc, argv); + + KylinAgent* agent = new KylinAgent(); + agent->startKylinAgent(); + + QTranslator trans_global; + qDebug() << "QLocale " << QLocale(); + if (trans_global.load(QLocale(), "kylin-keyring", "_", "/usr/share/kylin-keyring/")) + { + a.installTranslator(&trans_global); + qDebug()<<"Translations load success"; + } else { + qWarning() << "Translations load fail"; + } + + return a.exec(); +} diff --git a/libkylin-nm-base/kylin-keyring/svg.qrc b/libkylin-nm-base/kylin-keyring/svg.qrc new file mode 100644 index 00000000..d8a13d60 --- /dev/null +++ b/libkylin-nm-base/kylin-keyring/svg.qrc @@ -0,0 +1,7 @@ + + + authorize.svg + translations/kylin-keyring_zh_CN.qm + translations/kylin-keyring_bo_CN.qm + + diff --git a/libkylin-nm-base/kylin-keyring/translations/kylin-keyring_bo.ts b/libkylin-nm-base/kylin-keyring/translations/kylin-keyring_bo.ts new file mode 100644 index 00000000..0cbe6545 --- /dev/null +++ b/libkylin-nm-base/kylin-keyring/translations/kylin-keyring_bo.ts @@ -0,0 +1,75 @@ + + + + + KyPasswordDialog + + + Kylin NM + + + + + kylin network desktop message + + + + + Wi-Fi authentication required + + + + + Access wireless networks + + + + + needs password or encryption key + + + + + user name + + + + + Connect + + + + + Cancel + + + + + password error! + + + + + username or password error! + + + + + password + + + + + KylinSecretAgent + + + userAndPwd + + + + + tls + + + + diff --git a/libkylin-nm-base/kylin-keyring/translations/kylin-keyring_bo_CN.qm b/libkylin-nm-base/kylin-keyring/translations/kylin-keyring_bo_CN.qm new file mode 100644 index 00000000..980f2a26 Binary files /dev/null and b/libkylin-nm-base/kylin-keyring/translations/kylin-keyring_bo_CN.qm differ diff --git a/libkylin-nm-base/kylin-keyring/translations/kylin-keyring_bo_CN.ts b/libkylin-nm-base/kylin-keyring/translations/kylin-keyring_bo_CN.ts new file mode 100644 index 00000000..e3f701c2 --- /dev/null +++ b/libkylin-nm-base/kylin-keyring/translations/kylin-keyring_bo_CN.ts @@ -0,0 +1,75 @@ + + + + + KyPasswordDialog + + + Kylin NM + + + + + kylin network desktop message + དྲ་རྒྱའི་གསལ་འདེབས་ཆ་འཕྲིན། + + + + Wi-Fi authentication required + སྐུད་མེད་དྲ་རྒྱ་འདི་ལ་གསང་བའི་བདེན་དཔང་ར་སྤྲོད་བྱེད་དགོས། + + + + Access wireless networks + སྐུད་མེད་དྲ་རྒྱར་བཅར་འདྲི་བྱེད་པ། + + + + needs password or encryption key + གསང་བ་དང་གསང་བའི་ལྡེ་མིག་དགོས། + + + + password + གསང་བའི་ཨང་གྲངས། + + + + user name + སྤྱོད་མཁན་གྱི་མིང་། + + + + Connect + འབྲེལ་མཐུད་བཅས་བྱ་དགོས། + + + + Cancel + མེད་པར་བཟོ་དགོས། + + + + password error! + གསང་བའི་ཨང་གྲངས་ནོར་བ། + + + + username or password error! + སྤྱོད་མཁན་གྱི་མིང་ངམ་གསང་གྲངས་ནོར་འཁྲུལ་རེད། + + + + KylinSecretAgent + + + userAndPwd + སྤྱོད་མཁན་གྱི་མིང་དང་གསང་གྲངས། + + + + tls + + + + diff --git a/libkylin-nm-base/kylin-keyring/translations/kylin-keyring_tr.ts b/libkylin-nm-base/kylin-keyring/translations/kylin-keyring_tr.ts new file mode 100644 index 00000000..8eca6866 --- /dev/null +++ b/libkylin-nm-base/kylin-keyring/translations/kylin-keyring_tr.ts @@ -0,0 +1,75 @@ + + + + + KyPasswordDialog + + + Kylin NM + + + + + kylin network desktop message + + + + + Wi-Fi authentication required + + + + + Access wireless networks + + + + + needs password or encryption key + + + + + user name + + + + + Connect + + + + + Cancel + + + + + password error! + + + + + username or password error! + + + + + password + + + + + KylinSecretAgent + + + userAndPwd + + + + + tls + + + + diff --git a/libkylin-nm-base/kylin-keyring/translations/kylin-keyring_zh_CN.qm b/libkylin-nm-base/kylin-keyring/translations/kylin-keyring_zh_CN.qm new file mode 100644 index 00000000..0132f295 Binary files /dev/null and b/libkylin-nm-base/kylin-keyring/translations/kylin-keyring_zh_CN.qm differ diff --git a/libkylin-nm-base/kylin-keyring/translations/kylin-keyring_zh_CN.ts b/libkylin-nm-base/kylin-keyring/translations/kylin-keyring_zh_CN.ts new file mode 100644 index 00000000..3dbe6c92 --- /dev/null +++ b/libkylin-nm-base/kylin-keyring/translations/kylin-keyring_zh_CN.ts @@ -0,0 +1,83 @@ + + + + + KyPasswordDialog + + + Kylin NM + + + + + kylin network desktop message + 网络提示信息 + + + + Wi-Fi authentication required + 此无线网络需要密码认证 + + + + Access wireless networks + 访问无线网络 + + + + needs password or encryption key + 需要密码或加密秘钥 + + + + user name + 用户名 + + + + Connect + 连接 + + + + Cancel + 取消 + + + + password error! + 密码错误! + + + + username or password error! + 用户名或密码错误! + + + WiFi + 访问无线网络 + + + needs password + 需要密码或加密秘钥 + + + + password + 密码 + + + + KylinSecretAgent + + + userAndPwd + 用户名和密码 + + + + tls + + + + diff --git a/libkylin-nm-base/libkylin-nm-base.pro b/libkylin-nm-base/libkylin-nm-base.pro new file mode 100644 index 00000000..f4632285 --- /dev/null +++ b/libkylin-nm-base/libkylin-nm-base.pro @@ -0,0 +1,8 @@ +TEMPLATE = subdirs + +CONFIG += ordered \ + qt + +SUBDIRS = \ + libnm-kylin \ + kylin-keyring/kylin-keyring.pro diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kyapnetresource.cpp b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kyapnetresource.cpp new file mode 100644 index 00000000..5137fb99 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kyapnetresource.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include "kyapnetresource.h" +#include "kylinnetworkdeviceresource.h" +#include "kywirelessconnectoperation.h" +#include "kylinnetworkmanagerutil.h" + +const QString str2GBand = "2.4Ghz"; +const QString str5GBand = "5Ghz"; + +KyApNetResource::KyApNetResource(QObject *parent) : QObject(parent) +{ + m_networkResourceInstance = KyNetworkResourceManager::getInstance(); + connect(m_networkResourceInstance, &KyNetworkResourceManager::wirelessApConnectStateChange, + this, &KyApNetResource::wirelessApConnectStateChange); +} + +KyApNetResource::~KyApNetResource() +{ + m_networkResourceInstance = nullptr; +} + +KyApConnectItem KyApNetResource::getApConnectItem(NetworkManager::Connection::Ptr connectPtr) +{ + if (nullptr == connectPtr) { + qWarning()<<"[KyConnectResourse]"<<"get bluetooth connection item failed, the connect is empty"; + return KyApConnectItem(); + } + + NetworkManager::ConnectionSettings::Ptr settingPtr = connectPtr->settings(); + NetworkManager::WirelessSetting::Ptr wirelessSetting + = settingPtr->setting(NetworkManager::Setting::Wireless).dynamicCast(); + if (NetworkManager::WirelessSetting::NetworkMode::Ap + != wirelessSetting->mode()) { + qWarning() << "[KyConnectResourse]" <<"get ap item failed, the active connect mode is not ap."; + return KyApConnectItem(); + } + + KyNetworkDeviceResourse deviceResource; + if (!deviceResource.wirelessDeviceIsExist(settingPtr->interfaceName())) { + qWarning() << "[KyConnectResourse]" <<"get ap item failed, the ap device is not exist yet"; + return KyApConnectItem(); + } + + QByteArray rawSsid = wirelessSetting->ssid(); + + KyApConnectItem apConnectItem; + apConnectItem.m_connectName = connectPtr->name(); + apConnectItem.m_connectSsid = getSsidFromByteArray(rawSsid); + apConnectItem.m_connectUuid = connectPtr->uuid(); + if (wirelessSetting->band() == NetworkManager::WirelessSetting::FrequencyBand::A) { + apConnectItem.m_band = str2GBand; + } else if (wirelessSetting->band() == NetworkManager::WirelessSetting::FrequencyBand::Bg) { + apConnectItem.m_band = str5GBand; + } + apConnectItem.m_ifaceName = settingPtr->interfaceName(); + apConnectItem.m_isActivated = KyNetworkResourceManager::getInstance()->isActiveConnection(connectPtr->uuid()); + + //NetworkManager::WirelessSecuritySetting::Ptr wirelessSecuritySetting + // = settingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); + KyWirelessConnectOperation wirelessOperation; + apConnectItem.m_password = wirelessOperation.getPsk(apConnectItem.m_connectUuid);// wirelessSecuritySetting->psk(); + + return apConnectItem; +} + +KyApConnectItem KyApNetResource::getApConnectionByUuid(QString connectUuid) +{ + NetworkManager::Connection::Ptr connectPtr = nullptr; + + connectPtr = KyNetworkResourceManager::getInstance()->findConnectByUuid(connectUuid); + if (nullptr == connectPtr) { + return KyApConnectItem(); + } + + if (NetworkManager::ConnectionSettings::ConnectionType::Wireless + != connectPtr->settings()->connectionType()) { + return KyApConnectItem(); + } + + KyApConnectItem connectItem = getApConnectItem(connectPtr); + + return connectItem; +} + +void KyApNetResource::getApConnections(QList &apConnectItemList) +{ + QList apActiveConnectItemList; + QList apDeactiveConnectItemList; + NetworkManager::Connection::List connectList; + + connectList.clear(); + connectList = KyNetworkResourceManager::getInstance()->getConnectList(); + + if (connectList.empty()) { + qWarning()<<"[KyConnectResourse]"<<"get ap connections failed, the connect list is empty"; + return; + } + + NetworkManager::Connection::Ptr connectPtr = nullptr; + for (int index = 0; index < connectList.size(); index++) { + connectPtr = connectList.at(index); + if (NetworkManager::ConnectionSettings::ConnectionType::Wireless + != connectPtr->settings()->connectionType()) { + continue; + } + + KyApConnectItem connectItem = getApConnectItem(connectPtr); + if (connectItem.m_isActivated) { + apActiveConnectItemList << connectItem; + } else { + apDeactiveConnectItemList << connectItem; + } + } + + apConnectItemList << apActiveConnectItemList << apDeactiveConnectItemList; + + return; +} diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kyapnetresource.h b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kyapnetresource.h new file mode 100644 index 00000000..16b11b29 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kyapnetresource.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYAPNETRESOURCE_H +#define KYAPNETRESOURCE_H + +#include +#include "kylinapconnectitem.h" +#include "kylinnetworkresourcemanager.h" + +class KyApNetResource : public QObject +{ + Q_OBJECT +public: + explicit KyApNetResource(QObject *parent = nullptr); + ~KyApNetResource(); + + void getApConnections(QList &apConnectItemList); +Q_SIGNALS: + void wirelessApConnectStateChange(); +private: + KyApConnectItem getApConnectItem(NetworkManager::Connection::Ptr connectPtr); + KyApConnectItem getApConnectionByUuid(QString connectUuid); + + KyNetworkResourceManager *m_networkResourceInstance = nullptr; +}; + +#endif // KYAPNETRESOURCE_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kyenterpricesettinginfo.cpp b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kyenterpricesettinginfo.cpp new file mode 100644 index 00000000..3fc41aa0 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kyenterpricesettinginfo.cpp @@ -0,0 +1,188 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include "kyenterpricesettinginfo.h" + +void assembleEapMethodTlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTlsInfo &info) +{ + NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett + = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); + + QList list; + list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodTls); + wifi_8021x_sett->setInitialized(true); + wifi_8021x_sett->setEapMethods(list); + wifi_8021x_sett->setIdentity(info.identity); + if (!info.domain.isEmpty()){ + wifi_8021x_sett->setDomainSuffixMatch(info.domain); + } + if (info.bNeedCa) { + QByteArray caCerEndWithNull("file://" + info.caCertPath.toUtf8() + '\0'); + wifi_8021x_sett->setCaCertificate(caCerEndWithNull); + } else { + QByteArray caCerEndWithNull(""); + wifi_8021x_sett->setCaCertificate(caCerEndWithNull); + } + QByteArray cliCertEndWithNull("file://" + info.clientCertPath.toUtf8() + '\0'); + wifi_8021x_sett->setClientCertificate(cliCertEndWithNull); + QByteArray cliPriKeyEndWithNull("file://" + info.clientPrivateKey.toUtf8() + '\0'); + wifi_8021x_sett->setPrivateKey(cliPriKeyEndWithNull); + wifi_8021x_sett->setPrivateKeyPassword(info.clientPrivateKeyPWD); + wifi_8021x_sett->setPrivateKeyPasswordFlags(info.m_privateKeyPWDFlag); + + NetworkManager::WirelessSecuritySetting::Ptr security_sett + = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); + security_sett->setInitialized(true); + security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaEap); + + return; +} + +void assembleEapMethodPeapSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodPeapInfo &info) +{ + NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett + = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); + + QList list; + list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodPeap); + wifi_8021x_sett->setInitialized(true); + wifi_8021x_sett->setEapMethods(list); + wifi_8021x_sett->setPhase2AuthMethod((NetworkManager::Security8021xSetting::AuthMethod)info.phase2AuthMethod); + wifi_8021x_sett->setIdentity(info.userName); + wifi_8021x_sett->setPassword(info.userPWD); + wifi_8021x_sett->setPasswordFlags(info.m_passwdFlag); + + + NetworkManager::WirelessSecuritySetting::Ptr security_sett + = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); + security_sett->setInitialized(true); + security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaEap); + return; +} + +void assembleEapMethodTtlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTtlsInfo &info) +{ + + NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett + = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); + + QList list; + list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodTtls); + wifi_8021x_sett->setInitialized(true); + wifi_8021x_sett->setEapMethods(list); + if (info.authType == KyTtlsAuthMethod::AUTH_EAP) + { + wifi_8021x_sett->setPhase2AuthEapMethod((NetworkManager::Security8021xSetting::AuthEapMethod)info.authEapMethod);//gtc md5 mschapv2 otp tls + } else if (info.authType == KyTtlsAuthMethod::AUTH_NO_EAP) + { + wifi_8021x_sett->setPhase2AuthMethod((NetworkManager::Security8021xSetting::AuthMethod)info.authNoEapMethod);//chap md5 mschapv2 pap gtc mschap otp tls + } + wifi_8021x_sett->setIdentity(info.userName); + wifi_8021x_sett->setPassword(info.userPWD); + wifi_8021x_sett->setPasswordFlags(info.m_passwdFlag); + + NetworkManager::WirelessSecuritySetting::Ptr security_sett + = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); + security_sett->setInitialized(true); + security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaEap); + return; +} + + +void modifyEapMethodTlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTlsInfo &tlsInfo) +{ + NetworkManager::Security8021xSetting::Ptr setting = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); + setting->setInitialized(true); + + QList list; + list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodTls); + setting->setEapMethods(list); + setting->setIdentity(tlsInfo.identity); + if(!tlsInfo.domain.isEmpty()) + { + setting->setDomainSuffixMatch(tlsInfo.domain); + } + if (tlsInfo.bNeedCa) + { + QByteArray caCerEndWithNull("file://" + tlsInfo.caCertPath.toUtf8() + '\0'); + setting->setCaCertificate(caCerEndWithNull); + } else { + QByteArray caCerEndWithNull(""); + setting->setCaCertificate(caCerEndWithNull); + } + + QByteArray cliCertEndWithNull("file://" + tlsInfo.clientCertPath.toUtf8() + '\0'); + setting->setClientCertificate(cliCertEndWithNull); + QByteArray cliPriKeyEndWithNull("file://" + tlsInfo.clientPrivateKey.toUtf8() + '\0'); + setting->setPrivateKey(cliPriKeyEndWithNull); + setting->setPrivateKeyPasswordFlags(tlsInfo.m_privateKeyPWDFlag); + if(tlsInfo.bChanged) + { + setting->setPrivateKeyPassword(tlsInfo.clientPrivateKeyPWD); + } + return; +} + +void modifyEapMethodPeapSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodPeapInfo &peapInfo) +{ + NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett + = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); + wifi_8021x_sett->setInitialized(true); + + QList list; + list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodPeap); + wifi_8021x_sett->setEapMethods(list); + wifi_8021x_sett->setPhase2AuthMethod((NetworkManager::Security8021xSetting::AuthMethod)peapInfo.phase2AuthMethod); + wifi_8021x_sett->setIdentity(peapInfo.userName); + if(peapInfo.bChanged) { + wifi_8021x_sett->setPassword(peapInfo.userPWD); + } + wifi_8021x_sett->setPasswordFlags(peapInfo.m_passwdFlag); + + QByteArray caCerEndWithNull(""); + wifi_8021x_sett->setCaCertificate(caCerEndWithNull); + + return; +} + +void modifyEapMethodTtlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTtlsInfo &ttlsInfo) +{ + NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett + = connSettingPtr->setting(NetworkManager::Setting::Security8021x).dynamicCast(); + + QList list; + list.append(NetworkManager::Security8021xSetting::EapMethod::EapMethodTtls); + wifi_8021x_sett->setInitialized(true); + wifi_8021x_sett->setEapMethods(list); + if (ttlsInfo.authType == KyTtlsAuthMethod::AUTH_EAP) + { + wifi_8021x_sett->setPhase2AuthEapMethod((NetworkManager::Security8021xSetting::AuthEapMethod)ttlsInfo.authEapMethod);//gtc md5 mschapv2 otp tls + } else if (ttlsInfo.authType == KyTtlsAuthMethod::AUTH_NO_EAP) + { + wifi_8021x_sett->setPhase2AuthMethod((NetworkManager::Security8021xSetting::AuthMethod)ttlsInfo.authNoEapMethod);//chap md5 mschapv2 pap gtc mschap otp tls + } + wifi_8021x_sett->setIdentity(ttlsInfo.userName); + if(ttlsInfo.bChanged) + { + wifi_8021x_sett->setPassword(ttlsInfo.userPWD); + } + wifi_8021x_sett->setPasswordFlags(ttlsInfo.m_passwdFlag); + + QByteArray caCerEndWithNull(""); + wifi_8021x_sett->setCaCertificate(caCerEndWithNull); + return; +} diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kyenterpricesettinginfo.h b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kyenterpricesettinginfo.h new file mode 100644 index 00000000..aadef320 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kyenterpricesettinginfo.h @@ -0,0 +1,163 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYENTERPRICESETTINGINFO_H +#define KYENTERPRICESETTINGINFO_H + +#include +#include + +#include "kylinnetworkresourcemanager.h" +#include + +enum KyEapMethodType { + TLS = 0, + PEAP, + TTLS, +}; + +class KyEapMethodTlsInfo +{ +public: + QString identity; + QString domain; + QString devIfaceName; + QString caCertPath; + bool bNeedCa; + QString clientCertPath; + QString clientPrivateKey; + QString clientPrivateKeyPWD; + NetworkManager::Setting::SecretFlags m_privateKeyPWDFlag; + // only valid when update + bool bChanged; + + inline bool operator == (const KyEapMethodTlsInfo& info) const + { + if (this->identity == info.identity + && this->domain == info.domain +// && this->devIfaceName == info.devIfaceName + && this->caCertPath == info.caCertPath + && this->bNeedCa == info.bNeedCa + && this->clientCertPath == info.clientCertPath + && this->clientPrivateKey == info.clientPrivateKey + && this->clientPrivateKeyPWD == info.clientPrivateKeyPWD + && this->m_privateKeyPWDFlag == info.m_privateKeyPWDFlag) { + return true; + } else { + return false; + } + } +}; + +typedef enum { + KyAuthEapMethodUnknown = 0, + KyAuthEapMethodMd5, + KyAuthEapMethodMschapv2, + KyAuthEapMethodOtp, + KyAuthEapMethodGtc, + KyAuthEapMethodTls +} KyEapMethodAuth; + +typedef enum{ + KyAuthMethodUnknown = 0, + KyAuthMethodPap, + KyAuthMethodChap, + KyAuthMethodMschap, + KyAuthMethodMschapv2, + KyAuthMethodGtc, + KyAuthMethodOtp, + KyAuthMethodMd5, + KyAuthMethodTls +} KyNoEapMethodAuth; + + +class KyEapMethodPeapInfo +{ +public: + KyNoEapMethodAuth phase2AuthMethod; + QString userName; + QString userPWD; + NetworkManager::Setting::SecretFlags m_passwdFlag; + // only valid when update + bool bChanged; + + inline bool operator == (const KyEapMethodPeapInfo& info) const + { + if (this->phase2AuthMethod == info.phase2AuthMethod + && this->userName == info.userName + && this->userPWD == info.userPWD + && this->m_passwdFlag == info.m_passwdFlag) { + return true; + } else { + return false; + } + } +}; + +enum KyTtlsAuthMethod +{ + AUTH_EAP, + AUTH_NO_EAP +}; + +class KyEapMethodTtlsInfo +{ +public: + KyTtlsAuthMethod authType; + KyEapMethodAuth authEapMethod; + KyNoEapMethodAuth authNoEapMethod; + QString userName; + QString userPWD; + NetworkManager::Setting::SecretFlags m_passwdFlag; + // only valid when update + bool bChanged; + + inline bool operator == (const KyEapMethodTtlsInfo& info) const + { + if (this->authType == info.authType) { + if (authType == AUTH_EAP) { + if (this->authEapMethod == info.authEapMethod + && this ->userName == info.userName + && this->userPWD == info.userPWD + && this->m_passwdFlag == info.m_passwdFlag) { + return true; + } + } else { + if (authType == AUTH_EAP) { + if (this->authNoEapMethod == info.authNoEapMethod + && this ->userName == info.userName + && this->userPWD == info.userPWD + && this->m_passwdFlag == info.m_passwdFlag) { + return true; + } + } + } + + } + return false; + } +}; + +void assembleEapMethodTlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTlsInfo &tlsInfo); +void assembleEapMethodPeapSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodPeapInfo &peapInfo); +void assembleEapMethodTtlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTtlsInfo &ttlsInfo); + +void modifyEapMethodTlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTlsInfo &tlsInfo); +void modifyEapMethodPeapSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodPeapInfo &peapInfo); +void modifyEapMethodTtlsSettings(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyEapMethodTtlsInfo &ttlsInfo); + +#endif // KYENTERPRICESETTINGINFO_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinactiveconnectresource.cpp b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinactiveconnectresource.cpp new file mode 100644 index 00000000..07ef4bc5 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinactiveconnectresource.cpp @@ -0,0 +1,300 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include "kylinactiveconnectresource.h" +#include "kywirelessconnectoperation.h" +#include "kylinnetworkmanagerutil.h" +#include "kylinnetworkdeviceresource.h" + +#include +#include +#include + +#define LOG_FLAG "[KyActiveConnectResourse]" + +KyActiveConnectResourse::KyActiveConnectResourse(QObject *parent) : QObject(parent) +{ + m_networkResourceInstance = KyNetworkResourceManager::getInstance(); + + connect(m_networkResourceInstance, &KyNetworkResourceManager::wiredConnectStateChange, + this, &KyActiveConnectResourse::wiredStateChange); + connect(m_networkResourceInstance, &KyNetworkResourceManager::wirelessConnectStateChange, + this, &KyActiveConnectResourse::wirelessStateChange); +} + +KyActiveConnectResourse::~KyActiveConnectResourse() +{ + m_networkResourceInstance = nullptr; +} + +KyActivateItem KyActiveConnectResourse::getActiveConnectionItem(NetworkManager::ActiveConnection::Ptr activeConnectPtr) +{ + if (nullptr == activeConnectPtr) { + qWarning() << LOG_FLAG <<"the active connect is empty"; + return KyActivateItem(); + } + + if (NetworkManager::ActiveConnection::State::Activated != activeConnectPtr->state()) { + return KyActivateItem(); + } + + KyActivateItem activeConnectItem; + activeConnectItem.m_uuid = activeConnectPtr->uuid(); + + NetworkManager::Connection::Ptr connectPtr = activeConnectPtr->connection(); + activeConnectItem.m_connName = connectPtr->name(); + activeConnectItem.m_dbusPath = connectPtr->path(); + if (activeConnectPtr->type() == CONNECT_TYPE_WIRELESS) { + NetworkManager::WirelessSetting::Ptr wireless_sett = + connectPtr->settings()->setting(NetworkManager::Setting::Wireless).dynamicCast(); + QByteArray rawSsid = wireless_sett->ssid(); + activeConnectItem.m_ssid = getSsidFromByteArray(rawSsid); + } + + activeConnectItem.m_connStatus = CONNECT_STATE_ACTIVATED; + + return activeConnectItem; +} + +void KyActiveConnectResourse::getActiveConnectionList(QString deviceName, + KyConnectionType connectionType, + QList &activeConnectItemList) +{ + NetworkManager::ActiveConnection::List activeConnectList = m_networkResourceInstance->getActiveConnectList(); + + if (activeConnectList.isEmpty()) { + qWarning() << LOG_FLAG <<"the active connect list is empty"; + return; + } + NetworkManager::ActiveConnection::Ptr activeConnectPtr = nullptr; + for (int index = 0; index < activeConnectList.size(); index++) { + activeConnectPtr = nullptr; + activeConnectPtr = activeConnectList.at(index); + if (activeConnectPtr.isNull()) { + continue; + } + + if (connectionType != activeConnectPtr->type()) { + continue; + } + + QStringList interfaces = activeConnectPtr->devices(); + for (int index = 0; index < interfaces.size(); ++index) { + QString ifaceUni = interfaces.at(index); + NetworkManager::Device:: Ptr devicePtr = + m_networkResourceInstance->findDeviceByUni(ifaceUni); + if (devicePtr->interfaceName() == deviceName) { + KyActivateItem activeConnectItem = + getActiveConnectionItem(activeConnectPtr); + activeConnectItem.m_interface = deviceName; + activeConnectItemList << activeConnectItem; + break; + } + } + } +} + +//动态ip地址 +void KyActiveConnectResourse::getActiveConnectIpInfo( + const QString &connectUuid, + QString &ipv4Address, + QString &ipv6Address) +{ + ipv4Address.clear(); + ipv6Address.clear(); + NetworkManager::ActiveConnection::Ptr activeConnectPtr = + m_networkResourceInstance->findActiveConnectByUuid(connectUuid); + + if (activeConnectPtr.isNull()) { + qWarning() << LOG_FLAG <<"it can not find connect "<< connectUuid; + return; + } + + getActiveConnectIp(activeConnectPtr, ipv4Address, ipv6Address); +} + +void KyActiveConnectResourse::getActiveConnectIp( + NetworkManager::ActiveConnection::Ptr activeConnectPtr, + QString &ipv4Address, + QString &ipv6Address) +{ + NetworkManager::IpConfig ipv4Config =activeConnectPtr->ipV4Config(); + if (ipv4Config.isValid()) { + if (!ipv4Config.addresses().isEmpty()) { + NetworkManager::IpAddress address = ipv4Config.addresses().at(0); + ipv4Address = address.ip().toString(); + } else { + qWarning()<<"[KyActiveConnectResourse]"<<"the ipv4 address is empty."; + } + } else { + qWarning()<<"[KyActiveConnectResourse]"<<"ipv4 config is not valid"; + } + + NetworkManager::IpConfig ipv6Config =activeConnectPtr->ipV6Config(); + if (ipv6Config.isValid()) { + if (!ipv6Config.addresses().isEmpty()) { + NetworkManager::IpAddress address = ipv6Config.addresses().at(0); + ipv6Address = address.ip().toString(); + } else { + qWarning()<<"[KyActiveConnectResourse]"<<"ipv6 address is empty"; + } + } else { + qWarning()<<"[KyActiveConnectResourse]"<<"ipv6 config is not valid"; + } +} + +void KyActiveConnectResourse::getActiveConnectDnsInfo( + const QString &connectUuid, + QList &ipv4Dns, + QList &ipv6Dns) +{ + NetworkManager::ActiveConnection::Ptr activeConnectPtr = + m_networkResourceInstance->findActiveConnectByUuid(connectUuid); + if (activeConnectPtr.isNull()) { + qWarning()<< "[KyActiveConnectResourse]" <<"it can not find connect "<< connectUuid; + return; + } + + getActiveConnectDns(activeConnectPtr, ipv4Dns, ipv6Dns); +} + +void KyActiveConnectResourse::getActiveConnectDns( + NetworkManager::ActiveConnection::Ptr activeConnectPtr, + QList &ipv4Dns, + QList &ipv6Dns) +{ + NetworkManager::IpConfig ipv4Config = activeConnectPtr->ipV4Config(); + if (ipv4Config.isValid()) { + ipv4Dns = ipv4Config.nameservers(); + } else { + qWarning()<<"[KyActiveConnectResourse]"<<"ipv4 config is not valid"; + } + + NetworkManager::IpConfig ipv6Config =activeConnectPtr->ipV6Config(); + if (ipv6Config.isValid()) { + ipv6Dns = ipv6Config.nameservers(); + } else { + qWarning()<<"[KyActiveConnectResourse]"<<"ipv6 config is not valid"; + } + + return; +} + +bool KyActiveConnectResourse::wiredConnectIsActived() +{ + int index = 0; + NetworkManager::ActiveConnection::List activeConnectList; + + activeConnectList.clear(); + activeConnectList = m_networkResourceInstance->getActiveConnectList(); + + if (activeConnectList.empty()) { + qWarning()<<"[KyActiveConnectResourse]" + <<"get active connect failed, the active connect list is empty"; + return false; + } + + NetworkManager::ActiveConnection::Ptr activeConnectPtr = nullptr; + for (index = 0; index < activeConnectList.size(); index++) { + activeConnectPtr = activeConnectList.at(index); + if (activeConnectPtr.isNull()) { + continue; + } + + if (NetworkManager::ConnectionSettings::ConnectionType::Wired + != activeConnectPtr->type()) { + continue; + } + + QString path = activeConnectPtr->connection()->path(); + if (!m_networkResourceInstance->isWiredConnect(path)) { + continue; + } + + if (activeConnectPtr->state() == NetworkManager::ActiveConnection::State::Activated) { + return true; + } + } + + return false; +} + +bool KyActiveConnectResourse::wirelessConnectIsActived() +{ + int index = 0; + NetworkManager::ActiveConnection::List activeConnectList; + + activeConnectList.clear(); + activeConnectList = m_networkResourceInstance->getActiveConnectList(); + + if (activeConnectList.empty()) { + qWarning()<<"[KyActiveConnectResourse]" + <<"get active connect failed, the active connect list is empty"; + return false; + } + + NetworkManager::ActiveConnection::Ptr activeConnectPtr = nullptr; + for (index = 0; index < activeConnectList.size(); index++) { + activeConnectPtr = activeConnectList.at(index); + if (activeConnectPtr.isNull()) { + continue; + } + + if (NetworkManager::ConnectionSettings::ConnectionType::Wireless + != activeConnectPtr->type()) { + continue; + } + + if (activeConnectPtr->state() == NetworkManager::ActiveConnection::State::Activated) { + return true; + } + } + + return false; +} + +int KyActiveConnectResourse::getAcivateWifiSignal() +{ + int signalStrength = 0; + KyNetworkDeviceResourse devResource; + QStringList devList; + devResource.getNetworkDeviceList(DEVICE_TYPE_WIFI, devList); + + for (int i = 0; i < devList.size(); ++i) { + + NetworkManager::Device::Ptr connectDevice = + m_networkResourceInstance->findDeviceByName(devList.at(i)); + + if (nullptr == connectDevice || !connectDevice->isValid()) { + qWarning()<< LOG_FLAG <<"getDeviceActiveAPInfo failed, the device" << devList.at(i) << "is not existed"; + continue; + } + + if (connectDevice->type() == NetworkManager::Device::Wifi) { + NetworkManager::WirelessDevice *wirelessDevicePtr = + qobject_cast(connectDevice.data()); + NetworkManager::AccessPoint::Ptr apPtr = wirelessDevicePtr->activeAccessPoint(); + if (apPtr.isNull()) { + continue; + } + signalStrength = apPtr->signalStrength(); + break; + } + } + + return signalStrength; +} diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinactiveconnectresource.h b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinactiveconnectresource.h new file mode 100644 index 00000000..edd89c82 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinactiveconnectresource.h @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYLINACTIVECONNECTRESOURCE_H +#define KYLINACTIVECONNECTRESOURCE_H + +#include +#include "kylinnetworkresourcemanager.h" +#include "kylinconnectitem.h" +#include "kylinnetworkdeviceresource.h" +#include "kylinapconnectitem.h" +#include "kylinnetworkresourcetype.h" + +class KyActivateItem +{ +public: + QString m_interface; + QString m_uuid; + QString m_ssid; + QString m_connName; + QString m_dbusPath; + KyConnectState m_connStatus; +}; + +class KyActiveConnectResourse : public QObject +{ + Q_OBJECT + +public: + explicit KyActiveConnectResourse(QObject *parent = nullptr); + ~KyActiveConnectResourse(); + +public: + void getActiveConnectionList(QString deviceName, + KyConnectionType connectionType, QList &connectItemList); + + void getActiveConnectIpInfo(const QString &uuid, + QString &ipv4Address, QString &ipv6Address); + void getActiveConnectDnsInfo(const QString &uuid, + QList &ipv4Dns, QList &ipv6Dns); + + bool wiredConnectIsActived(); + bool wirelessConnectIsActived(); + + int getAcivateWifiSignal(); + +private: + void getActiveConnectIp(NetworkManager::ActiveConnection::Ptr activeConnectPtr, + QString &ipv4Address, QString &ipv6Address); + void getActiveConnectDns(NetworkManager::ActiveConnection::Ptr activeConnectPtr, + QList &ipv4Dns, QList &ipv6Dns); + + KyActivateItem getActiveConnectionItem(NetworkManager::ActiveConnection::Ptr activeConnectPtr); + +Q_SIGNALS: + void wiredStateChange(QString deviceName, QString uuid, KyConnectState state); + void wirelessStateChange(QString deviceName, QString ssid, QString uuid, KyConnectState state); + +private: + KyNetworkResourceManager *m_networkResourceInstance = nullptr; +}; +#endif // KYLINACTIVECONNECTRESOURCE_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinapconnectitem.cpp b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinapconnectitem.cpp new file mode 100644 index 00000000..c70fac49 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinapconnectitem.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include "kylinapconnectitem.h" + +KyApConnectItem::KyApConnectItem(QObject *parent) : QObject(parent) +{ + m_connectName = ""; + m_connectUuid = ""; + m_connectSsid = ""; + m_ifaceName = ""; + m_password = ""; + m_band = ""; + m_isActivated = false; +} diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinapconnectitem.h b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinapconnectitem.h new file mode 100644 index 00000000..4ce691f1 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinapconnectitem.h @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYLINAPCONNECTITEM_H +#define KYLINAPCONNECTITEM_H + +#include + +class KyApConnectItem +{ +public: + QString m_connectName = ""; + QString m_connectSsid = ""; + QString m_connectUuid = ""; + QString m_ifaceName = ""; + QString m_password = ""; + QString m_band = ""; + bool m_isActivated = false; + +}; + +#endif // KYLINAPCONNECTITEM_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinconnectitem.cpp b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinconnectitem.cpp new file mode 100644 index 00000000..366cd4ad --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinconnectitem.cpp @@ -0,0 +1,17 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinconnectitem.h b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinconnectitem.h new file mode 100644 index 00000000..bfe56a49 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinconnectitem.h @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYLINCONNECTITEM_H +#define KYLINCONNECTITEM_H + +#include + +class KyWiredItem +{ +public: + QString m_connectName; + QString m_connectUuid; + QString m_connectPath; + +}; + +#endif // KYLINWIREDCONNECTITEM_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinconnectoperation.cpp b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinconnectoperation.cpp new file mode 100644 index 00000000..6d046b24 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinconnectoperation.cpp @@ -0,0 +1,289 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "kylinconnectoperation.h" +#include "kylinnetworkdeviceresource.h" + +#include +#include +#include +#include +#include + +KyConnectOperation::KyConnectOperation(QObject *parent) : QObject(parent) +{ + m_networkResourceInstance = KyNetworkResourceManager::getInstance(); +} + +KyConnectOperation::~KyConnectOperation() +{ + m_networkResourceInstance = nullptr; +} + +void KyConnectOperation::ipv4SettingSet( + NetworkManager::Ipv4Setting::Ptr &ipv4Setting, + const KyConnectSetting &connectSettingsInfo) +{ + ipv4Setting->setInitialized(true); + ipv4Setting->setDns(connectSettingsInfo.m_ipv4Dns); + + if (CONFIG_IP_DHCP == connectSettingsInfo.m_ipv4ConfigIpType) { + ipv4Setting->setMethod(NetworkManager::Ipv4Setting::Automatic); + return; + } else { + ipv4Setting->setMethod(NetworkManager::Ipv4Setting::Manual); + } + ipv4Setting->setAddresses(connectSettingsInfo.m_ipv4Address); + + return; +} +void KyConnectOperation::ipv6SettingSet( + NetworkManager::Ipv6Setting::Ptr &ipv6Setting, + const KyConnectSetting &connectSettingsInfo) +{ + ipv6Setting->setInitialized(true); + ipv6Setting->setDns(connectSettingsInfo.m_ipv6Dns); + + if (CONFIG_IP_DHCP == connectSettingsInfo.m_ipv6ConfigIpType) { + ipv6Setting->setMethod(NetworkManager::Ipv6Setting::Automatic); + ipv6Setting->setPrivacy(NetworkManager::Ipv6Setting::Disabled); + return; + } + + ipv6Setting->setMethod(NetworkManager::Ipv6Setting::Manual); + ipv6Setting->setAddresses(connectSettingsInfo.m_ipv6Address); + + return ; +} + +void KyConnectOperation::connectSettingSet( + NetworkManager::ConnectionSettings::Ptr connectionSettings, + const KyConnectSetting &connectSettingsInfo) +{ + connectionSettings->setId(connectSettingsInfo.m_connectName); + connectionSettings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); + connectionSettings->setAutoconnect(true); + connectionSettings->setAutoconnectPriority(0); + if (!connectSettingsInfo.m_ifaceName.isEmpty()) { + connectionSettings->setInterfaceName(connectSettingsInfo.m_ifaceName); + } + return; +} + +void KyConnectOperation::setAutoConnect(NetworkManager::ConnectionSettings::Ptr &connectSetting, + bool bAutoConnect) +{ + if (connectSetting.isNull()) { + return; + } + + connectSetting->setAutoconnect(bAutoConnect); + + return; +} + +//ipv4 ipv6更新 +void KyConnectOperation::updateConnect(QString connectUuid, const KyConnectSetting &connectSettingsInfo) +{ + NetworkManager::Connection::Ptr connectPtr = + NetworkManager::findConnectionByUuid(connectUuid); + if (nullptr == connectPtr) { + QString errorMessage = tr("it can not find connection") + connectUuid; + qWarning() << errorMessage; + Q_EMIT updateConnectionError(errorMessage); + return; + } + + NetworkManager::ConnectionSettings::Ptr connectSettingPtr = connectPtr->settings(); + + NetworkManager::Ipv4Setting::Ptr ipv4Setting = connectSettingPtr->setting(NetworkManager::Setting::Ipv4).dynamicCast(); + ipv4SettingSet(ipv4Setting, connectSettingsInfo); + + NetworkManager::Ipv6Setting::Ptr ipv6Setting = connectSettingPtr->setting(NetworkManager::Setting::Ipv6).dynamicCast(); + ipv6SettingSet(ipv6Setting, connectSettingsInfo); + + + NMVariantMapMap connectMapMap = connectSettingPtr->toMap(); + + if (connectMapMap.contains("ipv4")) { + QVariantMap ipv4SettingMap = connectMapMap.value(QLatin1String("ipv4")); + if (ipv4SettingMap.contains("method") && ipv4SettingMap["method"] == "auto") { + if (ipv4SettingMap.contains("address-data")) { + ipv4SettingMap.remove("address-data"); + } + if (ipv4SettingMap.contains("addresses")) { + ipv4SettingMap.remove("addresses"); + } + if (ipv4SettingMap.contains("gateway")) { + ipv4SettingMap.remove("gateway"); + } + } + connectMapMap["ipv4"] = ipv4SettingMap; + } + + if (connectMapMap.contains("ipv6")) { + QVariantMap ipv4SettingMap = connectMapMap.value(QLatin1String("ipv6")); + if (ipv4SettingMap.contains("method") && ipv4SettingMap["method"] == "auto") { + if (ipv4SettingMap.contains("address-data")) { + ipv4SettingMap.remove("address-data"); + } + if (ipv4SettingMap.contains("addresses")) { + ipv4SettingMap.remove("addresses"); + } + if (ipv4SettingMap.contains("gateway")) { + ipv4SettingMap.remove("gateway"); + } + } + + connectMapMap["ipv6"] = ipv4SettingMap; + } + + connectPtr->update(connectMapMap); +} + +void KyConnectOperation::deleteConnect(const QString &connectUuid) +{ + qDebug()<<"delete connect uuid " << connectUuid; + + NetworkManager::Connection::Ptr connectPtr = + NetworkManager::findConnectionByUuid(connectUuid); + if (nullptr == connectPtr) { + QString errorMessage = tr("it can not find connection") + connectUuid; + qWarning()<remove(); + + return ; +} + +void KyConnectOperation::activateConnection(const QString connectUuid, const QString deviceName) +{ + QString connectPath = ""; + QString deviceIdentifier = ""; + QString connectName = ""; + QString specificObject = ""; + NetworkManager::Connection::Ptr connectPtr = nullptr; + + qDebug()<<"it will activate connect"<settings()->connectionType()) { + QString errorMessage = tr("the connect type is") + + connectPtr->settings()->connectionType() + + tr(", but it is not wired"); + qWarning()<path(); + connectName = connectPtr->name(); +// deviceName = connectPtr->settings()->interfaceName(); + +// for (auto const & dev : m_networkResourceInstance->m_devices) { +// for (auto const & dev_conn : dev->availableConnections()) { +// if (dev_conn == connectPtr) { +// deviceIdentifier = dev->uni(); +// deviceName = dev->interfaceName(); +// break; +// } +// } +// } + + auto dev = m_networkResourceInstance->findDeviceByName(deviceName); + if (!dev.isNull()) { + deviceIdentifier = dev->uni(); + } + + + if (deviceIdentifier.isEmpty()) { + QString errorMessage = tr("device Identifier is empty, its name") + deviceName; + qWarning() << errorMessage; + Q_EMIT activateConnectionError(errorMessage); + return; + } + + if (NetworkManager::ConnectionSettings::Wired == connectPtr->settings()->connectionType()) { + KyNetworkDeviceResourse deviceResource; + if (!deviceResource.wiredDeviceIsCarriered(deviceName)) { + qWarning() << deviceName << "is not carried, so can not activate connection"; + return; + } + } + + qDebug() <<"active wired connect: path "<< connectPath + << "device identify " << deviceIdentifier + << "connect name " << connectName + << "device name" << deviceName + << "specific parameter"<< specificObject; + + QDBusPendingCallWatcher * watcher; + watcher = new QDBusPendingCallWatcher{NetworkManager::activateConnection(connectPath, deviceIdentifier, specificObject), this}; + connect(watcher, &QDBusPendingCallWatcher::finished, [this, connectName, deviceName] (QDBusPendingCallWatcher * watcher) { + if (watcher->isError() || !watcher->isValid()) { + QString errorMessage = tr("activate connection failed: ") + watcher->error().message(); + qWarning()<activateConnectionError(errorMessage); + } else { + qWarning()<<"active wired connect complete."; + } + + watcher->deleteLater(); + }); +} + +void KyConnectOperation::deactivateConnection(const QString &activeConnectUuid) +{ + NetworkManager::ActiveConnection::Ptr activateConnectPtr = nullptr; + + + activateConnectPtr = m_networkResourceInstance->findActiveConnectByUuid(activeConnectUuid); + if (nullptr == activateConnectPtr) { + QString errorMessage = tr("it can not find the activate connect") + + tr("uuid") + activeConnectUuid; + qWarning()<path(); + QDBusPendingReply<> reply = NetworkManager::deactivateConnection(activateConnectPtr->path()); + QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this); + connect(watcher, &QDBusPendingCallWatcher::finished, [this, activateConnectPtr] (QDBusPendingCallWatcher * watcher) { + if (watcher->isError() || !watcher->isValid()) { + QString errorMessage = tr("deactivation of connection") + + activateConnectPtr->connection()->name() + tr("failed:") + + watcher->error().message(); + + qWarning()<deactivateConnectionError(errorMessage); + } else { + qWarning() << "deactive connect operation finished" << activateConnectPtr->connection()->name(); + } + watcher->deleteLater(); + }); +} diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinconnectoperation.h b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinconnectoperation.h new file mode 100644 index 00000000..a11f6eaf --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinconnectoperation.h @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYLINCONNECTOPERATION_H +#define KYLINCONNECTOPERATION_H + +#include "kylinnetworkresourcemanager.h" +#include "kylinconnectsetting.h" + +class KyConnectOperation : public QObject +{ + Q_OBJECT +public: + explicit KyConnectOperation(QObject *parent = nullptr); + ~KyConnectOperation(); + + void updateConnect(QString connectUuid, const KyConnectSetting &connectSettingsInfo); + void deleteConnect(const QString &connectUuid); + void activateConnection(const QString connectUuid, const QString deviceName); + void deactivateConnection(const QString &activeConnectUuid); + +protected: + void connectSettingSet(NetworkManager::ConnectionSettings::Ptr connectionSettings, + const KyConnectSetting &connectSettingsInfo); + void ipv4SettingSet(NetworkManager::Ipv4Setting::Ptr &ipv4Setting, + const KyConnectSetting &connectSettingsInfo); + void ipv6SettingSet(NetworkManager::Ipv6Setting::Ptr &ipv6Setting, + const KyConnectSetting &connectSettingsInfo); + void setAutoConnect(NetworkManager::ConnectionSettings::Ptr &connectSetting, bool bAutoConnect); + inline void errorProcess(QString errorMessage); + +Q_SIGNALS: + void createConnectionError(QString errorMessage); + void updateConnectionError(QString errorMessage); + void deleteConnectionError(QString errorMessage); + void activateConnectionError(QString errorMessage); + void deactivateConnectionError(QString errorMessage); + +protected: + KyNetworkResourceManager *m_networkResourceInstance = nullptr; +}; + +#endif // KYLINCONNECTOPERATION_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinconnectsetting.cpp b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinconnectsetting.cpp new file mode 100644 index 00000000..8dcc1d09 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinconnectsetting.cpp @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include "kylinconnectsetting.h" +#include + +KyConnectSetting::KyConnectSetting(/*QObject *parent) : QObject(parent*/) +{ + m_connectName = ""; + m_ifaceName = ""; + + m_ipv4ConfigIpType = CONFIG_IP_DHCP; + m_ipv4Address.clear(); + m_ipv4Dns.clear(); + + m_ipv6ConfigIpType = CONFIG_IP_DHCP; + m_ipv6Address.clear(); + m_ipv6Dns.clear(); + + m_isAutoConnect = true; +} + +KyConnectSetting::~KyConnectSetting() +{ + +} + +void KyConnectSetting::setIfaceName(QString &ifaceName) +{ + m_ifaceName = ifaceName; +} + +void KyConnectSetting::setConnectName(QString &connectName) +{ + m_connectName = connectName; +} + +int KyConnectSetting::setIpConfigType(KyIpAddressType ipType, KyIpConfigType ipConfigType) +{ + if (ipType != IPADDRESS_V4 && ipType != IPADDRESS_V6) { + qWarning()<<"set config ip type failed, the ip address type undefined"<. + * + */ + +#ifndef KYLINCONNECTSETTING_H +#define KYLINCONNECTSETTING_H + +#include +#include +//#include + +#include +#include +#include +#include +#include + +typedef enum { + CONFIG_IP_MANUAL, + CONFIG_IP_DHCP, +}KyIpConfigType; + +typedef enum { + IPADDRESS_V4, + IPADDRESS_V6, +}KyIpAddressType; + +class KyConnectSetting/* : public QObject*/ +{ +// Q_OBJECT +public: +/* explicit*/ KyConnectSetting(/*QObject *parent = nullptr*/); + ~KyConnectSetting(); + +public: + void setIfaceName(QString &ifaceName); + void setConnectName(QString &connectName); + int setIpConfigType(KyIpAddressType ipType, KyIpConfigType configType); + void ipv4AddressConstruct(QString &ipv4Address, QString &ipv4NetMask, QString &ipv4GateWay, QStringList &ipv4Dns); + void ipv6AddressConstruct(QString &ipv6Address, QString &ipv6NetMask, QString &ipv6GateWay, QStringList &ipv6Dns); + void dumpInfo(); + +public: + QString m_connectName; + QString m_ifaceName; + + KyIpConfigType m_ipv4ConfigIpType; + QList m_ipv4Address; + QList m_ipv4Dns; + + KyIpConfigType m_ipv6ConfigIpType; + QList m_ipv6Address; + QList m_ipv6Dns; + + bool m_isAutoConnect = true; +}; + +#endif // KYLINCONNECTSETTING_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylingeneral.cpp b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylingeneral.cpp new file mode 100644 index 00000000..bef96203 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylingeneral.cpp @@ -0,0 +1,119 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include "kylingeneral.h" +#include "kylinnetworkdeviceresource.h" +#include "kylinactiveconnectresource.h" +#include "kylinnetworkmanagerutil.h" + +KylinGeneralOpration::KylinGeneralOpration(QObject *parent) : QObject(parent) +{ + m_networkResourceInstance = KyNetworkResourceManager::getInstance(); + + connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiEnabledChanged, + this, &KylinGeneralOpration::wifiEnabledChanged); + connect(m_networkResourceInstance, &KyNetworkResourceManager::networkingEnabledChanged, + this, &KylinGeneralOpration::networkingEnabledChanged); + connect(m_networkResourceInstance, &KyNetworkResourceManager::primaryConnectionTypeChanged, + this, &KylinGeneralOpration::updateConnectStatus); + connect(m_networkResourceInstance, &KyNetworkResourceManager::connectivityChanged, + this, &KylinGeneralOpration::updateConnectStatus); + connect(m_networkResourceInstance, &KyNetworkResourceManager::wiredEnabledChanged, + this, &KylinGeneralOpration::wiredEnabledChanged); +} + +KylinGeneralOpration::~KylinGeneralOpration() +{ + m_networkResourceInstance = nullptr; +} + +void KylinGeneralOpration::getConnectStatus(KyConnectStatus &status) +{ + updateConnectStatus(); + status = m_status; +} + +void KylinGeneralOpration::updateConnectStatus() +{ + KyConnectStatus status; + + KyConnectionType connectType; + KyActiveConnectResourse activeResource; + getPrimaryConnectionType(connectType); + if (activeResource.wiredConnectIsActived()) { + status = LAN_CONNECTED; + } else if (activeResource.wirelessConnectIsActived()) { + status = WLAN_CONNECTED; + } else { + status = NOT_CONNECTED; + } + + KyConnectivity connecttivity; + getConnectivity(connecttivity); + if (connecttivity != CONNECTIVITY_FULL) { + if (status == LAN_CONNECTED) { + status = LAN_CONNECTED_LIMITED; + } else if (status == WLAN_CONNECTED) { + status = WLAN_CONNECTED_LIMITED; + } + } + + if (status != m_status) { + m_status = status; + Q_EMIT connectStatusChanged(m_status); + } +} + +void KylinGeneralOpration::getConnectivity(KyConnectivity &connectivity) +{ + connectivity = (KyConnectivity)NetworkManager::connectivity(); +} + +void KylinGeneralOpration::getPrimaryConnectionType(KyConnectionType &connectType) +{ + connectType = (KyConnectionType)NetworkManager::primaryConnectionType(); +} + +bool KylinGeneralOpration::getWirelessEnabled() +{ + return NetworkManager::isWirelessEnabled(); +} + +void KylinGeneralOpration::setWirelessNetworkEnabled(bool enabled) +{ + NetworkManager::setWirelessEnabled(enabled); +} + +bool KylinGeneralOpration::getNetworkingEnabled() +{ + return NetworkManager::isNetworkingEnabled(); +} + +void KylinGeneralOpration::setNetworkingEnabled(bool enabled) +{ + NetworkManager::setNetworkingEnabled(enabled); +} + +void KylinGeneralOpration::setWiredEnabled(bool enabled) +{ + setWiredEnabledByGDbus(enabled); +} + +bool KylinGeneralOpration::getWiredEnabled() +{ + return getWiredEnabledByGDbus(); +} diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylingeneral.h b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylingeneral.h new file mode 100644 index 00000000..19e02ffb --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylingeneral.h @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYLINGENERAL_H +#define KYLINGENERAL_H + +#include +#include "kylinnetworkresourcemanager.h" + +enum KyConnectStatus { + NOT_CONNECTED = 0, + LAN_CONNECTED, + WLAN_CONNECTED, + LAN_CONNECTED_LIMITED, + WLAN_CONNECTED_LIMITED, +}; + +class KylinGeneralOpration : public QObject +{ + Q_OBJECT +public: + explicit KylinGeneralOpration(QObject *parent = nullptr); + ~KylinGeneralOpration(); + void getConnectStatus(KyConnectStatus &status); + bool getWirelessEnabled(); + void setWirelessNetworkEnabled(bool enabled); + bool getNetworkingEnabled(); + void setNetworkingEnabled(bool enabled); + void setWiredEnabled(bool enabled); + bool getWiredEnabled(); + +Q_SIGNALS: + void connectStatusChanged(KyConnectStatus); + void wifiEnabledChanged(bool); + void wiredEnabledChanged(bool); + void networkingEnabledChanged(bool); + +private Q_SLOTS: + void updateConnectStatus(); + +private: + KyNetworkResourceManager *m_networkResourceInstance = nullptr; + KyConnectStatus m_status = NOT_CONNECTED; + + void updateGsetting(bool); + void getConnectivity(KyConnectivity &connectivity); + void getPrimaryConnectionType(KyConnectionType &connectType); +}; + +#endif // KYLINGENERAL_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetresource.cpp b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetresource.cpp new file mode 100644 index 00000000..6590e366 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetresource.cpp @@ -0,0 +1,160 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include "kylinnetresource.h" +#include "kylinnetworkdeviceresource.h" +#include "kylinactiveconnectresource.h" +#include "kywirelessnetresource.h" +#include "kylinnetworkmanagerutil.h" + +KyNetResource::KyNetResource(QObject *parent) : QObject(parent) +{ + m_networkResourceInstance = KyNetworkResourceManager::getInstance(); +} + +KyNetResource::~KyNetResource() { + m_networkResourceInstance = nullptr; +} + +void KyNetResource::getIpv4ConnectSetting( + NetworkManager::Ipv4Setting::Ptr &ipv4Setting, + KyConnectSetting &connectSetting) +{ + if (NetworkManager::Ipv4Setting::Automatic == ipv4Setting->method()) { + connectSetting.m_ipv4ConfigIpType = CONFIG_IP_DHCP; + return; + } + + connectSetting.m_ipv4ConfigIpType = CONFIG_IP_MANUAL; + + connectSetting.m_ipv4Address = ipv4Setting->addresses(); + connectSetting.m_ipv4Dns = ipv4Setting->dns(); +} + +void KyNetResource::getIpv6ConnectSetting( + NetworkManager::Ipv6Setting::Ptr &ipv6Setting, + KyConnectSetting &connectSetting) +{ + + if (NetworkManager::Ipv6Setting::Automatic == ipv6Setting->method()) { + connectSetting.m_ipv6ConfigIpType = CONFIG_IP_DHCP; + return; + } + + connectSetting.m_ipv6ConfigIpType = CONFIG_IP_MANUAL; + connectSetting.m_ipv6Address = ipv6Setting->addresses(); + connectSetting.m_ipv6Dns = ipv6Setting->dns(); +} + +void KyNetResource::getConnectionSetting(QString connectUuid, KyConnectSetting &connectSetting) +{ + NetworkManager::Connection::Ptr connectPtr = + m_networkResourceInstance->findConnectByUuid(connectUuid); + + if (nullptr == connectPtr + || !connectPtr->isValid()) { + qWarning() <<"[KyConnectResourse]" << "it can not find valid connection" << connectUuid; + return; + } + + connectSetting.m_connectName = connectPtr->name(); + + NetworkManager::ConnectionSettings::Ptr connectionSettings = connectPtr->settings(); + connectSetting.m_ifaceName = connectionSettings->interfaceName(); + connectSetting.m_isAutoConnect = connectionSettings->autoconnect(); + + NetworkManager::Ipv4Setting::Ptr ipv4Setting = connectionSettings->setting(NetworkManager::Setting::Ipv4).dynamicCast(); + getIpv4ConnectSetting(ipv4Setting, connectSetting); + + NetworkManager::Ipv6Setting::Ptr ipv6Setting = connectionSettings->setting(NetworkManager::Setting::Ipv6).dynamicCast(); + getIpv6ConnectSetting(ipv6Setting, connectSetting); +} + +void KyNetResource::getBaseInfo(QString devName,QString ssid, bool isWlan, bool isActive, KyDetailInfo &conInfo) +{ + //有线无线公有 + KyNetworkDeviceResourse devResource; + + QString hardAddress; + int bandWith; + devResource.getHardwareInfo(devName, hardAddress, bandWith); + + if (!hardAddress.isEmpty()) { + conInfo.strBandWidth = QString("%1").arg(bandWith/1000) + "Mbps"; + conInfo.strMac = hardAddress; + } + + if (isWlan) { + if (!isActive) { + NetworkManager::Device::Ptr devPtr = + KyNetworkResourceManager::getInstance()->findDeviceByName(devName); + if (devPtr.isNull()) { + return; + } + + NetworkManager::WirelessNetwork::Ptr netPtr = + KyNetworkResourceManager::getInstance()->findWifiNetwork(ssid, devPtr->uni()); + if (netPtr.isNull()) { + return; + } + + NetworkManager::AccessPoint::Ptr bestApPtr = netPtr->referenceAccessPoint(); + conInfo.strHz = QString::number(bestApPtr->frequency()) + "MHz"; + conInfo.strChan = QString::number(NetworkManager::findChannel(bestApPtr->frequency())); + NetworkManager::AccessPoint::Capabilities cap = bestApPtr->capabilities(); + NetworkManager::AccessPoint::WpaFlags wpaFlag = bestApPtr->wpaFlags(); + NetworkManager::AccessPoint::WpaFlags rsnFlag = bestApPtr->rsnFlags(); + conInfo.strSecType = enumToQstring(cap, wpaFlag, rsnFlag); + } else { + uint iHz,iChan; + QString strMac; + devResource.getDeviceActiveAPInfo(devName, strMac, iHz, iChan, conInfo.strSecType); + + conInfo.strHz = QString::number(iHz); + conInfo.strChan = QString::number(iChan); + } + + if (conInfo.strSecType.isEmpty()) { + conInfo.strSecType = tr("None"); + } + } +} + +//详情ipv4 ipv6 ipv4Dns +void KyNetResource::getDynamicIpInfo(QString uuid, KyDetailInfo &conInfo) +{ + //已激活的网络 详情页显示动态ipv4 ipv6 dns + QString ipv4,ipv6; + QList ipv4Dns,ipv6Dns; + KyActiveConnectResourse activeResourse; + activeResourse.getActiveConnectIpInfo(uuid,ipv4,ipv6); + activeResourse.getActiveConnectDnsInfo(uuid,ipv4Dns,ipv6Dns); + + //Ipv6 + if (!ipv6.isEmpty()) { + conInfo.strDynamicIpv6 = ipv6; + } + + //IPv4 + if (!ipv4.isEmpty()) { + conInfo.strDynamicIpv4 = ipv4; + } + + if (!ipv4Dns.isEmpty()) { + conInfo.strDynamicIpv4Dns = ipv4Dns.at(0).toString(); + } +} diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetresource.h b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetresource.h new file mode 100644 index 00000000..917aa07f --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetresource.h @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYNETRESOURCE_H +#define KYNETRESOURCE_H + +#include "kylinnetworkresourcemanager.h" +#include "kylinconnectsetting.h" +#include +#include + +class KyDetailInfo +{ +public: + QString strSecType; + QString strChan; + QString strMac; + QString strHz; + QString strBandWidth; + QString strDynamicIpv4; + QString strDynamicIpv6; + QString strDynamicIpv4Dns; + bool isAutoConnect = false; +}; + +class KyNetResource : public QObject +{ + Q_OBJECT +public: + explicit KyNetResource(QObject *parent = nullptr); + ~KyNetResource(); + + void getConnectionSetting(QString connectUuid, KyConnectSetting &connectSetting); + +protected: + KyNetworkResourceManager *m_networkResourceInstance = nullptr; + + void getBaseInfo(QString devName,QString ssid, bool isWlan, bool isActive, KyDetailInfo &conInfo); + void getDynamicIpInfo(QString uuid, KyDetailInfo &conInfo); + +private: + void getIpv4ConnectSetting(NetworkManager::Ipv4Setting::Ptr &ipv4Setting, + KyConnectSetting &connectSetting); + void getIpv6ConnectSetting(NetworkManager::Ipv6Setting::Ptr &ipv6Setting, + KyConnectSetting &connectSetting); +}; + +#endif // KYNETRESOURCE_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkdeviceresource.cpp b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkdeviceresource.cpp new file mode 100644 index 00000000..91d9ad31 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkdeviceresource.cpp @@ -0,0 +1,256 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include "kylinnetworkdeviceresource.h" +#include "kylinnetworkmanagerutil.h" +#include "kylinconnectoperation.h" + +#define VIRTURAL_DEVICE_PATH "/sys/devices/virtual/net" +#define LOG_FLAG "KyNetworkDeviceResourse" + +KyNetworkDeviceResourse::KyNetworkDeviceResourse(QObject *parent) : QObject(parent) +{ + m_networkResourceInstance = KyNetworkResourceManager::getInstance(); + + connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceCarrierChange, + this, &KyNetworkDeviceResourse::carrierChange); + connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceStateChange, + this, &KyNetworkDeviceResourse::deviceStateChange); + connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceManagedChange, + this, &KyNetworkDeviceResourse::deviceManagedChange); +// connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceBitRateChange, +// this, &KyNetworkDeviceResourse::deviceBitRateChange); +// connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceMacAddressChange, +// this, &KyNetworkDeviceResourse::deviceMacAddressChange); +// connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceActiveChange, +// this, &KyNetworkDeviceResourse::deviceActiveChange); + +} + +KyNetworkDeviceResourse::~KyNetworkDeviceResourse() +{ + m_networkResourceInstance = nullptr; +} + +void KyNetworkDeviceResourse::getNetworkDeviceList( + KyDeviceType deviceType, + QStringList &networkDeviceList) +{ + NetworkManager::Device::List deviceList + = m_networkResourceInstance->getNetworkDeviceList(); + + if (deviceList.isEmpty()) { + qDebug() << LOG_FLAG <<"network device is not exist. device type" << deviceType; + return; + } + + NetworkManager::Device::Ptr devicePtr = nullptr; + for (int index = 0; index < deviceList.size(); ++index) { + devicePtr = deviceList.at(index); + if (devicePtr.isNull()) { + continue; + } + + if (devicePtr->type() == deviceType) { + if (DEVICE_TYPE_ETHERNET == deviceType) { + //为了区分有线网卡和虚拟网卡 + qDebug()<< LOG_FLAG << "device uni" << devicePtr->udi(); + if (devicePtr->udi().startsWith(VIRTURAL_DEVICE_PATH)) { + continue; + } + } + + networkDeviceList<interfaceName(); + } + } + + return; +} + +void KyNetworkDeviceResourse::getHardwareInfo(QString ifaceName, QString &hardAddress, int &bandWith) +{ + NetworkManager::Device::Ptr connectDevice = + m_networkResourceInstance->findDeviceByName(ifaceName); + + if (nullptr == connectDevice || !connectDevice->isValid()) { + qWarning()<< LOG_FLAG <<"get hardware info failed, the device" << ifaceName << "is not existed"; + hardAddress.clear(); + bandWith = 0; + return; + } + + switch (connectDevice->type()) { + case NetworkManager::Device::Ethernet: + { + NetworkManager::WiredDevice *wiredDevicePtr = + qobject_cast(connectDevice.data()); + hardAddress = wiredDevicePtr->hardwareAddress(); + bandWith = wiredDevicePtr->bitRate(); + break; + } + case NetworkManager::Device::Wifi: + { + NetworkManager::WirelessDevice *wirelessDevicePtr = + qobject_cast(connectDevice.data()); + hardAddress = wirelessDevicePtr->hardwareAddress(); + bandWith = wirelessDevicePtr->bitRate(); + break; + } + default: + { + hardAddress = ""; + bandWith = 0; + qWarning()<< LOG_FLAG << "the network device type is undefined" << connectDevice->type(); + break; + } + } +} + +KyDeviceState KyNetworkDeviceResourse::getDeviceState(QString deviceName) +{ + NetworkManager::Device::Ptr connectDevice = + m_networkResourceInstance->findDeviceByName(deviceName); + if (!connectDevice.isNull() && connectDevice->isValid()) { + return (KyDeviceState)connectDevice->state(); + } + + qWarning()<< LOG_FLAG <<"get device state failed, the device is " << deviceName; + + return DEVICE_STATE_UNKNOWN; +} + +bool KyNetworkDeviceResourse::wiredDeviceIsCarriered(QString deviceName) +{ + NetworkManager::Device::Ptr connectDevice = + m_networkResourceInstance->findDeviceByName(deviceName); + if (connectDevice.isNull()) { + qWarning()<< LOG_FLAG << "check device carriered failed."; + return false; + } + + if (connectDevice->isValid() + && NetworkManager::Device::Type::Ethernet == connectDevice->type()) { + NetworkManager::WiredDevice *wiredDevicePtr = + qobject_cast(connectDevice.data()); + return wiredDevicePtr->carrier(); + } + + qWarning()<< LOG_FLAG << deviceName <<" can not get carrier state."; + + return false; +} + +void KyNetworkDeviceResourse::getDeviceActiveAPInfo(const QString devName, QString &strMac, uint &iHz, uint &iChan, QString &secuType) +{ + strMac.clear(); + iHz = 0; + iChan = 0; + secuType.clear(); + + NetworkManager::Device::Ptr connectDevice = + m_networkResourceInstance->findDeviceByName(devName); + + if (nullptr == connectDevice || !connectDevice->isValid()) { + qWarning()<< LOG_FLAG <<"getDeviceActiveAPInfo failed, the device" << devName << "is not existed"; + return; + } + + switch (connectDevice->type()) { + case NetworkManager::Device::Wifi: + { + NetworkManager::WirelessDevice *wirelessDevicePtr = + qobject_cast(connectDevice.data()); + NetworkManager::AccessPoint::Ptr apPtr = wirelessDevicePtr->activeAccessPoint(); + if (apPtr.isNull()) { + break; + } + strMac = apPtr->hardwareAddress(); + iHz = apPtr->frequency(); + iChan = NetworkManager::findChannel(iHz); + NetworkManager::AccessPoint::Capabilities capability = apPtr->capabilities(); + NetworkManager::AccessPoint::WpaFlags wpaFlag = apPtr->wpaFlags(); + NetworkManager::AccessPoint::WpaFlags rsnFlag = apPtr->rsnFlags(); + secuType = enumToQstring(capability, wpaFlag, rsnFlag); + break; + } + case NetworkManager::Device::Ethernet: + break; + default: + break; + } +} + +int KyNetworkDeviceResourse::getWirelessDeviceCapability(const QString deviceName) +{ + NetworkManager::Device::Ptr connectDevice = + m_networkResourceInstance->findDeviceByName(deviceName); + if (!connectDevice.isNull() && connectDevice->isValid() + && NetworkManager::Device::Type::Wifi == connectDevice->type()) { + NetworkManager::WirelessDevice *wirelessDevicePtr = + qobject_cast(connectDevice.data()); + + int cap = 0; + if (wirelessDevicePtr->wirelessCapabilities() & NetworkManager::WirelessDevice::ApCap) { + cap = cap | 0x01; + } + if (wirelessDevicePtr->wirelessCapabilities() & NetworkManager::WirelessDevice::Freq2Ghz) { + cap = cap | 0x02; + } + if (wirelessDevicePtr->wirelessCapabilities() & NetworkManager::WirelessDevice::Freq5Ghz) { + cap = cap | 0x04; + } + return cap; + } else { + qWarning()<<"[KyNetworkDeviceResourse]"<findDeviceByName(devName); + if (!connectDevice.isNull() && connectDevice->isValid()) { + dbusPath = connectDevice->uni(); + } else { + qWarning()<<"[KyNetworkDeviceResourse] can not find device " << devName; + return; + } + setDeviceManagedByGDbus(dbusPath, managed); +} + +bool KyNetworkDeviceResourse::getDeviceManaged(QString deviceName) +{ + NetworkManager::Device::Ptr connectDevice = + m_networkResourceInstance->findDeviceByName(deviceName); + if (connectDevice != nullptr && connectDevice->isValid()) { + return connectDevice->managed(); + } else { + qWarning()<<"[KyNetworkDeviceResourse] can not find device " << deviceName; + return false; + } +} + diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkdeviceresource.h b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkdeviceresource.h new file mode 100644 index 00000000..790b83d3 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkdeviceresource.h @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYLINNETORKDEVICERESOURCE_H +#define KYLINNETORKDEVICERESOURCE_H + +#include +#include "kylinnetworkresourcemanager.h" +#include "kylinconnectitem.h" +#include "kylinwiredconnectoperation.h" + +//设备操作和信息获取 +class KyNetworkDeviceResourse : public QObject +{ + Q_OBJECT +public: + explicit KyNetworkDeviceResourse(QObject *parent = nullptr); + ~KyNetworkDeviceResourse(); + +public: + void getNetworkDeviceList(KyDeviceType deviceType, QStringList &networkDeviceList); + void getHardwareInfo(QString ifaceName, QString &hardAddress, int &bandWith); + + //移动热点有关 + void getDeviceActiveAPInfo(const QString devName, QString &strMac, uint &iHz, uint &iChan, QString &secuType); + int getWirelessDeviceCapability(const QString deviceName); + + KyDeviceState getDeviceState(QString deviceName); + + bool wiredDeviceIsCarriered(QString deviceName); + bool wirelessDeviceIsExist(const QString devName); + + void setDeviceManaged(QString devName, bool managed); + bool getDeviceManaged(QString devName); + +private: + void getActiveConnection(QString &deviceName, QString &connectUuid); + void saveActiveConnection(QString &deviceName, QString &connectUuid); + +Q_SIGNALS: + void deviceStateChange(QString deviceName, KyDeviceState newstate, KyDeviceState oldstate, + NetworkManager::Device::StateChangeReason reason); + void carrierChange(QString deviceName, bool pluged); + + void wiredDeviceEnableChange(QString, bool); + void deviceManagedChange(QString deviceName, bool managed); + +// void deviceBitRateChanage(QString deviceName, int bitRate); +// void deviceMacAddressChanage(QString deviceName, const QString &hwAddress); +// void deviceActiveChanage(QString deviceName, bool deivceActive); + +private: + KyNetworkResourceManager *m_networkResourceInstance = nullptr; +}; +#endif // KYLINNETORKDEVICERESOURCE_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkmanagerutil.cpp b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkmanagerutil.cpp new file mode 100644 index 00000000..e54c5576 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkmanagerutil.cpp @@ -0,0 +1,240 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include +#include +#include +#include +#include +#include +#include +#include "kylinnetworkmanagerutil.h" +#include "kylinnetworkdeviceresource.h" +#define LOG_FLAG "[kylin-util]" +const QString CONFIG_FILE_PATH = QDir::homePath() + "/.config/ukui/kylin-nm.conf"; + +QString getConnectTypeByDbus(QString connectPath) +{ + QString connectType = ""; + if (connectPath.isEmpty()) { + qWarning() << LOG_FLAG << "connect path is empty, so can not get connect type"; + return connectType; + } + + QDBusInterface dbusInterface("org.freedesktop.NetworkManager", + connectPath, + "org.freedesktop.NetworkManager.Settings.Connection", + QDBusConnection::systemBus()); + + QDBusMessage result = dbusInterface.call("GetSettings"); + const QDBusArgument &dbusArg1st = result.arguments().at( 0 ).value(); + QMap> map; + dbusArg1st >> map; + + if (map.isEmpty()) { + qWarning() << LOG_FLAG <<"get connection settings failed."; + return connectType; + } + + QMap connectMap = map.value(KEY_CONNECTION); + if (connectMap.isEmpty()) { + qWarning() << LOG_FLAG <<"threre is not connection settings"; + return connectType; + } + + connectType = connectMap.value(KEY_CONNECT_TYPE).toString(); + return connectType; +} + +QString getSsidFromByteArray(QByteArray &rawSsid) +{ + QString wifiSsid = ""; + + if (rawSsid.isEmpty()) { + qWarning() << LOG_FLAG << "wifi raw ssid is empty"; + return wifiSsid; + } + + QTextCodec::ConverterState state; + QTextCodec *codec = QTextCodec::codecForName("UTF-8"); + codec->toUnicode( rawSsid.constData(), rawSsid.size(), &state); + if (state.invalidChars > 0) { + wifiSsid = QTextCodec::codecForName("GBK")->toUnicode(rawSsid); + } else { + wifiSsid = rawSsid; + } + + return wifiSsid; +} + +QString enumToQstring(NetworkManager::AccessPoint::Capabilities apCapability, + NetworkManager::AccessPoint::WpaFlags wpaFlags, + NetworkManager::AccessPoint::WpaFlags rsnFlags) +{ + QString out; + + if ((apCapability & AP_CAPABILITY_PRIVACY) + && (wpaFlags == AP_SECURITY_NONE) + && (rsnFlags == AP_SECURITY_NONE)) { + out += "WEP "; + } + + if (wpaFlags != AP_SECURITY_NONE) { + out += "WPA1 "; + } + + if ((rsnFlags & AP_SECURITY_KEY_MGMT_PSK) + || (rsnFlags & AP_SECURITY_KEY_MGMT_802_1X)) { + out += "WPA2 "; + } + + if (rsnFlags & AP_SECURITY_KEY_MGMT_SAE) { + out += "WPA3 "; + } + + if ((wpaFlags & AP_SECURITY_KEY_MGMT_802_1X) + || (rsnFlags & AP_SECURITY_KEY_MGMT_802_1X)) { + out += "802.1X "; + } + + return out; +} + +void setWiredEnabledByGDbus(bool enabled) +{ + GDBusProxy *props_proxy; + GVariant *ret = NULL; + GError *error = NULL; + + /* Create a D-Bus object proxy for the active connection object's properties */ + props_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM, + G_DBUS_PROXY_FLAGS_NONE, + NULL, + "org.freedesktop.NetworkManager", + "/org/freedesktop/NetworkManager", + "org.freedesktop.DBus.Properties", + NULL, NULL); + g_assert (props_proxy); + + /* Get the object path of the Connection details */ + ret = g_dbus_proxy_call_sync (props_proxy, + "Set", + g_variant_new ("(ssv)", + "org.freedesktop.NetworkManager", + "WiredEnabled", + g_variant_new_boolean(enabled)), + G_DBUS_CALL_FLAGS_NONE, -1, + NULL, &error); + if (!ret) { + g_dbus_error_strip_remote_error (error); + qDebug() << "failed to setWiredEnabledByGDbus"; + g_error_free (error); + } + +out: + if (ret) + g_variant_unref (ret); + g_object_unref (props_proxy); +} + +bool getWiredEnabledByGDbus() +{ + GDBusProxy *props_proxy; + GVariant *ret = NULL, *path_value = NULL; + GError *error = NULL; + gboolean bRet = false; + + /* Create a D-Bus object proxy for the active connection object's properties */ + props_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM, + G_DBUS_PROXY_FLAGS_NONE, + NULL, + "org.freedesktop.NetworkManager", + "/org/freedesktop/NetworkManager", + "org.freedesktop.DBus.Properties", + NULL, NULL); + g_assert (props_proxy); + + /* Get the object path of the Connection details */ + ret = g_dbus_proxy_call_sync (props_proxy, + "Get", + g_variant_new ("(ss)", + "org.freedesktop.NetworkManager", + "WiredEnabled"), + G_DBUS_CALL_FLAGS_NONE, -1, + NULL, &error); + if (!ret) { + g_dbus_error_strip_remote_error (error); + qDebug() << "failed to setWiredEnabledByGDbus"; + g_error_free (error); + } + + g_variant_get (ret, "(v)", &path_value); + if (!g_variant_is_of_type (path_value, G_VARIANT_TYPE_BOOLEAN)) { + g_warning ("Unexpected type returned getting Connection property: %s", + g_variant_get_type_string (path_value)); + goto out; + } + + bRet = g_variant_get_boolean (path_value); + +out: + if (path_value) + g_variant_unref (path_value); + if (ret) + g_variant_unref (ret); + g_object_unref (props_proxy); + + return bRet; +} + + +void setDeviceManagedByGDbus(QString dbusPath, bool managed) +{ + GDBusProxy *props_proxy; + GVariant *ret = NULL; + GError *error = NULL; + + /* Create a D-Bus object proxy for the active connection object's properties */ + props_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM, + G_DBUS_PROXY_FLAGS_NONE, + NULL, + "org.freedesktop.NetworkManager", + dbusPath.toStdString().c_str(), + "org.freedesktop.DBus.Properties", + NULL, NULL); + g_assert (props_proxy); + + /* Get the object path of the Connection details */ + ret = g_dbus_proxy_call_sync (props_proxy, + "Set", + g_variant_new ("(ssv)", + "org.freedesktop.NetworkManager.Device", + "Managed", + g_variant_new_boolean(managed)), + G_DBUS_CALL_FLAGS_NONE, -1, + NULL, &error); + if (!ret) { + g_dbus_error_strip_remote_error (error); + qDebug() << "failed to setWiredEnabledByGDbus"; + g_error_free (error); + } + +out: + if (ret) + g_variant_unref (ret); + g_object_unref (props_proxy); +} diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkmanagerutil.h b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkmanagerutil.h new file mode 100644 index 00000000..84be82fc --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkmanagerutil.h @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYLINUTIL_H +#define KYLINUTIL_H + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include "kylinnetworkresourcetype.h" +#include "kywirelessconnectoperation.h" + +#define KEY_CONNECTION "connection" +#define KEY_CONNECT_TYPE "type" +#define ETHERNET_TYPE "802-3-ethernet" + +QString getConnectTypeByDbus(QString connectPath); +QString getSsidFromByteArray(QByteArray &rawSsid); +QString enumToQstring(NetworkManager::AccessPoint::Capabilities cap, NetworkManager::AccessPoint::WpaFlags wpa_flags,NetworkManager::AccessPoint::WpaFlags rsn_flags); + +void setWiredEnabledByGDbus(bool enabled); +void setDeviceManagedByGDbus(QString dbusPath, bool managed); +bool getWiredEnabledByGDbus(); + + +#endif // KYLINUTIL_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkresourcemanager.cpp b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkresourcemanager.cpp new file mode 100644 index 00000000..299be78b --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkresourcemanager.cpp @@ -0,0 +1,1114 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "kylinnetworkresourcemanager.h" +#include +#include "kylinnetworkmanagerutil.h" +#include +#include + +#define SIGNAL_DELAY 80000 +#define EMIT_DELAY 10000 + +#define LOG_FLAG "[KyNetworkResourceManager]" + +//单例部分 +KyNetworkResourceManager* KyNetworkResourceManager::m_pInstance = nullptr; + +KyNetworkResourceManager* KyNetworkResourceManager::getInstance() +{ + if (m_pInstance == NULL) { + m_pInstance = new KyNetworkResourceManager(); + } + + return m_pInstance; +} + +void KyNetworkResourceManager::Release() +{ + if (m_pInstance != NULL) { + delete m_pInstance; + m_pInstance = NULL; + } +} + +KyNetworkResourceManager::KyNetworkResourceManager(QObject *parent) : QObject(parent) +{ + //线程 信号槽 类型声明 + qRegisterMetaType("KyConnectState"); + qRegisterMetaType("KyConnectivity"); + qRegisterMetaType("KyDeviceType"); +} + +//start后执行 循环检查m_initFinished 非true阻塞 +void KyNetworkResourceManager::onInitNetwork() +{ + insertActiveConnections(); + insertConnections(); + insertDevices(); + insertWifiNetworks(); + + //设备 + connect(NetworkManager::notifier(), &NetworkManager::Notifier::deviceAdded, + this, &KyNetworkResourceManager::onDeviceAdded); + connect(NetworkManager::notifier(), &NetworkManager::Notifier::deviceRemoved, + this, &KyNetworkResourceManager::onDeviceRemoved); + + //已连接 + connect(NetworkManager::notifier(), &NetworkManager::Notifier::activeConnectionAdded, + this, &KyNetworkResourceManager::onActiveConnectionAdded); + connect(NetworkManager::notifier(), &NetworkManager::Notifier::activeConnectionRemoved, + this, &KyNetworkResourceManager::onActiveConnectionRemoved); + + //Connection + connect(NetworkManager::settingsNotifier(), &NetworkManager::SettingsNotifier::connectionAdded, + this, &KyNetworkResourceManager::onConnectionAdded); + connect(NetworkManager::settingsNotifier(), &NetworkManager::SettingsNotifier::connectionRemoved, + this, static_cast(&KyNetworkResourceManager::onConnectionRemoved)); + + //通用能力 + connect(NetworkManager::notifier(), &NetworkManager::Notifier::connectivityChanged, + this, &KyNetworkResourceManager::onConnectivityChanged); + connect(NetworkManager::notifier(), &NetworkManager::Notifier::networkingEnabledChanged, + this, &KyNetworkResourceManager::networkingEnabledChanged); + connect(NetworkManager::notifier(), &NetworkManager::Notifier::wirelessEnabledChanged, + this, &KyNetworkResourceManager::wifiEnabledChanged); + connect(NetworkManager::notifier(), &NetworkManager::Notifier::primaryConnectionTypeChanged, + this, &KyNetworkResourceManager::onPrimaryConnectionTypeChanged); + + // Note: the connectionRemoved is never emitted in case network-manager service stop, + // we need remove the connections manually. + //NetworkManager服务 + connect(NetworkManager::notifier(), &NetworkManager::Notifier::serviceDisappeared, + this, &KyNetworkResourceManager::clearConnections); + connect(NetworkManager::notifier(), &NetworkManager::Notifier::serviceDisappeared, + this, &KyNetworkResourceManager::clearWifiNetworks); + + QDBusConnection::systemBus().connect(QString("org.freedesktop.DBus"), + QString("/org/freedesktop/DBus"), + QString("org.freedesktop.DBus"), + QString("NameOwnerChanged"), this, SLOT(onServiceAppear(QString,QString,QString))); + + QDBusConnection::systemBus().connect(QString("org.freedesktop.NetworkManager"), + QString("/org/freedesktop/NetworkManager"), + QString("org.freedesktop.NetworkManager"), + QString("PropertiesChanged"), this, SLOT(onPropertiesChanged(QVariantMap))); + + m_initFinished = true; +} + +bool KyNetworkResourceManager::NetworkManagerIsInited() +{ + return m_initFinished; +} + +KyNetworkResourceManager::~KyNetworkResourceManager() +{ + +} + +//服务重启后 没有add信号 需要重新初始化wifi +void KyNetworkResourceManager::onServiceAppear(QString interface, QString oldOwner, QString newOwner) +{ + if (interface == "org.freedesktop.NetworkManager" + && oldOwner.isEmpty() && !newOwner.isEmpty()) { + qDebug() << LOG_FLAG << "org.freedesktop.NetworkManager start"; + QTimer::singleShot(500,this,&KyNetworkResourceManager::insertWifiNetworks); + } +} + +//m_activeConnectList 删除 +void KyNetworkResourceManager::removeActiveConnection(int pos) +{ + //active connections signals + NetworkManager::ActiveConnection::Ptr connectPtr = m_activeConnectList.takeAt(pos); + connectPtr->disconnect(this); +} + +//m_activeConnectList 清空 +void KyNetworkResourceManager::clearActiveConnections() +{ + while (0 < m_activeConnectList.size()) { + removeActiveConnection(0); + } +} + +//m_activeConnectList 增加 +void KyNetworkResourceManager::addActiveConnection(NetworkManager::ActiveConnection::Ptr conn) +{ + m_activeConnectList.push_back(conn); + + connect(conn.data(), &NetworkManager::ActiveConnection::stateChanged, this, &KyNetworkResourceManager::onActiveConnectionChanged); + +// if (conn->vpn()) { +// connect(qobject_cast(conn.data()), &NetworkManager::VpnConnection::bannerChanged, this, &KyNetworkResourceManager::onActiveConnectionUpdated); +// connect(qobject_cast(conn.data()), &NetworkManager::VpnConnection::stateChanged, this, &KyNetworkResourceManager::onVpnActiveConnectChangedReason); +// } +} + +//初始化m_activeConnectList +void KyNetworkResourceManager::insertActiveConnections() +{ + for (auto const & conn : NetworkManager::activeConnections()) { + if (conn.isNull()) { + continue; + } + addActiveConnection(conn); + } +} + +//m_connectList 删除 +void KyNetworkResourceManager::removeConnection(int pos) +{ + NetworkManager::Connection::Ptr conn = m_connectList.takeAt(pos); + conn->disconnect(this); +} + +//m_connectList 清空 +void KyNetworkResourceManager::clearConnections() +{ + while (0 < m_connectList.size()) { + removeConnection(0); + } +} + +//m_connectList 增加 +void KyNetworkResourceManager::addConnection(NetworkManager::Connection::Ptr connectPtr) +{ + m_connectList.push_back(connectPtr); + + connect(connectPtr.data(), &NetworkManager::Connection::updated, this, &KyNetworkResourceManager::onConnectionUpdated); +// connect(connectPtr.data(), &NetworkManager::Connection::removed, this, &KyNetworkResourceManager::onConnectionRemoved); +} + +//m_connectList 初始化 +void KyNetworkResourceManager::insertConnections() +{ + for (auto const & connectPtr : NetworkManager::listConnections()) { + if (connectPtr.isNull()) { + continue; + } + + if (connectPtr->name().isEmpty() || connectPtr->uuid().isEmpty()) { + qWarning() << LOG_FLAG << " the name of connection is empty."; + continue; + } + + addConnection(connectPtr); + } +} + +//m_deviceList 删除 +void KyNetworkResourceManager::removeDevice(int pos) +{ + //connections signals + NetworkManager::Device::Ptr devicePtr = m_deviceList.takeAt(pos); + devicePtr->disconnect(this); + + m_deviceMap.remove(devicePtr->uni()); + Q_EMIT deviceRemove(devicePtr->interfaceName()); +} + +//m_deviceList 清空 +void KyNetworkResourceManager::clearDevices() +{ + while (0 < m_deviceList.size()) + removeDevice(0); +} + +//m_deviceList 增加 +void KyNetworkResourceManager::addDevice(NetworkManager::Device::Ptr device) +{ + m_deviceList.push_back(device); + m_deviceMap.insert(device->uni(), device->interfaceName()); + + connect(device.data(), &NetworkManager::Device::activeConnectionChanged, this, &KyNetworkResourceManager::onDeviceActiveChange); + connect(device.data(), &NetworkManager::Device::interfaceNameChanged, this, &KyNetworkResourceManager::onDeviceUpdated); + connect(device.data(), &NetworkManager::Device::managedChanged, this, &KyNetworkResourceManager::onDeviceManagedChange); + + switch (device->type()) + { + case NetworkManager::Device::Ethernet: + connect(qobject_cast(device.data()), &NetworkManager::WiredDevice::bitRateChanged, + this, &KyNetworkResourceManager::onDeviceBitRateChange); + connect(qobject_cast(device.data()), &NetworkManager::WiredDevice::carrierChanged, + this, &KyNetworkResourceManager::onDeviceCarrierChange); + connect(qobject_cast(device.data()), + &NetworkManager::WiredDevice::hardwareAddressChanged, this, &KyNetworkResourceManager::onDeviceMacAddressChange); + break; + + case NetworkManager::Device::Wifi: + connect(qobject_cast(device.data()), + &NetworkManager::WirelessDevice::networkAppeared, this, &KyNetworkResourceManager::onWifiNetworkAppeared); + connect(qobject_cast(device.data()), + &NetworkManager::WirelessDevice::networkDisappeared, this, &KyNetworkResourceManager::onWifiNetworkDisappeared); + break; + + default: + //TODO: other device types! + break; + } +} + +//m_deviceList 初始化 +void KyNetworkResourceManager::insertDevices() +{ + for (auto const & device : NetworkManager::networkInterfaces()) { + if (device.isNull()) { + continue; + } + addDevice(device); + } +} + +//m_wifiNetList 删除 +void KyNetworkResourceManager::removeWifiNetwork(int pos) +{ + //network signals + NetworkManager::WirelessNetwork::Ptr net = m_wifiNetList.takeAt(pos); + net->disconnect(this); +} + +//m_wifiNetList 清空 +void KyNetworkResourceManager::clearWifiNetworks() +{ + while (0 < m_wifiNetList.size()) + removeWifiNetwork(0); +} + +//m_wifiNetList 增加 +void KyNetworkResourceManager::addWifiNetwork(NetworkManager::WirelessNetwork::Ptr net) +{ + m_wifiNetList.push_back(net); + + connect(net.data(), &NetworkManager::WirelessNetwork::signalStrengthChanged, this, &KyNetworkResourceManager::onUpdateWirelessNet); + connect(net.data(), &NetworkManager::WirelessNetwork::referenceAccessPointChanged, this, &KyNetworkResourceManager::onUpdateWirelessNet); + connect(net.data(), &NetworkManager::WirelessNetwork::disappeared, this, &KyNetworkResourceManager::onUpdateWirelessNet); +} + +//m_wifiNetList 初始化 +void KyNetworkResourceManager::insertWifiNetworks() +{ + for (auto const & device : m_deviceList) { + if (device.isNull()) { + continue; + } + + if (NetworkManager::Device::Wifi == device->type()) { + NetworkManager::WirelessDevice::Ptr w_dev = device.objectCast(); + for (auto const & net : w_dev->networks()) { + if (!net.isNull()) { + addWifiNetwork(net); + Q_EMIT wifiNetworkAdded(device->interfaceName(),net->ssid()); + } + } + } + } +} + +//get +NetworkManager::ActiveConnection::List KyNetworkResourceManager::getActiveConnectList() +{ + return m_activeConnectList; +} + +NetworkManager::Connection::List KyNetworkResourceManager::getConnectList() +{ + return m_connectList; +} + +NetworkManager::Device::List KyNetworkResourceManager::getNetworkDeviceList() +{ + return m_deviceList; +} + +NetworkManager::WirelessNetwork::List KyNetworkResourceManager::getWifiNetworkList() +{ + return m_wifiNetList; +} + +//查找类接口===================================================================================================== +NetworkManager::ActiveConnection::Ptr KyNetworkResourceManager::findActiveConnectionByPath(QString const & path) +{ + NetworkManager::ActiveConnection::Ptr activeConnectPtr = nullptr; + + if (path.isEmpty()) { + return nullptr; + } + + if (m_activeConnectList.isEmpty()) { + return nullptr; + } + + for (int index = 0; index < m_activeConnectList.size(); ++index) { + activeConnectPtr = m_activeConnectList.at(index); + if (activeConnectPtr.isNull()) { + continue; + } + + if (activeConnectPtr->path() == path) { + return activeConnectPtr; + } + } + + return nullptr; +} + +NetworkManager::Device::Ptr KyNetworkResourceManager::findDeviceByUni(QString const & deviceUni) +{ + NetworkManager::Device::Ptr devicePtr = nullptr; + + if (deviceUni.isEmpty()) { + return nullptr; + } + + for (int index = 0; index < m_deviceList.size(); ++index) { + devicePtr = m_deviceList.at(index); + if (devicePtr.isNull()) { + continue; + } + + if (devicePtr->uni() == deviceUni) { + return devicePtr; + } + } + + return nullptr; +} + +NetworkManager::Device::Ptr KyNetworkResourceManager::findDeviceByName(QString interfaceName) +{ + NetworkManager::Device::Ptr devicePtr = nullptr; + if (interfaceName.isEmpty()) { + return nullptr; + } + + for (int index = 0; index < m_deviceList.size(); ++index) { + devicePtr = m_deviceList.at(index); + if (devicePtr.isNull()) { + continue; + } + + if (devicePtr->interfaceName() == interfaceName) { + return devicePtr; + } + } + + return nullptr; +} + +NetworkManager::WirelessNetwork::Ptr KyNetworkResourceManager::findWifiNetwork(QString const & ssid, QString const & deviceUni) +{ + NetworkManager::WirelessNetwork::Ptr wifiNetPtr = nullptr; + + if (ssid.isEmpty() || deviceUni.isEmpty()) { + return nullptr; + } + + if (m_wifiNetList.isEmpty()) { + return nullptr; + } + + for (int index = 0; index < m_wifiNetList.size(); ++index) { + wifiNetPtr = m_wifiNetList.at(index); + if (wifiNetPtr.isNull()) { + continue; + } + + if (wifiNetPtr->ssid() == ssid && wifiNetPtr->device() == deviceUni) { + return wifiNetPtr; + } + } + + return nullptr; +} + +NetworkManager::ActiveConnection::Ptr KyNetworkResourceManager::findActiveConnectByUuid(const QString activeConnectUuid) +{ + int index = 0; + NetworkManager::ActiveConnection::Ptr activateConnectPtr = nullptr; + + qDebug()<<"[KyNetworkResourceManager]"<<"get activetate connect with uuid"<< activeConnectUuid; + if (activeConnectUuid.isEmpty()) { + return nullptr; + } + + for (index = 0; index < m_activeConnectList.size(); ++index) { + activateConnectPtr = m_activeConnectList.at(index); + if (activateConnectPtr.isNull()) { + continue; + } + + if (activateConnectPtr->uuid() == activeConnectUuid) { + return activateConnectPtr; + } + } + + qWarning()<<"[KyNetworkResourceManager]"<<"it can not find the activate connect with uuid" <uuid() == connectUuid) { + return connectPtr; + } + } + + qWarning()<<"[KyNetworkResourceManager]"<<"it can not find connect with uuid"<uuid() == uuid + && NetworkManager::ActiveConnection::State::Activated == activateConnectPtr->state()) { + return true; + } + } + + return false; +} + +//属性判断类接口===================================================================== +bool KyNetworkResourceManager::isWiredConnect(QString connectPath) +{ + QString connectionType = getConnectTypeByDbus(connectPath); + if (ETHERNET_TYPE == connectionType) { + return true; + } + + return false; +} + +bool KyNetworkResourceManager::isActivatingConnection(QString uuid) +{ + int index = 0; + NetworkManager::ActiveConnection::Ptr activateConnectPtr = nullptr; + + if (uuid.isEmpty()) { + return false; + } + + for (index = 0; index < m_activeConnectList.size(); ++index) { + activateConnectPtr = m_activeConnectList.at(index); + if (activateConnectPtr.isNull()) { + continue; + } + + if (activateConnectPtr->uuid() == uuid + && NetworkManager::ActiveConnection::State::Activating == activateConnectPtr->state()) { + return true; + } + } + + return false; +} + +bool KyNetworkResourceManager::isApConnection(NetworkManager::Connection::Ptr connectPtr) +{ + if (nullptr == connectPtr) { + return false; + } + + if (NetworkManager::ConnectionSettings::ConnectionType::Wireless + != connectPtr->settings()->connectionType()) { + return false; + } + + NetworkManager::ConnectionSettings::Ptr settingPtr = connectPtr->settings(); + NetworkManager::WirelessSetting::Ptr wirelessSetting + = settingPtr->setting(NetworkManager::Setting::Wireless).dynamicCast(); + if (NetworkManager::WirelessSetting::NetworkMode::Ap + != wirelessSetting->mode()) { + return false; + } + + return true; +} + +void KyNetworkResourceManager::getConnectivity(KyConnectivity &connectivity) +{ + connectivity = (KyConnectivity)NetworkManager::connectivity(); +} + +void KyNetworkResourceManager::requestScan(NetworkManager::WirelessDevice *p_wirelessDevice) +{ + if (nullptr == p_wirelessDevice) { + qWarning() << LOG_FLAG << "request scan failed, wireless device is invalid."; + return; + } + + QDBusPendingReply<> reply = p_wirelessDevice->requestScan(); + QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, p_wirelessDevice); + connect(watcher, &QDBusPendingCallWatcher::finished, [p_wirelessDevice] (QDBusPendingCallWatcher * watcher) { + if (watcher->isError() || !watcher->isValid()) { + //TODO: in what form should we output the warning messages + qWarning() << QStringLiteral("requestScan on device '%1' failed: %3").arg(p_wirelessDevice->interfaceName()) + .arg(watcher->error().message()); + } + watcher->deleteLater(); + }); + + return; +} + +void KyNetworkResourceManager::onPropertiesChanged(QVariantMap qvm) +{ + for(QString keyStr : qvm.keys()) { + //收到wifi开关打开或关闭的信号后,进行处理 + if (keyStr == "WiredEnabled") { + bool wiredEnable = qvm.value("WiredEnabled").toBool(); + qDebug() << "wiredEnabledChanged" << wiredEnable; + Q_EMIT wiredEnabledChanged(wiredEnable); + } + } +} + + +void KyNetworkResourceManager::onConnectionUpdated() +{ + NetworkManager::Connection *connectPtr = + qobject_cast(sender()); + if (nullptr != connectPtr && connectPtr->isValid()) { + NetworkManager::ConnectionSettings::Ptr connectSettingPtr = connectPtr->settings(); + if (NetworkManager::ConnectionSettings::ConnectionType::Wireless == connectSettingPtr->connectionType()) { + Q_EMIT wirelessConnectionUpdate(connectSettingPtr->interfaceName(), connectPtr->uuid(), connectPtr->name(), connectPtr->path()); + } else if (isWiredConnect(connectPtr->path())) { + Q_EMIT wiredConnectionUpdate(connectSettingPtr->interfaceName(), connectPtr->uuid(), connectPtr->name(), connectPtr->path()); + } else { + Q_EMIT connectionUpdate(connectPtr->uuid(), connectPtr->name(), connectPtr->path()); + } + } else { + qWarning()<< LOG_FLAG + <<"onConnectionUpdate failed, the connect is invalid"; + } +} + +void KyNetworkResourceManager::wirelessActiveStateChange(NetworkManager::ConnectionSettings::Ptr connectSettingsPtr, + QString deviceName, + QString uuid, + KyConnectState state) +{ + NetworkManager::WirelessSetting::Ptr wirelessSettingsPtr + = connectSettingsPtr->setting(NetworkManager::Setting::Wireless).dynamicCast(); + if (wirelessSettingsPtr.isNull()) { + qDebug()<< LOG_FLAG << "don't have WirelessSetting connection"; + return; + } + + QByteArray rawSsid = wirelessSettingsPtr->ssid(); + QString ssid = getSsidFromByteArray(rawSsid); + + Q_EMIT wirelessConnectStateChange(deviceName, ssid, uuid, state); +} + +void KyNetworkResourceManager::wiredActiveStateChange(QString connectPath, + QString deviceName, + QString uuid, + KyConnectState state) +{ + QString connectionType = getConnectTypeByDbus(connectPath); + if (ETHERNET_TYPE == connectionType) { + Q_EMIT wiredConnectStateChange(deviceName, uuid, state); + } else { + qWarning() << LOG_FLAG << "the connect type is not wired" << connectionType; + } +} + +void KyNetworkResourceManager::connectActiveStateChange(NetworkManager::Connection::Ptr connectPtr, + QString deviceName, + KyConnectState state) +{ + QString uuid = connectPtr->uuid(); + NetworkManager::ConnectionSettings::Ptr connectSettingsPtr = connectPtr->settings(); + KyConnectionType connectionType = (KyConnectionType)connectSettingsPtr->connectionType(); + + if (connectionType == CONNECT_TYPE_WIRELESS) { + wirelessActiveStateChange(connectSettingsPtr, deviceName, uuid, state); + NetworkManager::WirelessSetting::Ptr wirelessSetting + = connectSettingsPtr->setting(NetworkManager::Setting::Wireless).dynamicCast(); + if (NetworkManager::WirelessSetting::NetworkMode::Ap + == wirelessSetting->mode()) { + Q_EMIT wirelessApConnectStateChange(); + } + } else if (connectionType == CONNECT_TYPE_WIRED) { + wiredActiveStateChange(connectPtr->path(), deviceName, uuid, state); + } else { + qWarning() << LOG_FLAG << "connect type is undefined" << connectionType; + } +} + +void KyNetworkResourceManager::onActiveConnectionChanged( + NetworkManager::ActiveConnection::State state) +{ + NetworkManager::ActiveConnection * activeConnect = + qobject_cast(sender()); + if (nullptr != activeConnect && activeConnect->isValid()) { + QString deviceName = ""; + QStringList interfaces = activeConnect->devices(); + if (interfaces.size() > 0) { + QString ifaceUni = interfaces.at(0); + NetworkManager::Device:: Ptr devicePtr = findDeviceByUni(ifaceUni); + deviceName = devicePtr->interfaceName(); + } + + NetworkManager::Connection::Ptr connectPtr = activeConnect->connection(); + connectActiveStateChange(connectPtr, deviceName, (KyConnectState)state); + } else { + qWarning() << LOG_FLAG << "onActiveConnectionChanged failed, the connection is invalid."; + } +} + +void KyNetworkResourceManager::onVpnActiveConnectChangedReason(NetworkManager::VpnConnection::State state, + NetworkManager::VpnConnection::StateChangeReason reason) +{ + NetworkManager::ActiveConnection *activeConnect = + qobject_cast(sender()); + + if (nullptr != activeConnect && activeConnect->isValid()) { + qDebug()<<"vpn connect uuid" << activeConnect->uuid() + <<"state change " <uuid(), state, reason); + } else { + qWarning() << LOG_FLAG << "onVpnActiveConnectChangedReason failed, the connection is invalid."; + } +} + +void KyNetworkResourceManager::onDeviceActiveChange() +{ + NetworkManager::Device *p_device = qobject_cast(sender()); + if (nullptr == p_device) { + return; + } + + QString deviceName = p_device->interfaceName(); + //此处需要取反,因为激活连接的网卡状态是false,断开连接的网卡状态是true + bool isActive = !p_device->isActive(); + + qDebug()<< LOG_FLAG << "device active change, device name " << deviceName + << "active state" << isActive; + + Q_EMIT deviceActiveChange(deviceName, isActive); +} + +void KyNetworkResourceManager::updateDeviceName(NetworkManager::Device *p_device) +{ + QString newDeviceName = p_device->interfaceName(); + QString deviceUni = p_device->uni(); + + if (m_deviceMap.contains(deviceUni)) { + if (m_deviceMap[deviceUni] != newDeviceName) { + QString oldDeviceName = m_deviceMap[deviceUni]; + m_deviceMap[deviceUni] = newDeviceName; + if (DEVICE_TYPE_WIFI == (KyDeviceType)p_device->type()) { + Q_EMIT wirelessDeviceUpdate(oldDeviceName, newDeviceName); + } else if (DEVICE_TYPE_ETHERNET == (KyDeviceType)p_device->type() + && !p_device->udi().startsWith(VIRTURAL_DEVICE_PATH)) { + Q_EMIT wiredDeviceUpdate(oldDeviceName, newDeviceName);; + } else { + Q_EMIT deviceUpdate(oldDeviceName, newDeviceName); + } + } + } +} + +void KyNetworkResourceManager::onDeviceUpdated() +{ + NetworkManager::Device *p_device = qobject_cast(sender()); + if (nullptr == p_device) { + return; + } + + updateDeviceName(p_device); +} + +void KyNetworkResourceManager::onDeviceManagedChange() +{ + NetworkManager::Device *p_device = qobject_cast(sender()); + if (nullptr == p_device) { + return; + } + + QString deviceName = p_device->interfaceName(); + bool managed = p_device->managed(); + + Q_EMIT deviceManagedChange(deviceName, managed); +} + +void KyNetworkResourceManager::onDeviceCarrierChange(bool pluged) +{ + NetworkManager::WiredDevice * networkDevice + = qobject_cast(sender()); + + qDebug()<< LOG_FLAG<<"device carrier change"<< pluged; + if (nullptr !=networkDevice && networkDevice->isValid()) { + Q_EMIT deviceCarrierChange(networkDevice->interfaceName(), pluged); + } else { + qWarning()<< LOG_FLAG<<"onDeviceCarrierChange failed."; + } +} + +void KyNetworkResourceManager::onDeviceBitRateChange(int bitRate) +{ + NetworkManager::WiredDevice * networkDevice + = qobject_cast(sender()); + + if (nullptr != networkDevice + && networkDevice->isValid()) { + Q_EMIT deviceBitRateChange(networkDevice->interfaceName(), bitRate); + } else { + qWarning()<< LOG_FLAG <<"the device is not invalid with bitrate" << bitRate; + } +} + +//暂未用到 +void KyNetworkResourceManager::onDeviceMacAddressChange(const QString &hwAddress) +{ + NetworkManager::WiredDevice * networkDevice + = qobject_cast(sender()); + + if (nullptr != networkDevice && networkDevice->isValid()) { + Q_EMIT deviceMacAddressChange(networkDevice->interfaceName(), hwAddress); + } else { + qWarning()<< LOG_FLAG <<"the device is not invalid with mac" << hwAddress; + } +} + +//设备状态变化 +void KyNetworkResourceManager::onDeviceStateChanged( + NetworkManager::Device::State newstate, + NetworkManager::Device::State oldstate, + NetworkManager::Device::StateChangeReason reason) +{ + qDebug() << LOG_FLAG <<"the device state "<(sender()); + Q_EMIT deviceStateChange(networkDevice->interfaceName(), (KyDeviceState)newstate, (KyDeviceState)oldstate, reason); +} + + +void KyNetworkResourceManager::wifiNetworkAdd(NetworkManager::Device * dev, QString const & ssid) +{ + if (nullptr == dev) { + return; + } + + NetworkManager::WirelessDevice * w_dev = qobject_cast(dev); + NetworkManager::WirelessNetwork::Ptr net = w_dev->findNetwork(ssid); + if (!net.isNull()) { + if (0 > m_wifiNetList.indexOf(net)){ + addWifiNetwork(net); + } else { + //TODO: onWifiNetworkUpdate + qDebug()<< LOG_FLAG << "add but already exist"; + } + + NetworkManager::AccessPoint::Ptr accessPoitPtr = net->referenceAccessPoint(); + QByteArray rawSsid = accessPoitPtr->rawSsid(); + QString wifiSsid = getSsidFromByteArray(rawSsid); + Q_EMIT wifiNetworkAdded(dev->interfaceName(), wifiSsid); + } + + return; +} + +void KyNetworkResourceManager::wifiNetworkUpdate(NetworkManager::WirelessNetwork * net) +{ + if (nullptr == net) { + return; + } + + auto index = std::find(m_wifiNetList.cbegin(), m_wifiNetList.cend(), net); + if (m_wifiNetList.cend() != index) { + if (net->accessPoints().isEmpty()) { + //emit + bool bFlag = false; + QString devIface; + NetworkManager::Device::Ptr dev = findDeviceByUni(net->device()); + if(dev.isNull()) { + qDebug()<< LOG_FLAG << "device invalid"; + bFlag = true; + } else { + devIface = dev->interfaceName(); + } + + //remove + auto pos = index - m_wifiNetList.cbegin(); + removeWifiNetwork(pos); + if(bFlag) { + Q_EMIT wifiNetworkDeviceDisappear(); + } else { + NetworkManager::AccessPoint::Ptr accessPoitPtr = net->referenceAccessPoint(); + if (accessPoitPtr.isNull()) { + return; + } + QByteArray rawSsid = accessPoitPtr->rawSsid(); + QString wifiSsid = getSsidFromByteArray(rawSsid); + Q_EMIT wifiNetworkRemoved(devIface, wifiSsid); + } + } else { + Q_EMIT wifiNetworkPropertyChange(*index); + } + } + + return; +} + +void KyNetworkResourceManager::wifiNetworkRemove(NetworkManager::Device * dev, QString const & ssid) +{ + if (nullptr == dev) { + return; + } + + NetworkManager::WirelessNetwork::Ptr net = findWifiNetwork(ssid, dev->uni()); + if (!net.isNull()) { + auto pos = m_wifiNetList.indexOf(net); + if (0 <= pos) { + removeWifiNetwork(pos); + NetworkManager::AccessPoint::Ptr accessPoitPtr = net->referenceAccessPoint(); + QByteArray rawSsid = accessPoitPtr->rawSsid(); + QString wifiSsid = getSsidFromByteArray(rawSsid); + Q_EMIT wifiNetworkRemoved(dev->interfaceName(), wifiSsid); + } + } + + return; +} + +void KyNetworkResourceManager::onWifiNetworkAppeared(QString const & ssid) +{ + NetworkManager::Device * p_device = qobject_cast(sender()); + if (nullptr != p_device) { + wifiNetworkAdd(p_device, ssid); + updateDeviceName(p_device); + } else { + qWarning()<< LOG_FLAG << "onWifiNetworkAppeared failed."; + } +} + +void KyNetworkResourceManager::onWifiNetworkDisappeared(QString const & ssid) +{ + NetworkManager::Device *p_device = qobject_cast(sender()); + if (nullptr != p_device) { + wifiNetworkRemove(p_device, ssid); + updateDeviceName(p_device); + } else { + qWarning()<< LOG_FLAG << "onWifiNetworkDisappeared failed."; + } +} + +void KyNetworkResourceManager::onUpdateWirelessNet() +{ + NetworkManager::WirelessNetwork *p_wirelessNet = + qobject_cast(sender()); + if (nullptr != p_wirelessNet) { + wifiNetworkUpdate(p_wirelessNet); + } +} + +void KyNetworkResourceManager::onDeviceAdded(QString const & uni) +{ + NetworkManager::Device::Ptr networkDevicePtr = NetworkManager::findNetworkInterface(uni); + if (networkDevicePtr.isNull()) { + qWarning()<<"the device is not exist in networkmanager."<< uni; + return; + } + + if (!networkDevicePtr->isValid()) { + qWarning() << uni << " is currently not invalid"; + return; + } + + if (0 > m_deviceList.indexOf(networkDevicePtr)) { + addDevice(networkDevicePtr); + if (DEVICE_TYPE_WIFI == (KyDeviceType)networkDevicePtr->type()) { + Q_EMIT wirelessDeviceAdd(networkDevicePtr->interfaceName()); + } else if (DEVICE_TYPE_ETHERNET == (KyDeviceType)networkDevicePtr->type() + && !networkDevicePtr->udi().startsWith(VIRTURAL_DEVICE_PATH)) { + Q_EMIT wiredDeviceAdd(networkDevicePtr->interfaceName()); + } else { + Q_EMIT deviceAdd(networkDevicePtr->interfaceName(), (KyDeviceType)networkDevicePtr->type()); + } + } else { + qWarning() << networkDevicePtr->interfaceName() <<"the device is exist in network device list."; + } +} + +void KyNetworkResourceManager::onDeviceRemoved(QString const & uni) +{ + NetworkManager::Device::Ptr networkDevice = findDeviceByUni(uni); + if (networkDevice.isNull()) { + qWarning()<<"the device is not exist in network device list ."<< uni; + return; + } + + auto index = std::find(m_deviceList.cbegin(), m_deviceList.cend(), networkDevice); + if (m_deviceList.cend() != index) { + const int pos = index - m_deviceList.cbegin(); + removeDevice(pos); + } +} + +void KyNetworkResourceManager::onActiveConnectionAdded(QString const & path) +{ + NetworkManager::ActiveConnection::Ptr activeConnectPtr = NetworkManager::findActiveConnection(path); + if (activeConnectPtr.isNull()) { + qWarning() << "[KyNetworkResourceManager]" << "the active connect is null, so do not add it."<isValid()) { + qWarning() << "[KyNetworkResourceManager]" << path << " connect is currently not valid"; + return; + } + +// qDebug()<<"add active connect"<connection()->name(); + + if (0 > m_activeConnectList.indexOf(activeConnectPtr)) { + addActiveConnection(activeConnectPtr); + Q_EMIT activeConnectionAdd(activeConnectPtr->uuid()); + } else { + //TODO: onActiveConnectionUpdate + qWarning() << "[KyNetworkResourceManager]" << "update active connection to do"; + //emit activeConnectionUpdate(conn->uuid()); + } +} + +void KyNetworkResourceManager::onActiveConnectionRemoved(QString const & path) +{ + NetworkManager::ActiveConnection::Ptr activeConnectPtr = findActiveConnectionByPath(path);//XXX: const QString &uni + if (activeConnectPtr.isNull()) { + qWarning() <<"[KyNetworkResourceManager]" + <<"the active connect is null, so do not remove it. "<< path; + return; + } + + auto index = std::find(m_activeConnectList.cbegin(), m_activeConnectList.cend(), activeConnectPtr); + if (m_activeConnectList.cend() != index) { + const int pos = index - m_activeConnectList.cbegin(); + removeActiveConnection(pos); + Q_EMIT activeConnectionRemove(activeConnectPtr->uuid()); + } +} + +void KyNetworkResourceManager::onConnectionAdded(QString const & path) +{ + NetworkManager::Connection::Ptr connectPtr = NetworkManager::findConnection(path); + if (connectPtr.isNull()) { + qWarning() <<"[KyNetworkResourceManager]" <<"it can not find in networkmanager."<isValid()) { + qWarning() <<"[KyNetworkResourceManager]" << path << " is currently not invalid"; + return; + } + + if (connectPtr->name().isEmpty() || connectPtr->uuid().isEmpty()) { + qWarning() <<"[KyNetworkResourceManager]" << "the name or uuid of connection is empty"; + return; + } + + if (0 > m_connectList.indexOf(connectPtr)) { + addConnection(connectPtr); + NetworkManager::ConnectionSettings::Ptr connectSettingPtr = connectPtr->settings(); + if (NetworkManager::ConnectionSettings::ConnectionType::Wireless == connectSettingPtr->connectionType()) { + Q_EMIT wirelessConnectionAdd(connectPtr->uuid(), connectPtr->name(), connectPtr->path()); + } else if (isWiredConnect(connectPtr->path())) { + Q_EMIT wiredConnectionAdd(connectPtr->settings()->interfaceName(), connectPtr->uuid(), connectPtr->name(), connectPtr->path()); + } else { + Q_EMIT connectionAdd(connectPtr->uuid(), connectPtr->name(), connectPtr->path()); + } + } else { + //TODO::updateconnect + qWarning() << "[KyNetworkResourceManager]" << connectPtr->uuid() <<" connect is exist in connect list."; + } +} + +void KyNetworkResourceManager::onConnectionRemoved(QString const & path) +{ + if (path.isEmpty()) { + qDebug() <<"[KyNetworkResourceManager]" <<"the connect path is empty"; + return; + } + NetworkManager::Connection::Ptr connectionPtr = nullptr; + for (int index = 0; index < m_connectList.size(); ++index) { + connectionPtr = m_connectList.at(index); + if (connectionPtr->path() == path) { + removeConnection(index); + Q_EMIT connectionRemove(path); + return; + } + } + + qWarning() <<"[KyNetworkResourceManager]" << path <<" connect is no exist in connect list"; +} + +void KyNetworkResourceManager::onConnectivityChanged(NetworkManager::Connectivity connectivity) +{ + qDebug() << "onConnectivityChanged"; + Q_EMIT connectivityChanged((KyConnectivity)connectivity); +} + +void KyNetworkResourceManager::onPrimaryConnectionTypeChanged(NetworkManager::ConnectionSettings::ConnectionType type) +{ + Q_EMIT primaryConnectionTypeChanged((KyConnectionType)type); +} + +void KyNetworkResourceManager::connectionDump() +{ + NetworkManager::Connection::Ptr connectionPtr = nullptr; + for (int index = 0; index < m_connectList.size(); ++index) { + connectionPtr = m_connectList.at(index); + qDebug()<<"connection info**********************"; + qDebug()<<"connection name"<< connectionPtr->name(); + qDebug()<<"connection uuid"<< connectionPtr->uuid(); + qDebug()<<"connection path"<< connectionPtr->path(); + } +} diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkresourcemanager.h b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkresourcemanager.h new file mode 100644 index 00000000..bc23add8 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkresourcemanager.h @@ -0,0 +1,245 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#ifndef KYLINNETWORKRESOURCEMANAGER_H +#define KYLINNETWORKRESOURCEMANAGER_H + +#include "NetworkManagerQt/Manager" +#include "NetworkManagerQt/Settings" +#include "NetworkManagerQt/WirelessDevice" +#include "NetworkManagerQt/GenericTypes" +#include "NetworkManagerQt/VpnConnection" +#include "NetworkManagerQt/WirelessDevice" +#include "NetworkManagerQt/AdslDevice" +#include "NetworkManagerQt/WiredDevice" +#include "NetworkManagerQt/WimaxDevice" +#include "NetworkManagerQt/VlanDevice" +#include "NetworkManagerQt/BondDevice" +#include "NetworkManagerQt/BridgeDevice" +#include "NetworkManagerQt/GenericDevice" +#include "NetworkManagerQt/InfinibandDevice" +#include "NetworkManagerQt/BluetoothDevice" +#include "NetworkManagerQt/OlpcMeshDevice" +#include "NetworkManagerQt/TeamDevice" +#include "NetworkManagerQt/WirelessSetting" +#include "NetworkManagerQt/WirelessSecuritySetting" +#include "NetworkManagerQt/Utils" +#include "NetworkManagerQt/ConnectionSettings" +#include "NetworkManagerQt/Security8021xSetting" +#include +#include + +#include "kylinnetworkresourcetype.h" + +#define VIRTURAL_DEVICE_PATH "/sys/devices/virtual/net" + +class KyNetworkResourceManager : public QObject +{ + Q_OBJECT +public: + static KyNetworkResourceManager* getInstance(); + static void Release(); + +public: + explicit KyNetworkResourceManager(QObject *parent = nullptr); + ~KyNetworkResourceManager(); + +public: + NetworkManager::ActiveConnection::Ptr findActiveConnectionByPath(QString const & path); + NetworkManager::ActiveConnection::Ptr findActiveConnectByUuid(const QString activeConnectUuid); + + NetworkManager::Connection::Ptr findConnectByUuid(const QString uuid); + + NetworkManager::Device::Ptr findDeviceByUni(QString const &deviceUni); + NetworkManager::Device::Ptr findDeviceByName(QString interfaceName); + + NetworkManager::WirelessNetwork::Ptr findWifiNetwork(QString const &ssid, QString const &deviceUni); + + NetworkManager::ActiveConnection::List getActiveConnectList(); + NetworkManager::Connection::List getConnectList(); + NetworkManager::Device::List getNetworkDeviceList(); + NetworkManager::WirelessNetwork::List getWifiNetworkList(); + + bool isActiveConnection(QString uuid); + bool isActivatingConnection(QString uuid); + + void getConnectivity(KyConnectivity &connectivity); + + bool NetworkManagerIsInited(); + + void requestScan(NetworkManager::WirelessDevice *p_wirelessDevice); + + bool isWiredConnect(QString connectPath); + bool isApConnection(NetworkManager::Connection::Ptr connectPtr); + +private: + void removeActiveConnection(int pos); + void clearActiveConnections(); + void insertActiveConnections(); + void addActiveConnection(NetworkManager::ActiveConnection::Ptr conn); + + void removeConnection(int pos); + void clearConnections(); + void insertConnections(); + void addConnection(NetworkManager::Connection::Ptr conn); + + void removeDevice(int pos); + void clearDevices(); + void insertDevices(); + void addDevice(NetworkManager::Device::Ptr conn); + void updateDeviceName(NetworkManager::Device *p_device); + + void removeWifiNetwork(int pos); + void clearWifiNetworks(); + void insertWifiNetworks(); + void addWifiNetwork(NetworkManager::WirelessNetwork::Ptr net); + + void connectionDump(); + + void wifiNetworkAdd(NetworkManager::Device * dev, QString const & ssid); + void wifiNetworkUpdate(NetworkManager::WirelessNetwork * net); + void wifiNetworkRemove(NetworkManager::Device * dev, QString const & ssid); + + + void wirelessActiveStateChange(NetworkManager::ConnectionSettings::Ptr connectSettingsPtr, + QString deviceName, QString uuid, KyConnectState state); + void wiredActiveStateChange(QString connectPath, QString deviceName, + QString uuid, KyConnectState state); + void connectActiveStateChange(NetworkManager::Connection::Ptr connectPtr, + QString deviceName, KyConnectState state); + +private Q_SLOTS: + void onServiceAppear(QString, QString, QString); + void onPropertiesChanged(QVariantMap qvm); + +Q_SIGNALS: + + // wired connect + void wiredConnectionAdd(QString devName, QString connectUuid, QString connectName, QString connectPath); + void wiredConnectionUpdate(QString devName, QString connectUuid, QString connectName, QString connectPath); +// void wiredConnectionRemove(QString path); + + void connectionAdd(QString connectUuid, QString connectName, QString connectPath); + void connectionUpdate(QString connectUuid, QString connectName, QString connectPath); + void connectionRemove(QString path); + + //device + void wiredDeviceAdd(QString deviceName); + void wiredDeviceUpdate(QString oldDeviceName, QString newDeviceName); + + void wirelessDeviceAdd(QString deviceName); + void wirelessDeviceUpdate(QString oldDeviceName, QString newDeviceName); + + void deviceAdd(QString deviceName, KyDeviceType deviceType); + void deviceUpdate(QString oldDeviceName, QString newDeviceName); + void deviceRemove(QString deviceName); + void deviceManagedChange(QString deviceName, bool managed); + + void deviceActiveChange(QString deviceName, bool deviceActive); + void deviceCarrierChange(QString deviceName, bool pluged); + void deviceBitRateChange(QString deviceName, int bitRate); + void deviceMacAddressChange(QString deviceName, const QString &hwAddress); + void deviceStateChange(QString deviceName, KyDeviceState newstate, KyDeviceState oldstate, + NetworkManager::Device::StateChangeReason reason); + + //wireless + void wifiNetworkRemoved(QString, QString); + void wifiNetworkAdded(QString, QString); + void wifiNetworkPropertyChange(NetworkManager::WirelessNetwork::Ptr net); + void wifiNetworkDeviceDisappear(); + + void wirelessConnectionAdd(QString connectUuid, QString connectName, QString connectPath); + void wirelessConnectionUpdate(QString devName,QString connectUuid, QString connectName, QString connectPath); +// void wirelessConnectionRemove(QString path); + +// void wiredConnectionUpdate(QString connectUuid, QString connectName, QString connectPath); + + + //activate connection + void activeConnectionAdd(QString uuid); + void activeConnectionRemove(QString uuid); + + void wiredConnectStateChange(QString deviceName, QString uuid, KyConnectState state); + void wirelessConnectStateChange(QString deviceName, QString ssid, QString uuid, KyConnectState state); + void wirelessApConnectStateChange(); + + + //general + void connectivityChanged(KyConnectivity connectivity); + void wifiEnabledChanged(bool); + void wiredEnabledChanged(bool); + void networkingEnabledChanged(bool); + void primaryConnectionTypeChanged(KyConnectionType type); + +public Q_SLOTS: + void onInitNetwork(); + + //connection + void onConnectionUpdated(); + //void onConnectionRemoved(); + + //active connection + void onActiveConnectionChanged(NetworkManager::ActiveConnection::State state); + void onVpnActiveConnectChangedReason(NetworkManager::VpnConnection::State state, + NetworkManager::VpnConnection::StateChangeReason reason); + + void onDeviceActiveChange(); + void onDeviceCarrierChange(bool pluged); + void onDeviceBitRateChange(int bitRate); + void onDeviceMacAddressChange(const QString &hwAddress); + void onDeviceStateChanged(NetworkManager::Device::State newstate, + NetworkManager::Device::State oldstate, NetworkManager::Device::StateChangeReason reason); + + void onWifiNetworkAppeared(QString const & ssid); + void onWifiNetworkDisappeared(QString const & ssid); + + //wifi network + void onUpdateWirelessNet(); + void onConnectivityChanged(NetworkManager::Connectivity connectivity); + + //notifier + void onDeviceAdded(QString const & uni); + void onDeviceRemoved(QString const & uni); + void onDeviceUpdated(); + void onDeviceManagedChange(); + + //active connection notifier + void onActiveConnectionAdded(QString const & path); + void onActiveConnectionRemoved(QString const & path); + + //settings notifier + void onConnectionAdded(QString const & path); + void onConnectionRemoved(QString const & path); + + void onPrimaryConnectionTypeChanged(NetworkManager::ConnectionSettings::ConnectionType); + +public: + static KyNetworkResourceManager* m_pInstance; + +private: + bool m_initFinished = false; + NetworkManager::ActiveConnection::List m_activeConnectList; + NetworkManager::Connection::List m_connectList; + NetworkManager::Device::List m_deviceList; + NetworkManager::WirelessNetwork::List m_wifiNetList; + + QMap m_deviceMap; +}; + + +#endif // KYLINNETWORKRESOURCEMANAGER_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkresourcetype.h b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkresourcetype.h new file mode 100644 index 00000000..d56f5c6c --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinnetworkresourcetype.h @@ -0,0 +1,224 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYLINNETWORKRESOURCETYPE_H +#define KYLINNETWORKRESOURCETYPE_H + + +typedef enum{ + CONNECT_STATE_UNKONW = 0, /**< The active connection is in an unknown state */ + CONNECT_STATE_ACTIVATING, /**< The connection is activating */ + CONNECT_STATE_ACTIVATED, /**< The connection is activated */ + CONNECT_STATE_DEACTIVATING, /**< The connection is being torn down and cleaned up */ + CONNECT_STATE_DEACTIVATED, /**< The connection is no longer active */ + + CONNECT_STATE_COUNT +}KyConnectState; + +typedef enum{ + CHANGE_REASON_UNKNOWN = 0, /**< The reason for the active connection state change is unknown */ + CHANGE_REASON_NONE, /**< No reason was given for the active connection state change */ + CHANGE_REASON_USER_DISCONNECTED, /**< The active connection changed state because the user disconnected it */ + CHANGE_REASON_DEVICE_DISCONNECTIED, /**< The active connection changed state because the device it was using was disconnected */ + CHANGE_REASON_SERVICE_STOP, /**< The service providing the VPN connection was stopped */ + + CHANGE_REASON_IPCONFIG_INVALID = 5, /**< The IP config of the active connection was invalid */ + CHANGE_REASON_CONNECT_TIMEOUT, /**< The connection attempt to the VPN service timed out */ + CHANGE_REASON_SERVICE_START_TIMEOUT,/**< A timeout occurred while starting the service providing the VPN connection */ + CHANGE_REASON_SERVICE_START_FAILED, /**< Starting the service providing the VPN connection failed */ + CHANGE_REASON_NO_SECRET, /**< Necessary secrets for the connection were not provided */ + + CHANGE_REASON_LOGIN_FAILED = 10, /**< Authentication to the server failed */ + CHANGE_REASON_CONNECT_REMOVED, /**< The connection was deleted from settings */ + CHANGE_REASON_DEPENDENCY_FAILED, /**< Master connection of this connection failed to activate */ + CHANGE_REASON_DEVICE_REALIZE_FAILED,/**< Could not create the software device link */ + CHANGE_REASON_DEVICE_REMOVED, /**< The device this connection depended on disappeared */ + + CHANGE_REASON_COUNT +}KyConnectChangeReason; + +typedef enum { + CONNECT_TYPE_UNKNOWN = 0, + CONNECT_TYPE_ADSL, + CONNECT_TYPE_BLUETOOTH, + CONNECT_TYPE_BOND, + CONNECT_TYPE_BRIDGE, + + CONNECT_TYPE_CDMA = 5, + CONNECT_TYPE_GSM, + CONNECT_TYPE_INFINIBAND, + CONNECT_TYPE_OLPCMESH, + CONNECT_TYPE_PPPOE, + + CONNECT_TYPE_VLAN = 10, + CONNECT_TYPE_VPN, + CONNECT_TYPE_WIMAX, + CONNECT_TYPE_WIRED, + CONNECT_TYPE_WIRELESS, + + CONNECT_TYPE_TEAM = 15, + CONNECT_TYPE_GENERIC, + CONNECT_TYPE_TUN, + CONNECT_TYPE_IPTUNNEL, + CONNECT_TYPE_WIREDGUARD, + + CONNECT_TYPE_COUNT +}KyConnectionType; + +typedef enum { + CONNECTIVITY_UNKNOWN = 0, /**< Network connectivity is unknown. */ + CONNECTIVITY_NO, /**< The host is not connected to any network. */ + CONNECTIVITY_PORTAL, /**< The host is behind a captive portal and cannot reach the full Internet. */ + CONNECTIVITY_LIMITED, /**< The host is connected to a network, but does not appear to be able to reach the full Internet. */ + CONNECTIVITY_FULL, /**< The host is connected to a network, and appears to be able to reach the full Internet. */ + + CONNECTIVITY_COUNT +}KyConnectivity; + +typedef enum { + DEVICE_TYPE_UNKNOWN = 0, /**< Unknown device type */ + DEVICE_TYPE_ETHERNET, /**< Ieee8023 wired ethernet */ + DEVICE_TYPE_WIFI, /**< the Ieee80211 family of wireless networks */ + DEVICE_TYPE_UNUSED1, /**< Currently unused */ + DEVICE_TYPE_UNUSED2, /**< Currently unused */ + + DEVICE_TYPE_BLUETOOTH = 5, /**< network bluetooth device (usually a cell phone) */ + DEVICE_TYPE_OLPCMESH, /**< OLPC Mesh networking device */ + DEVICE_TYPE_WIMAX, /**< WiMax WWAN technology */ + DEVICE_TYPE_MODEM, /**< POTS, GSM, CDMA or LTE modems */ + DEVICE_TYPE_INFINIBAND, /**< Infiniband network device */ + + DEVICE_TYPE_BOND = 10, /**< Bond virtual device */ + DEVICE_TYPE_VLAN, /**< Vlan virtual device */ + DEVICE_TYPE_ADSL, /**< ADSL modem device */ + DEVICE_TYPE_BRIDGE, /**< Bridge virtual device */ + DEVICE_TYPE_GENERIC, /**< Generic device @since 1.0.0 */ + + DEVICE_TYPE_TEAM = 15, /**< Team master device @since 1.0.0 */ + DEVICE_TYPE_GRE, /**< Gre virtual device @since 1.2.0, @deprecated use IpTunnel instead*/ + DEVICE_TYPE_MACVLAN, /**< MacVlan virtual device @since 1.2.0 */ + DEVICE_TYPE_TUN, /**< Tun virtual device @since 1.2.0 */ + DEVICE_TYPE_VETH, /**< Veth virtual device @since 1.2.0 */ + + DEVICE_TYPE_IPTUNNEL = 20, /**< IP Tunneling Device @since 1.2.0 */ + DEVICE_TYPE_VXLAN, /**< Vxlan Device @since 1.2.0 */ + DEVICE_TYPE_MACSEC, /**< MacSec Device @since 1.6.0 */ + DEVICE_TYPE_DUMMY, /**< Dummy Device @since 1.8.0 */ + DEVICE_TYPE_PPP, /**< Ppp Device @since 1.10 */ + + DEVICE_TYPE_OVSINTERFACE = 25, /**< OvsInterface Device @since 1.10 */ + DEVICE_TYPE_OVSPORT, /**< OvsPort Device @since 1.10 */ + DEVICE_TYPE_OVSBRIDGE, /**< OvsBridge Device @since 1.10 */ + DEVICE_TYPE_WPAN, /**< Wpan Device @since 1.14 */ + DEVICE_TYPE_LOWPAN, /**< Lowpan Device @since 1.14 */ + + DEVICE_TYPE_WIREGUARD = 30, /**< WireGuard Device @since 1.14 */ + DEVICE_TYPE_WIFIP2P, /**< WifiP2P Device @since 1.16 */ + DEVICE_TYPE_COUNT +}KyDeviceType; + +typedef enum { + DEVICE_STATE_UNKNOWN = 0, /**< The device is in an unknown state */ + DEVICE_STATE_UNMANAGED = 10, /**< The device is recognized but not managed by NetworkManager */ + DEVICE_STATE_UNAVAILABLE = 20, /**< The device cannot be used (carrier off, rfkill, etc) */ + DEVICE_STATE_DISCONNECTED = 30, /**< The device is not connected */ + DEVICE_STATE_PREPARING = 40, /**< The device is preparing to connect */ + DEVICE_STATE_CONFIGURINGHARDWARE = 50, /**< The device is being configured */ + DEVICE_STATE_NEEDAUTH = 60, /**< The device is awaiting secrets necessary to continue connection */ + DEVICE_STATE_CONFIGURINGIP = 70, /**< The IP settings of the device are being requested and configured */ + DEVICE_STATE_CHECKINGIP = 80, /**< The device's IP connectivity ability is being determined */ + DEVICE_STATE_WAITINGFORSECONDARIES = 90, /**< The device is waiting for secondary connections to be activated */ + DEVICE_STATE_ACTIVATED = 100, /**< The device is active */ + DEVICE_STATE_DEACTIVATING = 110, /**< The device's network connection is being torn down */ + DEVICE_STATE_FAILED = 120 /**< The device is in a failure state following an attempt to activate it */ +}KyDeviceState; + + +/** + * KyApSecurityFlags: + * @AP_SEC_NONE: the access point has no special security requirements + * @AP_SEC_PAIR_WEP40: 40/64-bit WEP is supported for + * pairwise/unicast encryption + * @AP_SEC_PAIR_WEP104: 104/128-bit WEP is supported for + * pairwise/unicast encryption + * @AP_SEC_PAIR_TKIP: TKIP is supported for pairwise/unicast encryption + * @AP_SEC_PAIR_CCMP: AES/CCMP is supported for pairwise/unicast encryption + * @AP_SEC_GROUP_WEP40: 40/64-bit WEP is supported for group/broadcast + * encryption + * @AP_SEC_GROUP_WEP104: 104/128-bit WEP is supported for + * group/broadcast encryption + * @AP_SEC_GROUP_TKIP: TKIP is supported for group/broadcast encryption + * @AP_SEC_GROUP_CCMP: AES/CCMP is supported for group/broadcast + * encryption + * @AP_SEC_KEY_MGMT_PSK: WPA/RSN Pre-Shared Key encryption is + * supported + * @AP_SEC_KEY_MGMT_802_1X: 802.1x authentication and key management + * is supported + * @AP_SEC_KEY_MGMT_SAE: WPA/RSN Simultaneous Authentication of Equals is + * supported + * + * 802.11 access point security and authentication flags. These flags describe + * the current security requirements of an access point as determined from the + * access point's beacon. + **/ +typedef enum { /*< underscore_name=nm_802_11_ap_security_flags, flags >*/ + AP_SECURITY_NONE = 0x00000000, + AP_SECURITY_PAIR_WEP40 = 0x00000001, + AP_SECURITY_PAIR_WEP104 = 0x00000002, + AP_SECURITY_PAIR_TKIP = 0x00000004, + AP_SECURITY_PAIR_CCMP = 0x00000008, + AP_SECURITY_GROUP_WEP40 = 0x00000010, + AP_SECURITY_GROUP_WEP104 = 0x00000020, + AP_SECURITY_GROUP_TKIP = 0x00000040, + AP_SECURITY_GROUP_CCMP = 0x00000080, + AP_SECURITY_KEY_MGMT_PSK = 0x00000100, + AP_SECURITY_KEY_MGMT_802_1X = 0x00000200, + AP_SECURITY_KEY_MGMT_SAE = 0x00000400, +}KyApSecurityFlags; + +/** + * KyApCapabilities: + * @AP_FLAGS_NONE: access point has no special capabilities + * @AP_FLAGS_PRIVACY: access point requires authentication and + * encryption (usually means WEP) + * @AP_FLAGS_WPS: access point supports some WPS method + * @AP_FLAGS_WPS_PBC: access point supports push-button WPS + * @AP_FLAGS_WPS_PIN: access point supports PIN-based WPS + * + * 802.11 access point fCapabilities. + **/ +typedef enum { + AP_CAPABILITY_NONE = 0x00000000, + AP_CAPABILITY_PRIVACY = 0x00000001, + AP_CAPABILITY_WPS = 0x00000002, + AP_CAPABILITY_WPS_PBC = 0x00000004, + AP_CAPABILITY_WPS_PIN = 0x00000008, +}KyApCapabilities; + +//class KySecretFlagType { +//public: +// enum KySecretFlag{ +// SECRET_FLAG_NONE = 0, +// SECRET_FLAG_AgentOWNED = 0x01, +// SECRET_FLAG_NOTSAVED = 0x02, +// SECRET_FLAG_NOTREQUIRED = 0x04 +// }; +// Q_DECLARE_FLAGS(kySecretFlags, KySecretFlag) +//}; +//Q_DECLARE_OPERATORS_FOR_FLAGS(KySecretFlagType::KySecretFlags) + +#endif // KYLINNETWORKRESOURCETYPE_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinwiredconnectoperation.cpp b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinwiredconnectoperation.cpp new file mode 100644 index 00000000..b0bb4fc8 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinwiredconnectoperation.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "kylinnetworkdeviceresource.h" +#include "kylinnetworkmanagerutil.h" + +#include +#include +#include +#include +#include + +KyWiredConnectOperation::KyWiredConnectOperation(QObject *parent) : KyConnectOperation(parent) +{ + +} + +void KyWiredConnectOperation::createWiredConnect(KyConnectSetting &connectSettingsInfo) +{ + connectSettingsInfo.dumpInfo(); + + NetworkManager::ConnectionSettings::Ptr wiredConnectionSettings = NetworkManager::ConnectionSettings::Ptr(new NetworkManager::ConnectionSettings(NetworkManager::ConnectionSettings::Wired)); + connectSettingSet(wiredConnectionSettings, connectSettingsInfo); + + NetworkManager::Ipv4Setting::Ptr ipv4Setting = wiredConnectionSettings->setting(NetworkManager::Setting::Ipv4).dynamicCast(); + ipv4SettingSet(ipv4Setting, connectSettingsInfo); + + NetworkManager::Ipv6Setting::Ptr ipv6Setting = wiredConnectionSettings->setting(NetworkManager::Setting::Ipv6).dynamicCast(); + ipv6SettingSet(ipv6Setting, connectSettingsInfo); + + NetworkManager::WiredSetting::Ptr wiredSetting = wiredConnectionSettings->setting(NetworkManager::Setting::Wired).dynamicCast(); + wiredSetting->setInitialized(true); + + QDBusPendingCallWatcher * watcher; + watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(wiredConnectionSettings->toMap()), this}; + connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { + if (watcher->isError() || !watcher->isValid()) { + QString errorMessage = tr("create wired connection failed: ") + watcher->error().message(); + qWarning() << errorMessage; + Q_EMIT this->createConnectionError(errorMessage); + } + watcher->deleteLater(); + }); +} diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinwiredconnectoperation.h b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinwiredconnectoperation.h new file mode 100644 index 00000000..ddb28c6d --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinwiredconnectoperation.h @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYLINWIREDCONNECTOPERATION_H +#define KYLINWIREDCONNECTOPERATION_H + +#include +#include + +#include "kylinnetworkresourcemanager.h" +#include "kylinconnectsetting.h" +#include "kylinconnectoperation.h" + +const QString WIRED_NETWORK_STATE_CONF_FILE = QDir::homePath() + "/.config/ukui/kylin-nm-wired.ini"; + +class KyWiredConnectOperation : public KyConnectOperation +{ + Q_OBJECT +public: + explicit KyWiredConnectOperation(QObject *parent = nullptr); + + void createWiredConnect(KyConnectSetting &connectSettingsInfo); +}; + +#endif // KYLINWIREDCONNECTOPERATION_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinwirednetresource.cpp b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinwirednetresource.cpp new file mode 100644 index 00000000..a9e8c659 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinwirednetresource.cpp @@ -0,0 +1,143 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include "kylinwirednetresource.h" +#include "kywirelessconnectoperation.h" +#include "kylinnetworkmanagerutil.h" + +#include +#include +#include +#include +#include + +static bool subLanListSort(const KyWiredItem info1, const KyWiredItem info2) +{ + QString name1 = info1.m_connectName; + QString name2 = info2.m_connectName; + bool result = true; + if (QString::compare(name1, name2, Qt::CaseInsensitive) > 0) { + result = false; + } + return result; +} + +static void lanListSort(QList &list) +{ + qSort(list.begin(), list.end(), subLanListSort); +} + +KyWiredConnectResourse::KyWiredConnectResourse(QObject *parent) : KyNetResource(parent) +{ + connect(m_networkResourceInstance, &KyNetworkResourceManager::wiredConnectionAdd, this, &KyWiredConnectResourse::wiredConnectionAdd); + connect(m_networkResourceInstance, &KyNetworkResourceManager::wiredConnectionUpdate, this, &KyWiredConnectResourse::wiredConnectionUpdate); + connect(m_networkResourceInstance, &KyNetworkResourceManager::connectionRemove, this, &KyWiredConnectResourse::connectionRemove); + + connect(m_networkResourceInstance, &KyNetworkResourceManager::wiredDeviceAdd, this, &KyWiredConnectResourse::wiredDeviceAdd); + connect(m_networkResourceInstance, &KyNetworkResourceManager::wiredDeviceUpdate, this, &KyWiredConnectResourse::wiredDeviceUpdate); + connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceRemove, this, &KyWiredConnectResourse::deviceRemove); +} + +//配合activeconnection 此处未单独区分已连接的wifi +void KyWiredConnectResourse::getWiredList(QMap> &map) +{ + map.clear(); + kyWirdNetItemListInit(); + if (m_wiredNetworkMap.isEmpty()) { + return; + } else { + QMap >::iterator iter = m_wiredNetworkMap.begin(); + while (iter != m_wiredNetworkMap.end()) { + lanListSort(m_wiredNetworkMap[iter.key()]); + iter++; + } + map = m_wiredNetworkMap; + } +} + +void KyWiredConnectResourse::getWiredConnectDetail(QString interface, QString uuid, KyDetailInfo &connectSetting) +{ + getBaseInfo(interface, "", false, false, connectSetting); + getDynamicIpInfo(uuid, connectSetting); +} + +KyWiredItem KyWiredConnectResourse::getConnectionItem(NetworkManager::Connection::Ptr connectPtr) +{ + if (nullptr == connectPtr) { + qWarning()<<"[KyConnectResourse]"<<"the connect is empty"; + return KyWiredItem(); + } + + KyWiredItem connectionItem; + connectionItem.m_connectName = connectPtr->name(); + connectionItem.m_connectUuid = connectPtr->uuid(); + connectionItem.m_connectPath = connectPtr->path(); + + return connectionItem; +} + + +void KyWiredConnectResourse::kyWirdNetItemListInit() +{ + m_wiredNetworkMap.clear(); + NetworkManager::Connection::List connectList = m_networkResourceInstance->getConnectList(); + + if (connectList.empty()) { + qWarning()<<"[KyConnectResourse]"<<"kyWirdNetItemListInit failed, the connect list is empty"; + return; + } + + KyNetworkDeviceResourse deviceResource; + QStringList devList; + deviceResource.getNetworkDeviceList(DEVICE_TYPE_ETHERNET, devList); + if (devList.isEmpty()) { + qWarning()<<"[KyConnectResourse]"<<"kyWirdNetItemListInit failed, the device list is empty"; + return; + } else { + for (int i = 0; i < devList.size(); ++i) { + m_wiredNetworkMap.insert(devList.at(i), QList()); + } + } + + NetworkManager::Connection::Ptr connectPtr = nullptr; + for (int index = 0; index < connectList.size(); index++) { + connectPtr = connectList.at(index); + if (connectPtr.isNull()) { + continue; + } + + if (!m_networkResourceInstance->isWiredConnect(connectPtr->path())) { + continue; + } + + KyWiredItem connectItem = getConnectionItem(connectPtr); + if (connectItem.m_connectUuid.isEmpty()) { + continue; + } + + QString connectInterface = connectPtr->settings()->interfaceName(); + if (connectInterface.isEmpty()) { + for (int i = 0; i < m_wiredNetworkMap.keys().size(); ++i) { + m_wiredNetworkMap[m_wiredNetworkMap.keys().at(i)] << connectItem; + } + } else { + if (m_wiredNetworkMap.contains(connectInterface)) { + m_wiredNetworkMap[connectInterface] << connectItem; + } + } + } +} diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinwirednetresource.h b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinwirednetresource.h new file mode 100644 index 00000000..ca4a7d92 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kylinwirednetresource.h @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYLINCONNECTRESOURCE_H +#define KYLINCONNECTRESOURCE_H + +#include +#include "kylinnetworkresourcemanager.h" +#include "kylinnetresource.h" +#include "kylinconnectitem.h" +#include "kylinnetworkdeviceresource.h" +#include "kylinconnectsetting.h" +#include "kylinapconnectitem.h" + +class KyWiredConnectResourse : public KyNetResource +{ + Q_OBJECT +public: + explicit KyWiredConnectResourse(QObject *parent = nullptr); + +public: + void getWiredList(QMap> &map); + + void getWiredConnectDetail(QString interface, QString uuid, KyDetailInfo &connectSetting); +private: + void kyWirdNetItemListInit(); + KyWiredItem getConnectionItem(NetworkManager::Connection::Ptr connectPtr); + +Q_SIGNALS: + void wiredConnectionAdd(QString devName, QString connectUuid, QString connectName, QString connectPath); + void wiredConnectionUpdate(QString devName, QString connectUuid, QString connectName, QString connectPath); + void connectionRemove(QString path); + + void wiredDeviceAdd(QString deviceName); + void wiredDeviceUpdate(QString oldDeviceName, QString newDeviceName); + void deviceRemove(QString deviceName); + +private: + QMap> m_wiredNetworkMap; +}; +#endif // KYLINCONNECTRESOURCE_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessconnectoperation.cpp b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessconnectoperation.cpp new file mode 100644 index 00000000..1e2d191a --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessconnectoperation.cpp @@ -0,0 +1,989 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include "kywirelessconnectoperation.h" +#include "kylinnetworkmanagerutil.h" + +#include + +#define PSK_SETTING_NAME "802-11-wireless-security" +#define PRIVATE_PSK_SETTING_NAME "802-1x" + +NetworkManager::ConnectionSettings::Ptr assembleWpaXPskSettings(NetworkManager::AccessPoint::Ptr accessPoint, QString &psk, bool isAutoConnect) +{ + QByteArray rawSsid = accessPoint->rawSsid(); + QString wifiSsid = getSsidFromByteArray(rawSsid); + + NetworkManager::ConnectionSettings::Ptr settings{new NetworkManager::ConnectionSettings{NetworkManager::ConnectionSettings::Wireless}}; + settings->setId(wifiSsid); + settings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); + settings->setAutoconnect(isAutoConnect); + //Note: workaround for wrongly (randomly) initialized gateway-ping-timeout + settings->setGatewayPingTimeout(0); + + NetworkManager::WirelessSetting::Ptr wifi_sett + = settings->setting(NetworkManager::Setting::Wireless).dynamicCast(); + wifi_sett->setInitialized(true); + wifi_sett->setSsid(rawSsid); + wifi_sett->setSecurity("802-11-wireless-security"); + + NetworkManager::WirelessSecuritySetting::Ptr security_sett + = settings->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); + security_sett->setInitialized(true); + if (NetworkManager::AccessPoint::Adhoc == accessPoint->mode()) { + wifi_sett->setMode(NetworkManager::WirelessSetting::Adhoc); + security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaNone); + } else { + security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaPsk); + } + if (!psk.isEmpty()) { + security_sett->setPsk(psk); + } + + return settings; +} + +NetworkManager::ConnectionSettings::Ptr assembleSaeSettings(NetworkManager::AccessPoint::Ptr accessPoint, QString &psk, bool isAutoConnect) +{ + QByteArray rawSsid = accessPoint->rawSsid(); + QString wifiSsid = getSsidFromByteArray(rawSsid); + + NetworkManager::ConnectionSettings::Ptr settings{new NetworkManager::ConnectionSettings{NetworkManager::ConnectionSettings::Wireless}}; + settings->setId(wifiSsid); + settings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); + settings->setAutoconnect(isAutoConnect); + //Note: workaround for wrongly (randomly) initialized gateway-ping-timeout + settings->setGatewayPingTimeout(0); + + NetworkManager::WirelessSetting::Ptr wifi_sett + = settings->setting(NetworkManager::Setting::Wireless).dynamicCast(); + wifi_sett->setInitialized(true); + wifi_sett->setSsid(rawSsid); + wifi_sett->setSecurity("802-11-wireless-security"); + + NetworkManager::WirelessSecuritySetting::Ptr security_sett + = settings->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); + security_sett->setInitialized(true); + if (NetworkManager::AccessPoint::Adhoc == accessPoint->mode()) { + wifi_sett->setMode(NetworkManager::WirelessSetting::Adhoc); + security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaNone); + } else { + security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::SAE); + } + if (!psk.isEmpty()) { + security_sett->setPsk(psk); + } + + return settings; +} + +NetworkManager::ConnectionSettings::Ptr assembleWirelessSettings(const NetworkManager::AccessPoint::Ptr accessPointPtr, + const KyWirelessConnectSetting &connSettingInfo, + KyKeyMgmt type, + bool isHidden) +{ + QByteArray rawSsid; + if (nullptr == accessPointPtr || accessPointPtr.isNull()) { + rawSsid = connSettingInfo.m_ssid.toUtf8(); + } else { + rawSsid = accessPointPtr->rawSsid(); + } + + NetworkManager::ConnectionSettings::Ptr settings{new NetworkManager::ConnectionSettings{NetworkManager::ConnectionSettings::Wireless}}; + settings->setId(connSettingInfo.m_connectName); + settings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); + settings->setAutoconnect(connSettingInfo.m_isAutoConnect); + //Note: workaround for wrongly (randomly) initialized gateway-ping-timeout + settings->setGatewayPingTimeout(0); + settings->setInterfaceName(connSettingInfo.m_ifaceName); + + NetworkManager::WirelessSetting::Ptr wifi_sett + = settings->setting(NetworkManager::Setting::Wireless).dynamicCast(); + wifi_sett->setInitialized(true); + wifi_sett->setSsid(rawSsid); + wifi_sett->setSecurity("802-11-wireless-security"); + wifi_sett->setHidden(isHidden); + + + if (type != KyKeyMgmt::WpaNone && type != KyKeyMgmt::Unknown) + { + NetworkManager::WirelessSecuritySetting::Ptr security_sett + = settings->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); + security_sett->setInitialized(true); + security_sett->setKeyMgmt((NetworkManager::WirelessSecuritySetting::KeyMgmt)type); + if (KyKeyMgmt::SAE == type || KyKeyMgmt::WpaPsk == type) + { + security_sett->setPsk(connSettingInfo.m_psk); + } + } + return settings; +} + + +KyWirelessConnectOperation::KyWirelessConnectOperation(QObject *parent) : KyConnectOperation(parent) +{ +} + +void KyWirelessConnectOperation::requestWirelessScan() +{ + NetworkManager::Device::List deviceList = m_networkResourceInstance->getNetworkDeviceList(); + + for (auto const & dev : deviceList) { + auto spec_dev = dev->as(); + if (nullptr != spec_dev) { + m_networkResourceInstance->requestScan(spec_dev); + } + } +} + +//普通wifi +void KyWirelessConnectOperation::addConnect(const KyWirelessConnectSetting &connSettingInfo, KySecuType &type) +{ + KyKeyMgmt mgmt; + if (type == NONE) { + mgmt = WpaNone; + } else if (type == WPA_AND_WPA2_PERSONAL) { + mgmt = WpaPsk; + } else if (type == WPA3_PERSONAL) { + mgmt = WpaEap; + } else { + return; + } + + NetworkManager::WirelessNetwork::Ptr wifiNet = + checkWifiNetExist(connSettingInfo.m_ssid, connSettingInfo.m_ifaceName); + if (wifiNet.isNull()) { + QString errorMessage = "the ssid " + connSettingInfo.m_ssid + + " is not exsit in " + connSettingInfo.m_ifaceName; + qWarning()<referenceAccessPoint(); + NetworkManager::ConnectionSettings::Ptr connSetting = + assembleWirelessSettings(accessPointPtr, connSettingInfo, mgmt, false); + setIpv4AndIpv6Setting(connSetting, connSettingInfo); + + QDBusPendingCallWatcher * watcher; + watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(connSetting->toMap()), this}; + connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { + if (watcher->isError() || !watcher->isValid()) { + QString errorMessage = tr("create wireless connection failed: ") + watcher->error().message(); + qWarning()<createConnectionError(errorMessage); + } + watcher->deleteLater(); + }); +} +//tls +void KyWirelessConnectOperation::addTlsConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodTlsInfo &tlsInfo) +{ + + NetworkManager::WirelessNetwork::Ptr wifiNet = + checkWifiNetExist(connSettingInfo.m_ssid, connSettingInfo.m_ifaceName); + if (wifiNet.isNull()) { + QString errorMessage = "the ssid " + connSettingInfo.m_ssid + + " is not exsit in " + connSettingInfo.m_ifaceName; + qWarning() << errorMessage; + Q_EMIT createConnectionError(errorMessage); + return; + } + + NetworkManager::AccessPoint::Ptr accessPointPtr = wifiNet->referenceAccessPoint(); + NetworkManager::ConnectionSettings::Ptr connSetting = + assembleWirelessSettings(accessPointPtr, connSettingInfo, WpaEap, false); + setIpv4AndIpv6Setting(connSetting, connSettingInfo); + assembleEapMethodTlsSettings(connSetting, tlsInfo); + + QDBusPendingCallWatcher * watcher; + watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(connSetting->toMap()), this}; + connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { + if (watcher->isError() || !watcher->isValid()) { + QString errorMessage = tr("create wireless tls connection failed: ") + watcher->error().message(); + qWarning()<createConnectionError(errorMessage); + } + watcher->deleteLater(); + }); + +} +//peap +void KyWirelessConnectOperation::addPeapConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodPeapInfo &peapInfo) +{ + NetworkManager::WirelessNetwork::Ptr wifiNet = + checkWifiNetExist(connSettingInfo.m_ssid, connSettingInfo.m_ifaceName); + if (wifiNet.isNull()) { + QString errorMessage = "the ssid " + connSettingInfo.m_ssid + + " is not exsit in " + connSettingInfo.m_ifaceName; + qWarning()<referenceAccessPoint(); + NetworkManager::ConnectionSettings::Ptr connSetting = + assembleWirelessSettings(accessPointPtr, connSettingInfo, WpaEap, false); + setIpv4AndIpv6Setting(connSetting, connSettingInfo); + assembleEapMethodPeapSettings(connSetting, peapInfo); + + QDBusPendingCallWatcher * watcher; + watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(connSetting->toMap()), this}; + connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { + if (watcher->isError() || !watcher->isValid()) { + QString errorMessage = tr("create wireless peap connection failed: ") + watcher->error().message(); + qWarning()<createConnectionError(errorMessage); + } + watcher->deleteLater(); + }); +} + +void KyWirelessConnectOperation::addTtlsConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodTtlsInfo &ttlsInfo) +{ + NetworkManager::WirelessNetwork::Ptr wifiNet = + checkWifiNetExist(connSettingInfo.m_ssid, connSettingInfo.m_ifaceName); + if (wifiNet.isNull()) { + QString errorMessage = "the ssid " + connSettingInfo.m_ssid + + " is not exsit in " + connSettingInfo.m_ifaceName; + qWarning()<referenceAccessPoint(); + NetworkManager::ConnectionSettings::Ptr connSetting = + assembleWirelessSettings(accessPointPtr, connSettingInfo, WpaEap, false); + setIpv4AndIpv6Setting(connSetting, connSettingInfo); + assembleEapMethodTtlsSettings(connSetting, ttlsInfo); + + QDBusPendingCallWatcher * watcher; + watcher = new QDBusPendingCallWatcher{NetworkManager::addConnection(connSetting->toMap()), this}; + connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher * watcher) { + if (watcher->isError() || !watcher->isValid()) { + QString errorMessage = tr("create wireless ttls connection failed: ") + watcher->error().message(); + qWarning()<createConnectionError(errorMessage); + } + watcher->deleteLater(); + }); + + return; +} + +void KyWirelessConnectOperation::setWirelessAutoConnect(const QString &uuid, bool bAutoConnect) +{ + NetworkManager::Connection::Ptr connectPtr = + NetworkManager::findConnectionByUuid(uuid); + if (nullptr == connectPtr) { + QString errorMessage = tr("it can not find connection") + uuid; + qWarning()<settings(); + setAutoConnect(connectionSettings, bAutoConnect); + connectPtr->update(connectionSettings->toMap()); +} + +QString KyWirelessConnectOperation::getPsk(const QString &connectUuid) +{ + NetworkManager::Connection::Ptr connectPtr = + NetworkManager::findConnectionByUuid(connectUuid); + if (connectPtr.isNull()) { + QString errorMessage = tr("it can not find connection") + connectUuid; + qWarning()< reply = connectPtr->secrets(PSK_SETTING_NAME); + QMap map(reply.value()); + if (map.contains("802-11-wireless-security") + && map.value("802-11-wireless-security").contains("psk")) { + QString psk = map.value("802-11-wireless-security").value("psk").toString(); + return psk; + } + return ""; +} + +QString KyWirelessConnectOperation::getPrivateKeyPassword(const QString &connectUuid) +{ + NetworkManager::Connection::Ptr connectPtr = + NetworkManager::findConnectionByUuid(connectUuid); + if (connectPtr.isNull()) { + QString errorMessage = tr("it can not find connection") + connectUuid; + qWarning()< reply = connectPtr->secrets(PRIVATE_PSK_SETTING_NAME); + QMap map(reply.value()); + if (map.contains("802-1x") + && map.value("802-1x").contains("private-key-password")) { + QString psk = map.value("802-1x").value("private-key-password").toString(); + return psk; + } + return ""; +} + +QString KyWirelessConnectOperation::get8021xPassword(const QString &connectUuid) +{ + NetworkManager::Connection::Ptr connectPtr = + NetworkManager::findConnectionByUuid(connectUuid); + if (connectPtr.isNull()) { + QString errorMessage = tr("it can not find connection") + connectUuid; + qWarning()< reply = connectPtr->secrets(PRIVATE_PSK_SETTING_NAME); + QMap map(reply.value()); + if (map.contains("802-1x") && map.value("802-1x").contains("password")) + { + QString psk = map.value("802-1x").value("password").toString(); + return psk; + } + return ""; +} + +void KyWirelessConnectOperation::updateIpv4AndIpv6SettingInfo(const QString &uuid, const KyConnectSetting &connectSettingsInfo) +{ + NetworkManager::Connection::Ptr connectPtr = + NetworkManager::findConnectionByUuid(uuid); + if (nullptr == connectPtr) { + QString errorMessage = tr("it can not find connection") + uuid; + qWarning()<settings(); + + setIpv4AndIpv6Setting(connectionSettings,connectSettingsInfo); + connectPtr->update(connectionSettings->toMap()); + return; +} + +void KyWirelessConnectOperation::updateWirelessPersonalConnect(const QString &uuid, const KyWirelessConnectSetting &connSettingInfo, bool bPwdChange) +{ + NetworkManager::Connection::Ptr connectPtr = + NetworkManager::findConnectionByUuid(uuid); + if (nullptr == connectPtr) { + QString errorMessage = tr("it can not find connection") + uuid; + qWarning()<settings(); + + NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett + = connectionSettings->setting(NetworkManager::Setting::Security8021x).dynamicCast(); + wifi_8021x_sett->setInitialized(false); + + updateWirelessSecu(connectionSettings, connSettingInfo, bPwdChange); + connectPtr->update(connectionSettings->toMap()); + return; +} + +void KyWirelessConnectOperation::updateWirelessEnterPriseTlsConnect(const QString &uuid, const KyEapMethodTlsInfo &tlsInfo) +{ + NetworkManager::Connection::Ptr connectPtr = + NetworkManager::findConnectionByUuid(uuid); + if (connectPtr.isNull()) { + QString errorMessage = tr("it can not find connection") + uuid; + qWarning()<settings(); + + setWirelessSecuWpaXEap(connectionSettings); + modifyEapMethodTlsSettings(connectionSettings, tlsInfo); + connectPtr->update(connectionSettings->toMap()); + return; +} + +void KyWirelessConnectOperation::updateWirelessEnterPrisePeapConnect(const QString &uuid, const KyEapMethodPeapInfo &peapInfo) +{ + NetworkManager::Connection::Ptr connectPtr = + NetworkManager::findConnectionByUuid(uuid); + if (nullptr == connectPtr) { + QString errorMessage = tr("it can not find connection") + uuid; + qWarning()<settings(); + + setWirelessSecuWpaXEap(connectionSettings); + modifyEapMethodPeapSettings(connectionSettings, peapInfo); + connectPtr->update(connectionSettings->toMap()); + return; +} + +void KyWirelessConnectOperation::updateWirelessEnterPriseTtlsConnect(const QString &uuid, const KyEapMethodTtlsInfo &ttlsInfo) +{ + NetworkManager::Connection::Ptr connectPtr = + NetworkManager::findConnectionByUuid(uuid); + if (nullptr == connectPtr) { + QString errorMessage = tr("it can not find connection") + uuid; + qWarning()<settings(); + + setWirelessSecuWpaXEap(connectionSettings); + modifyEapMethodTtlsSettings(connectionSettings, ttlsInfo); + connectPtr->update(connectionSettings->toMap()); + return; +} + +void KyWirelessConnectOperation::addAndActiveWirelessConnect(KyWirelessConnectSetting &connSettingInfo, KySecuType &type) +{ + KyKeyMgmt mgmt; + if (type == NONE) { + mgmt = WpaNone; + } else if (type == WPA_AND_WPA2_PERSONAL) { + mgmt = WpaPsk; + } else if (type == WPA3_PERSONAL) { + mgmt = SAE; + } else { + return; + } + + QString devIface = connSettingInfo.m_ifaceName; + QString conn_uni, dev_uni, conn_name, spec_object; + NMVariantMapMap map_settings; + + //检测wifi是否存在 + NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, devIface); + if (!connSettingInfo.isHidden && wifiNet.isNull()) { + QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + devIface; + qWarning() << errorMessage; + Q_EMIT activateConnectionError(errorMessage); + return; + } + //配置生成 + auto dev = m_networkResourceInstance->findDeviceByName(devIface); + if (dev.isNull()) { + return; + } + + dev_uni = dev->uni(); + auto spec_dev = dev->as(); + if (!connSettingInfo.isHidden) { + //非隐藏wifi + auto access_point = wifiNet->referenceAccessPoint(); + conn_uni = access_point->uni(); + conn_name = access_point->ssid(); + spec_object = conn_uni; + + NetworkManager::WirelessSecurityType sec_type = NetworkManager::findBestWirelessSecurity(spec_dev->wirelessCapabilities() + , true, (spec_dev->mode() == NetworkManager::WirelessDevice::Adhoc) + , access_point->capabilities(), access_point->wpaFlags(), access_point->rsnFlags()); + NetworkManager::ConnectionSettings::Ptr settings = nullptr; + switch (sec_type) + { + case NetworkManager::UnknownSecurity: + qWarning() << QStringLiteral("unknown security to use for '%1'").arg(conn_name); + case NetworkManager::NoneSecurity: + //nothing to do + break; + case NetworkManager::WpaPsk: + case NetworkManager::Wpa2Psk: + settings = assembleWpaXPskSettings(access_point, connSettingInfo.m_psk, connSettingInfo.m_isAutoConnect); + if (nullptr != settings) { + map_settings = settings->toMap(); + } else { + qWarning() << QStringLiteral("connection settings assembly for '%1' failed, abandoning activation...").arg(conn_name); + return; + } + break; + case NetworkManager::SAE: + settings = assembleSaeSettings(access_point, connSettingInfo.m_psk, connSettingInfo.m_isAutoConnect); + if (nullptr != settings) { + map_settings = settings->toMap(); + } else { + qWarning() << QStringLiteral("connection settings assembly for '%1' failed, abandoning activation...").arg(conn_name); + return; + } + break; + //TODO:其他加密类型 + default: + qWarning() << "addAndActiveWirelessConnect not support"; + return; + } + } else { + //隐藏wifi + map_settings = assembleWirelessSettings(nullptr, connSettingInfo, mgmt, connSettingInfo.isHidden)->toMap(); + } + //激活 + QDBusPendingCallWatcher * watcher; + watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(map_settings, dev_uni, spec_object), this}; + connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { + if (watcher->isError() || !watcher->isValid()) { + QString errorMessage = watcher->error().message(); + qWarning() << "activation of connection failed " << errorMessage; + } + watcher->deleteLater(); + }); +} + +void KyWirelessConnectOperation::addAndActiveWirelessEnterPriseTlsConnect(KyEapMethodTlsInfo &info, KyWirelessConnectSetting &connSettingInfo) +{ + QString devIface = connSettingInfo.m_ifaceName; + QString conn_uni, dev_uni, spec_object; + NMVariantMapMap map_settings; + NetworkManager::AccessPoint::Ptr accessPointPtr = nullptr; + + if (!connSettingInfo.isHidden) { + NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, devIface); + if (wifiNet.isNull()) { + QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + devIface; + qWarning()<referenceAccessPoint(); + conn_uni = accessPointPtr->uni(); + spec_object = conn_uni; + } + + auto dev = m_networkResourceInstance->findDeviceByName(devIface); + if (dev.isNull()) { + return; + } + dev_uni = dev->uni(); + + NetworkManager::ConnectionSettings::Ptr settings = assembleWirelessSettings(accessPointPtr, connSettingInfo, WpaEap, connSettingInfo.isHidden); + assembleEapMethodTlsSettings(settings, info); + + if(settings.isNull()) { + qWarning() << "assembleEapMethodTlsSettings failed"; + return; + } + + map_settings = settings->toMap(); + + QDBusPendingCallWatcher * watcher; + watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(map_settings, dev_uni, spec_object), this}; + connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { + if (watcher->isError() || !watcher->isValid()) { + QString errorMessage = watcher->error().message(); + qWarning() << "addAndActiveWirelessEnterPriseTlsConnect failed " << errorMessage; + } + watcher->deleteLater(); + }); + +} + +void KyWirelessConnectOperation::addAndActiveWirelessEnterPrisePeapConnect(KyEapMethodPeapInfo &info, KyWirelessConnectSetting &connSettingInfo) +{ + qDebug() << "addAndActiveWirelessEnterPrisePeapConnect"; + QString devIface = connSettingInfo.m_ifaceName; + QString conn_uni, dev_uni, spec_object; + NMVariantMapMap map_settings; + NetworkManager::AccessPoint::Ptr accessPointPtr = nullptr; + + if (!connSettingInfo.isHidden) { + NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, devIface); + if (wifiNet.isNull()) { + QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + devIface; + qWarning() << errorMessage; + Q_EMIT activateConnectionError(errorMessage); + return; + } + + accessPointPtr = wifiNet->referenceAccessPoint(); + conn_uni = accessPointPtr->uni(); + spec_object = conn_uni; + } + + auto dev = m_networkResourceInstance->findDeviceByName(devIface); + if (dev.isNull()) { + return; + } + dev_uni = dev->uni(); + + NetworkManager::ConnectionSettings::Ptr settings = + assembleWirelessSettings(accessPointPtr, connSettingInfo, WpaEap, connSettingInfo.isHidden); + assembleEapMethodPeapSettings(settings, info); + + if(settings.isNull()) { + qWarning() << "assembleEapMethodPeapSettings failed"; + return; + } + map_settings = settings->toMap(); + + QDBusPendingCallWatcher * watcher; + watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(map_settings, dev_uni, spec_object), this}; + connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { + if (watcher->isError() || !watcher->isValid()) { + QString errorMessage = watcher->error().message(); + qWarning() << "addAndActiveWirelessEnterPrisePeapConnect failed " << errorMessage; + } + watcher->deleteLater(); + }); + +} + +void KyWirelessConnectOperation::addAndActiveWirelessEnterPriseTtlsConnect(KyEapMethodTtlsInfo &info, KyWirelessConnectSetting &connSettingInfo) +{ + QString devIface = connSettingInfo.m_ifaceName; + QString conn_uni, dev_uni, spec_object; + NMVariantMapMap map_settings; + NetworkManager::AccessPoint::Ptr accessPointPtr = nullptr; + + if (!connSettingInfo.isHidden) { + NetworkManager::WirelessNetwork::Ptr wifiNet = checkWifiNetExist(connSettingInfo.m_ssid, devIface); + if (wifiNet.isNull()) { + QString errorMessage = "the ssid " + connSettingInfo.m_ssid + " is not exsit in " + devIface; + qWarning()<referenceAccessPoint(); + conn_uni = accessPointPtr->uni(); + spec_object = conn_uni; + } + + auto dev = m_networkResourceInstance->findDeviceByName(devIface); + if (dev.isNull()) { + return; + } + dev_uni = dev->uni(); + + NetworkManager::ConnectionSettings::Ptr settings = + assembleWirelessSettings(accessPointPtr, connSettingInfo, WpaEap, connSettingInfo.isHidden); + assembleEapMethodTtlsSettings(settings, info); + + if(settings.isNull()) { + qWarning() << "assembleEapMethodTtlsSettings failed"; + return; + } + + map_settings = settings->toMap(); + + QDBusPendingCallWatcher * watcher; + watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(map_settings, dev_uni, spec_object), this}; + connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { + if (watcher->isError() || !watcher->isValid()) { + QString errorMessage = watcher->error().message(); + qWarning() << "addAndActiveWirelessEnterPriseTtlsConnect failed " << errorMessage; + } + watcher->deleteLater(); + }); +} + +bool KyWirelessConnectOperation::getConnSecretFlags(QString &connUuid, NetworkManager::Setting::SecretFlags &flag) +{ + NetworkManager::Connection::Ptr conn; + conn = m_networkResourceInstance->findConnectByUuid(connUuid); + if (conn.isNull()) { + qWarning() <<"get failed"; + return false; + } + + NetworkManager::WirelessSecuritySetting::Ptr security_sett + = conn->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); + flag = security_sett->pskFlags(); + return true; +} + +NetworkManager::ConnectionSettings::Ptr + KyWirelessConnectOperation::createWirelessApSetting(const QString apSsid, + const QString apPassword, + const QString apDevice, + const QString wirelessBand) +{ + NetworkManager::ConnectionSettings::Ptr connectionSettings = + NetworkManager::ConnectionSettings::Ptr(new NetworkManager::ConnectionSettings(NetworkManager::ConnectionSettings::Wireless)); + connectionSettings->setId(apSsid); + connectionSettings->setUuid(NetworkManager::ConnectionSettings::createNewUuid()); + connectionSettings->setAutoconnect(false); + connectionSettings->setAutoconnectPriority(0); + connectionSettings->setInterfaceName(apDevice); + //Note: workaround for wrongly (randomly) initialized gateway-ping-timeout + connectionSettings->setGatewayPingTimeout(0); + + NetworkManager::Ipv4Setting::Ptr ipv4Setting = connectionSettings->setting(NetworkManager::Setting::Ipv4).dynamicCast(); + ipv4Setting->setInitialized(true); + ipv4Setting->setMethod(NetworkManager::Ipv4Setting::Shared); + + NetworkManager::Ipv6Setting::Ptr ipv6Setting = connectionSettings->setting(NetworkManager::Setting::Ipv6).dynamicCast(); + ipv6Setting->setInitialized(true); + ipv6Setting->setMethod(NetworkManager::Ipv6Setting::Ignored); + + NetworkManager::WirelessSetting::Ptr wirelessSetting + = connectionSettings->setting(NetworkManager::Setting::Wireless).dynamicCast(); + wirelessSetting->setInitialized(true); + wirelessSetting->setSsid(apSsid.toUtf8()); + wirelessSetting->setMode(NetworkManager::WirelessSetting::NetworkMode::Ap); + wirelessSetting->setSecurity("802-11-wireless-security"); + if (wirelessBand == WIFI_BAND_2_4GHZ) { + wirelessSetting->setBand(NetworkManager::WirelessSetting::FrequencyBand::Bg); + } else if (wirelessBand == WIFI_BAND_5GHZ) { + wirelessSetting->setBand(NetworkManager::WirelessSetting::FrequencyBand::A); + } else { + qWarning()<<"[KyWirelessConnectOperation] the band type undefined"<setBand(NetworkManager::WirelessSetting::FrequencyBand::Automatic); + } + + + NetworkManager::WirelessSecuritySetting::Ptr wirelessSecuritySetting + = connectionSettings->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); + if (apPassword.isEmpty()) { + wirelessSecuritySetting->setInitialized(false); + } else { + wirelessSecuritySetting->setInitialized(true); + wirelessSecuritySetting->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaPsk); + wirelessSecuritySetting->setPsk(apPassword); + } + + return connectionSettings; +} + +void KyWirelessConnectOperation::updateWirelessApSetting( + NetworkManager::Connection::Ptr apConnectPtr, + const QString apName, const QString apPassword, + const QString apDevice, const QString wirelessBand) + +{ + NetworkManager::ConnectionSettings::Ptr apConnectSettingPtr = apConnectPtr->settings(); + apConnectSettingPtr->setId(apName); + apConnectSettingPtr->setInterfaceName(apDevice); + apConnectSettingPtr->setAutoconnect(false); + + NetworkManager::WirelessSetting::Ptr wirelessSetting + = apConnectSettingPtr->setting(NetworkManager::Setting::Wireless).dynamicCast(); + wirelessSetting->setInitialized(true); + wirelessSetting->setSsid(apName.toUtf8()); + if (wirelessBand == WIFI_BAND_2_4GHZ) { + wirelessSetting->setBand(NetworkManager::WirelessSetting::FrequencyBand::Bg); + } else if (wirelessBand == WIFI_BAND_5GHZ) { + wirelessSetting->setBand(NetworkManager::WirelessSetting::FrequencyBand::A); + } else { + qWarning()<<"[KyWirelessConnectOperation] the band type undefined"<setBand(NetworkManager::WirelessSetting::FrequencyBand::Automatic); + } + + + NetworkManager::WirelessSecuritySetting::Ptr wirelessSecuritySetting + = apConnectSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); + if (apPassword.isEmpty()) { + wirelessSecuritySetting->setInitialized(false); + } else { + wirelessSecuritySetting->setInitialized(true); + wirelessSecuritySetting->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaPsk); + wirelessSecuritySetting->setPsk(apPassword); + } + + apConnectPtr->update(apConnectSettingPtr->toMap()); +} + +void KyWirelessConnectOperation::activeWirelessAp(const QString apUuid, const QString apName, + const QString apPassword, const QString apDevice, + const QString wirelessBand) + +{ + //1、检查连接是否存在 + NetworkManager::Connection::Ptr connectPtr = m_networkResourceInstance->findConnectByUuid(apUuid); + if (nullptr == connectPtr) { + NetworkManager::Device::Ptr devicePtr = m_networkResourceInstance->findDeviceByName(apDevice); + if (devicePtr.isNull()) { + QString errorMsg ="Create hotspot faild. " + apDevice + " is not existed"; + qWarning()<< errorMsg; + return; + } + + QString deviceIdentifier = devicePtr->uni(); + + NetworkManager::ConnectionSettings::Ptr apConnectSettingPtr = + createWirelessApSetting(apName, apPassword, apDevice, wirelessBand); + QString specificObject = ""; + QDBusPendingCallWatcher * watcher; + watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(apConnectSettingPtr->toMap(), deviceIdentifier, specificObject), this}; + connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) { + if (watcher->isError() || !watcher->isValid()) { + QString errorMsg = "Create hotspot faild. " + watcher->error().message(); + qWarning() << errorMsg; + } + watcher->deleteLater(); + }); + } else { + updateWirelessApSetting(connectPtr, apName, apPassword, apDevice, wirelessBand); + QTimer::singleShot(500, this, [=](){ + activateApConnectionByUuid(apUuid, apDevice); + }); + } +} + +void KyWirelessConnectOperation::deactiveWirelessAp(const QString apName, const QString apUuid) +{ + deactivateConnection(apUuid); +} + +//private +NetworkManager::WirelessNetwork::Ptr KyWirelessConnectOperation::checkWifiNetExist(QString ssid, QString devName) +{ + NetworkManager::WirelessNetwork::List wifiNetList = m_networkResourceInstance->getWifiNetworkList(); + + for (auto const & net : wifiNetList) { + auto dev = m_networkResourceInstance->findDeviceByUni(net->device()); + if (dev == nullptr) { + continue; + } + + if (dev->type() != NetworkManager::Device::Wifi || dev->interfaceName() != devName) { + continue; + } + + NetworkManager::AccessPoint::Ptr accessPointPtr = net->referenceAccessPoint(); + QByteArray rawSsid = accessPointPtr->rawSsid(); + QString wifiSsid = getSsidFromByteArray(rawSsid); + + if (ssid == wifiSsid) { + return net; + } + } + + return nullptr; +} + +KyKeyMgmt KyWirelessConnectOperation::getConnectKeyMgmt(const QString &uuid) +{ + NetworkManager::Connection::Ptr connectPtr = + NetworkManager::findConnectionByUuid(uuid); + if (connectPtr.isNull()) { + return KyKeyMgmt::Unknown; + } + + NetworkManager::WirelessSecuritySetting::Ptr security_sett + = connectPtr->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); + + if(security_sett.isNull()) { + return KyKeyMgmt::Unknown; + } + return (KyKeyMgmt)security_sett->keyMgmt(); +} + +KySecuType KyWirelessConnectOperation::getConnectSecuType(const QString &uuid) +{ + KyKeyMgmt type = getConnectKeyMgmt(uuid); + if (type == WpaNone) { + return KySecuType::NONE; + } else if (type == WpaPsk) { + return KySecuType::WPA_AND_WPA2_PERSONAL; + } else if (type == SAE) { + return KySecuType::WPA3_PERSONAL; + } else if (type == WpaEap) { + return KySecuType::WPA_AND_WPA2_ENTERPRISE; + } else { + qWarning() << "KeyMgmt not support now " << type; + return KySecuType::UNKNOWN; + } +} + +void KyWirelessConnectOperation::updateWirelessSecu(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyWirelessConnectSetting &connSettingInfo, bool bPwdChange) +{ + NetworkManager::WirelessSecuritySetting::Ptr security_sett + = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); + + KyKeyMgmt type = getConnectKeyMgmt(connSettingPtr->uuid()); + if (type == WpaNone) { + security_sett->setInitialized(false); + return; + } else { + security_sett->setInitialized(true); + } + security_sett->setKeyMgmt((NetworkManager::WirelessSecuritySetting::KeyMgmt)type); + if (bPwdChange) { + security_sett->setPsk(connSettingInfo.m_psk); + NetworkManager::Setting::SecretFlags flag = NetworkManager::Setting::None; + security_sett->setPskFlags(flag); + } +} + +void KyWirelessConnectOperation::setWirelessSecuWpaXEap(NetworkManager::ConnectionSettings::Ptr connSettingPtr) +{ + NetworkManager::WirelessSecuritySetting::Ptr security_sett + = connSettingPtr->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); + + security_sett->setInitialized(true); + security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::KeyMgmt::WpaEap); +} + +void KyWirelessConnectOperation::setIpv4AndIpv6Setting(NetworkManager::ConnectionSettings::Ptr connSetting, const KyConnectSetting &connSettingInfo) +{ + NetworkManager::Ipv4Setting::Ptr ipv4Setting = connSetting->setting(NetworkManager::Setting::Ipv4).dynamicCast(); + ipv4SettingSet(ipv4Setting, connSettingInfo); + + NetworkManager::Ipv6Setting::Ptr ipv6Setting = connSetting->setting(NetworkManager::Setting::Ipv6).dynamicCast(); + ipv6SettingSet(ipv6Setting, connSettingInfo); +} + +void KyWirelessConnectOperation::activateApConnectionByUuid(const QString apUuid, const QString apDevice) +{ + QString connectPath = ""; + QString deviceIdentifier = ""; + QString connectName = ""; + QString specificObject = ""; + + NetworkManager::Connection::Ptr connectPtr = m_networkResourceInstance->findConnectByUuid(apUuid); + if (connectPtr.isNull()) + { + QString errorMessage = tr("Create hotspot faild.UUID is empty, its name") + apUuid; + qWarning() << errorMessage; + Q_EMIT activateConnectionError(errorMessage); + return; + } + connectPath = connectPtr->path(); + connectName = connectPtr->name(); + + auto dev = m_networkResourceInstance->findDeviceByName(apDevice); + if (!dev.isNull()) { + deviceIdentifier = dev->uni(); + } + + if (deviceIdentifier.isEmpty()) { + QString errorMessage = tr("Create hotspot faild.Device Identifier is empty, its name") + apDevice; + qWarning() << errorMessage; + Q_EMIT activateConnectionError(errorMessage); + return ; + } + + QDBusPendingCallWatcher * watcher; + watcher = new QDBusPendingCallWatcher{NetworkManager::activateConnection(connectPath, deviceIdentifier, specificObject), this}; + connect(watcher, &QDBusPendingCallWatcher::finished, [this, connectName, apDevice] (QDBusPendingCallWatcher * watcher) { + if (watcher->isError() || !watcher->isValid()) { + QString errorMessage = tr("Create hotspot faild. ") + watcher->error().message(); + qWarning()<activateConnectionError(errorMessage); + } else { + qWarning()<<"active wired connect complete."; + } + + watcher->deleteLater(); + }); +} + +bool KyWirelessConnectOperation::isApConnection(QString uuid) +{ + NetworkManager::Connection::Ptr connectPtr = nullptr; + + connectPtr = m_networkResourceInstance->findConnectByUuid(uuid); + return m_networkResourceInstance->isApConnection(connectPtr); +} diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessconnectoperation.h b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessconnectoperation.h new file mode 100644 index 00000000..90bacef7 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessconnectoperation.h @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYWIRELESSCONNECTOPERATION_H +#define KYWIRELESSCONNECTOPERATION_H + +#include +#include +#include "kyenterpricesettinginfo.h" +#include "kylinconnectoperation.h" +#include "kyenterpricesettinginfo.h" + +const QByteArray GSETTINGS_SCHEMA = "org.ukui.kylin-nm.switch"; +const QString WIRELESS_SWITCH = "wirelessswitch"; + +const QString WIFI_BAND_2_4GHZ = "2.4Ghz"; +const QString WIFI_BAND_5GHZ = "5Ghz"; + +enum KySecuType { + UNKNOWN, + NONE, + WPA_AND_WPA2_PERSONAL, + WPA_AND_WPA2_ENTERPRISE, + WPA3_PERSONAL, +}; + +enum KyKeyMgmt { + Unknown = -1, + Wep, Ieee8021x, + WpaNone, + WpaPsk, + WpaEap, + SAE +}; + +class KyWirelessConnectSetting : public KyConnectSetting +{ +public: + QString m_ssid; + QString m_psk; + NetworkManager::Setting::SecretFlags m_secretFlag = NetworkManager::Setting::SecretFlagType::None; + bool isHidden = false; +}; + + +class KyWirelessConnectOperation : public KyConnectOperation +{ + Q_OBJECT +public: + explicit KyWirelessConnectOperation(QObject *parent = nullptr); + +public: + + void requestWirelessScan(); + //获取密码保存策略 + bool getConnSecretFlags(QString &connUuid, NetworkManager::Setting::SecretFlags &); + + //获取KeyMgmt + KyKeyMgmt getConnectKeyMgmt(const QString &uuid); + KySecuType getConnectSecuType(const QString &uuid); + + //激活连接 + void activeWirelessConnect(QString , QString); + //断开连接 + void deActivateWirelessConnection(const QString activeConnectName, const QString &activeConnectUuid); + //新增普通连接 + void addConnect(const KyWirelessConnectSetting &connSettingInfo, KySecuType &type); + //新增TLS连接 + void addTlsConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodTlsInfo &tlsinfo); + //新增PEAP连接 + void addPeapConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodPeapInfo &peapInfo); + //新增TTLS连接 + void addTtlsConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodTtlsInfo &ttlsInfo); + //新增连接并激活(普通wifi) + void addAndActiveWirelessConnect(KyWirelessConnectSetting &connSettingInfo, KySecuType &type); + + //新增连接并激活(企业wifi) + void addAndActiveWirelessEnterPriseTlsConnect(KyEapMethodTlsInfo &info, KyWirelessConnectSetting &connSettingInfo); + void addAndActiveWirelessEnterPrisePeapConnect(KyEapMethodPeapInfo &info, KyWirelessConnectSetting &connSettingInfo); + void addAndActiveWirelessEnterPriseTtlsConnect(KyEapMethodTtlsInfo &info, KyWirelessConnectSetting &connSettingInfo); + //属性页 page1 AutoConnect + void setWirelessAutoConnect(const QString &uuid, bool bAutoConnect); + //属性页 page2 page3 ipv6 + void updateIpv4AndIpv6SettingInfo(const QString &uuid, const KyConnectSetting &connectSettingsInfo); + //属性页 page4 wifi Security + //连接修改(安全改为个人/None) + void updateWirelessPersonalConnect(const QString &uuid, const KyWirelessConnectSetting &connSettingInfo, bool bPwdChange); + //连接修改(安全改为改为企业) + void updateWirelessEnterPriseTlsConnect(const QString &uuid, const KyEapMethodTlsInfo &tlsinfo); + void updateWirelessEnterPrisePeapConnect(const QString &uuid, const KyEapMethodPeapInfo &peapInfo); + void updateWirelessEnterPriseTtlsConnect(const QString &uuid, const KyEapMethodTtlsInfo &ttlsInfo); + //忘记 + void deleteWirelessConnect(const QString &connectUuid); + //获取密码 + QString getPsk(const QString &connectUuid); + QString getPrivateKeyPassword(const QString &connectUuid); + QString get8021xPassword(const QString &connectUuid); + + void activeWirelessAp(const QString apUuid, const QString apName, + const QString apPassword, const QString apDevice, + const QString wirelessBand); + void deactiveWirelessAp(const QString apName, const QString apUuid); + + bool isApConnection(QString uuid); + +private: + NetworkManager::ConnectionSettings::Ptr createWirelessApSetting(const QString apSsid, + const QString apPassword, const QString apDevice, const QString wirelessBand); + void updateWirelessApSetting(NetworkManager::Connection::Ptr apConnectPtr, const QString apName, + const QString apPassword, const QString apDevice, const QString wirelessBand); + + NetworkManager::WirelessNetwork::Ptr checkWifiNetExist(QString ssid, QString devName); + void updateWirelessSecu(NetworkManager::ConnectionSettings::Ptr connSettingPtr, const KyWirelessConnectSetting &connSettingInfo, bool bPwdChange = false); + void setIpv4AndIpv6Setting(NetworkManager::ConnectionSettings::Ptr connSetting, const KyConnectSetting &connSettingInfo); + void setWirelessSecuWpaXEap(NetworkManager::ConnectionSettings::Ptr connSettingPtr); + void activateApConnectionByUuid(const QString apUuid, const QString apDevice); +}; + +#endif // KYWIRELESSCONNECTOPERATION_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessnetitem.cpp b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessnetitem.cpp new file mode 100644 index 00000000..e267702b --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessnetitem.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include "kywirelessnetitem.h" + +KyWirelessNetItem::KyWirelessNetItem() +{ + m_NetSsid = ""; + m_connectUuid = ""; + m_connectSecuType = KySecuType::NONE; + m_secuType = ""; + m_signalStrength = 0; +} diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessnetitem.h b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessnetitem.h new file mode 100644 index 00000000..87b7eaa5 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessnetitem.h @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYWIRELESSNETITEM_H +#define KYWIRELESSNETITEM_H + +#include +#include "kywirelessconnectoperation.h" + +class KyWirelessNetItem +{ +public: + QString m_NetSsid = ""; + QString m_connectUuid = ""; + QString m_dbusPath = ""; + KySecuType m_connectSecuType = KySecuType::NONE; + bool m_isApConnection = false; + QString m_secuType = ""; + int m_signalStrength = 0; +}; + +#endif // KYWIRELESSNETITEM_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessnetresource.cpp b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessnetresource.cpp new file mode 100644 index 00000000..d2535187 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessnetresource.cpp @@ -0,0 +1,601 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include "kywirelessnetresource.h" +#include "kylinnetworkmanagerutil.h" + +#define LOG_FLAG "[KyWirelessNetResource]" + +#define PSK_SETTING_NAME "802-11-wireless-security" +#define PRIVATE_PSK_SETTING_NAME "802-1x" + +static bool subWifiListSort(const KyWirelessNetItem info1, const KyWirelessNetItem info2) +{ + if (info1.m_connectUuid.isEmpty() == info2.m_connectUuid.isEmpty()) { + if (info1.m_signalStrength != info2.m_signalStrength) { + return info1.m_signalStrength > info2.m_signalStrength; + } else { + if (QString::compare(info1.m_NetSsid, info2.m_NetSsid, Qt::CaseInsensitive) > 0) { + return false; + } else { + return true; + } + } + } + return !info1.m_connectUuid.isEmpty(); +} + +static void wifiListSort(QList &list) +{ + qSort(list.begin(), list.end(), subWifiListSort); +} + +KyWirelessNetResource::KyWirelessNetResource(QObject *parent) : KyNetResource(parent) +{ + qRegisterMetaType("KyWirelessNetItem&"); + qRegisterMetaType("NetworkManager::WirelessNetwork::Ptr"); + + kyWirelessNetItemListInit(); + + //无线出现/消失-->item 增删 + connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiNetworkAdded, + this, &KyWirelessNetResource::onWifiNetworkAdded); + connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiNetworkRemoved, + this, &KyWirelessNetResource::onWifiNetworkRemoved); + connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiNetworkPropertyChange, + this, &KyWirelessNetResource::onWifiNetworkPropertyChange); + connect(m_networkResourceInstance, &KyNetworkResourceManager::wifiNetworkDeviceDisappear, + this, &KyWirelessNetResource::onWifiNetworkDeviceDisappear); + + //无线配置变化-->item uuid变化 + connect(m_networkResourceInstance, &KyNetworkResourceManager::wirelessConnectionAdd, + this, &KyWirelessNetResource::onConnectionAdd); + connect(m_networkResourceInstance, &KyNetworkResourceManager::connectionRemove, + this, &KyWirelessNetResource::onConnectionRemove); + + //设备变化-->map key变化 + connect(m_networkResourceInstance, &KyNetworkResourceManager::wirelessDeviceAdd, + this, &KyWirelessNetResource::onDeviceAdd); + connect(m_networkResourceInstance, &KyNetworkResourceManager::deviceRemove, + this, &KyWirelessNetResource::onDeviceRemove); + connect(m_networkResourceInstance, &KyNetworkResourceManager::wirelessDeviceUpdate, + this, &KyWirelessNetResource::onDeviceNameUpdate); + + m_updateTimer = new QTimer(this); + m_updateTimer->start(10*1000); + connect(m_updateTimer, &QTimer::timeout, this, &KyWirelessNetResource::updateList); + +} + +//配合activeconnection 此处未单独区分已连接的wifi +void KyWirelessNetResource::getWifiNetworkList(QString devName, QList &list) +{ + list.clear(); + if (m_WifiNetworkList.isEmpty() || !m_WifiNetworkList.contains(devName)) { + return; + } else { + QMap >::iterator iter = m_WifiNetworkList.begin(); + while (iter != m_WifiNetworkList.end()) { + if (iter.key() == devName) { + list = m_WifiNetworkList[iter.key()]; + wifiListSort(list); + return; + } + iter++; + } + } +} + +void KyWirelessNetResource::kyWirelessNetItemListInit() +{ + m_WifiNetworkList.clear(); + + NetworkManager::WirelessNetwork::List m_wifiNetList = m_networkResourceInstance->getWifiNetworkList(); + for (auto const & net : m_wifiNetList) { + QString devIface = getDeviceIFace(net); + if (devIface.isEmpty()) { + continue; + } + + KyWirelessNetItem item; + wirelessNetItemInit(item, net); + if (!m_WifiNetworkList.contains(devIface)){ + QList list; + list.append(item); + m_WifiNetworkList.insert(devIface,list); + } else { + m_WifiNetworkList[devIface].append(item); + } + } + + return; +} + +void KyWirelessNetResource::wirelessNetItemInit(KyWirelessNetItem &wirelessItem, + NetworkManager::WirelessNetwork::Ptr wirelessNetPtr) +{ + if(wirelessNetPtr.isNull()) { + return; + } + + NetworkManager::AccessPoint::Ptr accessPointPtr = wirelessNetPtr->referenceAccessPoint(); + QByteArray rawSsid = accessPointPtr->rawSsid(); + wirelessItem.m_NetSsid = getSsidFromByteArray(rawSsid); + + wirelessItem.m_signalStrength = accessPointPtr->signalStrength(); + NetworkManager::AccessPoint::Capabilities cap = accessPointPtr->capabilities(); + NetworkManager::AccessPoint::WpaFlags wpaFlag = accessPointPtr->wpaFlags(); + NetworkManager::AccessPoint::WpaFlags rsnFlag = accessPointPtr->rsnFlags(); + wirelessItem.m_secuType = enumToQstring(cap, wpaFlag, rsnFlag); + QString interface = getDeviceIFace(wirelessNetPtr); + getUuidBySsid(wirelessItem.m_NetSsid, interface, wirelessItem.m_connectUuid, wirelessItem.m_dbusPath); + KyWirelessConnectOperation operation; + wirelessItem.m_connectSecuType = operation.getConnectSecuType(wirelessItem.m_connectUuid); + wirelessItem.m_isApConnection = operation.isApConnection(wirelessItem.m_connectUuid); +} + +void KyWirelessNetResource::getUuidBySsid(const QString &ssid, QString &deviceName, QString &uuid, QString &dbusPath) +{ + uuid.clear(); + dbusPath.clear(); + NetworkManager::Connection::List connectList; + + connectList.clear(); + connectList = m_networkResourceInstance->getConnectList(); + + if (connectList.empty()) { + qWarning()<<"[KyConnectResourse]"<<"get connection failed, the connect list is empty"; + return; + } + + NetworkManager::Connection::Ptr connectPtr = nullptr; + for (int index = 0; index < connectList.size(); index++) { + connectPtr = connectList.at(index); + if (connectPtr.isNull()) { + continue; + } + + if (NetworkManager::ConnectionSettings::Wireless != connectPtr->settings()->connectionType()) { + continue; + } + + QString connectInterface = connectPtr->settings()->interfaceName(); + if (!connectInterface.isEmpty() + && deviceName != connectInterface) { + continue; + } + + NetworkManager::WirelessSetting::Ptr wifi_sett + = connectPtr->settings()->setting(NetworkManager::Setting::Wireless).dynamicCast(); + if (wifi_sett->ssid() == ssid) { + uuid = connectPtr->settings()->uuid(); + dbusPath = connectPtr->path(); + } + } +} + +void KyWirelessNetResource::onWifiNetworkAdded(QString devIfaceName, QString ssid) +{ + NetworkManager::WirelessNetwork::Ptr wifi = nullptr; + NetworkManager::WirelessNetwork::List m_wifiNetList = m_networkResourceInstance->getWifiNetworkList(); + for (auto const & net : m_wifiNetList) { + if (net.isNull()) { + continue; + } + + NetworkManager::AccessPoint::Ptr accessPointPtr = net->referenceAccessPoint(); + QByteArray rawSsid = accessPointPtr->rawSsid(); + QString wifiSsid = getSsidFromByteArray(rawSsid); + + if (wifiSsid == ssid + && m_networkResourceInstance->findDeviceByUni(net->device())->interfaceName() == devIfaceName) { + wifi = net; + } + } + + if (wifi.isNull()) { + return; + } + + KyWirelessNetItem item; + wirelessNetItemInit(item, wifi); + + if (m_WifiNetworkList.contains(devIfaceName)) { + m_WifiNetworkList[devIfaceName].append(item); + } else { + QList list; + list.append(item); + m_WifiNetworkList.insert(devIfaceName,list); + } + + Q_EMIT wifiNetworkAdd(devIfaceName, item); +} + +void KyWirelessNetResource::onWifiNetworkRemoved(QString devIfaceName, QString ssid) +{ + if (m_WifiNetworkList.contains(devIfaceName)) { + int index = 0; + for ( ; index < m_WifiNetworkList.value(devIfaceName).size(); index++) { + if ( m_WifiNetworkList[devIfaceName].at(index).m_NetSsid == ssid) { + m_WifiNetworkList[devIfaceName].removeAt(index); + } + } + //remove后为空则删除 + if (m_WifiNetworkList.value(devIfaceName).isEmpty()) { + m_WifiNetworkList.remove(devIfaceName); + } + Q_EMIT wifiNetworkRemove(devIfaceName, ssid); + } +} + +void KyWirelessNetResource::onWifiNetworkPropertyChange(NetworkManager::WirelessNetwork::Ptr net) +{ + if (nullptr == net) { + return; + } + + NetworkManager::AccessPoint::Ptr accessPointPtr = net->referenceAccessPoint(); + QByteArray rawSsid = accessPointPtr->rawSsid(); + QString wifiSsid = getSsidFromByteArray(rawSsid); + + QString devIface = m_networkResourceInstance->findDeviceByUni(net->device())->interfaceName(); + if (m_WifiNetworkList.contains(devIface)) { + QList::iterator iter = m_WifiNetworkList[devIface].begin(); + while (iter != m_WifiNetworkList[devIface].end()) { + if (iter->m_NetSsid == wifiSsid) { + if (iter->m_signalStrength != net->signalStrength()) { + iter->m_signalStrength = net->signalStrength(); + } + + QString secuType = enumToQstring(accessPointPtr->capabilities(), + accessPointPtr->wpaFlags(), + accessPointPtr->rsnFlags()); + if (iter->m_secuType != secuType) { + iter->m_secuType = secuType; + KyWirelessNetItem item = *iter; + Q_EMIT wifiNetworkUpdate(devIface, wifiSsid, item); + } + break; + } + iter++; + } + } +} + +void KyWirelessNetResource::onWifiNetworkDeviceDisappear() +{ + qWarning() << "wifiNetworkDeviceDisappear!!!!!!!!!"; + for (int i = 0; i < m_WifiNetworkList.keys().size(); ++i) { + Q_EMIT deviceRemove(m_WifiNetworkList.keys().at(i)); + } + kyWirelessNetItemListInit(); +} + +//对应属性页-->安全 +bool KyWirelessNetResource::getNormalWifiConnectSecuInfo(QString &uuid, KyWpaPasswordInfo &info) +{ + KyWirelessConnectOperation operation; + info.pwd = operation.getPsk(uuid); + return operation.getConnSecretFlags(uuid, info.flag); +} + +bool KyWirelessNetResource::getEnterpiseEapMethod(const QString &uuid, KyEapMethodType &type) +{ + NetworkManager::Connection::Ptr connectPtr = + NetworkManager::findConnectionByUuid(uuid); + if (connectPtr.isNull()) { + qWarning() << "getEnterpiseEapMethod faild.Can't find uuid = " << uuid; + return false; + } + + KyWirelessConnectOperation operation; + KyKeyMgmt keyMgmt = operation.getConnectKeyMgmt(uuid); + if (keyMgmt != WpaEap) { + qWarning() << "getEnterpiseEapMethod but not WpaEap.it's " << keyMgmt; + return false; + } + + NetworkManager::ConnectionSettings::Ptr connectionSettings = connectPtr->settings(); + + NetworkManager::Security8021xSetting::Ptr wifi_8021x_sett + = connectionSettings->setting(NetworkManager::Setting::Security8021x).dynamicCast(); + + QList list = wifi_8021x_sett->eapMethods(); + + if (list.contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodTls)) { + type = TLS; + } else if (list.contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodPeap)) { + type = PEAP; + } else if (list.contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodTtls)) { + type = TTLS; + } + return true; +} + + +bool KyWirelessNetResource::getEnterPriseInfoTls(QString &uuid, KyEapMethodTlsInfo &info) +{ + NetworkManager::Connection::Ptr conn = m_networkResourceInstance->findConnectByUuid(uuid); + if (conn.isNull()) { + qWarning() << LOG_FLAG << "modifyEnterPriseInfoTls connection missing"; + return false; + } + + NetworkManager::WirelessSecuritySetting::Ptr security_sett = + conn->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); + if (security_sett.isNull()) { + qWarning()<< LOG_FLAG << "don't have WirelessSecurity connection"; + return false; + } + if (security_sett->keyMgmt() != NetworkManager::WirelessSecuritySetting::WpaEap) { + return false; + } + NetworkManager::Security8021xSetting::Ptr setting = + conn->settings()->setting(NetworkManager::Setting::Security8021x).dynamicCast(); + if (setting.isNull()) { + qWarning()<< LOG_FLAG << "don't have Security8021x connection"; + return false; + } + + + info.identity = setting->identity(); + info.domain = setting->domainSuffixMatch(); + info.caCertPath = setting->caPath(); + if (info.caCertPath.left(7) == "file://") { + info.caCertPath = info.caCertPath.mid(7); + } + + info.clientCertPath = setting->clientCertificate(); + if (info.clientCertPath.left(7) == "file://") { + info.clientCertPath = info.clientCertPath.mid(7); + } + + info.clientPrivateKey = QString(setting->privateKey()); + if (info.clientPrivateKey.left(7) == "file://") { + info.clientPrivateKey = info.clientPrivateKey.mid(7); + } + + info.m_privateKeyPWDFlag = setting->privateKeyPasswordFlags(); + if (!info.m_privateKeyPWDFlag) { + KyWirelessConnectOperation operation; + info.clientPrivateKeyPWD = operation.getPrivateKeyPassword(conn->uuid()); + } + + return true; +} + +bool KyWirelessNetResource::getEnterPriseInfoPeap(QString &uuid, KyEapMethodPeapInfo &info) +{ + NetworkManager::Connection::Ptr conn = m_networkResourceInstance->findConnectByUuid(uuid); + if (conn.isNull()) { + qWarning() << LOG_FLAG << "getEnterPriseInfoPeap connection missing"; + return false; + } + NetworkManager::WirelessSecuritySetting::Ptr security_sett + = conn->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); + if (security_sett.isNull()) { + qWarning() << LOG_FLAG << "don't have WirelessSecurity connection"; + return false; + } + + if (security_sett->keyMgmt() != NetworkManager::WirelessSecuritySetting::WpaEap) { + qWarning() << LOG_FLAG << "keyMgmt not WpaEap " << security_sett->keyMgmt(); + return false; + } + + NetworkManager::Security8021xSetting::Ptr setting = + conn->settings()->setting(NetworkManager::Setting::Security8021x).dynamicCast(); + if (setting.isNull() || !setting->eapMethods().contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodPeap)) { + qWarning()<< LOG_FLAG << "don't have Security8021x connection"; + return false; + } + + info.phase2AuthMethod = (KyNoEapMethodAuth)setting->phase2AuthMethod(); + info.userName = setting->identity(); + info.m_passwdFlag = setting->passwordFlags(); + if (!info.m_passwdFlag) { + KyWirelessConnectOperation operation; + info.userPWD = operation.get8021xPassword(conn->uuid()); + } + + return true; +} + +bool KyWirelessNetResource::getEnterPriseInfoTtls(QString &uuid, KyEapMethodTtlsInfo &info) +{ + NetworkManager::Connection::Ptr conn = m_networkResourceInstance->findConnectByUuid(uuid); + if (conn.isNull()) { + qWarning() << LOG_FLAG << "modifyEnterPriseInfoTtls connection missing"; + return false; + } + + NetworkManager::WirelessSecuritySetting::Ptr security_sett + = conn->settings()->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast(); + if (security_sett.isNull()) { + qWarning() << LOG_FLAG << "don't have WirelessSecurity connection"; + return false; + } + if (security_sett->keyMgmt() != NetworkManager::WirelessSecuritySetting::WpaEap) { + qWarning() << LOG_FLAG << "not wpaeap"<keyMgmt(); + return false; + } + + NetworkManager::Security8021xSetting::Ptr setting = conn->settings()->setting(NetworkManager::Setting::Security8021x).dynamicCast(); + if (setting.isNull() || !setting->eapMethods().contains(NetworkManager::Security8021xSetting::EapMethod::EapMethodTtls)) { + qWarning() << LOG_FLAG << "don't have Security8021x connection"; + return false; + } + + info.authEapMethod = (KyEapMethodAuth)setting->phase2AuthEapMethod(); + info.authNoEapMethod = (KyNoEapMethodAuth)setting->phase2AuthMethod(); + + info.authType = KyTtlsAuthMethod::AUTH_EAP; + if (info.authEapMethod != KyAuthEapMethodUnknown) { + info.authType = KyTtlsAuthMethod::AUTH_EAP; + } else { + info.authType = KyTtlsAuthMethod::AUTH_NO_EAP; + } + + info.userName = setting->identity(); + info.m_passwdFlag = setting->passwordFlags(); + if (!info.m_passwdFlag) { + KyWirelessConnectOperation operation; + info.userPWD = operation.get8021xPassword(conn->uuid()); + } + + return true; +} + +void KyWirelessNetResource::getWirelessConnectDetail(QString interface, QString ssid, QString uuid, KyDetailInfo &connectSetting) +{ + getBaseInfo(interface, ssid, true, !uuid.isEmpty(), connectSetting); + if (!uuid.isEmpty()) { + getDynamicIpInfo(uuid, connectSetting); + } +} + +void KyWirelessNetResource::onConnectionAdd(QString connectUuid, QString connectName, QString connectPath) +{ + Q_UNUSED(connectName); + NetworkManager::Connection::Ptr conn = m_networkResourceInstance->findConnectByUuid(connectUuid); + if (conn.isNull()) { + qWarning() << LOG_FLAG << "onConnectionAdd can not find connection" << connectUuid; + return; + } + + NetworkManager::ConnectionSettings::Ptr sett = conn->settings(); + NetworkManager::WirelessSetting::Ptr wireless_sett = + sett->setting(NetworkManager::Setting::Wireless).dynamicCast(); + + QByteArray rawSsid = wireless_sett->ssid(); + QString wifiSsid = getSsidFromByteArray(rawSsid); + + QMap map; + map.clear(); + QMap >::iterator iter = m_WifiNetworkList.begin(); + while (iter != m_WifiNetworkList.end()) { + for(int i = 0; i < iter.value().size(); i++) { + if (iter.value().at(i).m_NetSsid == wifiSsid + && (sett->interfaceName() == iter.key() || sett->interfaceName().isEmpty())) { + QString devIfaceName; + QString ssid; + KyWirelessConnectOperation operation; + m_WifiNetworkList[iter.key()][i].m_connectUuid = conn->uuid(); + m_WifiNetworkList[iter.key()][i].m_dbusPath = conn->path(); + m_WifiNetworkList[iter.key()][i].m_connectSecuType = operation.getConnectSecuType(conn->uuid()); + + devIfaceName = iter.key(); + ssid = iter.value().at(i).m_NetSsid; + + Q_EMIT wirelessConnectionAdd(devIfaceName, ssid, connectUuid, connectPath); + map.insert(devIfaceName, ssid); + + break; + } + } + iter++; + } +} + +void KyWirelessNetResource::onConnectionRemove(QString path) +{ + QMap map; + map.clear(); + + QMap >::iterator iter = m_WifiNetworkList.begin(); + while (iter != m_WifiNetworkList.end()) { + for(int i = 0; i < iter.value().size(); i++) { + if (iter.value().at(i).m_dbusPath == path) { + KyWirelessConnectOperation operation; + QString devIfaceName = iter.key(); + QString ssid = iter.value().at(i).m_NetSsid; + + getUuidBySsid(ssid, devIfaceName, m_WifiNetworkList[iter.key()][i].m_connectUuid, m_WifiNetworkList[iter.key()][i].m_dbusPath); + if (m_WifiNetworkList[iter.key()][i].m_connectUuid.isEmpty()) { + Q_EMIT wirelessConnectionRemove(devIfaceName, ssid); + } else { + Q_EMIT wirelessConnectionUpdate(devIfaceName, ssid, + m_WifiNetworkList[iter.key()][i].m_connectUuid, + m_WifiNetworkList[iter.key()][i].m_dbusPath, + operation.getConnectSecuType(m_WifiNetworkList[iter.key()][i].m_connectUuid)); + } + + map.insert(devIfaceName, ssid); + break; + + } + } + iter++; + } +} + +void KyWirelessNetResource::onDeviceAdd(QString deviceName) +{ + if (!m_WifiNetworkList.contains(deviceName)) { + m_WifiNetworkList.insert(deviceName,QList()); + Q_EMIT wirelessDeviceAdd(deviceName); + } +} + +void KyWirelessNetResource::onDeviceRemove(QString deviceName) +{ + if (m_WifiNetworkList.contains(deviceName)) { + m_WifiNetworkList.remove(deviceName); + Q_EMIT deviceRemove(deviceName); + } +} + +void KyWirelessNetResource::onDeviceNameUpdate(QString oldName, QString newName) +{ + if (m_WifiNetworkList.contains(oldName)) { + QMap> newWifiNetworkList(m_WifiNetworkList); + QList list = m_WifiNetworkList[oldName]; + newWifiNetworkList.remove(oldName); + newWifiNetworkList.insert(newName,list); + m_WifiNetworkList = newWifiNetworkList; + Q_EMIT wirelessDeviceNameUpdate(oldName, newName); + } +} + +void KyWirelessNetResource::updateList() +{ + for (int i = 0; i< m_WifiNetworkList.keys().size(); ++i) { + QString devName = m_WifiNetworkList.keys().at(i); + QList connectItemList; + KyActiveConnectResourse actResource; + actResource.getActiveConnectionList(devName, CONNECT_TYPE_WIRELESS, connectItemList); + QList list = m_WifiNetworkList[devName]; + wifiListSort(list); + Q_EMIT updateWifiList(devName, connectItemList, list); + } +} + +QString KyWirelessNetResource::getDeviceIFace(NetworkManager::WirelessNetwork::Ptr net) +{ + if (net.isNull()) { + return ""; + } + + QString devUni = net->device(); + NetworkManager::Device::Ptr dev = m_networkResourceInstance->findDeviceByUni(devUni); + if (dev.isNull()) { + qDebug()<< LOG_FLAG << "KyWirelessNetResource: can't find " << net->ssid() << " find in device list"; + return ""; + } + + return dev->interfaceName(); +} diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessnetresource.h b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessnetresource.h new file mode 100644 index 00000000..efe82ac9 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/depend/kywirelessnetresource.h @@ -0,0 +1,102 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYWIRELESSNETRESOURCE_H +#define KYWIRELESSNETRESOURCE_H + +#include +#include "kylinnetresource.h" +#include "kywirelessnetitem.h" +#include "kylinnetworkresourcemanager.h" +#include "kyenterpricesettinginfo.h" +#include "kywirelessconnectoperation.h" +#include "kylinactiveconnectresource.h" + +class KyWpaPasswordInfo{ +public: + QString pwd; + NetworkManager::Setting::SecretFlags flag; +}; + +class KyWirelessNetResource : public KyNetResource +{ + Q_OBJECT +public: + explicit KyWirelessNetResource(QObject *parent = nullptr); + +public: + //初始化列表用到的接口 + void getWifiNetworkList(QString devName, QList &list); + + //属性页---->安全 + bool getNormalWifiConnectSecuInfo(QString &uuid, KyWpaPasswordInfo &info); + bool getEnterPriseInfoTls(QString &uuid, KyEapMethodTlsInfo &info); + bool getEnterPriseInfoPeap(QString &uuid, KyEapMethodPeapInfo &info); + bool getEnterPriseInfoTtls(QString &uuid, KyEapMethodTtlsInfo &info); + + //获取企业网类型 + bool getEnterpiseEapMethod(const QString &uuid, KyEapMethodType &type); + + void getWirelessConnectDetail(QString interface, QString ssid, QString uuid, KyDetailInfo &connectSetting); + +private: + void kyWirelessNetItemListInit(); + void wirelessNetItemInit(KyWirelessNetItem &wirelessItem, + NetworkManager::WirelessNetwork::Ptr wirelessNetPtr); + void getUuidBySsid(const QString &ssid, QString &deviceName, QString &uuid, QString &dbusPath); + +public Q_SLOTS: + void onWifiNetworkAdded(QString devIfaceName, QString ssid); + void onWifiNetworkRemoved(QString devIfaceName, QString ssid); + void onWifiNetworkPropertyChange(NetworkManager::WirelessNetwork::Ptr net); + void onWifiNetworkDeviceDisappear(); + + void onConnectionAdd(QString connectUuid, QString connectName, QString connectPath); + void onConnectionRemove(QString); + + void onDeviceAdd(QString deviceName); + void onDeviceRemove(QString deviceName); + void onDeviceNameUpdate(QString oldName, QString newName); +private Q_SLOTS: + void updateList(); + +Q_SIGNALS: + void signalStrengthChange(QString deviceName, QString ssid, int strength); + void secuTypeChange(QString deviceName, QString ssid, QString securityType); + + void wirelessConnectionRemove(QString deviceName, QString ssid); + void wirelessConnectionAdd(QString deviceName, QString ssid, QString uuid, QString dbusPath); + void wirelessConnectionUpdate(QString deviceName, QString ssid, QString uuid, QString dbusPath, KySecuType connectSecuType); + + void wifiNetworkUpdate(QString, QString, KyWirelessNetItem); + void wifiNetworkAdd(QString deviceName, KyWirelessNetItem &item); + void wifiNetworkRemove(QString deviceName, QString ssid); + + void wirelessDeviceAdd(QString deviceName); + void deviceRemove(QString deviceName); + void wirelessDeviceNameUpdate(QString oldName, QString newName); + + void updateWifiList(QString, QList, QList); + +private: + QMap> m_WifiNetworkList; + QTimer * m_updateTimer = nullptr; + + QString getDeviceIFace(NetworkManager::WirelessNetwork::Ptr net); +}; + +#endif // KYWIRELESSNETRESOURCE_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/kylin-nm-interface.h b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/kylin-nm-interface.h new file mode 100644 index 00000000..622ad6da --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/kylin-nm-interface.h @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYLINNMINTERFACE_H +#define KYLINNMINTERFACE_H + +#include "libnm-base-kylin_global.h" +#include + +class QWidget; +enum PluginType { + SIMPLE = 0, //锁屏 && 登录 + COMPLEX, //托盘 +}; + +class LIBNMBASEKYLIN_EXPORT Interface : public QObject{ + Q_OBJECT +public: + virtual ~Interface(){} + virtual QWidget * pluginUi() = 0; // 插件主界面---setPluginType后调用 + virtual void setPluginType(PluginType type, bool useSwitch = true) = 0; // 设置插件类型 + virtual void setParentWidget(QWidget* widget) = 0; + virtual void setWidgetVisable(bool) = 0; + +Q_SIGNALS: + void needShowVirtualKeyboard(); +}; + +#define Interface_iid "org.kylin.network" + +Q_DECLARE_INTERFACE(Interface, Interface_iid) + +#endif // KYLINNMINTERFACE_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/kylinnetworkmanager.h b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/kylinnetworkmanager.h new file mode 100644 index 00000000..54d0687a --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/kylinnetworkmanager.h @@ -0,0 +1,198 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef KYLINNETWORKMANAGER_H +#define KYLINNETWORKMANAGER_H + +#include +#include "libnm-base-kylin_global.h" + +#include "depend/kylinnetworkresourcemanager.h" +#include "depend/kylinactiveconnectresource.h" +#include "depend/kylinnetworkdeviceresource.h" +#include "depend/kylinconnectoperation.h" +#include "depend/kylinwiredconnectoperation.h" +#include "depend/kylinwirednetresource.h" +#include "depend/kywirelessconnectoperation.h" +#include "depend/kywirelessnetresource.h" +#include "depend/kylinnetresource.h" +#include "depend/kyapnetresource.h" +#include "depend/kylingeneral.h" + +class LIBNMBASEKYLIN_EXPORT KyNetworkManager : public QObject +{ + Q_OBJECT +public: + explicit KyNetworkManager(QObject *parent = nullptr); + ~KyNetworkManager(); + +private: + bool m_init = false; + KyNetworkResourceManager *m_networkResource; + KyActiveConnectResourse *m_activeConnectResource; + KyNetworkDeviceResourse *m_deviceResource; + KylinGeneralOpration *m_general; + KyWiredConnectResourse *m_wiredConnectResourse; + KyWirelessNetResource *m_wirelessNetResource; + KyApNetResource *m_apNetResource; + + void initConnect(); + +Q_SIGNALS: + //activeConnection + void wiredStateChange(QString deviceName, QString uuid, KyConnectState state); + void wirelessStateChange(QString deviceName, QString ssid, QString uuid, KyConnectState state); + + //device + void deviceStateChange(QString deviceName, KyDeviceState newstate, KyDeviceState oldstate, + NetworkManager::Device::StateChangeReason reason); + void carrierChange(QString deviceName, bool pluged); + void deviceRemove(QString deviceName); + void deviceManagedChange(QString deviceName, bool managed); + + //general + void wifiEnabledChanged(bool); + void wiredEnabledChanged(bool); + void networkingEnabledChanged(bool); + void connectStatusChanged(KyConnectStatus); + + //wired + void wiredConnectionAdd(QString devName, QString connectUuid, QString connectName, QString connectPath); + void wiredConnectionUpdate(QString devName, QString connectUuid, QString connectName, QString connectPath); + void connectionRemove(QString path); + + void wiredDeviceAdd(QString deviceName); + void wiredDeviceUpdate(QString oldDeviceName, QString newDeviceName); + + //wireless + void signalStrengthChange(QString deviceName, QString ssid, int strength); + void secuTypeChange(QString deviceName, QString ssid, QString securityType); + + void wirelessConnectionRemove(QString deviceName, QString ssid); + void wirelessConnectionAdd(QString deviceName, QString ssid, QString uuid, QString dbusPath); + void wirelessConnectionUpdate(QString deviceName, QString ssid, QString uuid, QString dbusPath, KySecuType connectSecuType); + + void wifiNetworkUpdate(QString, QString, KyWirelessNetItem); + void wifiNetworkAdd(QString deviceName, KyWirelessNetItem &item); + void wifiNetworkRemove(QString deviceName, QString ssid); + + void wirelessDeviceAdd(QString deviceName); + void wirelessDeviceNameUpdate(QString oldName, QString newName); + + void updateWifiList(QString, QList, QList); + + //移动热点 + void wirelessApConnectStateChange(); + + + +public: + bool isInitFinished(){return m_init;} + //activeConnection + void getActiveConnectionList(QString deviceName, + KyConnectionType connectionType, QList &connectItemList); + int getAcivateWifiSignal(); + + //device + void getNetworkDeviceList(KyDeviceType deviceType, QStringList &networkDeviceList); + bool getDeviceManaged(QString devName); + + //general + bool getWirelessEnabled(); + bool getWiredEnabled(); + bool getNetworkingEnabled(); + void getConnectStatus(KyConnectStatus &status); + + //wired + void getWiredList(QMap> &map); + //wireless + void getWifiNetworkList(QString devName, QList &list); + //移动热点 + void getApConnections(QList &apConnectItemList); + + //详情页-->ipv4 + ipv6 + autoconnect + void getConnectIpInfo(QString uuid, KyConnectSetting &connectSetting); + + //详情页-->有线连接detail + void getWiredConnectDetail(QString interface, QString uuid, KyDetailInfo &connectSetting); + + //详情页-->无线连接detail + void getWirelessConnectDetail(QString interface, QString ssid, QString uuid, KyDetailInfo &connectSetting); + + //无线连接-->安全 + bool getNormalWifiConnectSecuInfo(QString &uuid, KyWpaPasswordInfo &info); + bool getEnterPriseInfoTls(QString &uuid, KyEapMethodTlsInfo &info); + bool getEnterPriseInfoPeap(QString &uuid, KyEapMethodPeapInfo &info); + bool getEnterPriseInfoTtls(QString &uuid, KyEapMethodTtlsInfo &info); + + //获取企业网类型 + bool getEnterpiseEapMethod(const QString &uuid, KyEapMethodType &type); + + bool wiredConnectIsActived(); + bool wirelessConnectIsActived(); + +public Q_SLOTS: + void kylinNetworkManagerInit(); + //general + void onSetWirelessNetworkEnabled(bool enabled); + void onSetNetworkingEnabled(bool enabled); + void onSetWiredEnabled(bool enabled); + void onSetDeviceManaged(QString devName, bool managed); + void onSetWiredDeviceEnable(QString interface, bool enable); + //有线无线公用 + void onDeleteConnect(const QString &connectUuid); + void onActivateConnection(const QString connectUuid, const QString deviceName); + void onDeactivateConnection(const QString &activeConnectUuid); + //wireless + //申请扫描 + void onRequestWirelessScan(); + + void onCreateWiredConnect(KyConnectSetting connectSettingsInfo); + + //详情页 + //=======================连接操作==================== + //连接无本地配置的非企业网热点 + void onAddAndActivateNormalWifi(KyWirelessConnectSetting connSettingInfo, KySecuType type); + //连接无本地配置的企业网热点 + void onAddAndActiveWirelessEnterPriseTlsConnect(KyEapMethodTlsInfo info, + KyWirelessConnectSetting connSettingInfo); + void onAddAndActiveWirelessEnterPrisePeapConnect(KyEapMethodPeapInfo info, + KyWirelessConnectSetting connSettingInfo); + void onAddAndActiveWirelessEnterPriseTtlsConnect(KyEapMethodTtlsInfo info, + KyWirelessConnectSetting connSettingInfo); + + //=====================新增配置操作==================== + //新增普通连接 + void onAddNormalConnect(const KyWirelessConnectSetting &connSettingInfo, KySecuType &type); + //新增TLS连接 + void onAddTlsConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodTlsInfo &tlsinfo); + //新增PEAP连接 + void onAddPeapConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodPeapInfo &peapInfo); + //新增TTLS连接 + void onAddTtlsConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodTtlsInfo &ttlsInfo); + + //=====================更新配置操作==================== + void onUpdateIpv4AndIpv6SettingInfo(const QString &uuid, const KyConnectSetting &connectSettingsInfo); + //连接修改(安全改为个人/None) + void onUpdateWirelessPersonalConnect(const QString &uuid, const KyWirelessConnectSetting &connSettingInfo, bool bPwdChange); + //连接修改(安全改为改为企业) + void onUpdateWirelessEnterPriseTlsConnect(const QString &uuid, const KyEapMethodTlsInfo &tlsinfo); + void onUpdateWirelessEnterPrisePeapConnect(const QString &uuid, const KyEapMethodPeapInfo &peapInfo); + void onUpdateWirelessEnterPriseTtlsConnect(const QString &uuid, const KyEapMethodTtlsInfo &ttlsInfo); +}; + +#endif // KYLINNETWORKMANAGER_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/kylinnetworkmanger.cpp b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/kylinnetworkmanger.cpp new file mode 100644 index 00000000..a3a17a1e --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/kylinnetworkmanger.cpp @@ -0,0 +1,375 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include "kylinnetworkmanager.h" + +#define WAIT_US 1000 + +KyNetworkManager::KyNetworkManager(QObject *parent) : QObject(parent) +{ +// kylinNetworkManagerInit(); + m_init = false; +} + +KyNetworkManager::~KyNetworkManager() +{ + m_networkResource = nullptr; +} + +void KyNetworkManager::kylinNetworkManagerInit() +{ + if (!m_init) { + qDebug() << "kylinNetworkManagerInit"; + m_networkResource = KyNetworkResourceManager::getInstance(); + if (!m_networkResource->NetworkManagerIsInited()) { + m_networkResource->onInitNetwork(); + } + m_activeConnectResource = new KyActiveConnectResourse(this); + m_deviceResource = new KyNetworkDeviceResourse(this); + m_general = new KylinGeneralOpration(this); + m_wiredConnectResourse = new KyWiredConnectResourse(this); + m_wirelessNetResource = new KyWirelessNetResource(this); + m_apNetResource = new KyApNetResource(this); + + initConnect(); + } + m_init = true; +} + +void KyNetworkManager::initConnect() +{ + connect(m_activeConnectResource, &KyActiveConnectResourse::wiredStateChange, + this, &KyNetworkManager::wiredStateChange); + connect(m_activeConnectResource, &KyActiveConnectResourse::wirelessStateChange, + this, &KyNetworkManager::wirelessStateChange); + + connect(m_deviceResource, &KyNetworkDeviceResourse::carrierChange, + this, &KyNetworkManager::carrierChange); + connect(m_deviceResource, &KyNetworkDeviceResourse::deviceStateChange, + this, &KyNetworkManager::deviceStateChange); + connect(m_deviceResource, &KyNetworkDeviceResourse::deviceManagedChange, + this, &KyNetworkManager::deviceManagedChange); + + connect(m_general, &KylinGeneralOpration::connectStatusChanged, + this, &KyNetworkManager::connectStatusChanged); + connect(m_general, &KylinGeneralOpration::networkingEnabledChanged, + this, &KyNetworkManager::networkingEnabledChanged); + connect(m_general, &KylinGeneralOpration::wifiEnabledChanged, + this, &KyNetworkManager::wifiEnabledChanged); + connect(m_general, &KylinGeneralOpration::wiredEnabledChanged, + this, &KyNetworkManager::wiredEnabledChanged); + + connect(m_apNetResource, &KyApNetResource::wirelessApConnectStateChange, + this, &KyNetworkManager::wirelessApConnectStateChange); + + connect(m_wiredConnectResourse, &KyWiredConnectResourse::wiredConnectionAdd, + this, &KyNetworkManager::wiredConnectionAdd); + connect(m_wiredConnectResourse, &KyWiredConnectResourse::wiredConnectionUpdate, + this, &KyNetworkManager::wiredConnectionUpdate); + connect(m_wiredConnectResourse, &KyWiredConnectResourse::connectionRemove, + this, &KyNetworkManager::connectionRemove); + connect(m_wiredConnectResourse, &KyWiredConnectResourse::wiredDeviceAdd, + this, &KyNetworkManager::wiredDeviceAdd); + connect(m_wiredConnectResourse, &KyWiredConnectResourse::wiredDeviceUpdate, + this, &KyNetworkManager::wiredDeviceUpdate); + connect(m_wiredConnectResourse, &KyWiredConnectResourse::deviceRemove, + this, &KyNetworkManager::deviceRemove); + + + connect(m_wirelessNetResource, &KyWirelessNetResource::signalStrengthChange, + this, &KyNetworkManager::signalStrengthChange); + connect(m_wirelessNetResource, &KyWirelessNetResource::secuTypeChange, + this, &KyNetworkManager::secuTypeChange); + connect(m_wirelessNetResource, &KyWirelessNetResource::wirelessConnectionRemove, + this, &KyNetworkManager::wirelessConnectionRemove); + connect(m_wirelessNetResource, &KyWirelessNetResource::wirelessConnectionAdd, + this, &KyNetworkManager::wirelessConnectionAdd); + connect(m_wirelessNetResource, &KyWirelessNetResource::wirelessConnectionUpdate, + this, &KyNetworkManager::wirelessConnectionUpdate); + connect(m_wirelessNetResource, &KyWirelessNetResource::wifiNetworkUpdate, + this, &KyNetworkManager::wifiNetworkUpdate); + connect(m_wirelessNetResource, &KyWirelessNetResource::wifiNetworkAdd, + this, &KyNetworkManager::wifiNetworkAdd); + connect(m_wirelessNetResource, &KyWirelessNetResource::wifiNetworkRemove, + this, &KyNetworkManager::wifiNetworkRemove); + connect(m_wirelessNetResource, &KyWirelessNetResource::wirelessDeviceAdd, + this, &KyNetworkManager::wirelessDeviceAdd); + connect(m_wirelessNetResource, &KyWirelessNetResource::wirelessDeviceNameUpdate, + this, &KyNetworkManager::wirelessDeviceNameUpdate); + connect(m_wirelessNetResource, &KyWirelessNetResource::updateWifiList, + this, &KyNetworkManager::updateWifiList); +} + +//同步方法 +//有线 无线 移动热点界面 +void KyNetworkManager::getActiveConnectionList(QString deviceName, + KyConnectionType connectionType, QList &connectItemList) +{ + m_activeConnectResource->getActiveConnectionList(deviceName, connectionType, connectItemList); +} + +int KyNetworkManager::getAcivateWifiSignal() +{ + return m_activeConnectResource->getAcivateWifiSignal(); +} + +void KyNetworkManager::getNetworkDeviceList(KyDeviceType deviceType, QStringList &networkDeviceList) +{ + m_deviceResource->getNetworkDeviceList(deviceType, networkDeviceList); +} + +bool KyNetworkManager::getDeviceManaged(QString devName) +{ + return m_deviceResource->getDeviceManaged(devName); +} + +void KyNetworkManager::getConnectStatus(KyConnectStatus &connectType) +{ + m_general->getConnectStatus(connectType); +} + +bool KyNetworkManager::getWirelessEnabled() +{ + return m_general->getWirelessEnabled(); +} + +bool KyNetworkManager::getWiredEnabled() +{ + return m_general->getWiredEnabled(); +} + +bool KyNetworkManager::getNetworkingEnabled() +{ + return m_general->getNetworkingEnabled(); +} + +void KyNetworkManager::getWiredList(QMap> &map) +{ + m_wiredConnectResourse->getWiredList(map); +} + +void KyNetworkManager::getWifiNetworkList(QString devName, QList &list) +{ + m_wirelessNetResource->getWifiNetworkList(devName, list); +} + +void KyNetworkManager::getApConnections(QList &apConnectItemList) +{ + m_apNetResource->getApConnections(apConnectItemList); +} +//详情页 +//共有ipv4 ipv6 包括autoconnect +void KyNetworkManager::getConnectIpInfo(QString uuid, KyConnectSetting &connectSetting) +{ + KyNetResource resource; + resource.getConnectionSetting(uuid, connectSetting); +} +//详情页-->有线连接detail +void KyNetworkManager::getWiredConnectDetail(QString interface, QString uuid, KyDetailInfo &connectSetting) +{ + KyWiredConnectResourse resource; + resource.getWiredConnectDetail(interface, uuid, connectSetting); +} + +//详情页-->无线连接detail +void KyNetworkManager::getWirelessConnectDetail(QString interface, QString ssid, QString uuid, KyDetailInfo &connectSetting) +{ + KyWirelessNetResource resource; + resource.getWirelessConnectDetail(interface, ssid, uuid, connectSetting); +} + +//无线连接-->安全 +bool KyNetworkManager::getNormalWifiConnectSecuInfo(QString &uuid, KyWpaPasswordInfo &info) +{ + KyWirelessNetResource resource; + return resource.getNormalWifiConnectSecuInfo(uuid, info); +} + +bool KyNetworkManager::getEnterPriseInfoTls(QString &uuid, KyEapMethodTlsInfo &info) +{ + KyWirelessNetResource resource; + return resource.getEnterPriseInfoTls(uuid, info); +} + +bool KyNetworkManager::getEnterPriseInfoPeap(QString &uuid, KyEapMethodPeapInfo &info) +{ + KyWirelessNetResource resource; + return resource.getEnterPriseInfoPeap(uuid, info); +} + +bool KyNetworkManager::getEnterPriseInfoTtls(QString &uuid, KyEapMethodTtlsInfo &info) +{ + KyWirelessNetResource resource; + return resource.getEnterPriseInfoTtls(uuid, info); +} + +//获取企业网类型 +bool KyNetworkManager::getEnterpiseEapMethod(const QString &uuid, KyEapMethodType &type) +{ + KyWirelessNetResource resource; + return resource.getEnterpiseEapMethod(uuid, type); +} + +bool KyNetworkManager::wiredConnectIsActived() +{ + return m_activeConnectResource->wiredConnectIsActived(); +} + +bool KyNetworkManager::wirelessConnectIsActived() +{ + return m_activeConnectResource->wirelessConnectIsActived(); +} + +//异步槽 +void KyNetworkManager::onSetWirelessNetworkEnabled(bool enabled) +{ + m_general->setWirelessNetworkEnabled(enabled); +} + +void KyNetworkManager::onSetNetworkingEnabled(bool enabled) +{ + m_general->setNetworkingEnabled(enabled); +} + +void KyNetworkManager::onSetWiredEnabled(bool enabled) +{ + m_general->setWiredEnabled(enabled); +} + +void KyNetworkManager::onSetDeviceManaged(QString devName, bool managed) +{ + m_deviceResource->setDeviceManaged(devName, managed); +} + +void KyNetworkManager::onSetWiredDeviceEnable(QString devName, bool enable) +{ + m_deviceResource->setDeviceManaged(devName, enable); +} + +void KyNetworkManager::onDeleteConnect(const QString &connectUuid) +{ + KyConnectOperation operate; + operate.deleteConnect(connectUuid); +} + +void KyNetworkManager::onActivateConnection(const QString connectUuid, const QString deviceName) +{ + KyConnectOperation operate; + operate.activateConnection(connectUuid, deviceName); +} + +void KyNetworkManager::onDeactivateConnection(const QString &activeConnectUuid) +{ + KyConnectOperation operate; + operate.deactivateConnection(activeConnectUuid); +} + +void KyNetworkManager::onCreateWiredConnect(KyConnectSetting connectSettingsInfo) +{ + KyWiredConnectOperation operate; + operate.createWiredConnect(connectSettingsInfo); +} + +//=====================申请无线扫描=================== +void KyNetworkManager::onRequestWirelessScan() +{ + KyWirelessConnectOperation operate; + operate.requestWirelessScan(); +} + +//=======================连接操作==================== +//连接无本地配置的非企业网热点 +void KyNetworkManager::onAddAndActivateNormalWifi(KyWirelessConnectSetting connSettingInfo, KySecuType type) +{ + KyWirelessConnectOperation operate; + operate.addAndActiveWirelessConnect(connSettingInfo, type); +} +//连接无本地配置的企业网热点 +void KyNetworkManager::onAddAndActiveWirelessEnterPriseTlsConnect(KyEapMethodTlsInfo info, + KyWirelessConnectSetting connSettingInfo) +{ + KyWirelessConnectOperation operate; + operate.addAndActiveWirelessEnterPriseTlsConnect(info, connSettingInfo); +} +void KyNetworkManager::onAddAndActiveWirelessEnterPrisePeapConnect(KyEapMethodPeapInfo info, + KyWirelessConnectSetting connSettingInfo) +{ + KyWirelessConnectOperation operate; + operate.addAndActiveWirelessEnterPrisePeapConnect(info, connSettingInfo); +} +void KyNetworkManager::onAddAndActiveWirelessEnterPriseTtlsConnect(KyEapMethodTtlsInfo info, + KyWirelessConnectSetting connSettingInfo) +{ + KyWirelessConnectOperation operate; + operate.addAndActiveWirelessEnterPriseTtlsConnect(info, connSettingInfo); +} + +//=====================新增配置操作==================== +//新增普通连接 +void KyNetworkManager::onAddNormalConnect(const KyWirelessConnectSetting &connSettingInfo, KySecuType &type) +{ + KyWirelessConnectOperation operate; + operate.addConnect(connSettingInfo, type); +} +//新增TLS连接 +void KyNetworkManager::onAddTlsConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodTlsInfo &tlsinfo) +{ + KyWirelessConnectOperation operate; + operate.addTlsConnect(connSettingInfo, tlsinfo); +} +//新增PEAP连接 +void KyNetworkManager::onAddPeapConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodPeapInfo &peapInfo) +{ + KyWirelessConnectOperation operate; + operate.addPeapConnect(connSettingInfo, peapInfo); +} +//新增TTLS连接 +void KyNetworkManager::onAddTtlsConnect(const KyWirelessConnectSetting &connSettingInfo, const KyEapMethodTtlsInfo &ttlsInfo) +{ + KyWirelessConnectOperation operate; + operate.addTtlsConnect(connSettingInfo, ttlsInfo); +} + +//=====================更新配置操作==================== +void KyNetworkManager::onUpdateIpv4AndIpv6SettingInfo(const QString &uuid, const KyConnectSetting &connectSettingsInfo) +{ + KyWirelessConnectOperation operate; + operate.updateIpv4AndIpv6SettingInfo(uuid, connectSettingsInfo); +} +//连接修改(安全改为个人/None) +void KyNetworkManager::onUpdateWirelessPersonalConnect(const QString &uuid, + const KyWirelessConnectSetting &connSettingInfo, bool bPwdChange) +{ + KyWirelessConnectOperation operate; + operate.updateWirelessPersonalConnect(uuid, connSettingInfo, bPwdChange); +} +//连接修改(安全改为改为企业) +void KyNetworkManager::onUpdateWirelessEnterPriseTlsConnect(const QString &uuid, const KyEapMethodTlsInfo &tlsinfo) +{ + KyWirelessConnectOperation operate; + operate.updateWirelessEnterPriseTlsConnect(uuid, tlsinfo); +} +void KyNetworkManager::onUpdateWirelessEnterPrisePeapConnect(const QString &uuid, const KyEapMethodPeapInfo &peapInfo) +{ + KyWirelessConnectOperation operate; + operate.updateWirelessEnterPrisePeapConnect(uuid, peapInfo); +} +void KyNetworkManager::onUpdateWirelessEnterPriseTtlsConnect(const QString &uuid, const KyEapMethodTtlsInfo &ttlsInfo) +{ + KyWirelessConnectOperation operate; + operate.updateWirelessEnterPriseTtlsConnect(uuid, ttlsInfo); +} diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/libnm-base-kylin.pro b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/libnm-base-kylin.pro new file mode 100644 index 00000000..bfaee49e --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/libnm-base-kylin.pro @@ -0,0 +1,108 @@ +#QT -= gui +#QT += core gui x11extras dbus KWindowSystem svg concurrent network +QT += core dbus network + +TARGET = kylin-nm-base +TEMPLATE = lib +DEFINES += LIBNMBASEKYLIN_LIBRARY + +CONFIG += c++11 qt warn_on link_pkgconfig no_keywords +#CONFIG += create_pc create_prl no_install_prl + + +PKGCONFIG +=libnm gsettings-qt gtk+-3.0 +#PKGCONFIG += gio-2.0 glib-2.0 gio-unix-2.0 libnm libnma libsecret-1 gsettings-qt +#INCLUDEPATH += /usr/include/dbus-1.0/dbu + +INCLUDEPATH += /usr/include/KF5/NetworkManagerQt +LIBS += -L/usr/lib/ -lKF5NetworkManagerQt + +# The following define makes your compiler emit warnings if you use +# any Qt feature that has been marked deprecated (the exact warnings +# depend on your compiler). Please consult the documentation of the +# deprecated API in order to know how to port your code away from it. +DEFINES += QT_DEPRECATED_WARNINGS + +# You can also make your code fail to compile if it uses deprecated APIs. +# In order to do so, uncomment the following line. +# You can also select to disable deprecated APIs only up to a certain version of Qt. +#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 + +SOURCES += \ + depend/kyapnetresource.cpp \ + depend/kyenterpricesettinginfo.cpp \ + depend/kylinactiveconnectresource.cpp \ + depend/kylinconnectoperation.cpp \ + depend/kylinconnectsetting.cpp \ + depend/kylingeneral.cpp \ + depend/kylinnetresource.cpp \ + depend/kylinnetworkdeviceresource.cpp \ + depend/kylinnetworkmanagerutil.cpp \ + kylinnetworkmanger.cpp \ + depend/kylinnetworkresourcemanager.cpp \ + depend/kylinwiredconnectoperation.cpp \ + depend/kylinwirednetresource.cpp \ + depend/kywirelessconnectoperation.cpp \ + depend/kywirelessnetresource.cpp + kylinnetworkmanger.cpp \ + +HEADERS += \ + libnm-base-kylin_global.h \ + kylin-nm-interface.h \ + kylinnetworkmanager.h \ + depend/kyapnetresource.h \ + depend/kyenterpricesettinginfo.h \ + depend/kylinactiveconnectresource.h \ + depend/kylinapconnectitem.h \ + depend/kylinconnectitem.h \ + depend/kylinconnectoperation.h \ + depend/kylinconnectsetting.h \ + depend/kylingeneral.h \ + depend/kylinnetresource.h \ + depend/kylinnetworkdeviceresource.h \ + depend/kylinnetworkmanagerutil.h \ + depend/kylinnetworkresourcemanager.h \ + depend/kylinnetworkresourcetype.h \ + depend/kylinwiredconnectoperation.h \ + depend/kylinwirednetresource.h \ + depend/kywirelessconnectoperation.h \ + depend/kywirelessnetitem.h \ + depend/kywirelessnetresource.h + +DESTDIR += $$PWD +# Default rules for deployment. +unix { + target.path = /usr/lib/ + + manager.path = /usr/include/kylin-nm + manager.files = kylinnetworkmanager.h \ + libnm-base-kylin_global.h \ + kylin-nm-interface.h + + depend.path = /usr/include/kylin-nm/depend + depend.files = depend/*.h + +# gschema.files = org.ukui.kylin-nm.switch.gschema.xml +# gschema.path = /usr/share/glib-2.0/schemas/ + + + INSTALLS += manager \ + depend \ + gschema + +# QMAKE_PKGCONFIG_NAME = kylin-nm-base +# QMAKE_PKGCONFIG_DESCRIPTION = kylin-nm Header files +# QMAKE_PKGCONFIG_VERSION = $$VERSION +# QMAKE_PKGCONFIG_LIBDIR = $$target.path +# QMAKE_PKGCONFIG_DESTDIR = pkgconfig +# QMAKE_PKGCONFIG_INCDIR = $$INCLUDEPATH +##/usr/include/kylin-nm /usr/include/KF5/NetworkManagerQt +## QMAKE_PKGCONFIG_INCDIR += /usr/include/KF5/NetworkManagerQt +# QMAKE_PKGCONFIG_CFLAGS += -I/usr/include/kylin-nm +# QMAKE_PKGCONFIG_REQUIRES = gio-2.0 glib-2.0 libnm +# QMAKE_INSTALL_DIR = /usr/share/pkgconfig/ +} +!isEmpty(target.path): INSTALLS += target + +DISTFILES += \ + org.ukui.kylin-nm.switch.gschema.xml diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/libnm-base-kylin_global.h b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/libnm-base-kylin_global.h new file mode 100644 index 00000000..97305776 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/libnm-base-kylin_global.h @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#ifndef LIBNMBASEKYLIN_GLOBAL_H +#define LIBNMBASEKYLIN_GLOBAL_H + +#include + +#if defined(LIBNMBASEKYLIN_LIBRARY) +# define LIBNMBASEKYLIN_EXPORT Q_DECL_EXPORT +#else +# define LIBNMBASEKYLIN_EXPORT Q_DECL_IMPORT +#endif + +#endif // LIBNMBASEKYLIN_GLOBAL_H diff --git a/libkylin-nm-base/libnm-kylin/libnm-base-kylin/pkgconfig/kylin-nm-base.pc b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/pkgconfig/kylin-nm-base.pc new file mode 100644 index 00000000..f2fa6293 --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-base-kylin/pkgconfig/kylin-nm-base.pc @@ -0,0 +1,13 @@ +prefix=/usr +exec_prefix=${prefix} +libdir=${prefix}/lib/ +includedir=${prefix}/include/KF5/NetworkManagerQt + + +Name: kylin-nm-base +Description: kylin-nm Header files +Version: 1.0.0 +Libs: -L${libdir} -lkylin-nm-base +Cflags: -I/usr/include/kylin-nm -I${includedir} +Requires: gio-2.0 glib-2.0 libnm + diff --git a/libkylin-nm-base/libnm-kylin/libnm-kylin.pro b/libkylin-nm-base/libnm-kylin/libnm-kylin.pro new file mode 100644 index 00000000..c45bcc8e --- /dev/null +++ b/libkylin-nm-base/libnm-kylin/libnm-kylin.pro @@ -0,0 +1,4 @@ +TEMPLATE = subdirs + +SUBDIRS += \ + libnm-base-kylin diff --git a/man/kylin-nm-plugin.1 b/man/kylin-nm-plugin.1 new file mode 100644 index 00000000..846cd7eb --- /dev/null +++ b/man/kylin-nm-plugin.1 @@ -0,0 +1,20 @@ +.\" Man page for Kylin-nm +.TH KYLIN-NM 1 "20 September 2019" "UKUI Desktop Environment" +.\" Please adjust this date when revising the manpage. +.\" +.SH "NAME" +kylin-nm \- The tool for the UKUI Desktop Environment +.SH "SYNOPSIS" +.B kylin-nm +.SH "DESCRIPTION" +The \fBkylin-nm\fR program is a part of the ukui-indicators, It provides network manager for the the UKUI Desktop Environment. Detect the system disk automatically, Can pop up and open the device. +.PP +This manual page documents the \fBkylin-nm\fR command. +.P +.SH "BUGS" +.SS Should you encounter any bugs, they may be reported at: +https://github.com/ukui/kylin-nm/issues +.SH "AUTHORS" +.SS This Man Page has been written for the UKUI Desktop Environment by: +shine (2019) +.SH "SEE ALSO" \ No newline at end of file diff --git a/man/kylin-nm-sysdbus.1 b/man/kylin-nm-sysdbus.1 new file mode 100644 index 00000000..a1e60bd8 --- /dev/null +++ b/man/kylin-nm-sysdbus.1 @@ -0,0 +1,20 @@ +.\" Man page for kylin-nm-sysdbus +.TH KYLIN-NM 1 "20 September 2019" "UKUI Desktop Environment" +.\" Please adjust this date when revising the manpage. +.\" +.SH "NAME" +kylin-nm \- The tool for the UKUI Desktop Environment +.SH "SYNOPSIS" +.B kylin-nm +.SH "DESCRIPTION" +The \fBkylin-nm\fR program is a part of the ukui-indicators, It provides network manager for the the UKUI Desktop Environment. Detect the system disk automatically, Can pop up and open the device. +.PP +This manual page documents the \fBkylin-nm\fR command. +.P +.SH "BUGS" +.SS Should you encounter any bugs, they may be reported at: +https://github.com/ukui/kylin-nm/issues +.SH "AUTHORS" +.SS This Man Page has been written for the UKUI Desktop Environment by: +shine (2019) +.SH "SEE ALSO" diff --git a/man/kylin-vpn.1 b/man/kylin-vpn.1 new file mode 100644 index 00000000..73b27c4c --- /dev/null +++ b/man/kylin-vpn.1 @@ -0,0 +1,20 @@ +.\" Man page for kylin-vpn +.TH KYLIN-NM 1 "20 September 2019" "UKUI Desktop Environment" +.\" Please adjust this date when revising the manpage. +.\" +.SH "NAME" +kylin-nm \- The tool for the UKUI Desktop Environment +.SH "SYNOPSIS" +.B kylin-nm +.SH "DESCRIPTION" +The \fBkylin-nm\fR program is a part of the ukui-indicators, It provides network manager for the the UKUI Desktop Environment. Detect the system disk automatically, Can pop up and open the device. +.PP +This manual page documents the \fBkylin-nm\fR command. +.P +.SH "BUGS" +.SS Should you encounter any bugs, they may be reported at: +https://github.com/ukui/kylin-nm/issues +.SH "AUTHORS" +.SS This Man Page has been written for the UKUI Desktop Environment by: +shine (2019) +.SH "SEE ALSO" diff --git a/src-vpn/src-vpn.pro b/src-vpn/src-vpn.pro index 312c4984..f34e21d9 100644 --- a/src-vpn/src-vpn.pro +++ b/src-vpn/src-vpn.pro @@ -15,7 +15,12 @@ CONFIG += c++14 qt warn_on link_pkgconfig no_keywords #CONFIG += release PKGCONFIG +=gio-2.0 glib-2.0 gio-unix-2.0 libnm libnma libsecret-1 gtk+-3.0 gsettings-qt libcap kysdk-qtwidgets kysdk-waylandhelper -PKGCONFIG +=kysdk-sysinfo + +exists(/usr/include/kysdk/kysdk-system/libkysysinfo.h) { +# message("kysysinfo find") + DEFINES += KY_SDK_SYSINFO + PKGCONFIG += kysdk-sysinfo +} INCLUDEPATH += /usr/include/KF5/NetworkManagerQt diff --git a/src/frontend/mainwindow.cpp b/src/frontend/mainwindow.cpp index 78fdd72e..cbd0e22c 100644 --- a/src/frontend/mainwindow.cpp +++ b/src/frontend/mainwindow.cpp @@ -32,7 +32,10 @@ #include "ukuistylehelper/ukuistylehelper.h" #include "windowmanager/windowmanager.h" + +#ifdef KY_SDK_SYSINFO #include "kysdk/kysdk-system/libkysysinfo.h" +#endif #define MAINWINDOW_WIDTH 420 #define MAINWINDOW_HEIGHT 476 @@ -193,6 +196,8 @@ void MainWindow::secondaryStart() */ void MainWindow::initPlatform() { +#ifdef KY_SDK_SYSINFO + char* projectName = kdk_system_get_projectName(); QString strProjectName(projectName); free(projectName); @@ -206,6 +211,7 @@ void MainWindow::initPlatform() m_isShowInCenter = true; } qDebug() << "projectName" << projectName << m_isShowInCenter; +#endif } /** diff --git a/src/main.cpp b/src/main.cpp index 05b5235f..6c42b56c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -165,7 +165,7 @@ int main(int argc, char *argv[]) QString locale = QLocale::system().name(); QTranslator trans_global; qDebug() << "QLocale " << QLocale(); - if (trans_global.load(QLocale(), "kylin-nm", "_", "/usr/share/kylin-nm/kylin-nm/")) + if (trans_global.load(QLocale(), "kylin-nm", "_", "/usr/share/kylin-nm/")) { a.installTranslator(&trans_global); qDebug()<<"Translations load success"; diff --git a/src/src.pro b/src/src.pro index bfeaabda..1cf14e96 100644 --- a/src/src.pro +++ b/src/src.pro @@ -15,7 +15,12 @@ CONFIG += c++14 qt warn_on link_pkgconfig no_keywords #CONFIG += release PKGCONFIG +=gio-2.0 glib-2.0 gio-unix-2.0 libnm libnma libsecret-1 gtk+-3.0 gsettings-qt libcap kysdk-qtwidgets kysdk-waylandhelper -PKGCONFIG +=kysdk-sysinfo + +exists(/usr/include/kysdk/kysdk-system/libkysysinfo.h) { +# message("kysysinfo find") + DEFINES += KY_SDK_SYSINFO + PKGCONFIG += kysdk-sysinfo +} INCLUDEPATH += /usr/include/KF5/NetworkManagerQt @@ -32,7 +37,7 @@ desktop.path = /etc/xdg/autostart/ desktop.files = kylin-nm.desktop gschema.files = org.ukui.kylin-nm.switch.gschema.xml gschema.path = /usr/share/glib-2.0/schemas/ -qm_files.path = $${PREFIX}/share/kylin-nm/kylin-nm/ +qm_files.path = $${PREFIX}/share/kylin-nm/ qm_files.files = translations/*.qm INSTALLS += target \ diff --git a/sys-dbus-register/sys-dbus-register.pro b/sys-dbus-register/sys-dbus-register.pro index 40d22c73..d71d3e6e 100644 --- a/sys-dbus-register/sys-dbus-register.pro +++ b/sys-dbus-register/sys-dbus-register.pro @@ -12,7 +12,7 @@ PKGCONFIG +=gio-2.0 glib-2.0 gio-unix-2.0 libcap inst1.files += conf/com.kylin.network.qt.systemdbus.service inst1.path = /usr/share/dbus-1/system-services/ inst2.files += conf/com.kylin.network.qt.systemdbus.conf -inst2.path = /etc/dbus-1/system.d/ +inst2.path = /usr/share/dbus-1/system.d/ target.source += $$TARGET target.path = /usr/bin