blob: 74486d0d75d3dedf021b8be3b60996297a53843f [file]
/*
*
* Copyright (c) 2020-2021 Project CHIP Authors
* Copyright (c) 2018 Nest Labs, Inc.
*
* 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 <lib/core/CHIPConfig.h>
#include <lib/support/FixedBuffer.h>
#include <platform/ConnectivityManager.h>
#include <platform/internal/GenericConnectivityManagerImpl.h>
#include <platform/internal/GenericConnectivityManagerImpl_UDP.h>
#if INET_CONFIG_ENABLE_TCP_ENDPOINT
#include <platform/internal/GenericConnectivityManagerImpl_TCP.h>
#endif
#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
#include <platform/internal/GenericConnectivityManagerImpl_BLE.h>
#else
#include <platform/internal/GenericConnectivityManagerImpl_NoBLE.h>
#endif
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
#include <platform/internal/GenericConnectivityManagerImpl_Thread.h>
#else
#include <platform/internal/GenericConnectivityManagerImpl_NoThread.h>
#endif
#if CHIP_DEVICE_CONFIG_ENABLE_WPA
#include <platform/internal/GenericConnectivityManagerImpl_WiFi.h>
#else
#include <platform/internal/GenericConnectivityManagerImpl_NoWiFi.h>
#endif
#if CHIP_DEVICE_CONFIG_ENABLE_WPA
#if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
#include <wifipaf/WiFiPAFEndPoint.h>
#include <wifipaf/WiFiPAFLayer.h>
#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
#endif // CHIP_DEVICE_CONFIG_ENABLE_WPA
#include <atomic>
#include <cstring>
#include <platform/Linux/NetworkCommissioningDriver.h>
#include <platform/NetworkCommissioning.h>
#include <vector>
#if CHIP_DEVICE_CONFIG_ENABLE_WPA
#include "WpaSupplicantClient.h"
#endif // CHIP_DEVICE_CONFIG_ENABLE_WPA
namespace chip {
namespace DeviceLayer {
#if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF && CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONING_PROXY
struct NanPeerInfo
{
uint8_t mac[6]{};
uint16_t vid = 0;
uint16_t pid = 0;
uint16_t discriminator = 0;
uint8_t opcode = 0;
uint16_t srvProtoType = 0;
std::vector<uint8_t> storage; // ExtendedData storage
bool hasExtendedData = false;
uint16_t band = 0; // WiFiBandBitmap value derived from scan frequency; 0 = unknown
/// Two reports are the same peer when the MAC and discriminator match.
bool operator==(const NanPeerInfo & o) const
{
return memcmp(mac, o.mac, sizeof(mac)) == 0 && discriminator == o.discriminator;
}
};
struct ScanTimerCtx
{
chip::DeviceLayer::ConnectivityManagerImpl * self = nullptr;
guint subscribe_id;
};
#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF && CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONING_PROXY
#if CHIP_DEVICE_CONFIG_ENABLE_WPA && CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
// Records when the radio can carry Wi-Fi PAF frames
enum class PafChannelState : uint8_t
{
kAvailable, // The radio is free and PAF frames may be sent
kConnecting, // Station connect in progress (scan, authenticate, associate, key handshake),
// during which the radio cannot carry PAF frames
kAwaitingNan, // STA link up but NAN not yet ready
kNoInterface, // No wpa_supplicant interface to send on
};
#endif // CHIP_DEVICE_CONFIG_ENABLE_WPA && CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
/**
* Concrete implementation of the ConnectivityManager singleton object for Linux platforms.
*/
class ConnectivityManagerImpl final : public ConnectivityManager,
#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
public Internal::GenericConnectivityManagerImpl_BLE<ConnectivityManagerImpl>,
#else
public Internal::GenericConnectivityManagerImpl_NoBLE<ConnectivityManagerImpl>,
#endif
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
public Internal::GenericConnectivityManagerImpl_Thread<ConnectivityManagerImpl>,
#else
public Internal::GenericConnectivityManagerImpl_NoThread<ConnectivityManagerImpl>,
#endif
#if CHIP_DEVICE_CONFIG_ENABLE_WPA
public Internal::GenericConnectivityManagerImpl_WiFi<ConnectivityManagerImpl>,
#else
public Internal::GenericConnectivityManagerImpl_NoWiFi<ConnectivityManagerImpl>,
#endif
public Internal::GenericConnectivityManagerImpl_UDP<ConnectivityManagerImpl>,
#if INET_CONFIG_ENABLE_TCP_ENDPOINT
public Internal::GenericConnectivityManagerImpl_TCP<ConnectivityManagerImpl>,
#endif
public Internal::GenericConnectivityManagerImpl<ConnectivityManagerImpl>
#if CHIP_DEVICE_CONFIG_ENABLE_WPA
,
public Internal::WpaSupplicantClient
#endif // CHIP_DEVICE_CONFIG_ENABLE_WPA
{
// Allow the ConnectivityManager interface class to delegate method calls to
// the implementation methods provided by this class.
friend class ConnectivityManager;
public:
// Singleton
static ConnectivityManagerImpl & GetDefaultInstance(void);
#if CHIP_DEVICE_CONFIG_ENABLE_WPA
// The connect callback may be null. No result is reported then, wpa_supplicant keeps retrying if the connect fails,
// and Wi-Fi PAF sends are not held back during the association. If Wi-Fi is blocked, the network is still written and
// selected, so it is joined once Wi-Fi is unblocked, and CHIP_ERROR_INCORRECT_STATE is returned.
CHIP_ERROR ConnectWiFiNetworkAsync(ByteSpan ssid, ByteSpan credentials,
NetworkCommissioning::Internal::WirelessDriver::ConnectCallback * connectCallback);
#if CHIP_DEVICE_CONFIG_ENABLE_WIFI_PDC
CHIP_ERROR ConnectWiFiNetworkWithPDCAsync(ByteSpan ssid, ByteSpan networkIdentity, ByteSpan clientIdentity,
const Crypto::P256Keypair & clientIdentityKeypair,
NetworkCommissioning::Internal::WirelessDriver::ConnectCallback * connectCallback);
#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI_PDC
// Stop waiting for the result of a pending connect, without invoking its callback.
void CancelConnectWiFiNetwork();
#if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
void PostWpaInterfaceProxyReady() CHIP_REQUIRES(mWpaSupplicantMutex);
void _WiFiPAFSetParam(const WiFiPAFAdvertiseParam & pafAdvParam);
CHIP_ERROR _SetWiFiPAFAdvertisingEnabled(bool enabled, uint32_t & publishId);
CHIP_ERROR _WiFiPAFSubscribe(const uint16_t & connDiscriminator, void * appState, OnConnectionCompleteFunct onSuccess,
OnConnectionErrorFunct onError);
CHIP_ERROR _WiFiPAFCancelSubscribe(uint32_t SubscribeId);
CHIP_ERROR _WiFiPAFCancelIncompleteSubscribe();
uint32_t GetPendingConnectSubscribeId() const { return mPendingConnectSubscribeId; }
void OnDiscoveryResult(GVariant * obj);
void OnReplied(GVariant * obj);
void OnNanReceive(GVariant * obj);
void OnNanPublishTerminated(guint public_id, gchar * reason);
void OnNanSubscribeTerminated(guint subscribe_id, gchar * reason);
CHIP_ERROR _WiFiPAFSend(const WiFiPAF::WiFiPAFSession & TxInfo, chip::System::PacketBufferHandle && msgBuf);
void _WiFiPafSetApFreq(const uint16_t freq) { mApFreq = freq; }
CHIP_ERROR _WiFiPAFShutdown(uint32_t id, WiFiPAF::WiFiPafRole role);
#else
inline void PostWpaInterfaceProxyReady() CHIP_REQUIRES(mWpaSupplicantMutex) {}
#endif
void PostNetworkConnect();
CHIP_ERROR CommitConfig();
void StartWiFiManagement();
CHIP_ERROR StartWiFiManagementSync();
// Release GLib objects before the GLib main loop is quit.
// Must be called from PlatformManagerImpl::_Shutdown() before g_main_loop_quit().
void StopWiFiManagement();
bool IsWiFiManagementStarted();
void StartNonConcurrentWiFiManagement();
int32_t GetDisconnectReason();
CHIP_ERROR GetWiFiBssId(MutableByteSpan & value);
CHIP_ERROR GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType);
CHIP_ERROR GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wiFiVersion);
CHIP_ERROR GetConfiguredNetwork(NetworkCommissioning::Network & network);
CHIP_ERROR StartWiFiScan(ByteSpan ssid, NetworkCommissioning::WiFiDriver::ScanCallback * callback);
#if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF && CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONING_PROXY
public:
void ScanNanReceive(GVariant * obj);
void ScanNanSubscribeTerminated(guint subscribe_id, gchar * reason);
void ScanDiscoveryResult(GVariant * discov_info);
using PafScanResultsCallback = void (*)(void * context, const std::vector<NanPeerInfo> & results);
CHIP_ERROR WiFiPAFScan(uint8_t scanMaxTime, PafScanResultsCallback cb, void * cbContext);
/** Per-peer callback fired each time a new NAN discovery result arrives
* during a background scan (including re-discoveries, to allow TTL reset). */
using BgScanDiscoveryCallback = void (*)(void * ctx, const NanPeerInfo & peer);
/**
* Start a continuous background NAN discovery scan.
* @param cb Called on every discovery result (including duplicates).
* @param cbCtx Passed unchanged to cb.
* @return CHIP_ERROR_BUSY if a one-shot scan is already running.
*/
CHIP_ERROR WiFiPAFStartBackgroundScan(BgScanDiscoveryCallback cb, void * cbCtx);
/**
* Stop the background scan started by WiFiPAFStartBackgroundScan.
* No-op if no background scan is active.
*/
void WiFiPAFStopBackgroundScan();
private:
/// Peers seen by the current scan, as a rolling window. Bounded at the same value the
/// CommissioningProxy cluster caps a ProxyScanResponse.
static constexpr size_t kMaxScanPeers = CHIP_CONFIG_COMMISSIONING_PROXY_MAX_CACHED_RESULTS;
std::vector<NanPeerInfo> mNanScanPeers;
/// Index of the oldest entry, overwritten next once the window is full.
size_t mNanScanPeersNext = 0;
PafScanResultsCallback mScanCb = nullptr;
void * mScanCbContext = nullptr;
uint32_t mActiveScanSubscribeId = 0; // subscribe_id of the current one-shot scan
void FinishWiFiPAFScan(ScanTimerCtx * ctx);
BgScanDiscoveryCallback mBgScanCb = nullptr;
void * mBgScanCbCtx = nullptr;
uint32_t mBgScanSubscribeId = 0;
uint32_t mScanFreq = 0; // freq (MHz) used for the current scan (one-shot or background)
// Handler IDs for the three scan GLib signals (nandiscovery-result, nanreceive,
// nansubscribe-terminated). Stored so DisconnectScanSignals() can remove exactly
// the scan handlers without disturbing PAF connect-path handlers on the same signals.
gulong mScanSignalIds[3] = {};
/** Connect the scan GLib signal handlers. Must be called before NANSubscribe;
* see the definition for why. Caller must hold mWpaSupplicantMutex. */
void ConnectScanSignals() CHIP_REQUIRES(mWpaSupplicantMutex);
/** Disconnect the scan GLib signal handlers registered by ConnectScanSignals().
* Uses stored handler IDs so it does not accidentally remove connect-path
* handlers on the same signals. */
void DisconnectScanSignals();
/** As DisconnectScanSignals(), for callers that already hold mWpaSupplicantMutex. */
void DisconnectScanSignalsLocked() CHIP_REQUIRES(mWpaSupplicantMutex);
#endif
private:
CHIP_ERROR _ConnectWiFiNetworkAsync(GVariant * networkArgs, GVariant * blobs,
NetworkCommissioning::Internal::WirelessDriver::ConnectCallback * connectCallback)
CHIP_REQUIRES(mWpaSupplicantMutex);
/** Remove all networks from wpa_supplicant (including PDC, if any blobs) */
CHIP_ERROR ClearNetworks() CHIP_REQUIRES(mWpaSupplicantMutex);
/** Replace all networks in wpa_supplicant with the one described by networkArgs (a{sv}), after adding blobs (a{say},
* nullable). After a failure wpa_supplicant holds no network and no PDC blobs. Neither argument is consumed. */
CHIP_ERROR WriteNetwork(GVariant * networkArgs, GVariant * blobs) CHIP_REQUIRES(mWpaSupplicantMutex);
/** The adding half of WriteNetwork, without its cleanup on failure. */
CHIP_ERROR AddNetwork(GVariant * networkArgs, GVariant * blobs) CHIP_REQUIRES(mWpaSupplicantMutex);
static void OnWiFiConnectTimeout(System::Layer * aLayer, void * aAppState);
void DisableNetworkAfterConnectFailure();
#endif
public:
const char * GetEthernetIfName() { return (mEthIfName[0] == '\0') ? nullptr : mEthIfName; }
void UpdateEthernetNetworkingStatus();
using NetworkStatusChangeCallback = NetworkCommissioning::Internal::BaseDriver::NetworkStatusChangeCallback;
using OneShotScanCallback = NetworkCommissioning::WiFiDriver::ScanCallback;
using OneShotConnectCallback = NetworkCommissioning::Internal::WirelessDriver::ConnectCallback;
void SetOneShotConnectCallback(OneShotConnectCallback * inOneShotConnectCallback) noexcept;
void SetOneShotScanCallback(OneShotScanCallback * inOneShotScanCallback) noexcept;
void SetNetworkStatusChangeCallback(NetworkStatusChangeCallback * inStatusChangeCallback) noexcept;
// Network Commissioning Action Delegation Methods
void OnScanFinished(NetworkCommissioning::Status inStatus, CharSpan inDebugText,
NetworkCommissioning::WiFiScanResponseIterator * inNetworks) noexcept;
void OnConnectResult(NetworkCommissioning::Status inCommissioningError, CharSpan inDebugText, int32_t inConnectStatus) noexcept;
void OnStatusChange(NetworkCommissioning::Status inCommissioningError, Optional<ByteSpan> inNetworkId,
Optional<int32_t> inConnectStatus) noexcept;
#if CHIP_DEVICE_CONFIG_ENABLE_WIFI
const char * GetWiFiIfName() { return (sWiFiIfName[0] == '\0') ? nullptr : sWiFiIfName; }
CHIP_ERROR SetWiFiIfName(const char * ifName);
#endif
private:
// ===== Members that implement the ConnectivityManager abstract interface.
CHIP_ERROR _Init();
void _OnPlatformEvent(const ChipDeviceEvent * event);
#if CHIP_DEVICE_CONFIG_ENABLE_WIFI
bool IsWiFiStationConnecting() const noexcept;
bool IsWiFiStationScanning() const noexcept;
#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI
#if CHIP_DEVICE_CONFIG_ENABLE_WPA
WiFiStationMode _GetWiFiStationMode();
CHIP_ERROR _SetWiFiStationMode(ConnectivityManager::WiFiStationMode val);
System::Clock::Timeout _GetWiFiStationReconnectInterval();
CHIP_ERROR _SetWiFiStationReconnectInterval(System::Clock::Timeout val);
bool _IsWiFiStationEnabled();
bool _IsWiFiStationConnected();
bool _IsWiFiStationApplicationControlled();
bool _IsWiFiStationProvisioned();
void _ClearWiFiStationProvision();
WiFiAPMode _GetWiFiAPMode();
CHIP_ERROR _SetWiFiAPMode(WiFiAPMode val);
bool _IsWiFiAPActive();
bool _IsWiFiAPApplicationControlled();
void _DemandStartWiFiAP();
void _StopOnDemandWiFiAP();
void _MaintainOnDemandWiFiAP();
System::Clock::Timeout _GetWiFiAPIdleTimeout();
void _SetWiFiAPIdleTimeout(System::Clock::Timeout val);
void NotifyWiFiConnectivityChange(ConnectivityChange change);
void UpdateNetworkStatus();
CHIP_ERROR StopAutoScan();
void _OnWpaProxyReady(GObject * sourceObject, GAsyncResult * res);
void _OnWpaInterfaceRemoved(WpaSupplicant1 * proxy, const char * path);
void _OnWpaInterfaceAdded(WpaSupplicant1 * proxy, const char * path, GVariant * properties);
void _OnWpaPropertiesChanged(WpaSupplicant1Interface * iface, GVariant * properties);
void _OnWpaInterfaceScanDone(WpaSupplicant1Interface * iface, gboolean success);
void _OnWpaInterfaceReady(GObject * sourceObject, GAsyncResult * res);
void _OnWpaInterfaceProxyReady(GObject * sourceObject, GAsyncResult * res);
#if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
WiFiPAFAdvertiseParam mPafAdvParam;
OnConnectionCompleteFunct mOnPafSubscribeComplete;
OnConnectionErrorFunct mOnPafSubscribeError;
WiFiPAF::WiFiPAFEndPoint mWiFiPAFEndPoint;
void * mAppState;
uint16_t mApFreq;
uint32_t mPendingConnectSubscribeId = 0; // set by _WiFiPAFSubscribe, read by app layer on timeout
CHIP_ERROR _WiFiPAFPublish(WiFiPAFAdvertiseParam & args);
CHIP_ERROR _WiFiPAFCancelPublish(uint32_t PublishId);
// The resource checking is needed right before sending data packets that they are initialized and connected.
bool _WiFiPAFResourceAvailable() { return mPafChannelState.load() == PafChannelState::kAvailable; };
// Written from both the glib D-Bus thread and the CHIP thread.
std::atomic<PafChannelState> mPafChannelState{ PafChannelState::kAvailable };
// Association hooks, called from the wpa_supplicant state machine. Defined in
// ConnectivityManagerImpl_WiFiPafWpaSupplicant.cpp; no-ops below when PAF is disabled so the
// call sites need no #if.
void OnAssociationRequested();
void OnAssociationStarting();
void OnAssociationFailed();
void OnAssociationCompleted();
void OnInterfaceRemoved();
// Evidence from the NAN layer that the radio is carrying PAF traffic again.
void PafChannelNoteNanActivity();
void ArmNanRecoveryTimer();
static void HandleNanRecoveryTimeout(chip::System::Layer * layer, void * context);
// True if this call released the wait, false if there was none to release.
bool TryReleaseNanRecoveryWait();
// Identifies the NAN recovery wait a timer was armed for, so it releases only its own.
std::atomic<uint32_t> mNanRecoveryId{ 0 };
std::atomic<uint32_t> mArmedNanRecoveryId{ 0 };
#else
void OnAssociationRequested() {}
void OnAssociationStarting() {}
void OnAssociationFailed() {}
void OnAssociationCompleted() {}
void OnInterfaceRemoved() {}
#endif
CHIP_ERROR _GetBssInfo(const char * bssPath, NetworkCommissioning::WiFiScanResponse & result);
CHIP_ERROR _StartWiFiManagement();
CHIP_ERROR _StopWiFiManagement();
// Written on the GLib thread, read by the connect deadline timer on the Matter thread.
std::atomic<bool> mAssociationStarted{ false };
// Identifies the connect a queued result belongs to, so a result that arrives after the next
// connect has started is not reported for it.
std::atomic<uint32_t> mConnectAttemptId{ 0 };
unsigned int mAssociationRetriesLeft = 0;
#endif // CHIP_DEVICE_CONFIG_ENABLE_WPA
private:
// ==================== ConnectivityManager Private Methods ====================
#if CHIP_DEVICE_CONFIG_ENABLE_WPA
void DriveAPState();
CHIP_ERROR ConfigureWiFiAP();
void ChangeWiFiAPState(WiFiAPState newState);
static void DriveAPState(::chip::System::Layer * aLayer, void * aAppState);
#endif
// ===== Private members reserved for use by this class only.
char mEthIfName[Inet::InterfaceId::kMaxIfNameLength];
#if CHIP_DEVICE_CONFIG_ENABLE_WPA
ConnectivityManager::WiFiStationMode mWiFiStationMode;
ConnectivityManager::WiFiAPMode mWiFiAPMode;
WiFiAPState mWiFiAPState;
System::Clock::Timestamp mLastAPDemandTime;
System::Clock::Timeout mWiFiStationReconnectInterval;
System::Clock::Timeout mWiFiAPIdleTimeout;
#endif
#if CHIP_DEVICE_CONFIG_ENABLE_WIFI
char sWiFiIfName[Inet::InterfaceId::kMaxIfNameLength];
#endif
#if CHIP_DEVICE_CONFIG_ENABLE_WPA
Internal::WiFiSSIDFixedBuffer mInterestedSSID;
#endif
/**
* A callback through which, when non-null, the Wi-Fi driver
* 'OnFinished' method is invoked after a Wi-Fi scan is
* complete. The semantics of this callback are one-shot in that
* it is set-scan-invoke-and-clear.
*
* A non-null value implies that a Wi-Fi scan is in progress.
*/
OneShotScanCallback * mpOneShotScanCallback;
/**
* A callback through which, when non-null, the wireless driver
* 'OnResult' method is invoked after a Wi-Fi association is
* complete. The semantics of this callback are one-shot in that
* it is set-associate-invoke-and-clear.
*
* A non-null value implies that a Wi-Fi association is in
* progress.
*/
OneShotConnectCallback * mpOneShotConnectCallback;
NetworkStatusChangeCallback * mpStatusChangeCallback;
};
} // namespace DeviceLayer
} // namespace chip