diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..e22420d4 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,62 @@ +{ + "files.associations": { + "cstdio": "cpp", + "array": "cpp", + "atomic": "cpp", + "bit": "cpp", + "*.tcc": "cpp", + "cctype": "cpp", + "chrono": "cpp", + "clocale": "cpp", + "cmath": "cpp", + "compare": "cpp", + "concepts": "cpp", + "condition_variable": "cpp", + "cstdarg": "cpp", + "cstddef": "cpp", + "cstdint": "cpp", + "cstdlib": "cpp", + "cstring": "cpp", + "ctime": "cpp", + "cwchar": "cpp", + "cwctype": "cpp", + "deque": "cpp", + "list": "cpp", + "map": "cpp", + "set": "cpp", + "string": "cpp", + "unordered_map": "cpp", + "vector": "cpp", + "exception": "cpp", + "algorithm": "cpp", + "functional": "cpp", + "iterator": "cpp", + "memory": "cpp", + "memory_resource": "cpp", + "numeric": "cpp", + "random": "cpp", + "ratio": "cpp", + "string_view": "cpp", + "system_error": "cpp", + "tuple": "cpp", + "type_traits": "cpp", + "utility": "cpp", + "fstream": "cpp", + "initializer_list": "cpp", + "iosfwd": "cpp", + "iostream": "cpp", + "istream": "cpp", + "limits": "cpp", + "mutex": "cpp", + "new": "cpp", + "numbers": "cpp", + "ostream": "cpp", + "semaphore": "cpp", + "sstream": "cpp", + "stdexcept": "cpp", + "stop_token": "cpp", + "streambuf": "cpp", + "thread": "cpp", + "typeinfo": "cpp" + } +} \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index edb86eda..901cac69 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -95,11 +95,11 @@ install(TARGETS ${MODULE_NAME} DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/${STORAGE if(ENABLE_GNOME_NETWORKMANAGER) target_sources(${MODULE_NAME} PRIVATE NetworkManagerGnomeProxy.cpp - NetworkManagerGnomeWIFI.cpp - NetworkManagerGnomeEvents.cpp - NetworkManagerGnomeUtils.cpp ) + GnomeProxy/NetworkManagerGnomeUtils.cpp + GnomeProxy/NetworkManagerGnomeClient.cpp + ) target_include_directories(${MODULE_NAME} PRIVATE ${GLIB_INCLUDE_DIRS} ${LIBNM_INCLUDE_DIRS}) - target_link_libraries(${MODULE_NAME} PRIVATE ${LIBNM_LIBRARIES}) + target_link_libraries(${MODULE_NAME} PRIVATE ${GLIB_LIBRARIES} ${GIO_LIBRARIES}) else() target_sources(${MODULE_NAME} PRIVATE NetworkManagerRDKProxy.cpp) target_include_directories(${MODULE_NAME} PRIVATE ${IARMBUS_INCLUDE_DIRS}) diff --git a/GnomeProxy/NetworkManagerDbusMgr.cpp b/GnomeProxy/NetworkManagerDbusMgr.cpp new file mode 100644 index 00000000..8b896162 --- /dev/null +++ b/GnomeProxy/NetworkManagerDbusMgr.cpp @@ -0,0 +1,66 @@ +/** +* If not stated otherwise in this file or this component's LICENSE +* file the following copyright and licenses apply: +* +* Copyright 2022 RDK Management +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +**/ + +#include +#include +#include +#include + +namespace WPEFramework +{ + namespace Plugin + { + + DbusConnectionManager::DbusConnectionManager() : connection(nullptr) { + NMLOG_INFO("DbusConnectionManager created"); + } + + DbusConnectionManager::~DbusConnectionManager() { + DeinitializeDbusConnection(); + } + + bool DbusConnectionManager::InitializeBusConnection(const std::string& busName) { + GError* error = nullptr; + connection = g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, &error); + + if (!connection) { + NMLOG_ERROR("Failed to initialize D-Bus connection: %s ", error->message); + g_error_free(error); + return false; + } + + NMLOG_INFO("D-Bus connection initialized successfully for bus: %s", busName.c_str()); + return true; + } + + void DbusConnectionManager::DeinitializeDbusConnection() { + if (connection) { + g_object_unref(connection); + connection = nullptr; + NMLOG_INFO("D-Bus connection deinitialized successfully"); + } + } + + GDBusConnection* DbusConnectionManager::getConnection() const { + return connection; + } + + } // Plugin +} // WPEFramework + diff --git a/GnomeProxy/NetworkManagerDbusMgr.h b/GnomeProxy/NetworkManagerDbusMgr.h new file mode 100644 index 00000000..e799afc1 --- /dev/null +++ b/GnomeProxy/NetworkManagerDbusMgr.h @@ -0,0 +1,48 @@ +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 RDK Management + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once +#include +#include +#include +#include + +/* include NetworkManager.h for the defines, but we don't link against libnm. */ +// #include +#include + +namespace WPEFramework +{ + namespace Plugin + { + class DbusConnectionManager { + public: + DbusConnectionManager(); + ~DbusConnectionManager(); + + bool InitializeBusConnection(const std::string& busName); + void DeinitializeDbusConnection(); + GDBusConnection* getConnection() const; + + private: + GDBusConnection* connection; + }; + + } +} \ No newline at end of file diff --git a/GnomeProxy/NetworkManagerGnomeClient.cpp b/GnomeProxy/NetworkManagerGnomeClient.cpp new file mode 100644 index 00000000..efe8de43 --- /dev/null +++ b/GnomeProxy/NetworkManagerGnomeClient.cpp @@ -0,0 +1,360 @@ +/** +* If not stated otherwise in this file or this component's LICENSE +* file the following copyright and licenses apply: +* +* Copyright 2022 RDK Management +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +**/ + +#include +#include +#include +#include +#include + +#include "NetworkManagerLogger.h" +#include "NetworkManagerGnomeClient.h" +#include "NetworkManagerGnomeUtils.h" + +namespace WPEFramework +{ + namespace Plugin + { + + NetworkManagerClient::NetworkManagerClient() { + NMLOG_INFO("NetworkManagerClient created"); + if (!dbusConnection.InitializeBusConnection("org.freedesktop.NetworkManager")) { + NMLOG_ERROR("Failed to initialize D-Bus connection for NetworkManager"); + } + } + + NetworkManagerClient::~NetworkManagerClient() { + NMLOG_INFO("NetworkManagerClient destroyed"); + } + + static void fetssidandbssid(GVariant *setting80211, std::string &ssid, std::string &bssid) + { + GVariantIter iter; + const char *property_name; + GVariant *value; + char *printed_value; + + g_variant_iter_init(&iter, setting80211); + while (g_variant_iter_next(&iter, "{&sv}", &property_name, &value)) { + + printed_value = g_variant_print(value, FALSE); + if (strcmp(property_name, "seen-bssids") == 0) { + bssid.clear(); + GVariantIter bssid_iter; + g_variant_iter_init(&bssid_iter, value); + gchar *bssid_elem; + + if (g_variant_iter_next(&bssid_iter, "s", &bssid_elem)) { + bssid = bssid_elem; + NMLOG_VERBOSE("BSSID: %s", bssid.c_str()); + } + + //g_variant_iter_free(&bssid_iter); + } + else if (strcmp(property_name, "ssid") == 0) { + // Decode SSID from GVariant of type "ay" + gsize ssid_length = 0; + const guchar *ssid_data = static_cast(g_variant_get_fixed_array(value, &ssid_length, sizeof(guchar))); + if (ssid_data && ssid_length > 0 && ssid_length <= 32) { + ssid.assign(reinterpret_cast(ssid_data), ssid_length); + NMLOG_INFO("SSID: %s", ssid.c_str()); + } else { + NMLOG_ERROR("Invalid SSID length: %zu (maximum is 32)", ssid_length); + ssid.clear(); + } + } + } + + g_free(printed_value); + g_variant_unref(value); + } + + static bool fetchSSIDFromConnection(GDBusConnection *dbusConn, const std::string& path, std::list& ssids) + { + GError *error = NULL; + GDBusProxy *ConnProxy = NULL; + GVariant *settingsProxy= NULL, *connection= NULL, *sCon= NULL; + bool isFound; + const char *connId= NULL, *connTyp= NULL, *iface= NULL; + + ConnProxy = g_dbus_proxy_new_sync(dbusConn, + G_DBUS_PROXY_FLAGS_NONE, + NULL, + "org.freedesktop.NetworkManager", + path.c_str(), + "org.freedesktop.NetworkManager.Settings.Connection", + NULL, + &error); + + if (error != NULL) { + NMLOG_ERROR("Failed to create proxy: %s", error->message); + g_error_free(error); + return false; + } + + settingsProxy = g_dbus_proxy_call_sync(ConnProxy, + "GetSettings", + NULL, + G_DBUS_CALL_FLAGS_NONE, + -1, + NULL, + &error); + if (!settingsProxy) { + g_dbus_error_strip_remote_error(error); + NMLOG_WARNING("Failed to get connection settings: %s", error->message); + g_error_free(error); + } + + g_variant_get(settingsProxy, "(@a{sa{sv}})", &connection); + sCon = g_variant_lookup_value(connection, "connection", NULL); + g_assert(sCon != NULL); // TODO change error return + G_VARIANT_LOOKUP(sCon, "type", "&s", &connTyp); + G_VARIANT_LOOKUP(sCon, "interface-name", "&s", &iface); + NMLOG_VERBOSE("type= %s, iface= %s", connTyp, iface); + if(strcmp(connTyp,"802-11-wireless") == 0 && strcmp(iface,"wlan0") == 0) + { + GVariant *setting = g_variant_lookup_value(connection, "802-11-wireless", NULL); + if (setting) { + std::string ssid, bssid; + fetssidandbssid(setting, ssid, bssid); + if(!ssid.empty()) + ssids.push_back(ssid); + g_variant_unref(setting); + } + } + + if (sCon) + g_variant_unref(sCon); + if (connection) + g_variant_unref(connection); + if (settingsProxy) + g_variant_unref(settingsProxy); + g_object_unref(ConnProxy); + + return true; + } + + bool NetworkManagerClient::getKnownSSIDs(std::list& ssids) + { + std::list paths; + if(!GnomeUtils::getConnectionPaths(dbusConnection.getConnection(), paths)) + { + NMLOG_ERROR("Connection path fetch failed"); + return false; + } + + for (const std::string& path : paths) { + NMLOG_VERBOSE("connection path %s", path.c_str()); + fetchSSIDFromConnection(dbusConnection.getConnection(), path, ssids); + } + + if(ssids.empty()) + return false; + return true; + } + + bool NetworkManagerClient::getConnectedSSID() + { + std::string wifiDevicePath; + GError* error = NULL; + GDBusProxy* wProxy = NULL; + GVariant* result = NULL; + gchar *activeApPath = NULL; + bool ret = false; + NMDeviceState state; + + if(GnomeUtils::getDeviceState(dbusConnection.getConnection(), "wlan0", state) && state < NM_DEVICE_STATE_DISCONNECTED) + { + NMDeviceStateReason StateReason; + GnomeUtils::getDeviceStateReason(dbusConnection.getConnection(), "wlan0", StateReason); + NMLOG_ERROR("wifi device state is invallied"); + return false; + } + + if(!GnomeUtils::getDeviceByIpIface(dbusConnection.getConnection(),"wlan0", wifiDevicePath)) + { + NMLOG_ERROR("no wifi device found"); + return false; + } + + //TODO check active connection path and return properties + wProxy = g_dbus_proxy_new_sync(dbusConnection.getConnection(), + G_DBUS_PROXY_FLAGS_NONE, + NULL, + "org.freedesktop.NetworkManager", + wifiDevicePath.c_str(), + "org.freedesktop.NetworkManager.Device.Wireless", + NULL, // GCancellable + &error); + + if (error) { + NMLOG_ERROR("Error creating proxy: %s", error->message); + g_error_free(error); + return false; + } + + result = g_dbus_proxy_get_cached_property(wProxy, "ActiveAccessPoint"); + if (!result) { + NMLOG_ERROR("Failed to get ActiveAccessPoint property."); + g_object_unref(wProxy); + return false; + } + + g_variant_get(result, "o", &activeApPath); + if(g_strdup(activeApPath) != NULL && g_strcmp0(activeApPath, "/") != 0) + { + NMLOG_TRACE("ActiveAccessPoint property path %s", activeApPath); + apProperties apDetails; + if(GnomeUtils::getApDetails(dbusConnection.getConnection(), g_strdup(activeApPath), apDetails)) + { + NMLOG_INFO("getApDetails success"); + ret = true; + } + } + else + NMLOG_ERROR("active access point not found"); + + g_variant_unref(result); + g_object_unref(wProxy); + return ret; + } + + bool NetworkManagerClient::getAvailableSSIDs(std::list& ssids) + { + // TODO Wifi device state fix it + GError* error = nullptr; + GDBusProxy* wProxy = nullptr; + std::string wifiDevicePath; + NMDeviceState state; + + if(GnomeUtils::getDeviceState(dbusConnection.getConnection(), "wlan0", state) && state < NM_DEVICE_STATE_DISCONNECTED) + { + NMDeviceStateReason StateReason; + GnomeUtils::getDeviceStateReason(dbusConnection.getConnection(), "wlan0", StateReason); + NMLOG_ERROR("wifi device state is invallied"); + return false; + } + + if(!GnomeUtils::getDeviceByIpIface(dbusConnection.getConnection(),"wlan0", wifiDevicePath)) + { + NMLOG_ERROR("no wifi device found"); + return false; + } + + wProxy = g_dbus_proxy_new_sync(dbusConnection.getConnection(), + G_DBUS_PROXY_FLAGS_NONE, + NULL, + "org.freedesktop.NetworkManager", + wifiDevicePath.c_str(), + "org.freedesktop.NetworkManager.Device.Wireless", + NULL, + &error); + + if (error) { + NMLOG_ERROR("Error creating proxy: %s", error->message); + g_error_free(error); + return false; + } + + GVariant* result = g_dbus_proxy_call_sync(wProxy, "GetAccessPoints", NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); + // TODO change to GetAllAccessPoints to include hidden ssid + if (error) { + NMLOG_ERROR("Error creating proxy: %s", error->message); + g_error_free(error); + g_object_unref(wProxy); + return false; + } + + GVariantIter* iter; + const gchar* apPath; + g_variant_get(result, "(ao)", &iter); + + while (g_variant_iter_loop(iter, "o", &apPath)) { + apProperties apDetails; + NMLOG_VERBOSE("Access Point Path: %s", apPath); + if(!GnomeUtils::getApDetails(dbusConnection.getConnection(), apPath, apDetails)) + { + NMLOG_WARNING("getApDetails failed"); + } + } + + g_variant_iter_free(iter); + g_variant_unref(result); + g_object_unref(wProxy); + + return true; + } + + bool NetworkManagerClient::startWifiScanning(const std::string& ssid) + { + GError* error = NULL; + GDBusProxy* wProxy = NULL; + std::string wifiDevicePath; + if(!GnomeUtils::getDeviceByIpIface(dbusConnection.getConnection(),"wlan0", wifiDevicePath)) + { + NMLOG_ERROR("no wifi device found"); + return false; + } + + wProxy = g_dbus_proxy_new_sync(dbusConnection.getConnection(), + G_DBUS_PROXY_FLAGS_NONE, + NULL, + "org.freedesktop.NetworkManager", + wifiDevicePath.c_str(), + "org.freedesktop.NetworkManager.Device.Wireless", + NULL, + &error); + + if (error) { + NMLOG_ERROR("Error creating proxy: %s", error->message); + g_error_free(error); + return false; + } + + GVariant *options = NULL; + if (!ssid.empty()) { + NMLOG_INFO("staring wifi scanning .. %s", ssid.c_str()); + GVariantBuilder builder, array_builder; + g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT); + g_variant_builder_init(&array_builder, G_VARIANT_TYPE("aay")); + g_variant_builder_add(&array_builder, "@ay", + g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, (const guint8 *) ssid.c_str(), ssid.length(), 1) + ); + g_variant_builder_add(&builder, "{sv}", "ssids", g_variant_builder_end(&array_builder)); + g_variant_builder_add(&builder, "{sv}", "hidden", g_variant_new_boolean(TRUE)); + options = g_variant_builder_end(&builder); + } + + g_dbus_proxy_call_sync(wProxy, "RequestScan", g_variant_new("(a{sv})", options), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); + if (error) { + NMLOG_ERROR("Error RequestScan: %s", error->message); + g_error_free(error); + g_object_unref(wProxy); + return false; + } + + if(options) + g_variant_unref(options); + g_object_unref(wProxy); + + return true; + } + + } // WPEFramework +} // Plugin diff --git a/GnomeProxy/NetworkManagerGnomeClient.h b/GnomeProxy/NetworkManagerGnomeClient.h new file mode 100644 index 00000000..40c1bdab --- /dev/null +++ b/GnomeProxy/NetworkManagerGnomeClient.h @@ -0,0 +1,58 @@ +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 RDK Management + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once +#include +#include +#include +#include + +#include "NetworkManagerLogger.h" +#include "NetworkManagerDbusMgr.h" + +namespace WPEFramework +{ + namespace Plugin + { + class NetworkManagerClient + { + public: + static NetworkManagerClient* getInstance() + { + static NetworkManagerClient instance; + return &instance; + } + + NetworkManagerClient(const NetworkManagerClient&) = delete; + NetworkManagerClient& operator=(const NetworkManagerClient&) = delete; + + bool getKnownSSIDs(std::list& ssids); + bool getAvailableSSIDs(std::list& ssids); + bool getConnectedSSID(); + bool startWifiScanning(const std::string& ssid); + + private: + + NetworkManagerClient(); + ~NetworkManagerClient(); + + DbusConnectionManager dbusConnection; + }; + } // Plugin +} // WPEFramework \ No newline at end of file diff --git a/GnomeProxy/NetworkManagerGnomeUtils.cpp b/GnomeProxy/NetworkManagerGnomeUtils.cpp new file mode 100644 index 00000000..558d754b --- /dev/null +++ b/GnomeProxy/NetworkManagerGnomeUtils.cpp @@ -0,0 +1,370 @@ +/** +* If not stated otherwise in this file or this component's LICENSE +* file the following copyright and licenses apply: +* +* Copyright 2022 RDK Management +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +**/ + +#include +#include +#include +#include + +#include "NetworkManagerLogger.h" +#include "NetworkManagerGnomeUtils.h" +#include "NetworkManagerDbusMgr.h" + +namespace WPEFramework +{ + namespace Plugin + { + static const char* ifnameEth = "eth0"; + static const char* ifnameWlan = "wlan0"; + + void GnomeUtils::printKeyVariant(const char *setting_name, GVariant *setting) + { + GVariantIter iter; + const char *property_name; + GVariant *value; + char *printed_value; + + NMLOG_VERBOSE(" %s:", setting_name); + g_variant_iter_init(&iter, setting); + while (g_variant_iter_next(&iter, "{&sv}", &property_name, &value)) { + printed_value = g_variant_print(value, FALSE); + if (strcmp(printed_value, "[]") != 0) + NMLOG_VERBOSE(" %s: %s", property_name, printed_value); + g_free(printed_value); + g_variant_unref(value); + } + } + + bool GnomeUtils::getDeviceByIpIface(GDBusConnection *connection, const gchar *iface_name, std::string& path) + { + GError *error = NULL; + GVariant *result; + gchar *device_path = NULL; + bool ret = false; + + result = g_dbus_connection_call_sync( + connection, + "org.freedesktop.NetworkManager", // D-Bus name + "/org/freedesktop/NetworkManager", // Object path + "org.freedesktop.NetworkManager", // Interface + "GetDeviceByIpIface", // Method name + g_variant_new("(s)", iface_name), // Input parameter (the interface name) + G_VARIANT_TYPE("(o)"), // Expected return type (object path) + G_DBUS_CALL_FLAGS_NONE, + -1, // Default timeout + NULL, + &error + ); + + if (error != NULL) { + NMLOG_ERROR("calling GetDeviceByIpIface: %s", error->message); + g_error_free(error); + return ret; + } + + g_variant_get(result, "(o)", &device_path); + if(g_strdup(device_path) != NULL) + { + path = std::string(g_strdup(device_path)); + ret = true; + } + + //NMLOG_TRACE("%s device path %s", iface_name, path.c_str()); + g_variant_unref(result); + return ret; + } + + static bool get_cached_property_u(GDBusProxy* proxy, const char* propertiy, uint32_t value) + { + GVariant* result = NULL; + result = g_dbus_proxy_get_cached_property(proxy, propertiy); + if (!result) { + NMLOG_ERROR("Failed to get AP properties"); + g_object_unref(proxy); + return false; + } + g_variant_get(result, "u", &value); + NMLOG_TRACE("%s: %d", propertiy, value); + g_variant_unref(result); + return true; + } + + bool GnomeUtils::getApDetails(GDBusConnection *connection, const char* apPath, apProperties& apDetails) + { + char *bssid = NULL; + uint8_t strength = 0; + GError* error = NULL; + GVariant* result = NULL; + + GDBusProxy* proxy = g_dbus_proxy_new_sync(connection, + G_DBUS_PROXY_FLAGS_NONE, + NULL, + "org.freedesktop.NetworkManager", + apPath, + "org.freedesktop.NetworkManager.AccessPoint", + NULL, + &error); + + if (error) { + NMLOG_ERROR("creating proxy: %s", error->message); + g_error_free(error); + return false; + } + + gsize ssid_length = 0; + result = g_dbus_proxy_get_cached_property(proxy,"Ssid"); + if (!result) { + NMLOG_ERROR("Failed to get AP properties."); + g_object_unref(proxy); + return false; + } + const guchar *ssid_data = static_cast(g_variant_get_fixed_array(result, &ssid_length, sizeof(guchar))); + if (ssid_data && ssid_length > 0 && ssid_length <= 32) { + apDetails.ssid.assign(reinterpret_cast(ssid_data), ssid_length); + NMLOG_TRACE("SSID: %s", apDetails.ssid.c_str()); + } else { + NMLOG_ERROR("Invalid SSID length: %zu (maximum is 32)", ssid_length); + apDetails.ssid="---"; + } + g_variant_unref(result); + + result = g_dbus_proxy_get_cached_property(proxy,"HwAddress"); + if (!result) { + NMLOG_ERROR("Failed to get AP properties."); + g_object_unref(proxy); + return false; + } + g_variant_get(result, "s", &bssid); + apDetails.bssid.assign(bssid); + NMLOG_TRACE("bssid %s", apDetails.bssid.c_str()); + g_variant_unref(result); + + result = g_dbus_proxy_get_cached_property(proxy,"Strength"); + if (!result) { + NMLOG_ERROR("Failed to get AP properties."); + g_object_unref(proxy); + return false; + } + g_variant_get(result, "y", &strength); + NMLOG_TRACE("strength %d", strength); + g_variant_unref(result); + + get_cached_property_u(proxy, "Flags", apDetails.flags); + get_cached_property_u(proxy, "WpaFlags", apDetails.wpaFlags); + get_cached_property_u(proxy, "RsnFlags", apDetails.rsnFlags); + get_cached_property_u(proxy, "Mode", apDetails.mode); + get_cached_property_u(proxy, "Frequency", apDetails.frequency); + + g_object_unref(proxy); + + return true; + } + + bool GnomeUtils::getConnectionPaths(GDBusConnection *dbusConn, std::list& pathsList) + { + GDBusProxy *sProxy= NULL; + GError *error= NULL; + GVariant *listProxy = NULL; + char **paths = NULL; + + sProxy = g_dbus_proxy_new_sync(dbusConn, + G_DBUS_PROXY_FLAGS_NONE, + NULL, + "org.freedesktop.NetworkManager", + "/org/freedesktop/NetworkManager/Settings", + "org.freedesktop.NetworkManager.Settings", + NULL, // GCancellable + &error); + + if(sProxy == NULL) + { + if (error != NULL) { + NMLOG_ERROR("Failed to create proxy: %s", error->message); + g_error_free(error); + } + return false; + } + + listProxy = g_dbus_proxy_call_sync(sProxy, + "ListConnections", + NULL, + G_DBUS_CALL_FLAGS_NONE, + -1, + NULL, + &error); + if(listProxy == NULL) + { + if (!error) { + NMLOG_ERROR("ListConnections failed: %s", error->message); + g_error_free(error); + g_object_unref(sProxy); + return false; + } + else + NMLOG_ERROR("ListConnections proxy failed no error message"); + } + + g_variant_get(listProxy, "(^ao)", &paths); + g_variant_unref(listProxy); + + if(paths == NULL) + { + NMLOG_WARNING("no connection path available"); + g_object_unref(sProxy); + return false; + } + + for (int i = 0; paths[i]; i++) { + NMLOG_VERBOSE("Connection path: %s", paths[i]); + pathsList.push_back(paths[i]); + } + + g_object_unref(sProxy); + if(pathsList.empty()) + return false; + + return true; + } + + bool GnomeUtils::getDeviceState(GDBusConnection *dbusConn, const gchar *iface_name, NMDeviceState& state) + { + GError *error = NULL; + GVariant *result; + std::string ifaceDevicePath; + + if(!GnomeUtils::getDeviceByIpIface(dbusConn, iface_name, ifaceDevicePath) && !ifaceDevicePath.empty()) + { + NMLOG_ERROR("Interface unknow to NetworkManger Deamon"); + return false; + } + + result = g_dbus_connection_call_sync( + dbusConn, + "org.freedesktop.NetworkManager", // D-Bus name + ifaceDevicePath.c_str(), // Object path + "org.freedesktop.DBus.Properties", // Interface for property access + "Get", // Method name for getting a property + g_variant_new("(ss)", // Input parameters (interface, property name) + "org.freedesktop.NetworkManager.Device", // Interface name + "State"), // Property name + G_VARIANT_TYPE("(v)"), // Expected return type (variant) + G_DBUS_CALL_FLAGS_NONE, + -1, // Default timeout + NULL, + &error + ); + if (error != NULL) { + NMLOG_ERROR("failed to DBus.Properties: %s", error->message); + g_error_free(error); + } else { + GVariant *variantValue; + g_variant_get(result, "(v)", &variantValue); + + state = static_cast(g_variant_get_uint32(variantValue)); + NMLOG_TRACE("Device state: %u", state); + + g_variant_unref(variantValue); + g_variant_unref(result); + return true; + } + + return false; + } + + bool GnomeUtils::getDeviceStateReason(GDBusConnection *dbusConn, const gchar *iface_name, NMDeviceStateReason& StateReason) + { + GError *error = NULL; + GVariant *resultReason; + std::string ifaceDevicePath; + + if(!GnomeUtils::getDeviceByIpIface(dbusConn, iface_name, ifaceDevicePath) && !ifaceDevicePath.empty()) + { + NMLOG_ERROR("Interface unknow to NetworkManger Deamon"); + return false; + } + + resultReason = g_dbus_connection_call_sync( dbusConn, + "org.freedesktop.NetworkManager", + ifaceDevicePath.c_str(), + "org.freedesktop.DBus.Properties", + "Get", + g_variant_new("(ss)", + "org.freedesktop.NetworkManager.Device", + "StateReason"), + G_VARIANT_TYPE("(v)"), + G_DBUS_CALL_FLAGS_NONE, + -1, + NULL, + &error + ); + + if (error != NULL) { + NMLOG_ERROR("getting StateReason property: %s", error->message); + g_error_free(error); + } else if (resultReason != NULL) { + GVariant *variantReason; + g_variant_get(resultReason, "(v)", &variantReason); + + guint32 state_reason_code, state_reason_detail; + g_variant_get(variantReason, "(uu)", &state_reason_code, &state_reason_detail); + NMLOG_WARNING("Device state reason: %u (detail: %u)", state_reason_code, state_reason_detail); + g_variant_unref(variantReason); + g_variant_unref(resultReason); + return true; + } + return false; + } + + DbusConnectionManager::DbusConnectionManager() : connection(nullptr) { + NMLOG_INFO("DbusConnectionManager created"); + } + + DbusConnectionManager::~DbusConnectionManager() { + DeinitializeDbusConnection(); + } + + bool DbusConnectionManager::InitializeBusConnection(const std::string& busName) { + GError* error = nullptr; + connection = g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, &error); + + if (!connection) { + NMLOG_ERROR("Failed to initialize D-Bus connection: %s ", error->message); + g_error_free(error); + return false; + } + + NMLOG_INFO("D-Bus connection initialized successfully for bus: %s", busName.c_str()); + return true; + } + + void DbusConnectionManager::DeinitializeDbusConnection() { + if (connection) { + g_object_unref(connection); + connection = nullptr; + NMLOG_INFO("D-Bus connection deinitialized successfully"); + } + } + + GDBusConnection* DbusConnectionManager::getConnection() const { + return connection; + } + + } // Plugin +} // WPEFramework + diff --git a/Tests/dbus-api-test/NetworkManagerGnomeUtils.h b/GnomeProxy/NetworkManagerGnomeUtils.h similarity index 61% rename from Tests/dbus-api-test/NetworkManagerGnomeUtils.h rename to GnomeProxy/NetworkManagerGnomeUtils.h index eb6125c3..e0744c82 100644 --- a/Tests/dbus-api-test/NetworkManagerGnomeUtils.h +++ b/GnomeProxy/NetworkManagerGnomeUtils.h @@ -1,4 +1,4 @@ - /* +/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * @@ -22,13 +22,9 @@ #include #include #include -#include -#include -#include -#include /* include NetworkManager.h for the defines, but we don't link against libnm. */ -//#include +// #include #include struct apProperties @@ -43,16 +39,22 @@ struct apProperties uint8_t strength; }; -class GnomeUtils +namespace WPEFramework { - public: - static bool getDeviceByIpIface(GDBusConnection *connection, const gchar *iface_name, std::string& path); - static bool getApDetails(GDBusConnection *connection, const char* apPath, apProperties& apDetails); - static bool getConnectionPaths(GDBusConnection *dbusConn, std::list& pathsList); - static bool getDeviceState(GDBusConnection *dbusConn, const gchar *iface_name, NMDeviceState& state); - static bool getDeviceStateReason(GDBusConnection *dbusConn, const gchar *iface_name, NMDeviceStateReason& StateReason); -}; + namespace Plugin + { + class GnomeUtils { + public: + static void printKeyVariant(const char *setting_name, GVariant *setting); + static bool getDeviceByIpIface(GDBusConnection *dbusConn, const gchar *iface_name, std::string& path); + static bool getApDetails(GDBusConnection *dbusConn, const char* apPath, apProperties& apDetails); + static bool getConnectionPaths(GDBusConnection *dbusConn, std::list& pathsList); + static bool getDeviceState(GDBusConnection *dbusConn, const gchar *iface_name, NMDeviceState& state); + static bool getDeviceStateReason(GDBusConnection *dbusConn, const gchar *iface_name, NMDeviceStateReason& StateReason); + }; + } // Plugin +} // WPEFramework #define G_VARIANT_LOOKUP(dict, key, format, ...) \ if (!g_variant_lookup(dict, key, format, __VA_ARGS__)) {\ diff --git a/NetworkManagerGnomeProxy.cpp b/NetworkManagerGnomeProxy.cpp index 5104d2ee..d4789286 100644 --- a/NetworkManagerGnomeProxy.cpp +++ b/NetworkManagerGnomeProxy.cpp @@ -1,12 +1,5 @@ #include "NetworkManagerImplementation.h" -#include "NetworkManagerGnomeWIFI.h" -#include "NetworkManagerGnomeEvents.h" -#include "NetworkManagerGnomeUtils.h" -#include -#include -#include -static NMClient *client = NULL; using namespace WPEFramework; using namespace WPEFramework::Plugin; using namespace std; @@ -15,13 +8,7 @@ namespace WPEFramework { namespace Plugin { - wifiManager *wifi = nullptr; - GnomeNetworkManagerEvents *nmEvent = nullptr; - const float signalStrengthThresholdExcellent = -50.0f; - const float signalStrengthThresholdGood = -60.0f; - const float signalStrengthThresholdFair = -67.0f; NetworkManagerImplementation* _instance = nullptr; - void NetworkManagerInternalEventHandler(const char *owner, int eventId, void *data, size_t len) { return; @@ -30,669 +17,101 @@ namespace WPEFramework void NetworkManagerImplementation::platform_init() { ::_instance = this; - GError *error = NULL; - // initialize the NMClient object - client = nm_client_new(NULL, &error); - if (client == NULL) { - NMLOG_TRACE("Error initializing NMClient: %s", error->message); - g_error_free(error); - return; - } - - nmEvent = GnomeNetworkManagerEvents::getInstance(); - nmEvent->startNetworkMangerEventMonitor(); - wifi = wifiManager::getInstance(); - return; } uint32_t NetworkManagerImplementation::GetAvailableInterfaces (Exchange::INetworkManager::IInterfaceDetailsIterator*& interfacesItr/* @out */) { - uint32_t rc = Core::ERROR_RPC_CALL_FAILED; - NMDeviceType type; - NMDeviceState state; - NMDevice *device = NULL; - static std::vector interfaceList; - - if(interfaceList.empty()) - { - std::string interfaces[2]; - if(!nmUtils::GetInterfacesName(interfaces[0], interfaces[1])) - { - NMLOG_WARNING("GetInterface Name Error !"); - return Core::ERROR_GENERAL; - } - for (size_t i = 0; i < 2; i++) - { - if(!interfaces[i].empty()) - { - Exchange::INetworkManager::InterfaceDetails tmp; - device = nm_client_get_device_by_iface(client, interfaces[i].c_str()); - if (device) - { - if(i == 0) - tmp.m_type = string("WIFI"); - else - tmp.m_type = string("ETHERNET"); - tmp.m_name = interfaces[i].c_str(); - tmp.m_mac = nm_device_get_hw_address(device); - state = nm_device_get_state(device); - tmp.m_isEnabled = (state > NM_DEVICE_STATE_UNAVAILABLE) ? true : false; - tmp.m_isConnected = (state > NM_DEVICE_STATE_DISCONNECTED) ? true : false; - interfaceList.push_back(tmp); - //g_clear_object(&device); - } - } - } - } - - using Implementation = RPC::IteratorType; - interfacesItr = Core::Service::Create(interfaceList); - rc = Core::ERROR_NONE; - return rc; + return Core::ERROR_NONE; } - /* @brief Get the active Interface used for external world communication */ uint32_t NetworkManagerImplementation::GetPrimaryInterface (string& interface /* @out */) { - uint32_t rc = Core::ERROR_RPC_CALL_FAILED; - GError *error = NULL; - NMActiveConnection *activeConn = NULL; - NMRemoteConnection *remoteConn = NULL; - if(client == nullptr) - { - NMLOG_WARNING("client connection null:"); - return Core::ERROR_GENERAL; - } - - activeConn = nm_client_get_primary_connection(client); - if (activeConn == NULL) { - NMLOG_ERROR("No active activeConn Interface found"); - return Core::ERROR_GENERAL; - } - remoteConn = nm_active_connection_get_connection(activeConn); - if(remoteConn == NULL) - { - NMLOG_WARNING("remote connection error"); - return Core::ERROR_GENERAL; - } - interface.clear(); - const char *ifacePtr = nm_connection_get_interface_name(NM_CONNECTION(remoteConn)); - if(ifacePtr == NULL) - { - NMLOG_ERROR("nm_connection_get_interface_name is failed"); - return Core::ERROR_GENERAL; - } - interface = ifacePtr; - if(interface != "eth0" && interface != "wlan0") - { - NMLOG_TRACE("interface name is unknow"); - interface.clear(); - } - else - rc = Core::ERROR_NONE; - - return rc; + return Core::ERROR_NONE; } - /* @brief Set the active Interface used for external world communication */ uint32_t NetworkManagerImplementation::SetPrimaryInterface (const string& interface/* @in */) { - uint32_t rc = Core::ERROR_RPC_CALL_FAILED; - if(client == nullptr) - { - NMLOG_WARNING("client connection null:"); - return Core::ERROR_RPC_CALL_FAILED; - } - - std::string iface = "eth0"; - std::string eth, wifi; - if(!nmUtils::GetInterfacesName(wifi, eth)) - { - NMLOG_WARNING("GetInterface Name Error !"); - return Core::ERROR_GENERAL; - } - - else if(interface == "wlan0" || nmUtils::caseInsensitiveCompare(interface,"WIFI")) - iface = wifi; - else if(interface == "eth0" || nmUtils::caseInsensitiveCompare(interface,"ETHERNET")) - iface = eth; - - NMDevice *device = nm_client_get_device_by_iface(client, iface.c_str()); - if (device == NULL) { - NMLOG_WARNING("no interface found "); - return Core::ERROR_GENERAL; - } - const GPtrArray *connections = nm_client_get_connections(client); - NMConnection *conn = NULL; - NMSettingConnection *settings; - NMRemoteConnection *remoteConnection; - for (guint i = 0; i < connections->len; i++) { - NMConnection *connection = NM_CONNECTION(connections->pdata[i]); - settings = nm_connection_get_setting_connection(connection); - - /* Check if the interface name matches */ - if (g_strcmp0(nm_setting_connection_get_interface_name(settings), iface.c_str()) == 0) { - conn = connection; - break; - } - } - if(conn == NULL) - { - NMLOG_WARNING("no nm setting available for the interface"); - return Core::ERROR_GENERAL; - } - g_object_set(settings, - NM_SETTING_CONNECTION_AUTOCONNECT, - true, - NM_SETTING_CONNECTION_AUTOCONNECT_PRIORITY, - NM_SETTING_CONNECTION_AUTOCONNECT_PRIORITY_MAX, - NULL); - const char *uuid = nm_connection_get_uuid(conn); - remoteConnection = nm_client_get_connection_by_uuid(client, uuid); - nm_remote_connection_commit_changes(remoteConnection, false, NULL, NULL); - - return rc; + return Core::ERROR_NONE; } uint32_t NetworkManagerImplementation::SetInterfaceState(const string& interface/* @in */, const bool& enabled /* @in */) { - uint32_t rc = Core::ERROR_NONE; - if(client == nullptr) - { - NMLOG_WARNING("client connection null:"); - return Core::ERROR_RPC_CALL_FAILED; - } - - std::string iface = "eth0"; - std::string eth, wifi; - if(!nmUtils::GetInterfacesName(wifi, eth)) - { - NMLOG_WARNING("GetInterface Name Error !"); - return Core::ERROR_GENERAL; - } - - else if(interface == "wlan0" || nmUtils::caseInsensitiveCompare(interface,"WIFI")) - iface = wifi; - else if(interface == "eth0" || nmUtils::caseInsensitiveCompare(interface,"ETHERNET")) - iface = eth; - - const GPtrArray *devices = nm_client_get_devices(client); - NMDevice *device = NULL; - - for (guint i = 0; i < devices->len; ++i) { - device = NM_DEVICE(g_ptr_array_index(devices, i)); - const char *name = nm_device_get_iface(device); - if (g_strcmp0(name, iface.c_str()) == 0) { - nm_device_set_managed(device, enabled); - NMLOG_INFO("Interface %s status set to %s", iface.c_str(), enabled ? "Enabled" : "Disabled"); - } - } - - // if(device) - // g_clear_object(&device); - return rc; + return Core::ERROR_NONE; } uint32_t NetworkManagerImplementation::GetInterfaceState(const string& interface/* @in */, bool& isEnabled /* @out */) { - uint32_t rc = Core::ERROR_NONE; -#if 0 //FIXME - const GPtrArray *devices = nm_client_get_devices(client); - NMDevice *device = NULL; - - for (guint i = 0; i < devices->len; ++i) { - device = NM_DEVICE(g_ptr_array_index(devices, i)); - - // Get the device details - const char *name = nm_device_get_iface(device); - - // Check if the device name matches - if (g_strcmp0(name, interface.c_str()) == 0) { - nm_device_set_managed(device, false); - - NMLOG_TRACE("Interface %s status set to disabled", - interface.c_str()); - } - } - - // Cleanup - if(device) - g_clear_object(&device); -#endif - return rc; + return Core::ERROR_NONE; } - /* @brief Get IP Address Of the Interface */ uint32_t NetworkManagerImplementation::GetIPSettings(const string& interface /* @in */, const string& ipversion /* @in */, IPAddressInfo& result /* @out */) { - uint32_t rc = Core::ERROR_RPC_CALL_FAILED; - NMActiveConnection *conn = NULL; - NMIPConfig *ip4_config = NULL; - NMIPConfig *ip6_config = NULL; - const gchar *gateway = NULL; - char **dns_arr = NULL; - NMDhcpConfig *dhcp4_config = NULL; - NMDhcpConfig *dhcp6_config = NULL; - const char* dhcpserver; - NMSettingConnection *settings; - NMIPAddress *address = NULL; - NMDevice *device = NULL; - - if(client == nullptr) - { - NMLOG_WARNING("client connection null:"); - return Core::ERROR_RPC_CALL_FAILED; - } - - std::string iface = "eth0"; - std::string ethIface, wifiIface; - if(!nmUtils::GetInterfacesName(wifiIface, ethIface)) - { - NMLOG_WARNING("GetInterface Name Error !"); - return Core::ERROR_GENERAL; - } - - else if(interface == "wlan0" || nmUtils::caseInsensitiveCompare(interface,"WIFI")) - iface = wifiIface; - else if(interface == "eth0" || nmUtils::caseInsensitiveCompare(interface,"ETHERNET")) - iface = ethIface; - else - { - if(Core::ERROR_NONE != GetPrimaryInterface(iface)) - { - NMLOG_WARNING("interface is not specified and default interface get failed"); - return Core::ERROR_GENERAL; - } - } - - device = nm_client_get_device_by_iface(client, iface.c_str()); - if (device == NULL) { - NMLOG_WARNING("no interface found / wifi not connected no ip found"); - return Core::ERROR_GENERAL; - } - - NMDeviceState deviceState = NM_DEVICE_STATE_UNKNOWN; - deviceState = nm_device_get_state(device); - if(deviceState != NM_DEVICE_STATE_ACTIVATED) - { - NMLOG_WARNING("device state is not activated state: (%d)", deviceState); - return Core::ERROR_GENERAL; - } - - if(ipversion.empty()) - NMLOG_WARNING("ipversion is empty default value IPV4"); - - const GPtrArray *connections = nm_client_get_active_connections(client); - if(connections == NULL) - { - NMLOG_WARNING("nm_client_get_active_connections error"); - return Core::ERROR_GENERAL; - } - for (guint i = 0; i < connections->len; i++){ - NMActiveConnection *connection = NM_ACTIVE_CONNECTION(connections->pdata[i]); - settings = nm_connection_get_setting_connection(NM_CONNECTION(nm_active_connection_get_connection(connection))); - - /* Check if the interface name matches */ - if (g_strcmp0(nm_setting_connection_get_interface_name(settings), iface.c_str()) == 0) { - conn = connection; - break; - } - } - if (conn == NULL) { - NMLOG_ERROR("no active connection found"); - return Core::ERROR_GENERAL; - } - - if(ipversion.empty()||nmUtils::caseInsensitiveCompare(ipversion,"IPV4")) - { - ip4_config = nm_active_connection_get_ip4_config(conn); - if (ip4_config != NULL) { - const GPtrArray *p; - int i; - p = nm_ip_config_get_addresses(ip4_config); - for (i = 0; i < p->len; i++) { - address = static_cast(p->pdata[i]); - } - gateway = nm_ip_config_get_gateway(ip4_config); - } - dns_arr = (char **)nm_ip_config_get_nameservers(ip4_config); - - dhcp4_config = nm_active_connection_get_dhcp4_config(conn); - dhcpserver = nm_dhcp_config_get_one_option (dhcp4_config, - "dhcp_server_identifier"); - if(!ipversion.empty()) - result.m_ipAddrType = ipversion.c_str(); - else - result.m_ipAddrType = "IPv4"; - if(dhcpserver) - result.m_dhcpServer = dhcpserver; - result.m_v6LinkLocal = ""; - result.m_ipAddress = nm_ip_address_get_address(address); - result.m_prefix = nm_ip_address_get_prefix(address); - result.m_gateway = gateway; - if((*(&dns_arr[0]))!=NULL) - result.m_primaryDns = *(&dns_arr[0]); - if((*(&dns_arr[1]))!=NULL ) - result.m_secondaryDns = *(&dns_arr[1]); - - rc = Core::ERROR_NONE; - } - else if(nmUtils::caseInsensitiveCompare(ipversion,"IPV6")) - { - NMIPAddress *a; - ip6_config = nm_active_connection_get_ip6_config(conn); - if (ip6_config != NULL) { - const GPtrArray *p; - int i; - p = nm_ip_config_get_addresses(ip6_config); - for (i = 0; i < p->len; i++) { - a = static_cast(p->pdata[i]); - result.m_ipAddress = nm_ip_address_get_address(a); - NMLOG_TRACE("\tinet6 %s/%d\n", nm_ip_address_get_address(a), nm_ip_address_get_prefix(a)); - } - gateway = nm_ip_config_get_gateway(ip6_config); - - dns_arr = (char **)nm_ip_config_get_nameservers(ip6_config); - - dhcp6_config = nm_active_connection_get_dhcp6_config(conn); - dhcpserver = nm_dhcp_config_get_one_option (dhcp6_config, - "dhcp_server_identifier"); - result.m_ipAddrType = ipversion.c_str(); - if(dhcpserver) - result.m_dhcpServer = dhcpserver; - result.m_v6LinkLocal = ""; - result.m_prefix = 0; - result.m_gateway = gateway; - if((*(&dns_arr[0]))!=NULL) - result.m_primaryDns = *(&dns_arr[0]); - if((*(&dns_arr[1]))!=NULL ) - result.m_secondaryDns = *(&dns_arr[1]); - } - rc = Core::ERROR_NONE; - } - else - NMLOG_WARNING("ipversion is not IPV4 orIPV6"); - return rc; - } - - // Callback for nm_client_deactivate_connection_async - static void on_deactivate_complete(GObject *source_object, GAsyncResult *res, gpointer user_data) { - GError *error = NULL; - - // Check if the operation was successful - if (!nm_client_deactivate_connection_finish(NM_CLIENT(source_object), res, &error)) { - NMLOG_TRACE("Deactivating connection failed: %s", error->message); - g_error_free(error); - } else { - NMLOG_TRACE("Deactivating connection successful"); - } - } - - // Callback for nm_client_activate_connection_async - static void on_activate_complete(GObject *source_object, GAsyncResult *res, gpointer user_data) { - GError *error = NULL; - - // Check if the operation was successful - if (!nm_client_activate_connection_finish(NM_CLIENT(source_object), res, &error)) { - NMLOG_TRACE("Activating connection failed: %s", error->message); - g_error_free(error); - } else { - NMLOG_TRACE("Activating connection successful"); - } - - g_main_loop_quit((GMainLoop*)user_data); + return Core::ERROR_NONE; } - - /* @brief Set IP Address Of the Interface */ uint32_t NetworkManagerImplementation::SetIPSettings(const string& interface /* @in */, const string &ipversion /* @in */, const IPAddressInfo& address /* @in */) { - GMainLoop *g_loop; - g_loop = g_main_loop_new(NULL, FALSE); - uint32_t rc = Core::ERROR_NONE; - if(client == nullptr) - { - NMLOG_WARNING("client connection null"); - return Core::ERROR_GENERAL; - } - const GPtrArray *connections = nm_client_get_connections(client); - NMSettingIP4Config *s_ip4; - NMSettingIP6Config *s_ip6; - NMConnection *conn = NULL; - NMSettingConnection *settings; - NMRemoteConnection *remote_connection; - NMSetting *setting; - const char *uuid; - NMDevice *device = NULL; - const char *spec_object; - - for (guint i = 0; i < connections->len; i++) { - NMConnection *connection = NM_CONNECTION(connections->pdata[i]); - settings = nm_connection_get_setting_connection(connection); - - /* Check if the interface name matches */ - if (g_strcmp0(nm_setting_connection_get_interface_name(settings), interface.c_str()) == 0) { - conn = connection; - break; - } - } - if (!address.m_autoConfig) - { - if (nmUtils::caseInsensitiveCompare("IPv4", ipversion)) - { - NMSettingIPConfig *ip4_config = nm_connection_get_setting_ip4_config(conn); - if (ip4_config == NULL) - { - ip4_config = (NMSettingIPConfig *)nm_setting_ip4_config_new(); - } - NMIPAddress *ipAddress; - setting = nm_connection_get_setting_by_name(conn, "ipv4"); - ipAddress = nm_ip_address_new(AF_INET, address.m_ipAddress.c_str(), address.m_prefix, NULL); - nm_setting_ip_config_clear_addresses(ip4_config); - nm_setting_ip_config_add_address(NM_SETTING_IP_CONFIG(setting), ipAddress); - nm_setting_ip_config_clear_dns(ip4_config); - nm_setting_ip_config_add_dns(ip4_config, address.m_primaryDns.c_str()); - nm_setting_ip_config_add_dns(ip4_config, address.m_secondaryDns.c_str()); - - g_object_set(G_OBJECT(ip4_config), - NM_SETTING_IP_CONFIG_GATEWAY, address.m_gateway.c_str(), - NM_SETTING_IP_CONFIG_NEVER_DEFAULT, - FALSE, - NULL); - } - else - { - //FIXME : Add IPv6 support here - printf("Setting IPv6 is not supported at this point in time. This is just a place holder\n"); - rc = Core::ERROR_NOT_SUPPORTED; - } - } - else - { - if (nmUtils::caseInsensitiveCompare("IPv4", ipversion)) - { - s_ip4 = (NMSettingIP4Config *)nm_setting_ip4_config_new(); - g_object_set(G_OBJECT(s_ip4), NM_SETTING_IP_CONFIG_METHOD, NM_SETTING_IP4_CONFIG_METHOD_AUTO, NULL); - nm_connection_add_setting(conn, NM_SETTING(s_ip4)); - } - else - { - s_ip6 = (NMSettingIP6Config *)nm_setting_ip6_config_new(); - g_object_set(G_OBJECT(s_ip6), NM_SETTING_IP_CONFIG_METHOD, NM_SETTING_IP6_CONFIG_METHOD_AUTO, NULL); - nm_connection_add_setting(conn, NM_SETTING(s_ip6)); - } - } - device = nm_client_get_device_by_iface(client, interface.c_str()); - uuid = nm_connection_get_uuid(conn); - remote_connection = nm_client_get_connection_by_uuid(client, uuid); - NMActiveConnection *active_connection = NULL; - - const GPtrArray *acv_connections = nm_client_get_active_connections(client); - for (guint i = 0; i < acv_connections->len; i++) { - NMActiveConnection *connection1 = NM_ACTIVE_CONNECTION(acv_connections->pdata[i]); - settings = nm_connection_get_setting_connection(NM_CONNECTION(nm_active_connection_get_connection(connection1))); - - /* Check if the interface name matches */ - if (g_strcmp0(nm_setting_connection_get_interface_name(settings), interface.c_str()) == 0) { - active_connection = connection1; - break; - } - } - - spec_object = nm_object_get_path(NM_OBJECT(active_connection)); - nm_remote_connection_commit_changes(remote_connection, false, NULL, NULL); - nm_client_deactivate_connection_async(client, active_connection, NULL, on_deactivate_complete, NULL); - nm_client_activate_connection_async(client, conn, device, spec_object, NULL, on_activate_complete, g_loop); - g_main_loop_run(g_loop); - return rc; + return Core::ERROR_NONE; } uint32_t NetworkManagerImplementation::StartWiFiScan(const WiFiFrequency frequency /* @in */) { - uint32_t rc = Core::ERROR_RPC_CALL_FAILED; - nmEvent->setwifiScanOptions(true, true); - if(wifi->wifiScanRequest(frequency)) - rc = Core::ERROR_NONE; - return rc; + return Core::ERROR_NONE; } uint32_t NetworkManagerImplementation::StopWiFiScan(void) { - uint32_t rc = Core::ERROR_NONE; - // TODO explore wpa_supplicant stop - nmEvent->setwifiScanOptions(false); // This will stop periodic posting of onAvailableSSID event - NMLOG_INFO ("StopWiFiScan is success"); - return rc; + return Core::ERROR_NONE; } uint32_t NetworkManagerImplementation::GetKnownSSIDs(IStringIterator*& ssids /* @out */) { - uint32_t rc = Core::ERROR_RPC_CALL_FAILED; - // TODO Fix the RPC waring [Process.cpp:78](Dispatch)<1>: We still have living object [1] - std::list ssidList; - if(wifi->getKnownSSIDs(ssidList)) - { - if (!ssidList.empty()) - { - ssids = Core::Service::Create(ssidList); - rc = Core::ERROR_NONE; - } - else - { - NMLOG_INFO("known ssids not found !"); - rc = Core::ERROR_GENERAL; - } - } - - return rc; + return Core::ERROR_NONE; } uint32_t NetworkManagerImplementation::AddToKnownSSIDs(const WiFiConnectTo& ssid /* @in */) { - uint32_t rc = Core::ERROR_GENERAL; - if(wifi->addToKnownSSIDs(ssid)) - rc = Core::ERROR_NONE; - return rc; + return Core::ERROR_NONE; } uint32_t NetworkManagerImplementation::RemoveKnownSSID(const string& ssid /* @in */) { - uint32_t rc = Core::ERROR_GENERAL; - if(wifi->removeKnownSSID(ssid)) - rc = Core::ERROR_NONE; - return rc; + return Core::ERROR_NONE; } uint32_t NetworkManagerImplementation::WiFiConnect(const WiFiConnectTo& ssid /* @in */) { - uint32_t rc = Core::ERROR_GENERAL; - if(ssid.m_ssid.empty() || ssid.m_ssid.size() > 32) - { - NMLOG_WARNING("ssid is invalied"); - return rc; - } - // Check the last scanning time and if it exceeds 10 sec do a rescanning - if(!wifi->isWifiScannedRecently()) - { - nmEvent->setwifiScanOptions(false, true); // not notify scan result but print logs - if(!wifi->wifiScanRequest(Exchange::INetworkManager::WiFiFrequency::WIFI_FREQUENCY_WHATEVER, ssid.m_ssid)) - { - NMLOG_WARNING("scanning failed but try to connect"); - } - } - if(wifi->wifiConnect(ssid)) - rc = Core::ERROR_NONE; - return rc; + return Core::ERROR_NONE; } uint32_t NetworkManagerImplementation::WiFiDisconnect(void) { - uint32_t rc = Core::ERROR_GENERAL; - if(wifi->wifiDisconnect()) - rc = Core::ERROR_NONE; - return rc; + return Core::ERROR_NONE; } uint32_t NetworkManagerImplementation::GetConnectedSSID(WiFiSSIDInfo& ssidInfo /* @out */) { - uint32_t rc = Core::ERROR_RPC_CALL_FAILED; - if(wifi->wifiConnectedSSIDInfo(ssidInfo)) - rc = Core::ERROR_NONE; - return rc; + return Core::ERROR_NONE; } uint32_t NetworkManagerImplementation::GetWiFiSignalStrength(string& ssid /* @out */, string& signalStrength /* @out */, WiFiSignalQuality& quality /* @out */) { - uint32_t rc = Core::ERROR_RPC_CALL_FAILED; - - WiFiSSIDInfo ssidInfo; - if(wifi->wifiConnectedSSIDInfo(ssidInfo)) - { - ssid = ssidInfo.m_ssid; - signalStrength = ssidInfo.m_signalStrength; - - float signalStrengthFloat = 0.0f; - if(!signalStrength.empty()) - signalStrengthFloat = std::stof(signalStrength.c_str()); - - if (signalStrengthFloat == 0) - quality = WiFiSignalQuality::WIFI_SIGNAL_DISCONNECTED; - else if (signalStrengthFloat >= signalStrengthThresholdExcellent && signalStrengthFloat < 0) - quality = WiFiSignalQuality::WIFI_SIGNAL_EXCELLENT; - else if (signalStrengthFloat >= signalStrengthThresholdGood && signalStrengthFloat < signalStrengthThresholdExcellent) - quality = WiFiSignalQuality::WIFI_SIGNAL_GOOD; - else if (signalStrengthFloat >= signalStrengthThresholdFair && signalStrengthFloat < signalStrengthThresholdGood) - quality = WiFiSignalQuality::WIFI_SIGNAL_FAIR; - else - quality = WiFiSignalQuality::WIFI_SIGNAL_WEAK; - - NMLOG_INFO ("GetWiFiSignalStrength success"); - - rc = Core::ERROR_NONE; - } - return rc; + return Core::ERROR_NONE; } uint32_t NetworkManagerImplementation::GetWifiState(WiFiState &state) { - uint32_t rc = Core::ERROR_NONE; - if(wifi->isWifiConnected()) - state = Exchange::INetworkManager::WIFI_STATE_CONNECTED; - else - state = Exchange::INetworkManager::WIFI_STATE_DISCONNECTED; - return rc; + return Core::ERROR_NONE; } uint32_t NetworkManagerImplementation::StartWPS(const WiFiWPS& method /* @in */, const string& wps_pin /* @in */) { - uint32_t rc = Core::ERROR_RPC_CALL_FAILED; - return rc; + return Core::ERROR_NONE; } uint32_t NetworkManagerImplementation::StopWPS(void) { - uint32_t rc = Core::ERROR_RPC_CALL_FAILED; - return rc; + return Core::ERROR_NONE; } } diff --git a/Tests/dbus-api-test/CMakeLists.txt b/Tests/dbus-api-test/CMakeLists.txt deleted file mode 100644 index 4dc76dd6..00000000 --- a/Tests/dbus-api-test/CMakeLists.txt +++ /dev/null @@ -1,32 +0,0 @@ -cmake_minimum_required(VERSION 3.5) -project(NmDbusClient) - -set(CMAKE_CXX_STANDARD 11) - -find_package(PkgConfig REQUIRED) -pkg_check_modules(GLIB REQUIRED glib-2.0) -pkg_check_modules(GIO REQUIRED gio-2.0) -pkg_check_modules(LIBNM REQUIRED libnm) - -include_directories( - ${GLIB_INCLUDE_DIRS} - ${GIO_INCLUDE_DIRS} - ${LIBNM_INCLUDE_DIRS} -) - -# Force the compiler to include utils.h automatically -add_compile_options(-include ${CMAKE_SOURCE_DIR}/utils.h) - -add_executable( - NmDbusClient - main.cpp - dbusConnectionManager.cpp - NetworkManagerGnomeClient.cpp - NetworkManagerGnomeUtils.cpp -) - -target_link_libraries( - NmDbusClient - ${GLIB_LIBRARIES} - ${GIO_LIBRARIES} -) \ No newline at end of file diff --git a/Tests/dbus-api-test/NetworkManagerGnomeClient.cpp b/Tests/dbus-api-test/NetworkManagerGnomeClient.cpp deleted file mode 100644 index ccc411d1..00000000 --- a/Tests/dbus-api-test/NetworkManagerGnomeClient.cpp +++ /dev/null @@ -1,335 +0,0 @@ -#include "NetworkManagerGnomeClient.h" -#include "dbusConnectionManager.h" - -NetworkManagerClient::NetworkManagerClient() { - NMLOG_INFO("NetworkManagerClient created"); - if (!dbusConnection.InitializeBusConnection("org.freedesktop.NetworkManager")) { - NMLOG_ERROR("Failed to initialize D-Bus connection for NetworkManager"); - } -} - -NetworkManagerClient::~NetworkManagerClient() { - NMLOG_INFO("NetworkManagerClient destroyed"); -} - -static void printKeyVariant(const char *setting_name, GVariant *setting) -{ - GVariantIter iter; - const char *property_name; - GVariant *value; - char *printed_value; - - NMLOG_VERBOSE(" %s:", setting_name); - g_variant_iter_init(&iter, setting); - while (g_variant_iter_next(&iter, "{&sv}", &property_name, &value)) { - printed_value = g_variant_print(value, FALSE); - if (strcmp(printed_value, "[]") != 0) - NMLOG_VERBOSE(" %s: %s", property_name, printed_value); - g_free(printed_value); - g_variant_unref(value); - } -} - -static void fetssidandbssid(GVariant *setting80211, std::string &ssid, std::string &bssid) -{ - GVariantIter iter; - const char *property_name; - GVariant *value; - char *printed_value; - - g_variant_iter_init(&iter, setting80211); - while (g_variant_iter_next(&iter, "{&sv}", &property_name, &value)) { - - printed_value = g_variant_print(value, FALSE); - if (strcmp(property_name, "seen-bssids") == 0) { - bssid.clear(); - GVariantIter bssid_iter; - g_variant_iter_init(&bssid_iter, value); - gchar *bssid_elem; - - if (g_variant_iter_next(&bssid_iter, "s", &bssid_elem)) { - bssid = bssid_elem; - NMLOG_VERBOSE("BSSID: %s", bssid.c_str()); - } - - //g_variant_iter_free(&bssid_iter); - } - else if (strcmp(property_name, "ssid") == 0) { - // Decode SSID from GVariant of type "ay" - gsize ssid_length = 0; - const guchar *ssid_data = static_cast(g_variant_get_fixed_array(value, &ssid_length, sizeof(guchar))); - if (ssid_data && ssid_length > 0 && ssid_length <= 32) { - ssid.assign(reinterpret_cast(ssid_data), ssid_length); - NMLOG_INFO("SSID: %s", ssid.c_str()); - } else { - NMLOG_ERROR("Invalid SSID length: %zu (maximum is 32)", ssid_length); - ssid.clear(); - } - } - } - - g_free(printed_value); - g_variant_unref(value); -} - -static bool fetchSSIDFromConnection(GDBusConnection *dbusConn, const std::string& path, std::list& ssids) -{ - GError *error = NULL; - GDBusProxy *ConnProxy = NULL; - GVariant *settingsProxy= NULL, *connection= NULL, *sCon= NULL; - bool isFound; - const char *connId= NULL, *connTyp= NULL, *iface= NULL; - - ConnProxy = g_dbus_proxy_new_sync(dbusConn, - G_DBUS_PROXY_FLAGS_NONE, - NULL, - "org.freedesktop.NetworkManager", - path.c_str(), - "org.freedesktop.NetworkManager.Settings.Connection", - NULL, - &error); - - if (error != NULL) { - NMLOG_ERROR("Failed to create proxy: %s", error->message); - g_error_free(error); - return false; - } - - settingsProxy = g_dbus_proxy_call_sync(ConnProxy, - "GetSettings", - NULL, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - if (!settingsProxy) { - g_dbus_error_strip_remote_error(error); - NMLOG_WARNING("Failed to get connection settings: %s", error->message); - g_error_free(error); - } - - g_variant_get(settingsProxy, "(@a{sa{sv}})", &connection); - sCon = g_variant_lookup_value(connection, "connection", NULL); - g_assert(sCon != NULL); // TODO change error return - G_VARIANT_LOOKUP(sCon, "type", "&s", &connTyp); - G_VARIANT_LOOKUP(sCon, "interface-name", "&s", &iface); - NMLOG_VERBOSE("type= %s, iface= %s", connTyp, iface); - if(strcmp(connTyp,"802-11-wireless") == 0 && strcmp(iface,"wlan0") == 0) - { - GVariant *setting = g_variant_lookup_value(connection, "802-11-wireless", NULL); - if (setting) { - std::string ssid, bssid; - fetssidandbssid(setting, ssid, bssid); - if(!ssid.empty()) - ssids.push_back(ssid); - g_variant_unref(setting); - } - } - - if (sCon) - g_variant_unref(sCon); - if (connection) - g_variant_unref(connection); - if (settingsProxy) - g_variant_unref(settingsProxy); - g_object_unref(ConnProxy); - - return true; -} - -bool NetworkManagerClient::getKnownSSIDs(std::list& ssids) -{ - std::list paths; - if(!GnomeUtils::getConnectionPaths(dbusConnection.getConnection(), paths)) - { - NMLOG_ERROR("Connection path fetch failed"); - return false; - } - - for (const std::string& path : paths) { - NMLOG_VERBOSE("connection path %s", path.c_str()); - fetchSSIDFromConnection(dbusConnection.getConnection(), path, ssids); - } - - if(ssids.empty()) - return false; - return true; -} - -bool NetworkManagerClient::getConnectedSSID() -{ - std::string wifiDevicePath; - GError* error = NULL; - GDBusProxy* wProxy = NULL; - GVariant* result = NULL; - gchar *activeApPath = NULL; - bool ret = false; - NMDeviceState state; - - if(GnomeUtils::getDeviceState(dbusConnection.getConnection(), "wlan0", state) && state < NM_DEVICE_STATE_DISCONNECTED) - { - NMDeviceStateReason StateReason; - GnomeUtils::getDeviceStateReason(dbusConnection.getConnection(), "wlan0", StateReason); - NMLOG_ERROR("wifi device state is invallied"); - return false; - } - - if(!GnomeUtils::getDeviceByIpIface(dbusConnection.getConnection(),"wlan0", wifiDevicePath)) - { - NMLOG_ERROR("no wifi device found"); - return false; - } - - //TODO check active connection path and return properties - wProxy = g_dbus_proxy_new_sync(dbusConnection.getConnection(), - G_DBUS_PROXY_FLAGS_NONE, - NULL, - "org.freedesktop.NetworkManager", - wifiDevicePath.c_str(), - "org.freedesktop.NetworkManager.Device.Wireless", - NULL, // GCancellable - &error); - - if (error) { - NMLOG_ERROR("Error creating proxy: %s", error->message); - g_error_free(error); - return false; - } - - result = g_dbus_proxy_get_cached_property(wProxy, "ActiveAccessPoint"); - if (!result) { - NMLOG_ERROR("Failed to get ActiveAccessPoint property."); - g_object_unref(wProxy); - return false; - } - - g_variant_get(result, "o", &activeApPath); - if(g_strdup(activeApPath) != NULL && g_strcmp0(activeApPath, "/") != 0) - { - NMLOG_TRACE("ActiveAccessPoint property path %s", activeApPath); - apProperties apDetails; - if(GnomeUtils::getApDetails(dbusConnection.getConnection(), g_strdup(activeApPath), apDetails)) - { - NMLOG_INFO("getApDetails success"); - ret = true; - } - } - else - NMLOG_ERROR("active access point not found"); - - g_variant_unref(result); - g_object_unref(wProxy); - return ret; -} - -bool NetworkManagerClient::getavilableSSID(std::list& ssids) -{ - // TODO Wifi device state fix it - GError* error = nullptr; - GDBusProxy* wProxy = nullptr; - std::string wifiDevicePath; - - if(!GnomeUtils::getDeviceByIpIface(dbusConnection.getConnection(),"wlan0", wifiDevicePath)) - { - NMLOG_ERROR("no wifi device found"); - return false; - } - - wProxy = g_dbus_proxy_new_sync(dbusConnection.getConnection(), - G_DBUS_PROXY_FLAGS_NONE, - NULL, - "org.freedesktop.NetworkManager", - wifiDevicePath.c_str(), - "org.freedesktop.NetworkManager.Device.Wireless", - NULL, - &error); - - if (error) { - NMLOG_ERROR("Error creating proxy: %s", error->message); - g_error_free(error); - return false; - } - - GVariant* result = g_dbus_proxy_call_sync(wProxy, "GetAccessPoints", NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); - // TODO change to GetAllAccessPoints to include hidden ssid - if (error) { - NMLOG_ERROR("Error creating proxy: %s", error->message); - g_error_free(error); - g_object_unref(wProxy); - return false; - } - - GVariantIter* iter; - const gchar* apPath; - g_variant_get(result, "(ao)", &iter); - - while (g_variant_iter_loop(iter, "o", &apPath)) { - apProperties apDetails; - NMLOG_VERBOSE("Access Point Path: %s", apPath); - if(!GnomeUtils::getApDetails(dbusConnection.getConnection(), apPath, apDetails)) - { - NMLOG_WARNING("getApDetails failed"); - } - } - - g_variant_iter_free(iter); - g_variant_unref(result); - g_object_unref(wProxy); - - return true; -} - -bool NetworkManagerClient::startWifiScanning(const std::string& ssid) -{ - GError* error = NULL; - GDBusProxy* wProxy = NULL; - std::string wifiDevicePath; - if(!GnomeUtils::getDeviceByIpIface(dbusConnection.getConnection(),"wlan0", wifiDevicePath)) - { - NMLOG_ERROR("no wifi device found"); - return false; - } - - wProxy = g_dbus_proxy_new_sync(dbusConnection.getConnection(), - G_DBUS_PROXY_FLAGS_NONE, - NULL, - "org.freedesktop.NetworkManager", - wifiDevicePath.c_str(), - "org.freedesktop.NetworkManager.Device.Wireless", - NULL, - &error); - - if (error) { - NMLOG_ERROR("Error creating proxy: %s", error->message); - g_error_free(error); - return false; - } - - GVariant *options = NULL; - if (!ssid.empty()) { - NMLOG_INFO("staring wifi scanning .. %s", ssid.c_str()); - GVariantBuilder builder, array_builder; - g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT); - g_variant_builder_init(&array_builder, G_VARIANT_TYPE("aay")); - g_variant_builder_add(&array_builder, "@ay", - g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, (const guint8 *) ssidReq.c_str(), ssidReq.length(), 1) - ); - g_variant_builder_add(&builder, "{sv}", "ssids", g_variant_builder_end(&array_builder)); - g_variant_builder_add(&builder, "{sv}", "hidden", g_variant_new_boolean(TRUE)); - options = g_variant_builder_end(&builder); - } - - g_dbus_proxy_call_sync(wProxy, "RequestScan", g_variant_new("(a{sv})", options), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); - if (error) { - NMLOG_ERROR("Error RequestScan: %s", error->message); - g_error_free(error); - g_object_unref(wProxy); - return false; - } - - if(options) - g_variant_unref(options); - g_object_unref(wProxy); - - return true; - } diff --git a/Tests/dbus-api-test/NetworkManagerGnomeClient.h b/Tests/dbus-api-test/NetworkManagerGnomeClient.h deleted file mode 100644 index 01047440..00000000 --- a/Tests/dbus-api-test/NetworkManagerGnomeClient.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once -#include -#include - -#include "dbusConnectionManager.h" -#include "NetworkManagerGnomeUtils.h" - - -class NetworkManagerClient { -public: - NetworkManagerClient(); - ~NetworkManagerClient(); - - bool getKnownSSIDs(std::list& ssids); - bool getavilableSSID(std::list& ssids); - bool getConnectedSSID(); - bool startWifiScanning(const std::string& ssid); - -private: - DbusConnectionManager dbusConnection; -}; diff --git a/Tests/dbus-api-test/NetworkManagerGnomeUtils.cpp b/Tests/dbus-api-test/NetworkManagerGnomeUtils.cpp deleted file mode 100644 index 46cee4ff..00000000 --- a/Tests/dbus-api-test/NetworkManagerGnomeUtils.cpp +++ /dev/null @@ -1,290 +0,0 @@ - -#include -#include -#include -#include - -#include "NetworkManagerGnomeUtils.h" - -// Function to get device path by network interface name -bool GnomeUtils::getDeviceByIpIface(GDBusConnection *connection, const gchar *iface_name, std::string& path) -{ - GError *error = NULL; - GVariant *result; - gchar *device_path = NULL; - bool ret = false; - - result = g_dbus_connection_call_sync( - connection, - "org.freedesktop.NetworkManager", // D-Bus name - "/org/freedesktop/NetworkManager", // Object path - "org.freedesktop.NetworkManager", // Interface - "GetDeviceByIpIface", // Method name - g_variant_new("(s)", iface_name), // Input parameter (the interface name) - G_VARIANT_TYPE("(o)"), // Expected return type (object path) - G_DBUS_CALL_FLAGS_NONE, - -1, // Default timeout - NULL, - &error - ); - - if (error != NULL) { - NMLOG_ERROR("calling GetDeviceByIpIface: %s", error->message); - g_error_free(error); - return ret; - } - - g_variant_get(result, "(o)", &device_path); - if(g_strdup(device_path) != NULL) - { - path = std::string(g_strdup(device_path)); - ret = true; - } - - //NMLOG_TRACE("%s device path %s", iface_name, path.c_str()); - g_variant_unref(result); - return ret; -} - -static bool get_cached_property_u(GDBusProxy* proxy, const char* propertiy, uint32_t value) -{ - GVariant* result = NULL; - result = g_dbus_proxy_get_cached_property(proxy, propertiy); - if (!result) { - NMLOG_ERROR("Failed to get AP properties"); - g_object_unref(proxy); - return false; - } - g_variant_get(result, "u", &value); - NMLOG_TRACE("%s: %d", propertiy, value); - g_variant_unref(result); - return true; -} - -bool GnomeUtils::getApDetails(GDBusConnection *connection, const char* apPath, apProperties& apDetails) -{ - char *bssid = NULL; - uint8_t strength = 0; - GError* error = NULL; - GVariant* result = NULL; - - GDBusProxy* proxy = g_dbus_proxy_new_sync(connection, - G_DBUS_PROXY_FLAGS_NONE, - NULL, - "org.freedesktop.NetworkManager", - apPath, - "org.freedesktop.NetworkManager.AccessPoint", - NULL, - &error); - - if (error) { - NMLOG_ERROR("creating proxy: %s", error->message); - g_error_free(error); - return false; - } - - gsize ssid_length = 0; - result = g_dbus_proxy_get_cached_property(proxy,"Ssid"); - if (!result) { - NMLOG_ERROR("Failed to get AP properties."); - g_object_unref(proxy); - return false; - } - const guchar *ssid_data = static_cast(g_variant_get_fixed_array(result, &ssid_length, sizeof(guchar))); - if (ssid_data && ssid_length > 0 && ssid_length <= 32) { - apDetails.ssid.assign(reinterpret_cast(ssid_data), ssid_length); - NMLOG_TRACE("SSID: %s", apDetails.ssid.c_str()); - } else { - NMLOG_ERROR("Invalid SSID length: %zu (maximum is 32)", ssid_length); - apDetails.ssid="---"; - } - g_variant_unref(result); - - result = g_dbus_proxy_get_cached_property(proxy,"HwAddress"); - if (!result) { - NMLOG_ERROR("Failed to get AP properties."); - g_object_unref(proxy); - return false; - } - g_variant_get(result, "s", &bssid); - apDetails.bssid.assign(bssid); - NMLOG_TRACE("bssid %s", apDetails.bssid.c_str()); - g_variant_unref(result); - - result = g_dbus_proxy_get_cached_property(proxy,"Strength"); - if (!result) { - NMLOG_ERROR("Failed to get AP properties."); - g_object_unref(proxy); - return false; - } - g_variant_get(result, "y", &strength); - NMLOG_TRACE("strength %d", strength); - g_variant_unref(result); - - get_cached_property_u(proxy, "Flags", apDetails.flags); - get_cached_property_u(proxy, "WpaFlags", apDetails.wpaFlags); - get_cached_property_u(proxy, "RsnFlags", apDetails.rsnFlags); - get_cached_property_u(proxy, "Mode", apDetails.mode); - get_cached_property_u(proxy, "Frequency", apDetails.frequency); - - g_object_unref(proxy); - - return true; -} - -bool GnomeUtils::getConnectionPaths(GDBusConnection *dbusConn, std::list& pathsList) -{ - GDBusProxy *sProxy= NULL; - GError *error= NULL; - GVariant *listProxy = NULL; - char **paths = NULL; - - sProxy = g_dbus_proxy_new_sync(dbusConn, - G_DBUS_PROXY_FLAGS_NONE, - NULL, - "org.freedesktop.NetworkManager", - "/org/freedesktop/NetworkManager/Settings", - "org.freedesktop.NetworkManager.Settings", - NULL, // GCancellable - &error); - - if(sProxy == NULL) - { - if (error != NULL) { - NMLOG_ERROR("Failed to create proxy: %s", error->message); - g_error_free(error); - } - return false; - } - - listProxy = g_dbus_proxy_call_sync(sProxy, - "ListConnections", - NULL, - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error); - if(listProxy == NULL) - { - if (!error) { - NMLOG_ERROR("ListConnections failed: %s", error->message); - g_error_free(error); - g_object_unref(sProxy); - return false; - } - else - NMLOG_ERROR("ListConnections proxy failed no error message"); - } - - g_variant_get(listProxy, "(^ao)", &paths); - g_variant_unref(listProxy); - - if(paths == NULL) - { - NMLOG_WARNING("no connection path available"); - g_object_unref(sProxy); - return false; - } - - for (int i = 0; paths[i]; i++) { - NMLOG_VERBOSE("Connection path: %s", paths[i]); - pathsList.push_back(paths[i]); - } - - g_object_unref(sProxy); - if(pathsList.empty()) - return false; - - return true; -} - -bool GnomeUtils::getDeviceState(GDBusConnection *dbusConn, const gchar *iface_name, NMDeviceState& state) -{ - GError *error = NULL; - GVariant *result; - std::string ifaceDevicePath; - - if(!GnomeUtils::getDeviceByIpIface(dbusConn, iface_name, ifaceDevicePath) && !ifaceDevicePath.empty()) - { - NMLOG_ERROR("Interface unknow to NetworkManger Deamon"); - return false; - } - - result = g_dbus_connection_call_sync( - dbusConn, - "org.freedesktop.NetworkManager", // D-Bus name - ifaceDevicePath.c_str(), // Object path - "org.freedesktop.DBus.Properties", // Interface for property access - "Get", // Method name for getting a property - g_variant_new("(ss)", // Input parameters (interface, property name) - "org.freedesktop.NetworkManager.Device", // Interface name - "State"), // Property name - G_VARIANT_TYPE("(v)"), // Expected return type (variant) - G_DBUS_CALL_FLAGS_NONE, - -1, // Default timeout - NULL, - &error - ); - if (error != NULL) { - NMLOG_ERROR("failed to DBus.Properties: %s", error->message); - g_error_free(error); - } else { - GVariant *variantValue; - g_variant_get(result, "(v)", &variantValue); - - state = static_cast(g_variant_get_uint32(variantValue)); - NMLOG_TRACE("Device state: %u", state); - - g_variant_unref(variantValue); - g_variant_unref(result); - return true; - } - - return false; -} - -bool GnomeUtils::getDeviceStateReason(GDBusConnection *dbusConn, const gchar *iface_name, NMDeviceStateReason& StateReason) -{ - GError *error = NULL; - GVariant *resultReason; - std::string ifaceDevicePath; - - if(!GnomeUtils::getDeviceByIpIface(dbusConn, iface_name, ifaceDevicePath) && !ifaceDevicePath.empty()) - { - NMLOG_ERROR("Interface unknow to NetworkManger Deamon"); - return false; - } - - resultReason = g_dbus_connection_call_sync( dbusConn, - "org.freedesktop.NetworkManager", - ifaceDevicePath.c_str(), - "org.freedesktop.DBus.Properties", - "Get", - g_variant_new("(ss)", - "org.freedesktop.NetworkManager.Device", - "StateReason"), - G_VARIANT_TYPE("(v)"), - G_DBUS_CALL_FLAGS_NONE, - -1, - NULL, - &error - ); - - if (error != NULL) { - NMLOG_ERROR("getting StateReason property: %s", error->message); - g_error_free(error); - } else if (resultReason != NULL) { - GVariant *variantReason; - g_variant_get(resultReason, "(v)", &variantReason); - - guint32 state_reason_code, state_reason_detail; - g_variant_get(variantReason, "(uu)", &state_reason_code, &state_reason_detail); - NMLOG_WARNING("Device state reason: %u (detail: %u)", state_reason_code, state_reason_detail); - g_variant_unref(variantReason); - g_variant_unref(resultReason); - return true; - } - return false; - -} - diff --git a/Tests/dbus-api-test/dbusConnectionManager.cpp b/Tests/dbus-api-test/dbusConnectionManager.cpp deleted file mode 100644 index fcfb70c1..00000000 --- a/Tests/dbus-api-test/dbusConnectionManager.cpp +++ /dev/null @@ -1,35 +0,0 @@ -#include "dbusConnectionManager.h" - -DbusConnectionManager::DbusConnectionManager() : connection(nullptr) { - NMLOG_INFO("DbusConnectionManager created"); -} - -DbusConnectionManager::~DbusConnectionManager() { - DeinitializeDbusConnection(); -} - -bool DbusConnectionManager::InitializeBusConnection(const std::string& busName) { - GError* error = nullptr; - connection = g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, &error); - - if (!connection) { - NMLOG_ERROR("Failed to initialize D-Bus connection: %s ", error->message); - g_error_free(error); - return false; - } - - NMLOG_INFO("D-Bus connection initialized successfully for bus: %s", busName.c_str()); - return true; -} - -void DbusConnectionManager::DeinitializeDbusConnection() { - if (connection) { - g_object_unref(connection); - connection = nullptr; - NMLOG_INFO("D-Bus connection deinitialized successfully"); - } -} - -GDBusConnection* DbusConnectionManager::getConnection() const { - return connection; -} diff --git a/Tests/dbus-api-test/dbusConnectionManager.h b/Tests/dbus-api-test/dbusConnectionManager.h deleted file mode 100644 index ec9f3d45..00000000 --- a/Tests/dbus-api-test/dbusConnectionManager.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include -#include - -#include - -class DbusConnectionManager { -public: - DbusConnectionManager(); - ~DbusConnectionManager(); - - bool InitializeBusConnection(const std::string& busName); - void DeinitializeDbusConnection(); - GDBusConnection* getConnection() const; - -private: - GDBusConnection* connection; -}; diff --git a/Tests/dbus-api-test/main.cpp b/Tests/dbus-api-test/main.cpp deleted file mode 100644 index 50bec2c1..00000000 --- a/Tests/dbus-api-test/main.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include "NetworkManagerGnomeClient.h" -#include "dbusConnectionManager.h" -#include -#include -#include - - -int main() { - // Create instances of the NetworkManager and wpa_supplicant clients - NetworkManagerClient nmClient; - // WpaSupplicantClient wpaClient; - int i=1; - while(i-- > 0) - { - std::list ssids; - nmClient.getKnownSSIDs(ssids); - if (ssids.empty()) { - NMLOG_INFO("No SSID found"); - } else { - NMLOG_INFO("SSID list available"); - } - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - - nmClient.getConnectedSSID(); - std::string ssid = "Mi11Lite"; - nmClient.startWifiScanning(ssid); - } - NMLOG_INFO("Program completed successfully"); - return 0; -} diff --git a/Tests/dbus-api-test/utils.h b/Tests/dbus-api-test/utils.h deleted file mode 100644 index 3a108063..00000000 --- a/Tests/dbus-api-test/utils.h +++ /dev/null @@ -1,52 +0,0 @@ -#pragma once - -#include - -// Define log levels -enum LogLevel { - LOG_LEVEL_ERROR = 0, - LOG_LEVEL_WARN = 1, - LOG_LEVEL_INFO = 2, - LOG_LEVEL_TRACE = 3, - LOG_LEVEL_VERBOSE = 4 -}; - -// Set the current log level (modify as needed) -static const int currentLogLevel = LOG_LEVEL_TRACE; - -#define NMLOG_ERROR(fmt, ...) \ - do { \ - if (currentLogLevel >= LOG_LEVEL_ERROR) { \ - fprintf(stderr, "[ERROR] [%s:%d] " fmt "\n", __FUNCTION__, __LINE__, ##__VA_ARGS__); \ - } \ - } while(0) - -#define NMLOG_WARNING(fmt, ...) \ - do { \ - if (currentLogLevel >= LOG_LEVEL_WARN) { \ - printf("[WARN] [%s:%d] " fmt "\n", __FUNCTION__, __LINE__, ##__VA_ARGS__); \ - } \ - } while(0) - -#define NMLOG_INFO(fmt, ...) \ - do { \ - if (currentLogLevel >= LOG_LEVEL_INFO) { \ - printf("[INFO] " fmt "\n", ##__VA_ARGS__); \ - } \ - } while(0) - -#define NMLOG_TRACE(fmt, ...) \ - do { \ - if (currentLogLevel >= LOG_LEVEL_TRACE) { \ - printf("[TRACE] [%s:%d] " fmt "\n", __FUNCTION__, __LINE__, ##__VA_ARGS__); \ - } \ - } while (0) - - -#define NMLOG_VERBOSE(fmt, ...) \ - do { \ - if (currentLogLevel >= LOG_LEVEL_VERBOSE) { \ - printf("[VERBOSE] [%s:%d] " fmt "\n", __FUNCTION__, __LINE__, ##__VA_ARGS__); \ - } \ - } while (0) - diff --git a/Tests/dbus-api-test/wpaSupplicantClient.cpp b/Tests/dbus-api-test/wpaSupplicantClient.cpp deleted file mode 100644 index 0c89a47b..00000000 --- a/Tests/dbus-api-test/wpaSupplicantClient.cpp +++ /dev/null @@ -1,53 +0,0 @@ -#include "wpaSupplicantClient.h" - -WpaSupplicantClient::WpaSupplicantClient() { - NMLOG_INFO("WpaSupplicantClient created"); - if (!dbusConnection.InitializeBusConnection("fi.w1.wpa_supplicant1")) { - NMLOG_ERROR("Failed to initialize D-Bus connection for wpa_supplicant"); - } -} - -WpaSupplicantClient::~WpaSupplicantClient() { - NMLOG_INFO("WpaSupplicantClient destroyed"); -} - -std::string WpaSupplicantClient::getWifiStatus() { - GVariant* result = nullptr; - std::string wifiStatus; - - if (dbusConnection.getConnection()) { - // Prepare DBus method call - GError* error = nullptr; - result = g_dbus_connection_call_sync( - dbusConnection.getConnection(), - "fi.w1.wpa_supplicant1", - "/fi/w1/wpa_supplicant1", - "fi.w1.wpa_supplicant1.Interface", - "GetStatus", - nullptr, - G_VARIANT_TYPE("(a{sv})"), - G_DBUS_CALL_FLAGS_NONE, - -1, - nullptr, - &error); - - if (error) { - NMLOG_ERROR("Failed to get Wi-Fi status: %s", error->message); - g_error_free(error); - return ""; - } - - // Extract Wi-Fi status from result - if (result) { - gchar* status; - g_variant_get(result, "(&s)", &status); - wifiStatus = status; - g_variant_unref(result); - NMLOG_INFO("Wi-Fi status: %s", wifiStatus.c_str()); - } - } else { - NMLOG_WARNING("No valid D-Bus connection to wpa_supplicant"); - } - - return wifiStatus; -} diff --git a/Tests/dbus-api-test/wpaSupplicantClient.h b/Tests/dbus-api-test/wpaSupplicantClient.h deleted file mode 100644 index 138e503a..00000000 --- a/Tests/dbus-api-test/wpaSupplicantClient.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include "dbusConnectionManager.h" -#include - -class WpaSupplicantClient { -public: - WpaSupplicantClient(); - ~WpaSupplicantClient(); - - std::string getWifiStatus(); - -private: - DbusConnectionManager dbusConnection; -}; \ No newline at end of file