diff --git a/src/platform/GLibTypeDeleter.h b/src/platform/GLibTypeDeleter.h index 1e187aa275adb3..565403566f60a8 100644 --- a/src/platform/GLibTypeDeleter.h +++ b/src/platform/GLibTypeDeleter.h @@ -86,6 +86,12 @@ struct GAutoPtrDeleter using deleter = GFree; }; +template <> +struct GAutoPtrDeleter +{ + using deleter = GFree; +}; + template <> struct GAutoPtrDeleter { diff --git a/src/platform/Linux/ConnectivityManagerImpl.cpp b/src/platform/Linux/ConnectivityManagerImpl.cpp index 8717d67d479b5a..48abb456a8be68 100644 --- a/src/platform/Linux/ConnectivityManagerImpl.cpp +++ b/src/platform/Linux/ConnectivityManagerImpl.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -279,14 +280,14 @@ void ConnectivityManagerImpl::_ClearWiFiStationProvision() if (mWiFiStationMode != kWiFiStationMode_ApplicationControlled) { - GError * err = nullptr; - wpa_fi_w1_wpa_supplicant1_interface_call_remove_all_networks_sync(mWpaSupplicant.iface, nullptr, &err); + GAutoPtr err; + wpa_fi_w1_wpa_supplicant1_interface_call_remove_all_networks_sync(mWpaSupplicant.iface, nullptr, + &MakeUniquePointerReceiver(err).Get()); if (err != nullptr) { ChipLogProgress(DeviceLayer, "wpa_supplicant: failed to remove all networks with error: %s", err ? err->message : "unknown error"); - g_error_free(err); } } } @@ -397,28 +398,27 @@ void ConnectivityManagerImpl::_OnWpaPropertiesChanged(WpaFiW1Wpa_supplicant1Inte if (g_variant_n_children(changed_properties) > 0) { - GVariantIter * iter; + GAutoPtr iter; const gchar * key; GVariant * value; WiFiDiagnosticsDelegate * delegate = GetDiagnosticDataProvider().GetWiFiDiagnosticsDelegate(); - g_variant_get(changed_properties, "a{sv}", &iter); + g_variant_get(changed_properties, "a{sv}", &MakeUniquePointerReceiver(iter).Get()); - while (g_variant_iter_loop(iter, "{&sv}", &key, &value)) + while (g_variant_iter_loop(iter.get(), "{&sv}", &key, &value)) { - gchar * value_str; - value_str = g_variant_print(value, TRUE); + GAutoPtr value_str(g_variant_print(value, TRUE)); ChipLogProgress(DeviceLayer, "wpa_supplicant:PropertiesChanged:key:%s -> %s", StringOrNullMarker(key), - StringOrNullMarker(value_str)); + StringOrNullMarker(value_str.get())); if (g_strcmp0(key, "State") == 0) { - if (g_strcmp0(value_str, "\'associating\'") == 0) + if (g_strcmp0(value_str.get(), "\'associating\'") == 0) { mAssociationStarted = true; } - else if (g_strcmp0(value_str, "\'disconnected\'") == 0) + else if (g_strcmp0(value_str.get(), "\'disconnected\'") == 0) { gint reason = wpa_fi_w1_wpa_supplicant1_interface_get_disconnect_reason(mWpaSupplicant.iface); @@ -471,7 +471,7 @@ void ConnectivityManagerImpl::_OnWpaPropertiesChanged(WpaFiW1Wpa_supplicant1Inte mAssociationStarted = false; } - else if (g_strcmp0(value_str, "\'associated\'") == 0) + else if (g_strcmp0(value_str.get(), "\'associated\'") == 0) { if (delegate) { @@ -480,7 +480,7 @@ void ConnectivityManagerImpl::_OnWpaPropertiesChanged(WpaFiW1Wpa_supplicant1Inte DeviceLayer::SystemLayer().ScheduleLambda([]() { ConnectivityMgrImpl().UpdateNetworkStatus(); }); } - else if (g_strcmp0(value_str, "\'completed\'") == 0) + else if (g_strcmp0(value_str.get(), "\'completed\'") == 0) { if (mAssociationStarted) { @@ -496,11 +496,7 @@ void ConnectivityManagerImpl::_OnWpaPropertiesChanged(WpaFiW1Wpa_supplicant1Inte mAssociationStarted = false; } } - - g_free(value_str); } - - g_variant_iter_free(iter); } } @@ -510,11 +506,12 @@ void ConnectivityManagerImpl::_OnWpaInterfaceProxyReady(GObject * source_object, // all D-Bus signals will be delivered to the GLib global default main context. VerifyOrDie(g_main_context_get_thread_default() != nullptr); - GError * err = nullptr; + GAutoPtr err; std::lock_guard lock(mWpaSupplicantMutex); - WpaFiW1Wpa_supplicant1Interface * iface = wpa_fi_w1_wpa_supplicant1_interface_proxy_new_for_bus_finish(res, &err); + WpaFiW1Wpa_supplicant1Interface * iface = + wpa_fi_w1_wpa_supplicant1_interface_proxy_new_for_bus_finish(res, &MakeUniquePointerReceiver(err).Get()); if (mWpaSupplicant.iface) { @@ -547,9 +544,6 @@ void ConnectivityManagerImpl::_OnWpaInterfaceProxyReady(GObject * source_object, ChipLogError(DeviceLayer, "wpa_supplicant: Failed to stop auto scan: %s", ErrorStr(errInner)); } }); - - if (err != nullptr) - g_error_free(err); } void ConnectivityManagerImpl::_OnWpaBssProxyReady(GObject * source_object, GAsyncResult * res, gpointer user_data) @@ -558,11 +552,12 @@ void ConnectivityManagerImpl::_OnWpaBssProxyReady(GObject * source_object, GAsyn // all D-Bus signals will be delivered to the GLib global default main context. VerifyOrDie(g_main_context_get_thread_default() != nullptr); - GError * err = nullptr; + GAutoPtr err; std::lock_guard lock(mWpaSupplicantMutex); - WpaFiW1Wpa_supplicant1BSS * bss = wpa_fi_w1_wpa_supplicant1_bss_proxy_new_for_bus_finish(res, &err); + WpaFiW1Wpa_supplicant1BSS * bss = + wpa_fi_w1_wpa_supplicant1_bss_proxy_new_for_bus_finish(res, &MakeUniquePointerReceiver(err).Get()); if (mWpaSupplicant.bss) { @@ -570,7 +565,7 @@ void ConnectivityManagerImpl::_OnWpaBssProxyReady(GObject * source_object, GAsyn mWpaSupplicant.bss = nullptr; } - if (bss != nullptr && err == nullptr) + if (bss != nullptr && err.get() == nullptr) { mWpaSupplicant.bss = bss; ChipLogProgress(DeviceLayer, "wpa_supplicant: connected to wpa_supplicant bss proxy"); @@ -580,9 +575,6 @@ void ConnectivityManagerImpl::_OnWpaBssProxyReady(GObject * source_object, GAsyn ChipLogProgress(DeviceLayer, "wpa_supplicant: failed to create wpa_supplicant bss proxy %s: %s", mWpaSupplicant.interfacePath, err ? err->message : "unknown error"); } - - if (err != nullptr) - g_error_free(err); } void ConnectivityManagerImpl::_OnWpaInterfaceReady(GObject * source_object, GAsyncResult * res, gpointer user_data) @@ -591,12 +583,12 @@ void ConnectivityManagerImpl::_OnWpaInterfaceReady(GObject * source_object, GAsy // all D-Bus signals will be delivered to the GLib global default main context. VerifyOrDie(g_main_context_get_thread_default() != nullptr); - GError * err = nullptr; + GAutoPtr err; std::lock_guard lock(mWpaSupplicantMutex); - gboolean result = - wpa_fi_w1_wpa_supplicant1_call_get_interface_finish(mWpaSupplicant.proxy, &mWpaSupplicant.interfacePath, res, &err); + gboolean result = wpa_fi_w1_wpa_supplicant1_call_get_interface_finish(mWpaSupplicant.proxy, &mWpaSupplicant.interfacePath, res, + &MakeUniquePointerReceiver(err).Get()); if (result) { mWpaSupplicant.state = GDBusWpaSupplicant::WPA_GOT_INTERFACE_PATH; @@ -611,7 +603,7 @@ void ConnectivityManagerImpl::_OnWpaInterfaceReady(GObject * source_object, GAsy } else { - GError * error = nullptr; + GAutoPtr error; GVariant * args = nullptr; GVariantBuilder builder; @@ -625,7 +617,7 @@ void ConnectivityManagerImpl::_OnWpaInterfaceReady(GObject * source_object, GAsy args = g_variant_builder_end(&builder); result = wpa_fi_w1_wpa_supplicant1_call_create_interface_sync(mWpaSupplicant.proxy, args, &mWpaSupplicant.interfacePath, - nullptr, &error); + nullptr, &MakeUniquePointerReceiver(error).Get()); if (result) { @@ -654,13 +646,7 @@ void ConnectivityManagerImpl::_OnWpaInterfaceReady(GObject * source_object, GAsy mWpaSupplicant.interfacePath = nullptr; } } - - if (error != nullptr) - g_error_free(error); } - - if (err != nullptr) - g_error_free(err); } void ConnectivityManagerImpl::_OnWpaInterfaceAdded(WpaFiW1Wpa_supplicant1 * proxy, const gchar * path, GVariant * properties, @@ -736,12 +722,12 @@ void ConnectivityManagerImpl::_OnWpaProxyReady(GObject * source_object, GAsyncRe // all D-Bus signals will be delivered to the GLib global default main context. VerifyOrDie(g_main_context_get_thread_default() != nullptr); - GError * err = nullptr; + GAutoPtr err; std::lock_guard lock(mWpaSupplicantMutex); - mWpaSupplicant.proxy = wpa_fi_w1_wpa_supplicant1_proxy_new_for_bus_finish(res, &err); - if (mWpaSupplicant.proxy != nullptr && err == nullptr) + mWpaSupplicant.proxy = wpa_fi_w1_wpa_supplicant1_proxy_new_for_bus_finish(res, &MakeUniquePointerReceiver(err).Get()); + if (mWpaSupplicant.proxy != nullptr && err.get() == nullptr) { mWpaSupplicant.state = GDBusWpaSupplicant::WPA_CONNECTED; ChipLogProgress(DeviceLayer, "wpa_supplicant: connected to wpa_supplicant proxy"); @@ -758,9 +744,6 @@ void ConnectivityManagerImpl::_OnWpaProxyReady(GObject * source_object, GAsyncRe err ? err->message : "unknown error"); mWpaSupplicant.state = GDBusWpaSupplicant::WPA_NOT_CONNECTED; } - - if (err != nullptr) - g_error_free(err); } void ConnectivityManagerImpl::StartWiFiManagement() @@ -860,10 +843,10 @@ void ConnectivityManagerImpl::DriveAPState() { if (mWpaSupplicant.networkPath) { - GError * error = nullptr; + GAutoPtr error(nullptr); gboolean result = wpa_fi_w1_wpa_supplicant1_interface_call_remove_network_sync( - mWpaSupplicant.iface, mWpaSupplicant.networkPath, nullptr, &error); + mWpaSupplicant.iface, mWpaSupplicant.networkPath, nullptr, &MakeUniquePointerReceiver(error).Get()); if (result) { @@ -878,9 +861,6 @@ void ConnectivityManagerImpl::DriveAPState() error ? error->message : "unknown error"); err = CHIP_ERROR_INTERNAL; } - - if (error != nullptr) - g_error_free(error); } } } @@ -896,8 +876,8 @@ void ConnectivityManagerImpl::DriveAPState() CHIP_ERROR ConnectivityManagerImpl::ConfigureWiFiAP() { - CHIP_ERROR ret = CHIP_NO_ERROR; - GError * err = nullptr; + CHIP_ERROR ret = CHIP_NO_ERROR; + GAutoPtr err; GVariant * args = nullptr; GVariantBuilder builder; @@ -930,17 +910,17 @@ CHIP_ERROR ConnectivityManagerImpl::ConfigureWiFiAP() g_variant_builder_add(&builder, "{sv}", "frequency", g_variant_new_int32(channel)); args = g_variant_builder_end(&builder); - gboolean result = wpa_fi_w1_wpa_supplicant1_interface_call_add_network_sync(mWpaSupplicant.iface, args, - &mWpaSupplicant.networkPath, nullptr, &err); + gboolean result = wpa_fi_w1_wpa_supplicant1_interface_call_add_network_sync( + mWpaSupplicant.iface, args, &mWpaSupplicant.networkPath, nullptr, &MakeUniquePointerReceiver(err).Get()); if (result) { - GError * error = nullptr; + GAutoPtr error; ChipLogProgress(DeviceLayer, "wpa_supplicant: added network: SSID: %s: %s", ssid, mWpaSupplicant.networkPath); result = wpa_fi_w1_wpa_supplicant1_interface_call_select_network_sync(mWpaSupplicant.iface, mWpaSupplicant.networkPath, - nullptr, &error); + nullptr, &MakeUniquePointerReceiver(error).Get()); if (result) { ChipLogProgress(DeviceLayer, "wpa_supplicant: succeeded to start softAP: SSID: %s", ssid); @@ -952,9 +932,6 @@ CHIP_ERROR ConnectivityManagerImpl::ConfigureWiFiAP() ret = CHIP_ERROR_INTERNAL; } - - if (error != nullptr) - g_error_free(error); } else { @@ -969,9 +946,6 @@ CHIP_ERROR ConnectivityManagerImpl::ConfigureWiFiAP() ret = CHIP_ERROR_INTERNAL; } - if (err != nullptr) - g_error_free(err); - return ret; } @@ -993,8 +967,8 @@ CHIP_ERROR ConnectivityManagerImpl::ConnectWiFiNetworkAsync(ByteSpan ssid, ByteSpan credentials, NetworkCommissioning::Internal::WirelessDriver::ConnectCallback * apCallback) { - CHIP_ERROR ret = CHIP_NO_ERROR; - GError * err = nullptr; + CHIP_ERROR ret = CHIP_NO_ERROR; + GAutoPtr err; GVariant * args = nullptr; GVariantBuilder builder; gboolean result; @@ -1015,9 +989,10 @@ ConnectivityManagerImpl::ConnectWiFiNetworkAsync(ByteSpan ssid, ByteSpan credent // wpa_supplicant DBus API: if network path of current network is not "/", means we have already selected some network. if (strcmp(networkPath, "/") != 0) { - GError * error = nullptr; + GAutoPtr error; - result = wpa_fi_w1_wpa_supplicant1_interface_call_remove_network_sync(mWpaSupplicant.iface, networkPath, nullptr, &error); + result = wpa_fi_w1_wpa_supplicant1_interface_call_remove_network_sync(mWpaSupplicant.iface, networkPath, nullptr, + &MakeUniquePointerReceiver(error).Get()); if (result) { @@ -1035,9 +1010,6 @@ ConnectivityManagerImpl::ConnectWiFiNetworkAsync(ByteSpan ssid, ByteSpan credent ret = CHIP_ERROR_INTERNAL; } - if (error != nullptr) - g_error_free(error); - SuccessOrExit(ret); } @@ -1050,7 +1022,7 @@ ConnectivityManagerImpl::ConnectWiFiNetworkAsync(ByteSpan ssid, ByteSpan credent args = g_variant_builder_end(&builder); result = wpa_fi_w1_wpa_supplicant1_interface_call_add_network_sync(mWpaSupplicant.iface, args, &mWpaSupplicant.networkPath, - nullptr, &err); + nullptr, &MakeUniquePointerReceiver(err).Get()); if (result) { @@ -1078,9 +1050,6 @@ ConnectivityManagerImpl::ConnectWiFiNetworkAsync(ByteSpan ssid, ByteSpan credent } exit: - if (err != nullptr) - g_error_free(err); - return ret; } @@ -1110,20 +1079,16 @@ void ConnectivityManagerImpl::_ConnectWiFiNetworkAsyncCallback(GObject * source_ return; } - GError * gerror = nullptr; - - result = wpa_fi_w1_wpa_supplicant1_interface_call_save_config_sync(mWpaSupplicant.iface, nullptr, &gerror); + result = wpa_fi_w1_wpa_supplicant1_interface_call_save_config_sync(mWpaSupplicant.iface, nullptr, + &MakeUniquePointerReceiver(err).Get()); if (result) { ChipLogProgress(DeviceLayer, "wpa_supplicant: save config succeeded!"); } else { - ChipLogProgress(DeviceLayer, "wpa_supplicant: failed to save config: %s", gerror ? gerror->message : "unknown error"); + ChipLogProgress(DeviceLayer, "wpa_supplicant: failed to save config: %s", err ? err->message : "unknown error"); } - - if (gerror != nullptr) - g_error_free(gerror); } } @@ -1387,8 +1352,8 @@ CHIP_ERROR ConnectivityManagerImpl::StartWiFiScan(ByteSpan ssid, WiFiDriver::Sca VerifyOrReturnError(mpScanCallback == nullptr, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnError(ssid.size() <= sizeof(sInterestedSSID), CHIP_ERROR_INVALID_ARGUMENT); - CHIP_ERROR ret = CHIP_NO_ERROR; - GError * err = nullptr; + CHIP_ERROR ret = CHIP_NO_ERROR; + GAutoPtr err; GVariant * args = nullptr; GVariantBuilder builder; gboolean result; @@ -1400,7 +1365,8 @@ CHIP_ERROR ConnectivityManagerImpl::StartWiFiScan(ByteSpan ssid, WiFiDriver::Sca g_variant_builder_add(&builder, "{sv}", "Type", g_variant_new_string("active")); args = g_variant_builder_end(&builder); - result = wpa_fi_w1_wpa_supplicant1_interface_call_scan_sync(mWpaSupplicant.iface, args, nullptr, &err); + result = wpa_fi_w1_wpa_supplicant1_interface_call_scan_sync(mWpaSupplicant.iface, args, nullptr, + &MakeUniquePointerReceiver(err).Get()); if (result) { @@ -1413,10 +1379,6 @@ CHIP_ERROR ConnectivityManagerImpl::StartWiFiScan(ByteSpan ssid, WiFiDriver::Sca ret = CHIP_ERROR_INTERNAL; } - if (err != nullptr) - { - g_error_free(err); - } return ret; } @@ -1589,16 +1551,18 @@ bool ConnectivityManagerImpl::_GetBssInfo(const gchar * bssPath, NetworkCommissi return 0; } - GVariant * keyMgmt = g_variant_lookup_value(wpa, "KeyMgmt", nullptr); + GAutoPtr keyMgmt(g_variant_lookup_value(wpa, "KeyMgmt", nullptr)); if (keyMgmt == nullptr) { return 0; } - const gchar ** keyMgmts = g_variant_get_strv(keyMgmt, nullptr); - const gchar ** keyMgmtsForFree = keyMgmts; - uint8_t res = 0; - for (const gchar * keyMgmtVal = (keyMgmts != nullptr ? *keyMgmts : nullptr); keyMgmtVal != nullptr; - keyMgmtVal = *(++keyMgmts)) + GAutoPtr keyMgmts(g_variant_get_strv(keyMgmt.get(), nullptr)); + const gchar ** keyMgmtsHendle = keyMgmts.get(); + uint8_t res = 0; + + VerifyOrReturnError(keyMgmtsHendle != nullptr, res); + + for (auto keyMgmtVal = *keyMgmtsHendle; keyMgmtVal != nullptr; keyMgmtVal = *(++keyMgmtsHendle)) { if (g_strcasecmp(keyMgmtVal, "wpa-psk") == 0 || g_strcasecmp(keyMgmtVal, "wpa-none") == 0) { @@ -1609,8 +1573,7 @@ bool ConnectivityManagerImpl::_GetBssInfo(const gchar * bssPath, NetworkCommissi res |= (kEAP); } } - g_variant_unref(keyMgmt); - g_free(keyMgmtsForFree); + return res; }; auto IsNetworkWPA2PSK = [](GVariant * rsn) -> uint8_t { @@ -1618,16 +1581,18 @@ bool ConnectivityManagerImpl::_GetBssInfo(const gchar * bssPath, NetworkCommissi { return 0; } - GVariant * keyMgmt = g_variant_lookup_value(rsn, "KeyMgmt", nullptr); + GAutoPtr keyMgmt(g_variant_lookup_value(rsn, "KeyMgmt", nullptr)); if (keyMgmt == nullptr) { return 0; } - const gchar ** keyMgmts = g_variant_get_strv(keyMgmt, nullptr); - const gchar ** keyMgmtsForFree = keyMgmts; - uint8_t res = 0; - for (const gchar * keyMgmtVal = (keyMgmts != nullptr ? *keyMgmts : nullptr); keyMgmtVal != nullptr; - keyMgmtVal = *(++keyMgmts)) + GAutoPtr keyMgmts(g_variant_get_strv(keyMgmt.get(), nullptr)); + const gchar ** keyMgmtsHendle = keyMgmts.get(); + uint8_t res = 0; + + VerifyOrReturnError(keyMgmtsHendle != nullptr, res); + + for (auto keyMgmtVal = *keyMgmtsHendle; keyMgmtVal != nullptr; keyMgmtVal = *(++keyMgmtsHendle)) { if (g_strcasecmp(keyMgmtVal, "wpa-psk") == 0 || g_strcasecmp(keyMgmtVal, "wpa-psk-sha256") == 0 || g_strcasecmp(keyMgmtVal, "wpa-ft-psk") == 0) @@ -1646,8 +1611,7 @@ bool ConnectivityManagerImpl::_GetBssInfo(const gchar * bssPath, NetworkCommissi res |= (1 << 4); // SecurityType::WPA3_PERSONAL } } - g_variant_unref(keyMgmt); - g_free(keyMgmtsForFree); + return res; }; auto GetNetworkSecurityType = [IsNetworkWPAPSK, IsNetworkWPA2PSK](WpaFiW1Wpa_supplicant1BSSProxy * proxy) -> uint8_t { diff --git a/src/platform/Linux/bluez/AdapterIterator.cpp b/src/platform/Linux/bluez/AdapterIterator.cpp index 868671e405eaf3..3197be4e73e175 100644 --- a/src/platform/Linux/bluez/AdapterIterator.cpp +++ b/src/platform/Linux/bluez/AdapterIterator.cpp @@ -19,6 +19,7 @@ #include #include +#include #include namespace chip { @@ -51,12 +52,12 @@ CHIP_ERROR AdapterIterator::Initialize(AdapterIterator * self) VerifyOrDie(g_main_context_get_thread_default() != nullptr); CHIP_ERROR err = CHIP_NO_ERROR; - GError * error = nullptr; + GAutoPtr error; - self->mManager = g_dbus_object_manager_client_new_for_bus_sync(G_BUS_TYPE_SYSTEM, G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE, - BLUEZ_INTERFACE, "/", bluez_object_manager_client_get_proxy_type, - nullptr /* unused user data in the Proxy Type Func */, - nullptr /*destroy notify */, nullptr /* cancellable */, &error); + self->mManager = g_dbus_object_manager_client_new_for_bus_sync( + G_BUS_TYPE_SYSTEM, G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE, BLUEZ_INTERFACE, "/", + bluez_object_manager_client_get_proxy_type, nullptr /* unused user data in the Proxy Type Func */, + nullptr /*destroy notify */, nullptr /* cancellable */, &MakeUniquePointerReceiver(error).Get()); VerifyOrExit(self->mManager != nullptr, ChipLogError(DeviceLayer, "Failed to get DBUS object manager for listing adapters."); err = CHIP_ERROR_INTERNAL); @@ -68,7 +69,6 @@ CHIP_ERROR AdapterIterator::Initialize(AdapterIterator * self) if (error != nullptr) { ChipLogError(DeviceLayer, "DBus error: %s", error->message); - g_error_free(error); } return err; diff --git a/src/platform/Linux/bluez/ChipDeviceScanner.cpp b/src/platform/Linux/bluez/ChipDeviceScanner.cpp index fec7ff519b2425..4e1dba335779dc 100644 --- a/src/platform/Linux/bluez/ChipDeviceScanner.cpp +++ b/src/platform/Linux/bluez/ChipDeviceScanner.cpp @@ -209,12 +209,12 @@ CHIP_ERROR ChipDeviceScanner::StopScan() CHIP_ERROR ChipDeviceScanner::MainLoopStopScan(ChipDeviceScanner * self) { - GError * error = nullptr; + GAutoPtr error; - if (!bluez_adapter1_call_stop_discovery_sync(self->mAdapter, nullptr /* not cancellable */, &error)) + if (!bluez_adapter1_call_stop_discovery_sync(self->mAdapter, nullptr /* not cancellable */, + &MakeUniquePointerReceiver(error).Get())) { ChipLogError(Ble, "Failed to stop discovery %s", error->message); - g_error_free(error); } self->mIsScanning = false; @@ -276,18 +276,17 @@ void ChipDeviceScanner::RemoveDevice(BluezDevice1 & device) } const auto devicePath = g_dbus_proxy_get_object_path(G_DBUS_PROXY(&device)); - GError * error = nullptr; + GAutoPtr error; - if (!bluez_adapter1_call_remove_device_sync(mAdapter, devicePath, nullptr, &error)) + if (!bluez_adapter1_call_remove_device_sync(mAdapter, devicePath, nullptr, &MakeUniquePointerReceiver(error).Get())) { ChipLogDetail(Ble, "Failed to remove device %s: %s", StringOrNullMarker(devicePath), error->message); - g_error_free(error); } } CHIP_ERROR ChipDeviceScanner::MainLoopStartScan(ChipDeviceScanner * self) { - GError * error = nullptr; + GAutoPtr error; self->mObjectAddedSignal = g_signal_connect(self->mManager, "object-added", G_CALLBACK(SignalObjectAdded), self); self->mInterfaceChangedSignal = @@ -315,18 +314,18 @@ CHIP_ERROR ChipDeviceScanner::MainLoopStartScan(ChipDeviceScanner * self) g_variant_builder_add(&filterBuilder, "{sv}", "Transport", g_variant_new_string("le")); GVariant * filter = g_variant_builder_end(&filterBuilder); - if (!bluez_adapter1_call_set_discovery_filter_sync(self->mAdapter, filter, self->mCancellable, &error)) + if (!bluez_adapter1_call_set_discovery_filter_sync(self->mAdapter, filter, self->mCancellable, + &MakeUniquePointerReceiver(error).Get())) { // Not critical: ignore if fails ChipLogError(Ble, "Failed to set discovery filters: %s", error->message); - g_clear_error(&error); + g_clear_error(&MakeUniquePointerReceiver(error).Get()); } ChipLogProgress(Ble, "BLE initiating scan."); - if (!bluez_adapter1_call_start_discovery_sync(self->mAdapter, self->mCancellable, &error)) + if (!bluez_adapter1_call_start_discovery_sync(self->mAdapter, self->mCancellable, &MakeUniquePointerReceiver(error).Get())) { ChipLogError(Ble, "Failed to start discovery: %s", error->message); - g_error_free(error); self->mIsScanning = false; self->mDelegate->OnScanComplete(); diff --git a/src/platform/Linux/bluez/Helper.cpp b/src/platform/Linux/bluez/Helper.cpp index 3513c846dd254d..47bfb51452b123 100644 --- a/src/platform/Linux/bluez/Helper.cpp +++ b/src/platform/Linux/bluez/Helper.cpp @@ -111,10 +111,10 @@ static BluezLEAdvertisement1 * BluezAdvertisingCreate(BluezEndpoint * apEndpoint BluezObjectSkeleton * object; GVariant * serviceData; GVariant * serviceUUID; - gchar * localName = nullptr; + GAutoPtr localName; GVariantBuilder serviceDataBuilder; GVariantBuilder serviceUUIDsBuilder; - char * debugStr; + GAutoPtr debugStr; VerifyOrExit(apEndpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); if (apEndpoint->mpAdvPath == nullptr) @@ -134,16 +134,15 @@ static BluezLEAdvertisement1 * BluezAdvertisingCreate(BluezEndpoint * apEndpoint g_variant_builder_add(&serviceUUIDsBuilder, "s", apEndpoint->mpAdvertisingUUID); if (apEndpoint->mpAdapterName != nullptr) - localName = g_strdup_printf("%s", apEndpoint->mpAdapterName); + localName = GAutoPtr(g_strdup_printf("%s", apEndpoint->mpAdapterName)); else - localName = g_strdup_printf("%s%04x", CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX, getpid() & 0xffff); + localName = GAutoPtr(g_strdup_printf("%s%04x", CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX, getpid() & 0xffff)); serviceData = g_variant_builder_end(&serviceDataBuilder); serviceUUID = g_variant_builder_end(&serviceUUIDsBuilder); - debugStr = g_variant_print(serviceData, TRUE); - ChipLogDetail(DeviceLayer, "SET service data to %s", StringOrNullMarker(debugStr)); - g_free(debugStr); + debugStr = GAutoPtr(g_variant_print(serviceData, TRUE)); + ChipLogDetail(DeviceLayer, "SET service data to %s", StringOrNullMarker(debugStr.get())); bluez_leadvertisement1_set_type_(adv, (apEndpoint->mType & BLUEZ_ADV_TYPE_CONNECTABLE) ? "peripheral" : "broadcast"); // empty manufacturer data @@ -159,7 +158,7 @@ static BluezLEAdvertisement1 * BluezAdvertisingCreate(BluezEndpoint * apEndpoint bluez_leadvertisement1_set_discoverable_timeout(adv, UINT16_MAX); // advertising name corresponding to the PID and object path, for debug purposes - bluez_leadvertisement1_set_local_name(adv, localName); + bluez_leadvertisement1_set_local_name(adv, localName.get()); bluez_leadvertisement1_set_service_uuids(adv, serviceUUID); // 0xffff means no appearance @@ -179,20 +178,20 @@ static BluezLEAdvertisement1 * BluezAdvertisingCreate(BluezEndpoint * apEndpoint BLEManagerImpl::NotifyBLEPeripheralAdvConfiguredComplete(true, nullptr); exit: - g_free(localName); return adv; } static void BluezAdvStartDone(GObject * aObject, GAsyncResult * aResult, gpointer apClosure) { BluezLEAdvertisingManager1 * advMgr = BLUEZ_LEADVERTISING_MANAGER1(aObject); - GError * error = nullptr; - BluezEndpoint * endpoint = static_cast(apClosure); - gboolean success = FALSE; + GAutoPtr error; + BluezEndpoint * endpoint = static_cast(apClosure); + gboolean success = FALSE; VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); - success = bluez_leadvertising_manager1_call_register_advertisement_finish(advMgr, aResult, &error); + success = + bluez_leadvertising_manager1_call_register_advertisement_finish(advMgr, aResult, &MakeUniquePointerReceiver(error).Get()); if (success == FALSE) { g_dbus_object_manager_server_unexport(endpoint->mpRoot, endpoint->mpAdvPath); @@ -205,20 +204,19 @@ static void BluezAdvStartDone(GObject * aObject, GAsyncResult * aResult, gpointe exit: BLEManagerImpl::NotifyBLEPeripheralAdvStartComplete(success == TRUE, nullptr); - if (error != nullptr) - g_error_free(error); } static void BluezAdvStopDone(GObject * aObject, GAsyncResult * aResult, gpointer apClosure) { BluezLEAdvertisingManager1 * advMgr = BLUEZ_LEADVERTISING_MANAGER1(aObject); BluezEndpoint * endpoint = static_cast(apClosure); - GError * error = nullptr; - gboolean success = FALSE; + GAutoPtr error; + gboolean success = FALSE; VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); - success = bluez_leadvertising_manager1_call_unregister_advertisement_finish(advMgr, aResult, &error); + success = + bluez_leadvertising_manager1_call_unregister_advertisement_finish(advMgr, aResult, &MakeUniquePointerReceiver(error).Get()); if (success == FALSE) { @@ -235,8 +233,6 @@ static void BluezAdvStopDone(GObject * aObject, GAsyncResult * aResult, gpointer exit: BLEManagerImpl::NotifyBLEPeripheralAdvStopComplete(success == TRUE, nullptr); - if (error != nullptr) - g_error_free(error); } static CHIP_ERROR BluezAdvSetup(BluezEndpoint * endpoint) @@ -380,16 +376,16 @@ static gboolean BluezCharacteristicAcquireWrite(BluezGattCharacteristic1 * aChar char * errStr; #endif // CHIP_ERROR_LOGGING BluezConnection * conn = nullptr; - GVariantDict * options = nullptr; - GVariant * option_mtu = nullptr; - bool isSuccess = false; + GAutoPtr option_mtu; BluezEndpoint * endpoint = static_cast(apEndpoint); - VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); + + VerifyOrReturnValue(endpoint != nullptr, FALSE, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); conn = GetBluezConnectionViaDevice(endpoint); - VerifyOrExit(conn != nullptr, - g_dbus_method_invocation_return_dbus_error(aInvocation, "org.bluez.Error.Failed", "No Chipoble connection")); + VerifyOrReturnValue( + conn != nullptr, FALSE, + g_dbus_method_invocation_return_dbus_error(aInvocation, "org.bluez.Error.Failed", "No Chipoble connection")); ChipLogDetail(DeviceLayer, "BluezCharacteristicAcquireWrite is called, conn: %p", conn); @@ -400,15 +396,13 @@ static gboolean BluezCharacteristicAcquireWrite(BluezGattCharacteristic1 * aChar #endif // CHIP_ERROR_LOGGING ChipLogError(DeviceLayer, "FAIL: socketpair: %s in %s", StringOrNullMarker(errStr), __func__); g_dbus_method_invocation_return_dbus_error(aInvocation, "org.bluez.Error.Failed", "FD creation failed"); - goto exit; + return FALSE; } - options = g_variant_dict_new(aOptions); - option_mtu = g_variant_dict_lookup_value(options, "mtu", G_VARIANT_TYPE_UINT16); - VerifyOrExit( - option_mtu != nullptr, ChipLogError(DeviceLayer, "FAIL: No MTU in options in %s", __func__); + VerifyOrReturnValue( + g_variant_lookup(aOptions, "mtu", "q", &conn->mMtu), FALSE, + ChipLogError(DeviceLayer, "FAIL: No MTU in options in %s", __func__); g_dbus_method_invocation_return_dbus_error(aInvocation, "org.bluez.Error.InvalidArguments", "MTU negotiation failed")); - conn->mMtu = g_variant_get_uint16(option_mtu); channel = g_io_channel_unix_new(fds[0]); g_io_channel_set_encoding(channel, nullptr, nullptr); @@ -425,18 +419,8 @@ static gboolean BluezCharacteristicAcquireWrite(BluezGattCharacteristic1 * aChar Bluez_gatt_characteristic1_complete_acquire_write_with_fd(aInvocation, fds[1], conn->mMtu); close(fds[1]); - isSuccess = true; -exit: - if (options != nullptr) - { - g_variant_dict_unref(options); - } - if (option_mtu != nullptr) - { - g_variant_unref(option_mtu); - } - return isSuccess ? TRUE : FALSE; + return TRUE; } static gboolean BluezCharacteristicAcquireWriteError(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, @@ -458,29 +442,26 @@ static gboolean BluezCharacteristicAcquireNotify(BluezGattCharacteristic1 * aCha char * errStr; #endif // CHIP_ERROR_LOGGING BluezConnection * conn = nullptr; - GVariantDict * options = nullptr; - GVariant * option_mtu = nullptr; - bool isSuccess = false; + GAutoPtr option_mtu; BluezEndpoint * endpoint = static_cast(apEndpoint); - VerifyOrExit(endpoint != nullptr, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); + VerifyOrReturnValue(endpoint != nullptr, FALSE, ChipLogError(DeviceLayer, "endpoint is NULL in %s", __func__)); if (bluez_gatt_characteristic1_get_notifying(aChar)) { g_dbus_method_invocation_return_dbus_error(aInvocation, "org.bluez.Error.NotPermitted", "Already notifying"); - goto exit; + return FALSE; } conn = GetBluezConnectionViaDevice(endpoint); - VerifyOrExit(conn != nullptr, - g_dbus_method_invocation_return_dbus_error(aInvocation, "org.bluez.Error.Failed", "No Chipoble connection")); + VerifyOrReturnValue( + conn != nullptr, FALSE, + g_dbus_method_invocation_return_dbus_error(aInvocation, "org.bluez.Error.Failed", "No Chipoble connection")); - options = g_variant_dict_new(aOptions); - option_mtu = g_variant_dict_lookup_value(options, "mtu", G_VARIANT_TYPE_UINT16); - VerifyOrExit( - option_mtu != nullptr, ChipLogError(DeviceLayer, "FAIL: No MTU in options in %s", __func__); - g_dbus_method_invocation_return_dbus_error(aInvocation, "org.bluez.Error.InvalidArguments", "MTU negotiation failed")); - conn->mMtu = g_variant_get_uint16(option_mtu); + VerifyOrReturnValue(g_variant_lookup(aOptions, "mtu", "q", &conn->mMtu), FALSE, { + ChipLogError(DeviceLayer, "FAIL: No MTU in options in %s", __func__); + g_dbus_method_invocation_return_dbus_error(aInvocation, "org.bluez.Error.InvalidArguments", "MTU negotiation failed"); + }); if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, fds) < 0) { @@ -489,7 +470,7 @@ static gboolean BluezCharacteristicAcquireNotify(BluezGattCharacteristic1 * aCha #endif // CHIP_ERROR_LOGGING ChipLogError(DeviceLayer, "FAIL: socketpair: %s in %s", StringOrNullMarker(errStr), __func__); g_dbus_method_invocation_return_dbus_error(aInvocation, "org.bluez.Error.Failed", "FD creation failed"); - goto exit; + return FALSE; } channel = g_io_channel_unix_new(fds[0]); @@ -511,18 +492,8 @@ static gboolean BluezCharacteristicAcquireNotify(BluezGattCharacteristic1 * aCha conn->mIsNotify = true; BLEManagerImpl::HandleTXCharCCCDWrite(conn); - isSuccess = true; -exit: - if (options != nullptr) - { - g_variant_dict_unref(options); - } - if (option_mtu != nullptr) - { - g_variant_unref(option_mtu); - } - return isSuccess ? TRUE : FALSE; + return TRUE; } static gboolean BluezCharacteristicAcquireNotifyError(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, @@ -787,22 +758,19 @@ static BluezGattCharacteristic1 * BluezCharacteristicCreate(BluezGattService1 * static void BluezPeripheralRegisterAppDone(GObject * aObject, GAsyncResult * aResult, gpointer apClosure) { - GError * error = nullptr; + GAutoPtr error; BluezGattManager1 * gattMgr = BLUEZ_GATT_MANAGER1(aObject); - gboolean success = bluez_gatt_manager1_call_register_application_finish(gattMgr, aResult, &error); + gboolean success = + bluez_gatt_manager1_call_register_application_finish(gattMgr, aResult, &MakeUniquePointerReceiver(error).Get()); - VerifyOrExit(success == TRUE, ChipLogError(DeviceLayer, "FAIL: RegisterApplication : %s", error->message)); + VerifyOrReturn(success == TRUE, { + ChipLogError(DeviceLayer, "FAIL: RegisterApplication : %s", error->message); + BLEManagerImpl::NotifyBLEPeripheralRegisterAppComplete(false, nullptr); + }); BLEManagerImpl::NotifyBLEPeripheralRegisterAppComplete(true, nullptr); ChipLogDetail(DeviceLayer, "BluezPeripheralRegisterAppDone done"); - -exit: - if (error != nullptr) - { - BLEManagerImpl::NotifyBLEPeripheralRegisterAppComplete(false, nullptr); - g_error_free(error); - } } static CHIP_ERROR BluezPeripheralRegisterApp(BluezEndpoint * endpoint) @@ -1249,7 +1217,7 @@ static CHIP_ERROR StartupEndpointBindings(BluezEndpoint * endpoint) static CHIP_ERROR BluezC2Indicate(ConnectionDataBundle * closure) { BluezConnection * conn = nullptr; - GError * error = nullptr; + GAutoPtr error; GIOStatus status; const char * buf; size_t len, written; @@ -1265,7 +1233,8 @@ static CHIP_ERROR BluezC2Indicate(ConnectionDataBundle * closure) buf = (char *) g_variant_get_fixed_array(closure->mpVal, &len, sizeof(uint8_t)); VerifyOrExit(len <= static_cast(std::numeric_limits::max()), ChipLogError(DeviceLayer, "FAIL: buffer too large in %s", __func__)); - status = g_io_channel_write_chars(conn->mC2Channel.mpChannel, buf, static_cast(len), &written, &error); + status = g_io_channel_write_chars(conn->mC2Channel.mpChannel, buf, static_cast(len), &written, + &MakeUniquePointerReceiver(error).Get()); g_variant_unref(closure->mpVal); closure->mpVal = nullptr; @@ -1280,16 +1249,9 @@ static CHIP_ERROR BluezC2Indicate(ConnectionDataBundle * closure) exit: if (closure != nullptr) { - if (closure->mpVal) - { - g_variant_unref(closure->mpVal); - } g_free(closure); } - if (error != nullptr) - g_error_free(error); - return CHIP_NO_ERROR; } @@ -1310,7 +1272,7 @@ CHIP_ERROR SendBluezIndication(BLE_CONNECTION_OBJECT apConn, chip::System::Packe static CHIP_ERROR BluezDisconnect(BluezConnection * conn) { - GError * error = nullptr; + GAutoPtr error; gboolean success; VerifyOrExit(conn != nullptr, ChipLogError(DeviceLayer, "conn is NULL in %s", __func__)); @@ -1318,12 +1280,10 @@ static CHIP_ERROR BluezDisconnect(BluezConnection * conn) ChipLogDetail(DeviceLayer, "%s peer=%s", __func__, bluez_device1_get_address(conn->mpDevice)); - success = bluez_device1_call_disconnect_sync(conn->mpDevice, nullptr, &error); + success = bluez_device1_call_disconnect_sync(conn->mpDevice, nullptr, &MakeUniquePointerReceiver(error).Get()); VerifyOrExit(success == TRUE, ChipLogError(DeviceLayer, "FAIL: Disconnect: %s", error->message)); exit: - if (error != nullptr) - g_error_free(error); return CHIP_NO_ERROR; } @@ -1447,15 +1407,11 @@ CHIP_ERROR ShutdownBluezBleLayer(BluezEndpoint * apEndpoint) static void SendWriteRequestDone(GObject * aObject, GAsyncResult * aResult, gpointer apConnection) { BluezGattCharacteristic1 * c1 = BLUEZ_GATT_CHARACTERISTIC1(aObject); - GError * error = nullptr; - gboolean success = bluez_gatt_characteristic1_call_write_value_finish(c1, aResult, &error); + GAutoPtr error; + gboolean success = bluez_gatt_characteristic1_call_write_value_finish(c1, aResult, &MakeUniquePointerReceiver(error).Get()); - VerifyOrExit(success == TRUE, ChipLogError(DeviceLayer, "FAIL: BluezSendWriteRequest : %s", error->message)); + VerifyOrReturn(success == TRUE, ChipLogError(DeviceLayer, "FAIL: BluezSendWriteRequest : %s", error->message)); BLEManagerImpl::HandleWriteComplete(static_cast(apConnection)); - -exit: - if (error != nullptr) - g_error_free(error); } static CHIP_ERROR SendWriteRequestImpl(ConnectionDataBundle * data) @@ -1504,16 +1460,12 @@ static void OnCharacteristicChanged(GDBusProxy * aInterface, GVariant * aChanged static void SubscribeCharacteristicDone(GObject * aObject, GAsyncResult * aResult, gpointer apConnection) { BluezGattCharacteristic1 * c2 = BLUEZ_GATT_CHARACTERISTIC1(aObject); - GError * error = nullptr; - gboolean success = bluez_gatt_characteristic1_call_write_value_finish(c2, aResult, &error); + GAutoPtr error; + gboolean success = bluez_gatt_characteristic1_call_write_value_finish(c2, aResult, &MakeUniquePointerReceiver(error).Get()); - VerifyOrExit(success == TRUE, ChipLogError(DeviceLayer, "FAIL: BluezSubscribeCharacteristic : %s", error->message)); + VerifyOrReturn(success == TRUE, ChipLogError(DeviceLayer, "FAIL: BluezSubscribeCharacteristic : %s", error->message)); BLEManagerImpl::HandleSubscribeOpComplete(static_cast(apConnection), true); - -exit: - if (error != nullptr) - g_error_free(error); } static CHIP_ERROR SubscribeCharacteristicImpl(BluezConnection * connection) @@ -1541,18 +1493,14 @@ CHIP_ERROR BluezSubscribeCharacteristic(BLE_CONNECTION_OBJECT apConn) static void UnsubscribeCharacteristicDone(GObject * aObject, GAsyncResult * aResult, gpointer apConnection) { BluezGattCharacteristic1 * c2 = BLUEZ_GATT_CHARACTERISTIC1(aObject); - GError * error = nullptr; - gboolean success = bluez_gatt_characteristic1_call_write_value_finish(c2, aResult, &error); + GAutoPtr error; + gboolean success = bluez_gatt_characteristic1_call_write_value_finish(c2, aResult, &MakeUniquePointerReceiver(error).Get()); - VerifyOrExit(success == TRUE, ChipLogError(DeviceLayer, "FAIL: BluezUnsubscribeCharacteristic : %s", error->message)); + VerifyOrReturn(success == TRUE, ChipLogError(DeviceLayer, "FAIL: BluezUnsubscribeCharacteristic : %s", error->message)); // Stop listening to the TX characteristic changes g_signal_handlers_disconnect_by_data(c2, apConnection); BLEManagerImpl::HandleSubscribeOpComplete(static_cast(apConnection), false); - -exit: - if (error != nullptr) - g_error_free(error); } static CHIP_ERROR UnsubscribeCharacteristicImpl(BluezConnection * connection) @@ -1586,9 +1534,9 @@ struct ConnectParams static void ConnectDeviceDone(GObject * aObject, GAsyncResult * aResult, gpointer apParams) { - BluezDevice1 * device = BLUEZ_DEVICE1(aObject); - GError * error = nullptr; - gboolean success = bluez_device1_call_connect_finish(device, aResult, &error); + BluezDevice1 * device = BLUEZ_DEVICE1(aObject); + GAutoPtr error; + gboolean success = bluez_device1_call_connect_finish(device, aResult, &MakeUniquePointerReceiver(error).Get()); ConnectParams * params = static_cast(apParams); assert(params != nullptr); @@ -1602,14 +1550,14 @@ static void ConnectDeviceDone(GObject * aObject, GAsyncResult * aResult, gpointe // BlueZ returns "Software caused connection abort error", and we should make a connection retry. // It's important to make sure that the connection is correctly ceased, by calling `Disconnect()` // D-Bus method, or else `Connect()` returns immediately without any effect. - if (g_error_matches(error, G_IO_ERROR, G_IO_ERROR_DBUS_ERROR) && params->mNumRetries++ < kMaxConnectRetries) + if (g_error_matches(error.get(), G_IO_ERROR, G_IO_ERROR_DBUS_ERROR) && params->mNumRetries++ < kMaxConnectRetries) { // Clear the error before usage in subsequent call. - g_clear_error(&error); + g_clear_error(&MakeUniquePointerReceiver(error).Get()); - bluez_device1_call_disconnect_sync(device, nullptr, &error); + bluez_device1_call_disconnect_sync(device, nullptr, &MakeUniquePointerReceiver(error).Get()); bluez_device1_call_connect(device, params->mEndpoint->mpConnectCancellable, ConnectDeviceDone, params); - ExitNow(); + return; } BLEManagerImpl::HandleConnectFailed(CHIP_ERROR_INTERNAL); @@ -1620,10 +1568,6 @@ static void ConnectDeviceDone(GObject * aObject, GAsyncResult * aResult, gpointe } chip::Platform::Delete(params); - -exit: - if (error != nullptr) - g_error_free(error); } static CHIP_ERROR ConnectDeviceImpl(ConnectParams * apParams) diff --git a/src/platform/Linux/bluez/Types.h b/src/platform/Linux/bluez/Types.h index 3f61c430a5f7a2..df1485a5104989 100644 --- a/src/platform/Linux/bluez/Types.h +++ b/src/platform/Linux/bluez/Types.h @@ -50,6 +50,7 @@ #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE #include +#include #include #include