From fae0eb4c7a6ed3a11cdb47c59f229670062ff3fe Mon Sep 17 00:00:00 2001 From: zhangfeng Date: Thu, 9 Sep 2021 01:32:29 +0000 Subject: [PATCH 1/5] wifi framework code optimize Signed-off-by: zhangfeng --- .../wifi_standard/include/wifi_device.h | 19 +- .../wifi_standard/interfaces/i_wifi_device.h | 15 +- .../wifi_standard/interfaces/i_wifi_hotspot.h | 10 +- .../wifi_standard/interfaces/wifi_ap_msg.h | 13 +- .../wifi_standard/interfaces/wifi_msg.h | 54 +- .../src/wifi_device_callback_stub.cpp | 12 +- .../wifi_standard/src/wifi_device_impl.cpp | 10 +- .../wifi_standard/src/wifi_device_impl.h | 15 +- .../wifi_standard/src/wifi_device_proxy.cpp | 187 +++--- .../wifi_standard/src/wifi_device_proxy.h | 15 +- .../src/wifi_hotspot_callback_stub.cpp | 12 +- .../wifi_standard/src/wifi_hotspot_proxy.cpp | 133 ++-- .../wifi_standard/src/wifi_hotspot_proxy.h | 8 - .../ipc_framework/cRPC/include/client.h | 1 - .../ipc_framework/cRPC/include/evloop.h | 8 +- .../ipc_framework/cRPC/include/net.h | 2 + .../ipc_framework/cRPC/include/server.h | 4 +- .../ipc_framework/cRPC/src/client.c | 54 +- .../ipc_framework/cRPC/src/context.c | 37 +- .../ipc_framework/cRPC/src/evloop.c | 46 +- .../ipc_framework/cRPC/src/hash_table.c | 2 +- .../ipc_framework/cRPC/src/net.c | 13 +- .../ipc_framework/cRPC/src/serial.c | 4 +- .../ipc_framework/cRPC/src/server.c | 36 +- .../common/config/wifi_config_file_spec.cpp | 4 + .../common/config/wifi_settings.cpp | 21 +- .../common/config/wifi_settings.h | 28 +- .../common/include/wifi_internal_msg.h | 239 ++++---- .../common/net_helper/network_interface.cpp | 2 +- .../common/utils/wifi_global_func.cpp | 84 ++- .../common/utils/wifi_global_func.h | 45 +- .../dhcp_manage/dhcp_client/BUILD.gn | 76 +-- .../dhcp_client/include/dhcp_api.h | 25 + .../dhcp_client/include/dhcp_client.h | 6 + .../dhcp_client/include/dhcp_define.h | 21 +- .../dhcp_client/include/dhcp_ipv4.h | 3 + .../dhcp_manage/dhcp_client/src/dhcp_api.cpp | 60 ++ .../dhcp_manage/dhcp_client/src/dhcp_client.c | 22 +- .../dhcp_client/src/dhcp_function.c | 113 ++-- .../dhcp_manage/dhcp_client/src/dhcp_ipv4.c | 570 ++++++++++++++---- .../dhcp_manage/dhcp_client/src/dhcp_main.c | 78 +-- .../dhcp_client/src/dhcp_options.c | 52 +- .../dhcp_manage/dhcp_client/src/dhcp_socket.c | 92 +-- .../dhcp_manage/mgr_service/BUILD.gn | 29 +- .../include/dhcp_client_service_impl.h | 53 +- .../mgr_service/include/dhcp_define.h | 32 +- .../include/dhcp_event_subscriber.h | 40 ++ .../mgr_service/include/dhcp_func.h | 17 +- .../src/dhcp_client_service_impl.cpp | 476 ++++++++------- .../mgr_service/src/dhcp_event_subscriber.cpp | 39 ++ .../dhcp_manage/mgr_service/src/dhcp_func.cpp | 237 +++++--- .../src/dhcp_server_service_impl.cpp | 203 ++++--- .../mgr_service/src/dhcp_service.cpp | 40 +- .../wifi_framework/wifi_manage/BUILD.gn | 12 +- .../wifi_manage/common/state_machine.cpp | 4 +- .../idl_interface/i_wifi_hotspot_iface.c | 23 - .../idl_interface/i_wifi_hotspot_iface.h | 12 +- .../idl_client/wifi_ap_hal_interface.cpp | 5 - .../idl_client/wifi_ap_hal_interface.h | 10 - .../idl_client/wifi_idl_client.cpp | 10 +- .../wifi_manage/idl_client/wifi_idl_client.h | 10 - .../wifi_manage/wifi_ap/ap_config_use.h | 1 - .../wifi_manage/wifi_ap/ap_interface.cpp | 56 +- .../wifi_manage/wifi_ap/ap_interface.h | 85 ++- .../wifi_manage/wifi_ap/ap_service.cpp | 138 +---- .../wifi_manage/wifi_ap/ap_service.h | 102 ++-- .../wifi_manage/wifi_ap/ap_started_state.cpp | 2 +- .../wifi_manage/wifi_ap/ap_state_machine.cpp | 39 ++ .../wifi_manage/wifi_ap/ap_state_machine.h | 23 + .../wifi_ap/ap_stations_manager.cpp | 7 +- .../wifi_manage/wifi_ap/i_ap_service.h | 50 ++ .../wifi_ap/i_ap_service_callbacks.h | 34 ++ .../wifi_manage/wifi_config_center.cpp | 45 +- .../wifi_manage/wifi_config_center.h | 29 + .../wifi_device_callback_proxy.cpp | 14 +- .../wifi_manage/wifi_device_death_recipient.h | 4 +- .../wifi_manage/wifi_device_service_impl.cpp | 241 ++++---- .../wifi_manage/wifi_device_service_impl.h | 4 +- .../wifi_manage/wifi_device_stub.cpp | 72 ++- .../wifi_manage/wifi_device_stub.h | 5 +- .../wifi_hotspot_callback_proxy.cpp | 12 +- .../wifi_hotspot_death_recipient.cpp | 2 +- .../wifi_hotspot_death_recipient.h | 4 +- .../wifi_manage/wifi_hotspot_service_impl.cpp | 174 +++--- .../wifi_manage/wifi_hotspot_service_impl.h | 8 - .../wifi_manage/wifi_hotspot_stub.cpp | 67 +- .../wifi_manage/wifi_hotspot_stub.h | 1 - .../wifi_internal_event_dispatcher.cpp | 290 ++++----- .../wifi_internal_event_dispatcher.h | 20 +- .../wifi_manage/wifi_manager.cpp | 570 +++++++++--------- .../wifi_framework/wifi_manage/wifi_manager.h | 122 ++-- .../wifi_manage/wifi_scan/iscan_service.h | 98 +++ .../wifi_scan/iscan_service_callbacks.h | 33 + .../wifi_manage/wifi_scan/scan_common.h | 26 +- .../wifi_manage/wifi_scan/scan_interface.cpp | 217 ++----- .../wifi_manage/wifi_scan/scan_interface.h | 81 ++- .../wifi_manage/wifi_scan/scan_service.cpp | 105 ++-- .../wifi_manage/wifi_scan/scan_service.h | 37 +- .../wifi_manage/wifi_scan_callback_proxy.cpp | 2 +- .../wifi_manage/wifi_scan_death_recipient.h | 4 +- .../wifi_manage/wifi_scan_service_impl.cpp | 63 +- .../wifi_manage/wifi_scan_service_impl.h | 1 + .../wifi_manage/wifi_scan_stub.cpp | 63 +- .../wifi_manage/wifi_service_manager.cpp | 227 +++++-- .../wifi_manage/wifi_service_manager.h | 95 ++- .../wifi_manage/wifi_sta/ista_service.h | 166 +++++ .../wifi_sta/sta_auto_connect_service.cpp | 20 +- .../wifi_sta/sta_auto_connect_service.h | 18 +- .../wifi_manage/wifi_sta/sta_define.h | 15 +- .../wifi_sta/sta_device_appraisal.h | 2 +- .../wifi_manage/wifi_sta/sta_interface.cpp | 213 +++---- .../wifi_manage/wifi_sta/sta_interface.h | 153 +++-- .../wifi_sta/sta_saved_device_appraisal.cpp | 20 +- .../wifi_sta/sta_saved_device_appraisal.h | 4 +- .../wifi_manage/wifi_sta/sta_service.cpp | 179 +++--- .../wifi_manage/wifi_sta/sta_service.h | 108 ++-- .../wifi_sta/sta_service_callback.h | 36 ++ .../wifi_sta/sta_state_machine.cpp | 295 +++++---- .../wifi_manage/wifi_sta/sta_state_machine.h | 33 +- .../wifi_hal/wifi_hal_crpc_server.c | 4 +- .../hostapd_hal/wifi_hostapd_hal.c | 2 +- .../wifi_hal/wifi_hal_module_manage.c | 33 +- 122 files changed, 4677 insertions(+), 3400 deletions(-) create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_api.h create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_api.cpp create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_event_subscriber.h create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_event_subscriber.cpp create mode 100644 services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/i_ap_service.h create mode 100644 services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/i_ap_service_callbacks.h create mode 100644 services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/iscan_service.h create mode 100644 services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/iscan_service_callbacks.h create mode 100644 services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/ista_service.h create mode 100644 services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service_callback.h diff --git a/interfaces/innerkits/native_cpp/wifi_standard/include/wifi_device.h b/interfaces/innerkits/native_cpp/wifi_standard/include/wifi_device.h index 24ad940dc..aa71abcbe 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/include/wifi_device.h +++ b/interfaces/innerkits/native_cpp/wifi_standard/include/wifi_device.h @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef WIFI_DEVICE_H -#define WIFI_DEVICE_H +#ifndef OHOS_WIFI_DEVICE_H +#define OHOS_WIFI_DEVICE_H #include "i_wifi_device_callback.h" #include "wifi_errcode.h" @@ -139,13 +139,12 @@ public: virtual ErrCode GetCountryCode(std::string &countryCode) = 0; /** - * @Description Client register callback event. + * @Description Register callback function. * - * @param name - client's name, which is a unique identifier - * @param callback - client object + * @param callback - IWifiDeviceCallBack object * @return ErrCode - operation result */ - virtual ErrCode RegisterCallBackClient(const std::string &name, const sptr &callback) = 0; + virtual ErrCode RegisterCallBack(const sptr &callback) = 0; /** * @Description Get the signal level object. @@ -173,6 +172,14 @@ public: * @return false - unsupported */ virtual bool IsFeatureSupported(long feature) = 0; + + /** + * @Description Get the device MAC address. + * + * @param result - Get device mac String + * @return ErrCode - operation result + */ + virtual ErrCode GetDeviceMacAddress(std::string &result) = 0; }; } // namespace Wifi } // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_device.h b/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_device.h index 1b6c1d4c5..244c0f468 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_device.h +++ b/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_device.h @@ -193,13 +193,12 @@ public: virtual ErrCode GetCountryCode(std::string &countryCode) = 0; /** - * @Description Client register callback event + * @Description Register callback function. * - * @param name - client's name, which is a unique identifier - * @param callback - client object + * @param callback - IWifiDeviceCallBack object * @return ErrCode - operation result */ - virtual ErrCode RegisterCallBackClient(const std::string &name, const sptr &callback) = 0; + virtual ErrCode RegisterCallBack(const sptr &callback) = 0; /** * @Description Get the Signal Level object @@ -219,6 +218,14 @@ public: */ virtual ErrCode GetSupportedFeatures(long &features) = 0; + /** + * @Description Get the device MAC address. + * + * @param result - Get device mac String + * @return ErrCode - operation result + */ + virtual ErrCode GetDeviceMacAddress(std::string &result) = 0; + public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.wifi.IWifiDeviceService"); }; diff --git a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_hotspot.h b/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_hotspot.h index b8e08548c..3469e00c1 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_hotspot.h +++ b/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_hotspot.h @@ -65,15 +65,7 @@ public: virtual ErrCode SetHotspotConfig(const HotspotConfig &config) = 0; /** - * @Description Get the device MAC address - * - * @param result - Get device mac String - * @return ErrCode - operation result - */ - virtual ErrCode GetDeviceMacAddress(std::string &result) = 0; - - /** - * @Description Get the Station List object + * @Description Get the Station List object. * * @param result - Get result vector of connect Station Info * @return ErrCode - operation result diff --git a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_ap_msg.h b/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_ap_msg.h index e85ef61c4..4ccefe084 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_ap_msg.h +++ b/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_ap_msg.h @@ -20,6 +20,7 @@ namespace OHOS { namespace Wifi { +#define AP_CHANNEL_DEFAULT 6 enum class ApState { AP_STATE_NONE = 0, AP_STATE_IDLE, @@ -52,9 +53,9 @@ struct HotspotConfig { HotspotConfig() { securityType = KeyMgmt::WPA2_PSK; - band = BandType::BAND_NONE; - channel = 0; - maxConn = 0; + band = BandType::BAND_2GHZ; + channel = AP_CHANNEL_DEFAULT; + maxConn = -1; } inline void SetSsid(const std::string &newSsid) @@ -115,9 +116,9 @@ private: std::string ssid; /* Hotspot name, The string length range is 1~32 */ std::string preSharedKey; /* Hotspot password ,The string length range is 8~63 */ KeyMgmt securityType; /* Hotspot Encryption type, Optional NONE/WPA_PSK/WPA2_PSK */ - BandType band; /* Hotspot band */ - int32_t channel; /* Hotspot channel */ - int32_t maxConn; /* Hotspot maximum number of connections, The range is 1-32 */ + BandType band; + int32_t channel; + int32_t maxConn; }; struct StationInfo { diff --git a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_msg.h b/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_msg.h index 3dfa2299c..6b6ea4518 100755 --- a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_msg.h +++ b/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_msg.h @@ -29,7 +29,7 @@ namespace OHOS { namespace Wifi { -#define MAX_COUNTRY_CODE_LEN 2 +#define WIFI_COUNTRY_CODE_LEN 2 #define WEPKEYS_SIZE 4 #define INVALID_NETWORK_ID (-1) #define REOPEN_STA_INTERVAL 500 @@ -135,12 +135,6 @@ enum class SetupMethod { INVALID = 4, }; -/* is wps connected to a network */ -enum class IsWpsConnected { - WPS_CONNECTED = 0, - WPS_INVALID = -1, -}; - /* WPS config */ struct WpsConfig { SetupMethod setup; /* WPS type */ @@ -372,17 +366,20 @@ enum class WifiState { DISABLING = 0, DISABLED = 1, ENABLING = 2, ENABLED = 3, U enum class ConnectionState { CONNECT_CONNECTING = 0, - CONNECT_OBTAINING_IP = 1, - CONNECT_OBTAINING_IP_FAIL = 2, - CONNECT_AP_CONNECTED = 3, - CONNECT_CHECK_PORTAL = 4, - CONNECT_NETWORK_ENABLED = 5, - CONNECT_NETWORK_DISABLED = 6, - DISCONNECT_DISCONNECTING = 7, - DISCONNECT_DISCONNECT_FAILED = 8, - DISCONNECT_DISCONNECTED = 9, - CONNECT_PASSWORD_WRONG = 10, - CONNECT_CONNECTING_TIMEOUT = 11, + CONNECT_AP_CONNECTED = 1, + CONNECT_CHECK_PORTAL = 2, + CONNECT_NETWORK_ENABLED = 3, + CONNECT_NETWORK_DISABLED = 4, + DISCONNECT_DISCONNECTING = 5, + DISCONNECT_DISCONNECT_FAILED = 6, + DISCONNECT_DISCONNECTED = 7, + CONNECT_PASSWORD_WRONG = 8, + CONNECT_CONNECTING_TIMEOUT = 9, + CONNECT_OBTAINING_IP = 10, + CONNECT_OBTAINING_IP_FAILED = 11, + CONNECT_ASSOCIATING = 12, + CONNECT_ASSOCIATED = 13, + UNKNOWN, }; @@ -403,23 +400,10 @@ enum class WpsStartState { WPS_TIME_OUT = 12, }; -/* mock api state */ -struct WifiMockState { - /* mock type: 1 screen 2 airplane 3 App run mode 4 power saving 5 Customer-defined scenario */ - int type; - /** - * when screen: 1 on 2 off; - * airplane: 1 on 2 off; - * App run state: 1 front 2 backend; - * power saving: 1 on 2 off; - * other Customer-defined scene: 1 on 2 off - */ - int state; - WifiMockState() - { - type = 0; - state = 0; - } +enum class StreamDirection { + STREAM_DIRECTION_UP = 0, + STREAM_DIRECTION_DOWN = 1, + UNKNOWN, }; /* DHCP info */ diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_callback_stub.cpp b/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_callback_stub.cpp index a2ad2b1ba..8927eb0cb 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_callback_stub.cpp +++ b/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_callback_stub.cpp @@ -144,13 +144,13 @@ int WifiDeviceCallBackStub::RemoteOnWifiConnectionChanged(uint32_t code, Message int state = data.ReadInt32(); WifiLinkedInfo info; info.networkId = data.ReadInt32(); - info.ssid = Str16ToStr8(data.ReadString16()); - info.bssid = Str16ToStr8(data.ReadString16()); + info.ssid = data.ReadCString(); + info.bssid = data.ReadCString(); info.rssi = data.ReadInt32(); info.band = data.ReadInt32(); info.frequency = data.ReadInt32(); info.linkSpeed = data.ReadInt32(); - info.macAddress = Str16ToStr8(data.ReadString16()); + info.macAddress = data.ReadCString(); info.ipAddress = data.ReadInt32(); int tmpConnState = data.ReadInt32(); if (tmpConnState >= 0 && tmpConnState <= int(ConnState::FAILED)) { @@ -159,8 +159,8 @@ int WifiDeviceCallBackStub::RemoteOnWifiConnectionChanged(uint32_t code, Message info.connState = ConnState::FAILED; } info.ifHiddenSSID = data.ReadBool(); - info.rxLinkSpeed = Str16ToStr8(data.ReadString16()); - info.txLinkSpeed = Str16ToStr8(data.ReadString16()); + info.rxLinkSpeed = data.ReadCString(); + info.txLinkSpeed = data.ReadCString(); info.chload = data.ReadInt32(); info.snr = data.ReadInt32(); int tmpState = data.ReadInt32(); @@ -194,7 +194,7 @@ int WifiDeviceCallBackStub::RemoteOnWifiWpsStateChanged(uint32_t code, MessagePa { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); int state = data.ReadInt32(); - std::string pinCode = Str16ToStr8(data.ReadString16()); + std::string pinCode = data.ReadCString(); OnWifiWpsStateChanged(state, pinCode); reply.WriteInt32(0); /* Reply 0 to indicate that no exception occurs. */ return 0; diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_impl.cpp b/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_impl.cpp index 704fcdeca..856507b94 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_impl.cpp +++ b/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_impl.cpp @@ -193,10 +193,10 @@ ErrCode WifiDeviceImpl::GetSignalLevel(const int &rssi, const int &band, int &le return client_->GetSignalLevel(rssi, band, level); } -ErrCode WifiDeviceImpl::RegisterCallBackClient(const std::string &name, const sptr &callback) +ErrCode WifiDeviceImpl::RegisterCallBack(const sptr &callback) { RETURN_IF_FAIL(client_); - return client_->RegisterCallBackClient(name, callback); + return client_->RegisterCallBack(callback); } ErrCode WifiDeviceImpl::GetSupportedFeatures(long &features) @@ -214,5 +214,11 @@ bool WifiDeviceImpl::IsFeatureSupported(long feature) } return ((tmpFeatures & feature) == feature); } + +ErrCode WifiDeviceImpl::GetDeviceMacAddress(std::string &result) +{ + RETURN_IF_FAIL(client_); + return client_->GetDeviceMacAddress(result); +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_impl.h b/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_impl.h index 3204bad84..aa2576611 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_impl.h +++ b/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_impl.h @@ -137,13 +137,12 @@ public: ErrCode GetCountryCode(std::string &countryCode) override; /** - * @Description Client register callback event + * @Description Register callback function. * - * @param name - client's name, which is a unique identifier - * @param callback - client object + * @param callback - IWifiDeviceCallBack object * @return ErrCode - operation result */ - ErrCode RegisterCallBackClient(const std::string &name, const sptr &callback) override; + ErrCode RegisterCallBack(const sptr &callback) override; /** * @Description Get the Signal Level object @@ -226,6 +225,14 @@ public: */ ErrCode CancelWps(void); + /** + * @Description Get the device MAC address. + * + * @param result - Get device mac String + * @return ErrCode - operation result + */ + ErrCode GetDeviceMacAddress(std::string &result) override; + private: int systemAbilityId_; sptr client_; diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_proxy.cpp b/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_proxy.cpp index 95ca3b4c8..87e0d2689 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_proxy.cpp +++ b/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_proxy.cpp @@ -50,19 +50,14 @@ ErrCode WifiDeviceProxy::EnableWifi() int error = Remote()->SendRequest(WIFI_SVR_CMD_ENABLE_WIFI, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_ENABLE_WIFI, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; } - int ret = reply.ReadInt32(); - if (ret != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } - - return WIFI_OPT_SUCCESS; + return ErrCode(reply.ReadInt32()); } ErrCode WifiDeviceProxy::DisableWifi() @@ -78,18 +73,13 @@ ErrCode WifiDeviceProxy::DisableWifi() int error = Remote()->SendRequest(WIFI_SVR_CMD_DISABLE_WIFI, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_DISABLE_WIFI, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; } - int ret = reply.ReadInt32(); - if (ret != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } - - return WIFI_OPT_SUCCESS; + return ErrCode(reply.ReadInt32()); } void WifiDeviceProxy::WriteIpAddress(MessageParcel &data, const WifiIpAddress &address) @@ -158,7 +148,7 @@ ErrCode WifiDeviceProxy::AddDeviceConfig(const WifiDeviceConfig &config, int &re int error = Remote()->SendRequest(WIFI_SVR_CMD_ADD_DEVICE_CONFIG, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_ADD_DEVICE_CONFIG, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { @@ -187,18 +177,13 @@ ErrCode WifiDeviceProxy::RemoveDevice(int networkId) int error = Remote()->SendRequest(WIFI_SVR_CMD_REMOVE_DEVICE_CONFIG, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_REMOVE_DEVICE_CONFIG, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; } - int ret = reply.ReadInt32(); - if (ret != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } - - return WIFI_OPT_SUCCESS; + return ErrCode(reply.ReadInt32()); } ErrCode WifiDeviceProxy::RemoveAllDevice() @@ -215,19 +200,14 @@ ErrCode WifiDeviceProxy::RemoveAllDevice() int error = Remote()->SendRequest(WIFI_SVR_CMD_REMOVE_ALL_DEVICE_CONFIG, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_REMOVE_ALL_DEVICE_CONFIG, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; } - int ret = reply.ReadInt32(); - if (ret != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } - - return WIFI_OPT_SUCCESS; + return ErrCode(reply.ReadInt32()); } void WifiDeviceProxy::ReadIpAddress(MessageParcel &reply, WifiIpAddress &address) @@ -302,7 +282,7 @@ ErrCode WifiDeviceProxy::GetDeviceConfigs(std::vector &result) int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_DEVICE_CONFIGS, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_DEVICE_CONFIGS, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { @@ -332,18 +312,13 @@ ErrCode WifiDeviceProxy::EnableDeviceConfig(int networkId, bool attemptEnable) int error = Remote()->SendRequest(WIFI_SVR_CMD_ENABLE_DEVICE, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_ENABLE_DEVICE, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; } - int ret = reply.ReadInt32(); - if (ret != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } - - return WIFI_OPT_SUCCESS; + return ErrCode(reply.ReadInt32()); } ErrCode WifiDeviceProxy::DisableDeviceConfig(int networkId) @@ -360,18 +335,13 @@ ErrCode WifiDeviceProxy::DisableDeviceConfig(int networkId) int error = Remote()->SendRequest(WIFI_SVR_CMD_DISABLE_DEVICE, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_DISABLE_DEVICE, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; } - int ret = reply.ReadInt32(); - if (ret != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } - - return WIFI_OPT_SUCCESS; + return ErrCode(reply.ReadInt32()); } ErrCode WifiDeviceProxy::ConnectToNetwork(int networkId) @@ -388,18 +358,13 @@ ErrCode WifiDeviceProxy::ConnectToNetwork(int networkId) int error = Remote()->SendRequest(WIFI_SVR_CMD_CONNECT_TO, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_CONNECT_TO, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; } - int ret = reply.ReadInt32(); - if (ret != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } - - return WIFI_OPT_SUCCESS; + return ErrCode(reply.ReadInt32()); } ErrCode WifiDeviceProxy::ConnectToDevice(const WifiDeviceConfig &config) @@ -416,18 +381,13 @@ ErrCode WifiDeviceProxy::ConnectToDevice(const WifiDeviceConfig &config) int error = Remote()->SendRequest(WIFI_SVR_CMD_CONNECT2_TO, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_CONNECT2_TO, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; } - int ret = reply.ReadInt32(); - if (ret != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } - - return WIFI_OPT_SUCCESS; + return ErrCode(reply.ReadInt32()); } ErrCode WifiDeviceProxy::ReConnect() @@ -443,18 +403,13 @@ ErrCode WifiDeviceProxy::ReConnect() int error = Remote()->SendRequest(WIFI_SVR_CMD_RECONNECT, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_RECONNECT, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; } - int ret = reply.ReadInt32(); - if (ret != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } - - return WIFI_OPT_SUCCESS; + return ErrCode(reply.ReadInt32()); } ErrCode WifiDeviceProxy::ReAssociate(void) @@ -470,18 +425,13 @@ ErrCode WifiDeviceProxy::ReAssociate(void) int error = Remote()->SendRequest(WIFI_SVR_CMD_REASSOCIATE, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_REASSOCIATE, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; } - int ret = reply.ReadInt32(); - if (ret != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } - - return WIFI_OPT_SUCCESS; + return ErrCode(reply.ReadInt32()); } ErrCode WifiDeviceProxy::Disconnect(void) @@ -497,18 +447,13 @@ ErrCode WifiDeviceProxy::Disconnect(void) int error = Remote()->SendRequest(WIFI_SVR_CMD_DISCONNECT, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_DISCONNECT, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; } - int ret = reply.ReadInt32(); - if (ret != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } - - return WIFI_OPT_SUCCESS; + return ErrCode(reply.ReadInt32()); } ErrCode WifiDeviceProxy::StartWps(const WpsConfig &config) @@ -527,18 +472,13 @@ ErrCode WifiDeviceProxy::StartWps(const WpsConfig &config) int error = Remote()->SendRequest(WIFI_SVR_CMD_START_WPS, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_START_WPS, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; } - int ret = reply.ReadInt32(); - if (ret != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } - - return WIFI_OPT_SUCCESS; + return ErrCode(reply.ReadInt32()); } ErrCode WifiDeviceProxy::CancelWps(void) @@ -554,18 +494,13 @@ ErrCode WifiDeviceProxy::CancelWps(void) int error = Remote()->SendRequest(WIFI_SVR_CMD_CANCEL_WPS, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_CANCEL_WPS, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; } - int ret = reply.ReadInt32(); - if (ret != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } - - return WIFI_OPT_SUCCESS; + return ErrCode(reply.ReadInt32()); } ErrCode WifiDeviceProxy::IsWifiActive(bool &bActive) @@ -581,7 +516,7 @@ ErrCode WifiDeviceProxy::IsWifiActive(bool &bActive) int error = Remote()->SendRequest(WIFI_SVR_CMD_IS_WIFI_ACTIVE, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_IS_WIFI_ACTIVE, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { @@ -609,7 +544,7 @@ ErrCode WifiDeviceProxy::GetWifiState(int &state) int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_WIFI_STATE, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_WIFI_STATE, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { @@ -675,7 +610,7 @@ ErrCode WifiDeviceProxy::GetLinkedInfo(WifiLinkedInfo &info) int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_LINKED_INFO, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_LINKED_INFO, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); @@ -704,7 +639,7 @@ ErrCode WifiDeviceProxy::GetIpInfo(IpInfo &info) int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_DHCP_INFO, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_DHCP_INFO, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { @@ -739,18 +674,13 @@ ErrCode WifiDeviceProxy::SetCountryCode(const std::string &countryCode) int error = Remote()->SendRequest(WIFI_SVR_CMD_SET_COUNTRY_CODE, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_SET_COUNTRY_CODE, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; } - int ret = reply.ReadInt32(); - if (ret != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } - - return WIFI_OPT_SUCCESS; + return ErrCode(reply.ReadInt32()); } ErrCode WifiDeviceProxy::GetCountryCode(std::string &countryCode) @@ -765,7 +695,7 @@ ErrCode WifiDeviceProxy::GetCountryCode(std::string &countryCode) int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_COUNTRY_CODE, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_COUNTRY_CODE, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { @@ -780,7 +710,7 @@ ErrCode WifiDeviceProxy::GetCountryCode(std::string &countryCode) return WIFI_OPT_SUCCESS; } -ErrCode WifiDeviceProxy::RegisterCallBackClient(const std::string &name, const sptr &callback) +ErrCode WifiDeviceProxy::RegisterCallBack(const sptr &callback) { if (mRemoteDied) { WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); @@ -789,7 +719,6 @@ ErrCode WifiDeviceProxy::RegisterCallBackClient(const std::string &name, const s MessageParcel data, reply; MessageOption option(MessageOption::TF_ASYNC); data.WriteInt32(0); - data.WriteCString(name.c_str()); g_deviceCallBackStub->RegisterUserCallBack(callback); @@ -801,18 +730,13 @@ ErrCode WifiDeviceProxy::RegisterCallBackClient(const std::string &name, const s int error = Remote()->SendRequest(WIFI_SVR_CMD_REGISTER_CALLBACK_CLIENT, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed, code is %{public}d", WIFI_SVR_CMD_REGISTER_CALLBACK_CLIENT, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; } - int ret = reply.ReadInt32(); - if (ret != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } - - return WIFI_OPT_SUCCESS; + return ErrCode(reply.ReadInt32()); } ErrCode WifiDeviceProxy::GetSignalLevel(const int &rssi, const int &band, int &level) @@ -830,7 +754,7 @@ ErrCode WifiDeviceProxy::GetSignalLevel(const int &rssi, const int &band, int &l int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_SIGNAL_LEVEL, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_SIGNAL_LEVEL, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { @@ -857,7 +781,7 @@ ErrCode WifiDeviceProxy::GetSupportedFeatures(long &features) int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_SUPPORTED_FEATURES, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_SUPPORTED_FEATURES, error); - return ErrCode(error); + return WIFI_OPT_FAILED; } int exception = reply.ReadInt32(); if (exception) { @@ -872,7 +796,36 @@ ErrCode WifiDeviceProxy::GetSupportedFeatures(long &features) return WIFI_OPT_SUCCESS; } -void WifiDeviceProxy::OnRemoteDied(const wptr& remoteObject) +ErrCode WifiDeviceProxy::GetDeviceMacAddress(std::string &result) +{ + if (mRemoteDied) { + WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data; + MessageParcel reply; + data.WriteInt32(0); + + int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_DERVICE_MAC_ADD, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed", WIFI_SVR_CMD_GET_DERVICE_MAC_ADD); + return WIFI_OPT_FAILED; + } + + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + int ret = reply.ReadInt32(); + if (ErrCode(ret) != WIFI_OPT_SUCCESS) { + return ErrCode(ret); + } + result = reply.ReadCString(); + return WIFI_OPT_SUCCESS; +} + +void WifiDeviceProxy::OnRemoteDied(const wptr &remoteObject) { WIFI_LOGD("Remote service is died!"); mRemoteDied = true; diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_proxy.h b/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_proxy.h index 7aaadff0c..b27c3dea0 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_proxy.h +++ b/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_proxy.h @@ -191,13 +191,12 @@ public: ErrCode GetCountryCode(std::string &countryCode) override; /** - * @Description Client register callback event + * @Description Register callback function. * - * @param name - client's name, which is a unique identifier - * @param callback - client object + * @param callback - IWifiDeviceCallBack object * @return ErrCode - operation result */ - ErrCode RegisterCallBackClient(const std::string &name, const sptr &callback) override; + ErrCode RegisterCallBack(const sptr &callback) override; /** * @Description Get the Signal Level object @@ -217,6 +216,14 @@ public: */ ErrCode GetSupportedFeatures(long &features) override; + /** + * @Description Get the device MAC address + * + * @param result - Get device mac String + * @return ErrCode - operation result + */ + ErrCode GetDeviceMacAddress(std::string &result) override; + void OnRemoteDied(const wptr &remoteObject) override; private: diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_callback_stub.cpp b/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_callback_stub.cpp index 05297074a..1de0a6eca 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_callback_stub.cpp +++ b/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_callback_stub.cpp @@ -74,9 +74,9 @@ int WifiHotspotCallbackStub::RemoteOnHotspotStaJoin(uint32_t code, MessageParcel { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); StationInfo info; - info.deviceName = Str16ToStr8(data.ReadString16()); - info.bssid = Str16ToStr8(data.ReadString16()); - info.ipAddr = Str16ToStr8(data.ReadString16()); + info.deviceName = data.ReadCString(); + info.bssid = data.ReadCString(); + info.ipAddr = data.ReadCString(); OnHotspotStaJoin(info); reply.WriteInt32(0); return 0; @@ -86,9 +86,9 @@ int WifiHotspotCallbackStub::RemoteOnHotspotStaLeave(uint32_t code, MessageParce { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); StationInfo info; - info.deviceName = Str16ToStr8(data.ReadString16()); - info.bssid = Str16ToStr8(data.ReadString16()); - info.ipAddr = Str16ToStr8(data.ReadString16()); + info.deviceName = data.ReadCString(); + info.bssid = data.ReadCString(); + info.ipAddr = data.ReadCString(); OnHotspotStaLeave(info); reply.WriteInt32(0); return 0; diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_proxy.cpp b/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_proxy.cpp index 3f5726f0b..ca24f854f 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_proxy.cpp +++ b/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_proxy.cpp @@ -56,14 +56,13 @@ ErrCode WifiHotspotProxy::IsHotspotActive(bool &bActive) int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; - } else { - int ret = reply.ReadInt32(); - if (ErrCode(ret) != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } - bActive = ((reply.ReadInt32() == 1) ? true : false); - return WIFI_OPT_SUCCESS; } + int ret = reply.ReadInt32(); + if (ErrCode(ret) != WIFI_OPT_SUCCESS) { + return ErrCode(ret); + } + bActive = ((reply.ReadInt32() == 1) ? true : false); + return WIFI_OPT_SUCCESS; } ErrCode WifiHotspotProxy::GetHotspotState(int &state) @@ -85,14 +84,13 @@ ErrCode WifiHotspotProxy::GetHotspotState(int &state) int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; - } else { - int ret = reply.ReadInt32(); - if (ErrCode(ret) != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } - state = reply.ReadInt32(); - return WIFI_OPT_SUCCESS; } + int ret = reply.ReadInt32(); + if (ErrCode(ret) != WIFI_OPT_SUCCESS) { + return ErrCode(ret); + } + state = reply.ReadInt32(); + return WIFI_OPT_SUCCESS; } ErrCode WifiHotspotProxy::GetHotspotConfig(HotspotConfig &result) @@ -114,21 +112,20 @@ ErrCode WifiHotspotProxy::GetHotspotConfig(HotspotConfig &result) int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; - } else { - int ret = reply.ReadInt32(); - if (ErrCode(ret) != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } + } + int ret = reply.ReadInt32(); + if (ErrCode(ret) != WIFI_OPT_SUCCESS) { + return ErrCode(ret); + } - result.SetSsid(reply.ReadCString()); - result.SetSecurityType(static_cast(reply.ReadInt32())); - result.SetBand(static_cast(reply.ReadInt32())); - result.SetChannel(reply.ReadInt32()); - result.SetPreSharedKey(reply.ReadCString()); - result.SetMaxConn(reply.ReadInt32()); + result.SetSsid(reply.ReadCString()); + result.SetSecurityType(static_cast(reply.ReadInt32())); + result.SetBand(static_cast(reply.ReadInt32())); + result.SetChannel(reply.ReadInt32()); + result.SetPreSharedKey(reply.ReadCString()); + result.SetMaxConn(reply.ReadInt32()); - return WIFI_OPT_SUCCESS; - } + return WIFI_OPT_SUCCESS; } ErrCode WifiHotspotProxy::SetHotspotConfig(const HotspotConfig &config) @@ -156,38 +153,8 @@ ErrCode WifiHotspotProxy::SetHotspotConfig(const HotspotConfig &config) int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; - } else { - return ErrCode(reply.ReadInt32()); - } -} - -ErrCode WifiHotspotProxy::GetDeviceMacAddress(std::string &result) -{ - if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); - return WIFI_OPT_FAILED; - } - MessageOption option; - MessageParcel data; - MessageParcel reply; - data.WriteInt32(0); - int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_DERVICE_MAC_ADD, data, reply, option); - if (error != ERR_NONE) { - WIFI_LOGE("Set Attr(%{public}d) failed", WIFI_SVR_CMD_GET_DERVICE_MAC_ADD); - return WIFI_OPT_FAILED; - } - - int exception = reply.ReadInt32(); - if (exception) { - return WIFI_OPT_FAILED; - } else { - int ret = reply.ReadInt32(); - if (ErrCode(ret) != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } - result = reply.ReadCString(); - return WIFI_OPT_SUCCESS; } + return ErrCode(reply.ReadInt32()); } ErrCode WifiHotspotProxy::GetStationList(std::vector &result) @@ -209,22 +176,21 @@ ErrCode WifiHotspotProxy::GetStationList(std::vector &result) int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; - } else { - int ret = reply.ReadInt32(); - if (ErrCode(ret) != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } - int size = reply.ReadInt32(); - for (int i = 0; i < size; i++) { - StationInfo info; - info.deviceName = reply.ReadCString(); - info.bssid = reply.ReadCString(); - info.ipAddr = reply.ReadCString(); - result.emplace_back(info); - } - - return WIFI_OPT_SUCCESS; } + int ret = reply.ReadInt32(); + if (ErrCode(ret) != WIFI_OPT_SUCCESS) { + return ErrCode(ret); + } + int size = reply.ReadInt32(); + for (int i = 0; i < size; i++) { + StationInfo info; + info.deviceName = reply.ReadCString(); + info.bssid = reply.ReadCString(); + info.ipAddr = reply.ReadCString(); + result.emplace_back(info); + } + + return WIFI_OPT_SUCCESS; } ErrCode WifiHotspotProxy::DisassociateSta(const StationInfo &info) @@ -249,9 +215,8 @@ ErrCode WifiHotspotProxy::DisassociateSta(const StationInfo &info) int exception = reply.ReadInt32(); if (exception) { return ErrCode(exception); - } else { - return ErrCode(reply.ReadInt32()); } + return ErrCode(reply.ReadInt32()); } ErrCode WifiHotspotProxy::EnableHotspot(void) @@ -269,9 +234,8 @@ ErrCode WifiHotspotProxy::EnableHotspot(void) int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; - } else { - return ErrCode(reply.ReadInt32()); } + return ErrCode(reply.ReadInt32()); } ErrCode WifiHotspotProxy::DisableHotspot(void) @@ -293,9 +257,8 @@ ErrCode WifiHotspotProxy::DisableHotspot(void) int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; - } else { - return ErrCode(reply.ReadInt32()); } + return ErrCode(reply.ReadInt32()); } ErrCode WifiHotspotProxy::GetBlockLists(std::vector &infos) @@ -355,9 +318,8 @@ ErrCode WifiHotspotProxy::AddBlockList(const StationInfo &info) int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; - } else { - return ErrCode(reply.ReadInt32()); } + return ErrCode(reply.ReadInt32()); } ErrCode WifiHotspotProxy::DelBlockList(const StationInfo &info) @@ -382,9 +344,8 @@ ErrCode WifiHotspotProxy::DelBlockList(const StationInfo &info) int exception = reply.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; - } else { - return ErrCode(reply.ReadInt32()); } + return ErrCode(reply.ReadInt32()); } ErrCode WifiHotspotProxy::GetValidBands(std::vector &bands) @@ -476,11 +437,7 @@ ErrCode WifiHotspotProxy::RegisterCallBack(const sptr &cal return WIFI_OPT_FAILED; } int ret = reply.ReadInt32(); - if (ret != WIFI_OPT_SUCCESS) { - return ErrCode(ret); - } - - return WIFI_OPT_SUCCESS; + return ErrCode(ret); } ErrCode WifiHotspotProxy::GetSupportedFeatures(long &features) diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_proxy.h b/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_proxy.h index 84f9f2666..573b5535e 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_proxy.h +++ b/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_proxy.h @@ -61,14 +61,6 @@ public: */ ErrCode SetHotspotConfig(const HotspotConfig &config) override; - /** - * @Description Get the device MAC address - * - * @param result - Get device mac String - * @return ErrCode - operation result - */ - ErrCode GetDeviceMacAddress(std::string &result) override; - /** * @Description Get the Station List object * diff --git a/services/wifi_standard/ipc_framework/cRPC/include/client.h b/services/wifi_standard/ipc_framework/cRPC/include/client.h index 3722a30e2..0cf659719 100644 --- a/services/wifi_standard/ipc_framework/cRPC/include/client.h +++ b/services/wifi_standard/ipc_framework/cRPC/include/client.h @@ -44,7 +44,6 @@ struct RpcClient { pthread_t threadId; int waitReply; pthread_mutex_t mutex; - pthread_cond_t condN; pthread_cond_t condW; int callLockFlag; pthread_mutex_t lockMutex; diff --git a/services/wifi_standard/ipc_framework/cRPC/include/evloop.h b/services/wifi_standard/ipc_framework/cRPC/include/evloop.h index 430d8a74f..0e60caba6 100644 --- a/services/wifi_standard/ipc_framework/cRPC/include/evloop.h +++ b/services/wifi_standard/ipc_framework/cRPC/include/evloop.h @@ -22,8 +22,8 @@ extern "C" { #endif -typedef struct FdEvent FdEvent; -struct FdEvent { +typedef struct FdMask FdMask; +struct FdMask { int fd; unsigned int mask; }; @@ -32,10 +32,10 @@ typedef struct EventLoop EventLoop; struct EventLoop { int maxFd; int setSize; - FdEvent *events; + FdMask *fdMasks; int stop; int epfd; - struct epoll_event *epoll_events; + struct epoll_event *epEvents; }; /** diff --git a/services/wifi_standard/ipc_framework/cRPC/include/net.h b/services/wifi_standard/ipc_framework/cRPC/include/net.h index 7417cbab3..1cf69659a 100644 --- a/services/wifi_standard/ipc_framework/cRPC/include/net.h +++ b/services/wifi_standard/ipc_framework/cRPC/include/net.h @@ -16,6 +16,8 @@ #ifndef CRPC_NET_H #define CRPC_NET_H +#include "common.h" + #ifdef __cplusplus extern "C" { #endif diff --git a/services/wifi_standard/ipc_framework/cRPC/include/server.h b/services/wifi_standard/ipc_framework/cRPC/include/server.h index 392378253..c47f4dede 100644 --- a/services/wifi_standard/ipc_framework/cRPC/include/server.h +++ b/services/wifi_standard/ipc_framework/cRPC/include/server.h @@ -119,7 +119,7 @@ int OnTransact(RpcServer *server, Context *context); * @param context - Message context * @return int - 0 success; -1 failed */ -int OnCallbackTransact(RpcServer *server, int event, Context *context); +int OnCallbackTransact(const RpcServer *server, int event, Context *context); /** * @Description End processing callback events, This function must be implemented by users @@ -129,7 +129,7 @@ int OnCallbackTransact(RpcServer *server, int event, Context *context); * @param event - Event type * @return int - 0 Success; -1 Failed */ -int EndCallbackTransact(RpcServer *server, int event); +int EndCallbackTransact(const RpcServer *server, int event); #ifdef __cplusplus } diff --git a/services/wifi_standard/ipc_framework/cRPC/src/client.c b/services/wifi_standard/ipc_framework/cRPC/src/client.c index 6a1e80174..848d0279c 100644 --- a/services/wifi_standard/ipc_framework/cRPC/src/client.c +++ b/services/wifi_standard/ipc_framework/cRPC/src/client.c @@ -18,15 +18,13 @@ #include "log.h" #undef LOG_TAG -#define LOG_TAG "OHOS_WIFI_RPC_CLIENT" +#define LOG_TAG "WifiRpcClient" const int FD_CHECK_TIMEOUT = 1000; /* poll wait time, units: ms */ -const int REMOTE_CALL_TIMEOUT = 5; /* remote call timeout, units: second */ const int CLIENT_STATE_IDLE = 0; const int CLIENT_STATE_DEAL_REPLY = 1; -const int CLIENT_STATE_DEAL_CALLBACK = 2; +const int CLIENT_STATE_EXIT = 2; const int TMP_BUFF_SIZE = 16; -const int US_1000 = 1000; static void *RpcClientThreadDeal(void *arg); @@ -48,6 +46,7 @@ static char *RpcClientReadMsg(RpcClient *client) } ret = ContextReadNet(client->context); if (ret < 0) { + LOGE("read server reply message failed!"); client->threadRunFlag = 0; return NULL; } @@ -74,31 +73,23 @@ static void RpcClientDealReadMsg(RpcClient *client, char *buff) } if (strncmp(buff, szTmp, strlen(szTmp)) == 0) { /* deal reply message */ pthread_mutex_lock(&client->mutex); - while (client->waitReply) { - pthread_cond_wait(&client->condW, &client->mutex); - } client->waitReply = CLIENT_STATE_DEAL_REPLY; client->context->oneProcess = buff; client->context->nPos = strlen(szTmp); client->context->nSize = strlen(buff); - pthread_cond_signal(&client->condN); + pthread_cond_signal(&client->condW); pthread_mutex_unlock(&client->mutex); } else { /* deal callback message */ pthread_mutex_lock(&client->mutex); - while (client->waitReply) { + while (client->waitReply == CLIENT_STATE_DEAL_REPLY) { pthread_cond_wait(&client->condW, &client->mutex); } - client->waitReply = CLIENT_STATE_DEAL_CALLBACK; + pthread_mutex_unlock(&client->mutex); client->context->oneProcess = buff; client->context->nPos = strlen(szTmp); client->context->nSize = strlen(buff); - pthread_mutex_unlock(&client->mutex); OnTransact(client->context); - pthread_mutex_lock(&client->mutex); free(buff); - client->waitReply = CLIENT_STATE_IDLE; - pthread_cond_signal(&client->condW); - pthread_mutex_unlock(&client->mutex); } return; } @@ -117,6 +108,11 @@ static void *RpcClientThreadDeal(void *arg) } RpcClientDealReadMsg(client, buff); } + pthread_mutex_lock(&client->mutex); + client->waitReply = CLIENT_STATE_EXIT; + pthread_cond_signal(&client->condW); + pthread_mutex_unlock(&client->mutex); + LOGI("Client read message thread exiting!"); return NULL; } @@ -144,13 +140,11 @@ RpcClient *CreateRpcClient(const char *path) client->waitReply = CLIENT_STATE_IDLE; client->callLockFlag = 0; pthread_mutex_init(&client->mutex, NULL); - pthread_cond_init(&client->condN, NULL); pthread_cond_init(&client->condW, NULL); pthread_mutex_init(&client->lockMutex, NULL); pthread_cond_init(&client->lockCond, NULL); int ret = pthread_create(&client->threadId, NULL, RpcClientThreadDeal, client); if (ret) { - pthread_cond_destroy(&client->condN); pthread_cond_destroy(&client->condW); pthread_mutex_destroy(&client->mutex); pthread_cond_destroy(&client->lockCond); @@ -171,7 +165,6 @@ void ReleaseRpcClient(RpcClient *client) client->threadRunFlag = 0; pthread_join(client->threadId, NULL); } - pthread_cond_destroy(&client->condN); pthread_cond_destroy(&client->condW); pthread_mutex_destroy(&client->mutex); pthread_cond_destroy(&client->lockCond); @@ -188,7 +181,9 @@ int RemoteCall(RpcClient *client) if (client == NULL) { return -1; } - + if (client->waitReply == CLIENT_STATE_EXIT) { + return -1; + } int ret = 0; Context *context = client->context; while (context->wBegin != context->wEnd && ret >= 0) { @@ -199,19 +194,14 @@ int RemoteCall(RpcClient *client) } ret = 0; /* reset ret value */ pthread_mutex_lock(&client->mutex); - struct timeval now; - struct timespec outtime; - gettimeofday(&now, NULL); - outtime.tv_sec = now.tv_sec + REMOTE_CALL_TIMEOUT; - outtime.tv_nsec = now.tv_usec * US_1000; - while (client->waitReply != CLIENT_STATE_DEAL_REPLY) { - ret = pthread_cond_timedwait(&client->condN, &client->mutex, &outtime); - if (ret != 0) { - break; - } + while (client->waitReply != CLIENT_STATE_DEAL_REPLY && client->waitReply != CLIENT_STATE_EXIT) { + pthread_cond_wait(&client->condW, &client->mutex); + } + if (client->waitReply == CLIENT_STATE_EXIT) { + ret = -1; } pthread_mutex_unlock(&client->mutex); - return ((ret == 0) ? 0 : -1); + return ret; } void ReadClientEnd(RpcClient *client) @@ -223,7 +213,9 @@ void ReadClientEnd(RpcClient *client) pthread_mutex_lock(&client->mutex); free(client->context->oneProcess); client->context->oneProcess = NULL; - client->waitReply = CLIENT_STATE_IDLE; + if (client->waitReply == CLIENT_STATE_DEAL_REPLY) { + client->waitReply = CLIENT_STATE_IDLE; + } pthread_cond_signal(&client->condW); pthread_mutex_unlock(&client->mutex); return; diff --git a/services/wifi_standard/ipc_framework/cRPC/src/context.c b/services/wifi_standard/ipc_framework/cRPC/src/context.c index 0b307b900..35e3b2f62 100644 --- a/services/wifi_standard/ipc_framework/cRPC/src/context.c +++ b/services/wifi_standard/ipc_framework/cRPC/src/context.c @@ -266,30 +266,27 @@ int ContextWriteNet(Context *context) if (context->wBegin == context->wEnd) { return 0; - } else if (context->wBegin < context->wEnd) { + } + if (context->wBegin < context->wEnd) { int ret = MyWrite(context->fd, context->szWrite + context->wBegin, context->wEnd - context->wBegin); if (ret > 0) { context->wBegin += ret; } return ret; - } else { - int len = context->wCapacity - context->wBegin; - int ret = MyWrite(context->fd, context->szWrite + context->wBegin, len); - if (ret < 0) { - return ret; - } else if (ret < len) { - context->wBegin += ret; - return ret; - } else { - context->wBegin = 0; - ret = MyWrite(context->fd, context->szWrite, context->wEnd); - if (ret < 0) { - return ret; - } else { - context->wBegin = ret; - return ret; - } - } } - return 0; + int len = context->wCapacity - context->wBegin; + int ret = MyWrite(context->fd, context->szWrite + context->wBegin, len); + if (ret < 0) { + return ret; + } + if (ret < len) { + context->wBegin += ret; + return ret; + } + context->wBegin = 0; + ret = MyWrite(context->fd, context->szWrite, context->wEnd); + if (ret > 0) { + context->wBegin = ret; + } + return ret; } diff --git a/services/wifi_standard/ipc_framework/cRPC/src/evloop.c b/services/wifi_standard/ipc_framework/cRPC/src/evloop.c index 7cf024d01..b32619484 100644 --- a/services/wifi_standard/ipc_framework/cRPC/src/evloop.c +++ b/services/wifi_standard/ipc_framework/cRPC/src/evloop.c @@ -17,7 +17,7 @@ #include "log.h" #undef LOG_TAG -#define LOG_TAG "OHOS_WIFI_RPC_EVLOOP" +#define LOG_TAG "WifiRpcEventLoop" const int ELOOP_MAX_FD_SIZE = 1024; @@ -38,9 +38,9 @@ EventLoop *CreateEventLoop(int size) free(evLoop); return NULL; } - evLoop->events = (FdEvent *)calloc(size, sizeof(FdEvent)); - evLoop->epoll_events = (struct epoll_event *)calloc(size, sizeof(struct epoll_event)); - if (evLoop->events == NULL || evLoop->epoll_events == NULL) { + evLoop->fdMasks = (FdMask *)calloc(size, sizeof(FdMask)); + evLoop->epEvents = (struct epoll_event *)calloc(size, sizeof(struct epoll_event)); + if (evLoop->fdMasks == NULL || evLoop->epEvents == NULL) { flag = 1; /* fail */ LOGE("Failed to calloc events or epoll_event struct!"); break; @@ -55,11 +55,11 @@ EventLoop *CreateEventLoop(int size) if (flag == 0) { return evLoop; } - if (evLoop->events != NULL) { - free(evLoop->events); + if (evLoop->fdMasks != NULL) { + free(evLoop->fdMasks); } - if (evLoop->epoll_events != NULL) { - free(evLoop->epoll_events); + if (evLoop->epEvents != NULL) { + free(evLoop->epEvents); } free(evLoop); return NULL; @@ -74,11 +74,11 @@ void DestroyEventLoop(EventLoop *loop) if (loop->epfd != -1) { close(loop->epfd); } - if (loop->events != NULL) { - free(loop->events); + if (loop->fdMasks != NULL) { + free(loop->fdMasks); } - if (loop->epoll_events != NULL) { - free(loop->epoll_events); + if (loop->epEvents != NULL) { + free(loop->epEvents); } free(loop); return; @@ -103,11 +103,11 @@ int AddFdEvent(EventLoop *loop, int fd, unsigned int addMask) if (fd >= loop->setSize) { return -1; } - if (loop->events[fd].mask & addMask) { + if (loop->fdMasks[fd].mask & addMask) { return 0; } - int op = (loop->events[fd].mask == NONE_EVENT) ? EPOLL_CTL_ADD : EPOLL_CTL_MOD; - addMask |= loop->events[fd].mask; + int op = (loop->fdMasks[fd].mask == NONE_EVENT) ? EPOLL_CTL_ADD : EPOLL_CTL_MOD; + addMask |= loop->fdMasks[fd].mask; struct epoll_event pollEvent = {0}; if (addMask & READ_EVENT) { pollEvent.events |= EPOLLIN; @@ -119,8 +119,8 @@ int AddFdEvent(EventLoop *loop, int fd, unsigned int addMask) if (epoll_ctl(loop->epfd, op, fd, &pollEvent) == -1) { return -1; } - loop->events[fd].fd = fd; - loop->events[fd].mask |= addMask; + loop->fdMasks[fd].fd = fd; + loop->fdMasks[fd].mask |= addMask; if (fd > loop->maxFd) { loop->maxFd = fd; } @@ -136,13 +136,13 @@ int DelFdEvent(EventLoop *loop, int fd, unsigned int delMask) if (fd >= loop->setSize) { return 0; } - if (loop->events[fd].mask == NONE_EVENT) { + if (loop->fdMasks[fd].mask == NONE_EVENT) { return 0; } - if ((loop->events[fd].mask & delMask) == 0) { + if ((loop->fdMasks[fd].mask & delMask) == 0) { return 0; } - unsigned int mask = loop->events[fd].mask & (~delMask); + unsigned int mask = loop->fdMasks[fd].mask & (~delMask); struct epoll_event pollEvent = {0}; pollEvent.events = 0; if (mask & READ_EVENT) { @@ -156,11 +156,11 @@ int DelFdEvent(EventLoop *loop, int fd, unsigned int delMask) if (epoll_ctl(loop->epfd, op, fd, &pollEvent) == -1) { return -1; } - loop->events[fd].mask &= ~delMask; - if (fd == loop->maxFd && loop->events[fd].mask == NONE_EVENT) { + loop->fdMasks[fd].mask &= ~delMask; + if (fd == loop->maxFd && loop->fdMasks[fd].mask == NONE_EVENT) { int j = loop->maxFd - 1; for (; j >= 0; --j) { - if (loop->events[j].mask != NONE_EVENT) { + if (loop->fdMasks[j].mask != NONE_EVENT) { break; } } diff --git a/services/wifi_standard/ipc_framework/cRPC/src/hash_table.c b/services/wifi_standard/ipc_framework/cRPC/src/hash_table.c index b9a20664a..20db54869 100644 --- a/services/wifi_standard/ipc_framework/cRPC/src/hash_table.c +++ b/services/wifi_standard/ipc_framework/cRPC/src/hash_table.c @@ -17,7 +17,7 @@ #include "log.h" #undef LOG_TAG -#define LOG_TAG "OHWIFI_RPC_HASHTABLE" +#define LOG_TAG "WifiRpcHashTable" const int START_PRIME_NUM = 3; const int START_CALC_PRIME_NUM = 2; diff --git a/services/wifi_standard/ipc_framework/cRPC/src/net.c b/services/wifi_standard/ipc_framework/cRPC/src/net.c index a719d0468..1e059f69d 100644 --- a/services/wifi_standard/ipc_framework/cRPC/src/net.c +++ b/services/wifi_standard/ipc_framework/cRPC/src/net.c @@ -14,10 +14,8 @@ */ #include "net.h" #include "log.h" -#include "common.h" - #undef LOG_TAG -#define LOG_TAG "OHWIFI_RPC_NET" +#define LOG_TAG "WifiRpcNet" int SetNonBlock(int fd, int type) { @@ -50,7 +48,7 @@ int MyRead(int fd, char *buf, int count) if (errno == EWOULDBLOCK || errno == EINTR || errno == EAGAIN) { break; } else { - LOGE("read failed! error is %d", errno); + LOGE("read failed! error is %{public}d", errno); return SOCK_ERR; } } else { @@ -60,7 +58,7 @@ int MyRead(int fd, char *buf, int count) } buf[pos] = 0; #ifdef DEBUG - LOGD("read: %s", buf); + LOGD("read: %{private}s", buf); #endif return pos; } @@ -76,7 +74,7 @@ int MyWrite(int fd, const char *buf, int count) if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN) { break; } else { - LOGE("write failed! error is %d", errno); + LOGE("write failed! error is %{public}d", errno); return SOCK_ERR; } } @@ -85,7 +83,7 @@ int MyWrite(int fd, const char *buf, int count) char *szTmp = (char *)calloc(tmpSize, sizeof(char)); if (szTmp != NULL) { if (strncpy_s(szTmp, tmpSize, buf + pos, ret) == EOK) { - LOGD("write: %s", szTmp); + LOGD("write: %{private}s", szTmp); } free(szTmp); } @@ -134,6 +132,7 @@ int CreateUnixServer(const char *path, int backlog) close(sock); return -1; } + fcntl(sock, F_SETFD, FD_CLOEXEC); if (listen(sock, backlog) < 0) { LOGE("listen failed!"); close(sock); diff --git a/services/wifi_standard/ipc_framework/cRPC/src/serial.c b/services/wifi_standard/ipc_framework/cRPC/src/serial.c index 3bec7315f..b320d8ebb 100644 --- a/services/wifi_standard/ipc_framework/cRPC/src/serial.c +++ b/services/wifi_standard/ipc_framework/cRPC/src/serial.c @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#include #include "serial.h" const int TMP_CHAR_LEN = 64; @@ -89,7 +89,7 @@ int WriteInt64(Context *context, int64_t iData) } char szTmp[TMP_CHAR_LEN] = {0}; - if (snprintf_s(szTmp, sizeof(szTmp), sizeof(szTmp) - 1, "%lld%c", iData, context->cSplit) < 0) { + if (snprintf_s(szTmp, sizeof(szTmp), sizeof(szTmp) - 1, "%" PRIu64 "%c", iData, context->cSplit) < 0) { return -1; } return ContextAppendWrite(context, szTmp, strlen(szTmp)); diff --git a/services/wifi_standard/ipc_framework/cRPC/src/server.c b/services/wifi_standard/ipc_framework/cRPC/src/server.c index 58527e660..b30538e0b 100644 --- a/services/wifi_standard/ipc_framework/cRPC/src/server.c +++ b/services/wifi_standard/ipc_framework/cRPC/src/server.c @@ -16,7 +16,7 @@ #include "log.h" #undef LOG_TAG -#define LOG_TAG "OHWIFI_RPC_SERVER" +#define LOG_TAG "WifiRpcServer" const int DEFAULT_LISTEN_QUEUE_SIZE = 10; const int MAX_SUPPORT_CLIENT_FD_SIZE = 256; /* support max clients online */ @@ -40,6 +40,7 @@ static int OnAccept(RpcServer *server, unsigned int mask) return -1; } SetNonBlock(fd, 1); + fcntl(fd, F_SETFD, FD_CLOEXEC); Context *context = CreateContext(CONTEXT_BUFFER_MIN_SIZE); if (context != NULL) { context->fd = fd; @@ -93,19 +94,19 @@ RpcServer *CreateRpcServer(const char *path) static int DealReadMessage(RpcServer *server, Context *client) { if ((server == NULL) || (client == NULL)) { - return -1; + return 0; } char *buf = ContextGetReadRecord(client); - if (buf != NULL) { - client->oneProcess = buf; - client->nPos = SERIAL_DATA_HEAD_SIZE; /* N| */ - client->nSize = strlen(buf); - OnTransact(server, client); - free(buf); - AddFdEvent(server->loop, client->fd, WRIT_EVENT); - return 1; + if (buf == NULL) { + return 0; } - return 0; + client->oneProcess = buf; + client->nPos = SERIAL_DATA_HEAD_SIZE; /* N| */ + client->nSize = strlen(buf); + OnTransact(server, client); + free(buf); + AddFdEvent(server->loop, client->fd, WRIT_EVENT); + return 1; } static unsigned int CheckEventMask(const struct epoll_event *e) @@ -132,7 +133,6 @@ static void DealFdReadEvent(RpcServer *server, Context *client, unsigned int mas if ((server == NULL) || (client == NULL)) { return; } - DealReadMessage(server, client); int ret = ContextReadNet(client); if ((ret == SOCK_ERR) || ((ret == SOCK_CLOSE) && (mask & EXCP_EVENT))) { @@ -172,7 +172,7 @@ static void DealFdEvents(RpcServer *server, int fd, unsigned int mask) } Context *client = FindContext(server->clients, fd); if (client == NULL) { - LOGD("not find %d clients!", fd); + LOGD("not find %{public}d clients!", fd); return; } if (mask & READ_EVENT) { @@ -181,7 +181,7 @@ static void DealFdEvents(RpcServer *server, int fd, unsigned int mask) if (mask & WRIT_EVENT) { DealFdWriteEvent(server, client); } - if (server->loop->events[fd].mask == NONE_EVENT) { + if (server->loop->fdMasks[fd].mask == NONE_EVENT) { close(fd); DeleteHashTable(server->clients, client); RemoveCallback(server, client); @@ -199,9 +199,9 @@ int RunRpcLoop(RpcServer *server) EventLoop *loop = server->loop; while (!loop->stop) { BeforeLoop(server); - int retval = epoll_wait(loop->epfd, loop->epoll_events, loop->setSize, 1); /* wait 1ms */ + int retval = epoll_wait(loop->epfd, loop->epEvents, loop->setSize, 1); /* wait 1ms */ for (int i = 0; i < retval; ++i) { - struct epoll_event *e = loop->epoll_events + i; + struct epoll_event *e = loop->epEvents + i; int fd = e->data.fd; unsigned int mask = CheckEventMask(e); if (fd == server->listenFd) { @@ -237,8 +237,8 @@ static int BeforeLoop(RpcServer *server) return -1; } pthread_mutex_lock(&server->mutex); - for (int i = server->nEvents; i > 0; --i) { - int event = server->events[i - 1]; + for (int i = 0; i < server->nEvents; ++i) { + int event = server->events[i]; int num = sizeof(server->eventNode) / sizeof(server->eventNode[0]); int pos = event % num; struct Node *p = server->eventNode[pos].head; diff --git a/services/wifi_standard/wifi_framework/common/config/wifi_config_file_spec.cpp b/services/wifi_standard/wifi_framework/common/config/wifi_config_file_spec.cpp index 630aae8e9..32cbaf576 100644 --- a/services/wifi_standard/wifi_framework/common/config/wifi_config_file_spec.cpp +++ b/services/wifi_standard/wifi_framework/common/config/wifi_config_file_spec.cpp @@ -441,6 +441,7 @@ void ClearTClass(WifiConfig &item) { item.scanAlwaysSwitch = false; item.staAirplaneMode = false; + item.canOpenStaWhenAirplane = false; item.staLastState = false; item.savedDeviceAppraisalPriority = PRIORITY_1; item.scoretacticsScoreSlope = SCORE_SLOPE; @@ -478,6 +479,8 @@ static int SetWifiConfigValueFirst(WifiConfig &item, const std::string &key, con item.scanAlwaysSwitch = (std::stoi(value) != 0); /* 0 -> false 1 -> true */ } else if (key == "staAirplaneMode") { item.staAirplaneMode = (std::stoi(value) != 0); /* 0 -> false 1 -> true */ + } else if (key == "canOpenStaWhenAirplane") { + item.canOpenStaWhenAirplane = (std::stoi(value) != 0); } else if (key == "staLastState") { item.staLastState = (std::stoi(value) != 0); } else if (key == "savedDeviceAppraisalPriority") { @@ -562,6 +565,7 @@ std::string OutTClassString(WifiConfig &item) std::ostringstream ss; ss << "scanAlwaysSwitch=" << item.scanAlwaysSwitch << std::endl; /* bool false->0 true->1 */ ss << "staAirplaneMode=" << item.staAirplaneMode << std::endl; + ss << "canOpenStaWhenAirplane=" << item.canOpenStaWhenAirplane << std::endl; ss << "staLastState=" << item.staLastState << std::endl; ss << "savedDeviceAppraisalPriority=" << item.savedDeviceAppraisalPriority << std::endl; ss << "scoretacticsScoreSlope=" << item.scoretacticsScoreSlope << std::endl; diff --git a/services/wifi_standard/wifi_framework/common/config/wifi_settings.cpp b/services/wifi_standard/wifi_framework/common/config/wifi_settings.cpp index c06ab23af..d7b79ed88 100644 --- a/services/wifi_standard/wifi_framework/common/config/wifi_settings.cpp +++ b/services/wifi_standard/wifi_framework/common/config/wifi_settings.cpp @@ -137,7 +137,7 @@ int WifiSettings::GetScanInfoList(std::vector &results) int64_t curr = static_cast(clkTime.tv_sec) * MSEC * MSEC + clkTime.tv_nsec / MSEC; /* us */ std::unique_lock lock(mInfoMutex); for (auto iter = mWifiScanInfoList.begin(); iter != mWifiScanInfoList.end(); ++iter) { - if (iter->timestamp + WIFI_GET_SCAN_RESULT_VALID_TIMESTAMP * MSEC * MSEC < curr) { + if (iter->timestamp + WIFI_GET_SCAN_INFO_VALID_TIMESTAMP * MSEC * MSEC < curr) { continue; } results.push_back(*iter); @@ -230,6 +230,18 @@ int WifiSettings::GetDeviceConfig(const std::string &index, const int &indexType return -1; } +int WifiSettings::GetDeviceConfig(const std::string &ssid, const std::string &keymgmt, WifiDeviceConfig &config) +{ + std::unique_lock lock(mConfigMutex); + for (auto iter = mWifiDeviceConfig.begin(); iter != mWifiDeviceConfig.end(); iter++) { + if ((iter->second.ssid == ssid) && (iter->second.keyMgmt == keymgmt)) { + config = iter->second; + return 0; + } + } + return -1; +} + int WifiSettings::GetHiddenDeviceConfig(std::vector &results) { std::unique_lock lock(mConfigMutex); @@ -589,7 +601,7 @@ void WifiSettings::InitDefaultHotspotConfig() { mHotspotConfig.SetSecurityType(KeyMgmt::WPA_PSK); mHotspotConfig.SetBand(BandType::BAND_2GHZ); - mHotspotConfig.SetChannel(1); /* AP_CHANNEL_DEFAULT */ + mHotspotConfig.SetChannel(AP_CHANNEL_DEFAULT); mHotspotConfig.SetMaxConn(GetApMaxConnNum()); mHotspotConfig.SetSsid("OHOS_" + GetRandomStr(RANDOM_STR_LEN)); mHotspotConfig.SetPreSharedKey("12345678"); @@ -713,6 +725,11 @@ int WifiSettings::SetCanUseStaWhenAirplaneMode(bool bCan) return 0; } +bool WifiSettings::GetCanOpenStaWhenAirplaneMode() +{ + return mWifiConfig.canOpenStaWhenAirplane; +} + bool WifiSettings::GetStaLastRunState() { return mWifiConfig.staLastState; diff --git a/services/wifi_standard/wifi_framework/common/config/wifi_settings.h b/services/wifi_standard/wifi_framework/common/config/wifi_settings.h index ee6eb5b8b..990ef90b9 100644 --- a/services/wifi_standard/wifi_framework/common/config/wifi_settings.h +++ b/services/wifi_standard/wifi_framework/common/config/wifi_settings.h @@ -42,12 +42,12 @@ constexpr int MODE_ADD = 0; constexpr int MODE_DEL = 1; constexpr int MODE_UPDATE = 2; /* Obtain the scanning result that is valid within 180s. */ -constexpr int WIFI_GET_SCAN_RESULT_VALID_TIMESTAMP = 180; +constexpr int WIFI_GET_SCAN_INFO_VALID_TIMESTAMP = 180; -constexpr char DEVICE_CONFIG_FILE_PATH[] = "./device_config.conf"; -constexpr char HOTSPOT_CONFIG_FILE_PATH[] = "./hotspot_config.conf"; -constexpr char BLOCK_LIST_FILE_PATH[] = "./block_list.conf"; -constexpr char WIFI_CONFIG_FILE_PATH[] = "./wifi_config.conf"; +constexpr char DEVICE_CONFIG_FILE_PATH[] = "/data/misc/wifi/device_config.conf"; +constexpr char HOTSPOT_CONFIG_FILE_PATH[] = "/data/misc/wifi/hotspot_config.conf"; +constexpr char BLOCK_LIST_FILE_PATH[] = "/data/misc/wifi/block_list.conf"; +constexpr char WIFI_CONFIG_FILE_PATH[] = "/data/misc/wifi/wifi_config.conf"; namespace OHOS { namespace Wifi { @@ -191,6 +191,16 @@ public: */ int GetDeviceConfig(const std::string &index, const int &indexType, WifiDeviceConfig &config); + /** + * @Description Get the specify wifi device config which ssid is equal to input ssid and keymgmt is equal to input + * keymgmt + * + * @param ssid - ssid string + * @param keymgmt - keymgmt string + * @param config - output WifiDeviceConfig struct + * @return int - 0 success; -1 not find the device config + */ + int GetDeviceConfig(const std::string &ssid, const std::string &keymgmt, WifiDeviceConfig &config); /** * @Description Get the wifi device configs which hiddenSSID is true * @@ -484,6 +494,14 @@ public: */ int SetCanUseStaWhenAirplaneMode(bool bCan); + /** + * @Description Get the config whether can open sta when airplane mode opened + * + * @return true - can open + * @return false - can't open + */ + bool GetCanOpenStaWhenAirplaneMode(); + /** * @Description Get the STA service last running state * diff --git a/services/wifi_standard/wifi_framework/common/include/wifi_internal_msg.h b/services/wifi_standard/wifi_framework/common/include/wifi_internal_msg.h index 4eebcfe0c..b582f32a2 100755 --- a/services/wifi_standard/wifi_framework/common/include/wifi_internal_msg.h +++ b/services/wifi_standard/wifi_framework/common/include/wifi_internal_msg.h @@ -17,8 +17,6 @@ #define OHOS_WIFI_INTERNAL_MSG_H #include "wifi_msg.h" -#include "wifi_message_queue.h" -#include "refbase.h" namespace OHOS { namespace Wifi { @@ -43,77 +41,31 @@ namespace Wifi { #define RSSI_LEVEL_3_5G (-72) #define RSSI_LEVEL_4_5G (-65) -enum WifiInternalMsgCode { - MAIN_EXIT_CODE = -9999, /* special code, using when program exits. */ - - /* STA SERVICE MESSAGE CODE DEFINE, START WITH 1000 AND MUST LESS THEN 2000 */ - STA_START_MSG_CODE = 1000, /* IDENTIFY: START MSGCODE FOR STA SERVICE. PLEASE ADD NEW CODE FOR STA AFTER THIS ! */ - STA_OPEN_RES, - STA_CLOSE_RES, - STA_CONNECT_REQ, - STA_CONNECT_RES, - STA_RECONNECT_REQ, - STA_RECONNECT_RES, - STA_REASSOCIATE_REQ, - STA_REASSOCIATE_RES, - STA_DISCONNECT_REQ, - STA_DISCONNECT_RES, - STA_START_WPS_REQ, - STA_START_WPS_RES, - STA_CANCEL_WPS_REQ, - STA_CANCEL_WPS_RES, - STA_REMOVE_DEVICE_REQ, - STA_REMOVE_ALL_DEVICE_REQ, - STA_CONNECT_MANAGE_REQ, - STA_SET_COUNTRY_CODE, - STA_END_MSG_CODE, /* IDENTIFY: MAX MSGCODE FOR STA SERVICE . PLEASE ADD NEW CODE FOR STA BEFORE THIS ! */ - - /* AP SERVICE MESSAGE CODE DEFINE, START WITH 2000 AND MUST LESS THEN 3000 */ - AP_START_MSG_CODE = 2000, /* IDENTIFY: START MSGCODE FOR AP SERVICE . PLEASE ADD NEW CODE FOR AP AFTER THIS ! */ - AP_OPEN_RES, - AP_CLOSE_RES, - AP_JOIN_RES, - AP_LEAVE_RES, - AP_SET_HOTSPOT_CONFIG_REQ, - AP_ADD_BLOCK_LIST_REQ, - AP_DEL_BLOCK_LIST_REQ, - AP_DISCCONECT_STA_BY_MAC_REQ, - AP_END_MSG_CODE, /* IDENTIFY: MAX MSGCODE FOR AP SERVICE . PLEASE ADD NEW CODE FOR AP BEFORE THIS ! */ - - /* SCAN SERVICE MESSAGE CODE DEFINE, START WITH 3000 AND MUST LESS THEN 4000 */ - SCAN_START_MSG_CODE = - 3000, /* IDENTIFY: START MSGCODE FOR SCAN SERVICE. PLEASE ADD NEW CODE FOR SCAN AFTER THIS ! */ - SCAN_START_RES, - SCAN_STOP_RES, - SCAN_REQ, - SCAN_RES, - SCAN_PARAM_REQ, - SCAN_PARAM_RES, - SCAN_RECONNECT_REQ, - SCAN_RESULT_RES, - SCAN_NOTIFY_STA_CONN_REQ, - SCAN_END_MSG_CODE, /* IDENTIFY: MAX MSGCODE FOR SCAN SERVICE . PLEASE ADD NEW CODE FOR SCAN BEFORE THIS ! */ - SCAN_CONTROL_REQ, +enum class WifiOprMidState { CLOSED = 0, OPENING = 1, RUNNING = 2, CLOSING = 3, UNKNOWN }; - /* MOCK SYSTEM STATUS CHANGED MESSAGE CODE DEFINE, START WITH 4000 AND MUST LESS THEN 5000 */ - SCREEN_CHANGE_NOTICE = 4000, /* notify screen state */ - AIRPLANE_MODE_CHANGE_NOTICE = 4001, /* notify airplane state */ - APP_RUNNING_MODE_CHANGE_NOTICE = 4002, /* notify App running state */ - POWER_SAVING_MODE_CHANGE_NOTICE = 4003, /* notify power saving state */ - FRONT_BACK_STATUS_CHANGE_NOTICE = 4004, /* notify front/backend state */ - CUSTOM_STATUS_CHANGE_NOTICE = 4005, /* notify other custom state */ +enum class WifiFeatures { + WIFI_FEATURE_INFRA = 0x0001, // The feature id indicates support basic infrastructure mode + WIFI_FEATURE_INFRA_5G = 0x0002, // The feature id indicates support 5 GHz Band + WIFI_FEATURE_PASSPOINT = 0x0004, // The feature id indicates support GAS/ANQP + WIFI_FEATURE_P2P = 0x0008, // The feature id indicates support Wifi-Direct + WIFI_FEATURE_MOBILE_HOTSPOT = 0x0010, // The feature id indicates support Soft AP + WIFI_FEATURE_AWARE = 0x0040, // The feature id indicates support Wi-Fi AWare networking + WIFI_FEATURE_AP_STA = 0x8000, // The feature id indicates support AP STA Concurrency + WIFI_FEATURE_WPA3_SAE = 0x8000000, // The feature id indicates support WPA3-Personal SAE + WIFI_FEATURE_WPA3_SUITE_B = 0x10000000, // The feature id indicates support WPA3-Enterprise Suite-B + WIFI_FEATURE_OWE = 0x20000000, // The feature id indicates support Enhanced Open }; -enum class WifiOprMidState { CLOSED = 0, OPENING = 1, RUNNING = 2, CLOSING = 3, UNKNOWN }; - enum class OperateResState { - OPEN_WIFI_SUCCEED = 0, /* open wifi succeed */ + OPEN_WIFI_OPENING = 0, /* open wifi opening */ + OPEN_WIFI_SUCCEED, /* open wifi succeed */ OPEN_WIFI_FAILED, /* open wifi failed */ OPEN_WIFI_OVERRIDE_OPEN_FAILED, /* enable wifi repeatedly */ OPEN_WIFI_DISABLED, /* open wifi failed, set wifi disabled */ OPEN_WIFI_SUPPLICANT_INIT_FAILED, /* wpa_supplicant not inited or init failed */ OPEN_WIFI_OPEN_SUPPLICANT_FAILED, /* wpa_supplicant start failed */ OPEN_WIFI_CONN_SUPPLICANT_FAILED, /* connect wpa_supplicant failed */ + CLOSE_WIFI_CLOSING, /* close wifi closing */ CLOSE_WIFI_SUCCEED, /* close wifi succeed */ CLOSE_WIFI_FAILED, /* close wifi failed */ CONNECT_CONNECTING, /* connecting */ @@ -131,83 +83,97 @@ enum class OperateResState { DISCONNECT_DISCONNECTED, /* disconnect succeed */ CONNECT_PASSWORD_WRONG, /* wrong password */ CONNECT_OBTAINING_IP, /* obtain ip */ - CONNECT_OBTAINING_IP_FAIL + CONNECT_OBTAINING_IP_FAILED, /* obtain ip FAILED*/ + CONNECT_ASSOCIATING, + CONNECT_ASSOCIATED, }; -enum class WifiFeatures { - WIFI_FEATURE_INFRA = 0x0001, // The feature id indicates support basic infrastructure mode - WIFI_FEATURE_INFRA_5G = 0x0002, // The feature id indicates support 5 GHz Band - WIFI_FEATURE_PASSPOINT = 0x0004, // The feature id indicates support GAS/ANQP - WIFI_FEATURE_P2P = 0x0008, // The feature id indicates support Wifi-Direct - WIFI_FEATURE_MOBILE_HOTSPOT = 0x0010, // The feature id indicates support Soft AP - WIFI_FEATURE_AWARE = 0x0040, // The feature id indicates support Wi-Fi AWare networking - WIFI_FEATURE_AP_STA = 0x8000, // The feature id indicates support AP STA Concurrency - WIFI_FEATURE_WPA3_SAE = 0x8000000, // The feature id indicates support WPA3-Personal SAE - WIFI_FEATURE_WPA3_SUITE_B = 0x10000000, // The feature id indicates support WPA3-Enterprise Suite-B - WIFI_FEATURE_OWE = 0x20000000, // The feature id indicates support Enhanced Open -}; - -struct WifiRequestParams { - WifiScanParams wifiScanParams; - WpsConfig wpsConfig; - HotspotConfig hotspotConfig; - WifiDeviceConfig deviceConfig; - StationInfo stationInfo; - std::vector scanInfos; - WifiMockState wifiMockState; - int argInt; - - WifiRequestParams() : argInt(-1) - {} - - WifiRequestParams(const WifiRequestParams &) = delete; - WifiRequestParams &operator=(const WifiRequestParams &) = delete; +/* is wps connected to a network */ +enum class IsWpsConnected { + WPS_CONNECTED = 0, + WPS_INVALID = -1, }; -struct WifiResponseParams { - int result; - int argInt; - WifiLinkedInfo linkedInfo; - StationInfo staInfo; - std::vector scanInfos; - WifiResponseParams() : result(0), argInt(0) - {} +enum class Ant { + NETWORK_PRIVATE = 0, + NETWORK_PRIVATEWITHGUEST = 1, + NETWORK_CHARGEABLEPUBLIC = 2, + NETWORK_FREEPUBLIC = 3, + NETWORK_PERSONAL = 4, + NETWORK_EMERGENCYONLY = 5, + NETWORK_RESVD6 = 6, + NETWORK_RESVD7 = 7, + NETWORK_RESVD8 = 8, + NETWORK_RESVD9 = 9, + NETWORK_RESVD10 = 10, + NETWORK_RESVD11 = 11, + NETWORK_RESVD12 = 12, + NETWORK_RESVD13 = 13, + NETWORK_TESTOREXPERIMENTAL = 14, + NETWORK_WILDCARD = 15, + NETWORK_ANT_INVALID = 16 }; -struct WifiRequestMsgInfo { - int msgCode; - - WifiRequestParams params; +struct InterScanInfo { + std::string bssid; + std::string ssid; + /** + * Network performance, including authentication, + * key management, and encryption mechanisms + * supported by the access point + */ + std::string capabilities; + int frequency; + int band; /* ap band, 1: 2.4G, 2: 5G */ + WifiChannelWidth channelWidth; + int centerFrequency0; + int centerFrequency1; + int rssi; /* signal level */ + WifiSecurity securityType; + std::vector infoElems; + int64_t features; + int64_t timestamp; + Ant ant; - WifiRequestMsgInfo() : msgCode(0) + InterScanInfo() + : frequency(0), + band(0), + channelWidth(WifiChannelWidth::WIDTH_INVALID), + centerFrequency0(0), + centerFrequency1(0), + rssi(0), + securityType(WifiSecurity::INVALID), + features(0), + timestamp(0), + ant(Ant::NETWORK_ANT_INVALID) {} - WifiRequestMsgInfo(const WifiRequestMsgInfo &) = delete; - WifiRequestMsgInfo &operator=(const WifiRequestMsgInfo &) = delete; -}; - -struct WifiResponseMsgInfo { - int msgCode; - WifiResponseParams params; - - WifiResponseMsgInfo() : msgCode(0) + ~InterScanInfo() {} -}; -struct WifiEventCallbackMsg { - int msgCode; - int msgData; - std::string pinCode; /* wps pin mode code */ - WifiLinkedInfo linkInfo; - StationInfo staInfo; - - WifiEventCallbackMsg() + void GetDeviceMgmt(std::string &mgmt) { - msgCode = 0; - msgData = 0; + switch (securityType) { + case WifiSecurity::PSK: + mgmt = "WPA-PSK"; + break; + case WifiSecurity::EAP: + mgmt = "WPA-EAP"; + break; + case WifiSecurity::SAE: + mgmt = "SAE"; + break; + case WifiSecurity::OWE: + mgmt = "OWE"; + break; + default: + mgmt = "NONE"; + break; + } } }; + struct SingleAppForbid { int appID; ScanIntervalMode scanIntervalMode; @@ -229,6 +195,20 @@ struct SingleAppForbid { } }; +struct WifiEventCallbackMsg { + int msgCode; + int msgData; + std::string pinCode; /* wps pin mode code */ + WifiLinkedInfo linkInfo; + StationInfo staInfo; + + WifiEventCallbackMsg() + { + msgCode = 0; + msgData = 0; + } +}; + enum class DhcpIpType { /* dhcp IP type: ipv4 ipv6 mix */ DHCP_IPTYPE_IPV4, DHCP_IPTYPE_IPV6, @@ -237,10 +217,9 @@ enum class DhcpIpType { /* dhcp IP type: ipv4 ipv6 mix */ /* wifi config store */ struct WifiConfig { - /* scan always switch */ - bool scanAlwaysSwitch; - /* airplane mode can use sta switch */ - bool staAirplaneMode; + bool scanAlwaysSwitch; /* scan always switch */ + bool staAirplaneMode; /* when open airplane mode, whether close sta */ + bool canOpenStaWhenAirplane; /* if airplane is opened, whether can open sta */ /** * last sta service state, when service started, power * saving off, airplane mode off we use this saved state to @@ -260,7 +239,6 @@ struct WifiConfig { bool whetherToAllowNetworkSwitchover; int dhcpIpType; std::string defaultWifiInterface; - /* pre load sta/scan/ap/p2p/aware so switch */ bool preLoadSta; bool preLoadScan; bool preLoadAp; @@ -282,6 +260,7 @@ struct WifiConfig { { scanAlwaysSwitch = false; staAirplaneMode = false; + canOpenStaWhenAirplane = false; staLastState = false; savedDeviceAppraisalPriority = PRIORITY_1; scoretacticsScoreSlope = SCORE_SLOPE; diff --git a/services/wifi_standard/wifi_framework/common/net_helper/network_interface.cpp b/services/wifi_standard/wifi_framework/common/net_helper/network_interface.cpp index ed5e11f7e..4052ba067 100755 --- a/services/wifi_standard/wifi_framework/common/net_helper/network_interface.cpp +++ b/services/wifi_standard/wifi_framework/common/net_helper/network_interface.cpp @@ -140,7 +140,7 @@ bool NetworkInterface::IsExistAddressForInterface(const std::string &interfaceNa return true; } - for (const auto iter : vecIPv6) { + for (const auto &iter : vecIPv6) { if (iter == address) { return true; } diff --git a/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.cpp b/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.cpp index 393e3de0e..6461d1f5c 100755 --- a/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.cpp +++ b/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.cpp @@ -15,12 +15,22 @@ #include "wifi_global_func.h" #include #include "wifi_log.h" - #undef LOG_TAG -#define LOG_TAG "OHWIFI_COMMON_GLOBAL_FUNC" +#define LOG_TAG "WifiGlobalFunc" namespace OHOS { namespace Wifi { +constexpr int FREP_2G_MIN = 2412; +constexpr int FREP_2G_MAX = 2472; + +constexpr int FREP_5G_MIN = 5170; +constexpr int FREP_5G_MAX = 5825; +constexpr int CHANNEL_14_FREP = 2484; +constexpr int CHANNEL_14 = 14; +constexpr int CENTER_FREP_DIFF = 5; +constexpr int CHANNEL_2G_MIN = 1; +constexpr int CHANNEL_5G_MIN = 34; + ErrCode CfgCheckSsid(const HotspotConfig &cfg) { if (cfg.GetSsid().length() < MIN_SSID_LEN || cfg.GetSsid().length() > MAX_SSID_LEN) { @@ -54,14 +64,6 @@ ErrCode CfgCheckChannel(const HotspotConfig &cfg, ChannelsTable &channInfoFromCe return ((it == channels.end()) ? ErrCode::WIFI_OPT_INVALID_PARAM : ErrCode::WIFI_OPT_SUCCESS); } -ErrCode CfgCheckMaxconnum(const HotspotConfig &cfg) -{ - if (cfg.GetMaxConn() < 1 || cfg.GetMaxConn() > MAX_AP_CONN) { - return ErrCode::WIFI_OPT_INVALID_PARAM; - } - return ErrCode::WIFI_OPT_SUCCESS; -} - ErrCode IsValidHotspotConfig(const HotspotConfig &cfg, const HotspotConfig &cfgFromCenter, std::vector &bandsFromCenter, ChannelsTable &channInfoFromCenter) { @@ -93,9 +95,6 @@ ErrCode IsValidHotspotConfig(const HotspotConfig &cfg, const HotspotConfig &cfgF } } - if (CfgCheckMaxconnum(cfg) == ErrCode::WIFI_OPT_INVALID_PARAM) { - return ErrCode::WIFI_OPT_INVALID_PARAM; - } return ErrCode::WIFI_OPT_SUCCESS; } @@ -144,10 +143,6 @@ ConnectionState ConvertConnStateInternal(OperateResState resState) switch (resState) { case OperateResState::CONNECT_CONNECTING: return ConnectionState::CONNECT_CONNECTING; - case OperateResState::CONNECT_OBTAINING_IP: - return ConnectionState::CONNECT_OBTAINING_IP; - case OperateResState::CONNECT_OBTAINING_IP_FAIL: - return ConnectionState::CONNECT_OBTAINING_IP_FAIL; case OperateResState::CONNECT_AP_CONNECTED: return ConnectionState::CONNECT_AP_CONNECTED; case OperateResState::CONNECT_CHECK_PORTAL: @@ -166,6 +161,14 @@ ConnectionState ConvertConnStateInternal(OperateResState resState) return ConnectionState::CONNECT_PASSWORD_WRONG; case OperateResState::CONNECT_CONNECTING_TIMEOUT: return ConnectionState::CONNECT_CONNECTING_TIMEOUT; + case OperateResState::CONNECT_OBTAINING_IP: + return ConnectionState::CONNECT_OBTAINING_IP; + case OperateResState::CONNECT_OBTAINING_IP_FAILED: + return ConnectionState::CONNECT_OBTAINING_IP_FAILED; + case OperateResState::CONNECT_ASSOCIATING: + return ConnectionState::CONNECT_ASSOCIATING; + case OperateResState::CONNECT_ASSOCIATED: + return ConnectionState::CONNECT_ASSOCIATED; default: return ConnectionState::UNKNOWN; } @@ -230,5 +233,52 @@ void SplitString(const std::string &str, const std::string &split, std::vector &freqVector, std::vector &chanVector) +{ + int channel; + for (size_t i = 0; i < freqVector.size(); ++i) { + if (freqVector[i] >= FREP_2G_MIN && freqVector[i] <= FREP_2G_MAX) { + channel = (freqVector[i] - FREP_2G_MIN) / CENTER_FREP_DIFF + CHANNEL_2G_MIN; + } else if (freqVector[i] == CHANNEL_14_FREP) { + channel = CHANNEL_14; + } else if (freqVector[i] >= FREP_5G_MIN && freqVector[i] <= FREP_5G_MAX) { + channel = (freqVector[i] - FREP_5G_MIN) / CENTER_FREP_DIFF + CHANNEL_5G_MIN; + } else { + LOGW("Invalid Freq:%d", freqVector[i]); + continue; + } + chanVector.push_back(channel); + } +} + +bool IsValid24GHz(int freq) +{ + return freq > 2400 && freq < 2500; +} + +bool IsValid5GHz(int freq) +{ + return freq > 4900 && freq < 5900; +} + +void CheckBandChannel(HotspotConfig &apConfig, const std::map> &validChanTable) +{ + bool cfgValid = false; + auto it = validChanTable.find(apConfig.GetBand()); + if (it != validChanTable.end() && it->second.size() != 0) { + for (auto vecIt = it->second.begin(); vecIt != it->second.end(); ++vecIt) { + if (*vecIt == apConfig.GetChannel()) { + cfgValid = true; + break; + } + } + } + if (!cfgValid) { + LOGW("Error band or error channels in band, use 2.4G band default channel."); + apConfig.SetBand(BandType::BAND_2GHZ); + apConfig.SetChannel(AP_CHANNEL_DEFAULT); + } +} } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.h b/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.h index 376eb9ae6..8c360e222 100644 --- a/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.h +++ b/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.h @@ -16,7 +16,6 @@ #ifndef OHOS_WIFI_GLOBAL_FUNC_H #define OHOS_WIFI_GLOBAL_FUNC_H - #include #include #include @@ -69,14 +68,6 @@ ErrCode CfgCheckBand(const HotspotConfig &cfg, std::vector &bandsFromC */ ErrCode CfgCheckChannel(const HotspotConfig &cfg, ChannelsTable &channInfoFromCenter); -/** - * @Description Check valid connect number config - * - * @param cfg - HotspotConfig - * @return ErrCode - WIFI_OPT_SUCCESS or others - */ -ErrCode CfgCheckMaxconnum(const HotspotConfig &cfg); - /** * @Description Check valid hotspot config * @@ -124,12 +115,46 @@ int CheckMacIsValid(const std::string &macStr); /** * @Description Split string to vector accord split - * + * * @param str - input string * @param split - split string * @param vec - return string vector */ void SplitString(const std::string &str, const std::string &split, std::vector &vec); + +/** + * @Description Check is a valid 5G frequency. + * + * @param freq - Frequency input + * @return true - valid + * @return false - invalid + */ +bool IsValid5GHz(int freq); + +/** + * @Description Check is a valid 2.4G frequency. + * + * @param freq - Frequency input + * @return true - valid + * @return false - invalid + */ +bool IsValid24GHz(int freq); + +/** + * @Description Obtain and report available channel information. + * + * @param apConfig - configuration input + * @param validChanTable - Valid channel tables. + */ +void CheckBandChannel(HotspotConfig &apConfig, const std::map> &validChanTable); + +/** + * @Description Convert the frequency in the container into a channel. + * + * @param freqVector - frequency vector input + * @param chanVector - Channel vector output + */ +void TransformFrequencyIntoChannel(const std::vector &freqVector, std::vector &chanVector); } // namespace Wifi } // namespace OHOS #endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/BUILD.gn b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/BUILD.gn index 1365faf22..ab4100637 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/BUILD.gn +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/BUILD.gn @@ -12,42 +12,46 @@ # limitations under the License. import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +################################################################################ ohos_executable("dhcp_client_service") { - install_enable = true - sources = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_main.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_client.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_ipv4.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_function.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_socket.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_options.c" - ] - - include_dirs = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include", - "//utils/native/base/include" - ] - - deps = [ - "//utils/native/base:utils" - ] - - cflags_cc = [ - "-fno-rtti", - ] - - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - defines = [ - ] - - part_name = "wifi_standard" - subsystem_name = "communication" + install_enable = true + sources = [ + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_api.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_client.c", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_function.c", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_ipv4.c", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_main.c", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_options.c", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_socket.c", + ] + + include_dirs = [ + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include", + "//utils/native/base/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//third_party/openssl/include", + ] + + deps = [ + "${aafwk_path}/interfaces/innerkits/base:base", + "${aafwk_path}/interfaces/innerkits/want:want", + "//third_party/openssl:libcrypto_static", + "//utils/native/base:utils", + ] + + cflags_cc = [ "-fno-rtti" ] + + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + ] + defines = [] + + part_name = "wifi_standard" + subsystem_name = "communication" } - -group("dhcp_client"){ - deps = [ - ":dhcp_client_service" - ] -} \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_api.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_api.h new file mode 100644 index 000000000..3cddbd99c --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_api.h @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ +#ifndef DHCP_API_H +#define DHCP_API_H + + +#include "dhcp_define.h" + +extern "C" { +bool PublishDhcpIpv4ResultEvent(const int code, const char *data, const char *ifname); +} + +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_client.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_client.h index 53c31ff7e..2679ba400 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_client.h +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_client.h @@ -15,6 +15,8 @@ #ifndef OHOS_DHCPC_H #define OHOS_DHCPC_H +#include + #include "dhcp_define.h" #ifdef __cplusplus @@ -26,6 +28,7 @@ extern "C" { #define DHCPC_CONF "dhcp_client_service.conf" #define DHCPC_PID "dhcp_client_service.pid" #define DHCPC_VERSION "1.0" +#define DHCPC_LEASE "dhcp_client_service-%s.lease" enum DHCP_IP_TYPE { DHCP_IP_TYPE_NONE = 0, @@ -46,6 +49,9 @@ struct DhcpClientCfg { unsigned char ifaceMac[MAC_ADDR_LEN]; /* Mac addr of the network interface used by the current process. */ unsigned char *pOptClientId; /* DHCP packet options field clientid. */ bool timeoutExit; /* DHCP packet sending times out and exits automatically. */ + char leaseFile[DIR_MAX_LEN]; + char result6File[DIR_MAX_LEN]; + pthread_t thrId; }; int StartProcess(void); diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_define.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_define.h index ffe9ee538..ff854ca0d 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_define.h +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_define.h @@ -17,8 +17,10 @@ #include +#include #include #include +#include #include "wifi_log.h" @@ -32,8 +34,8 @@ extern "C" { #define NUMBER_FOUR 4 #define NUMBER_FIVE 5 -#define T1 0.5 -#define T2 0.875 +#define RENEWAL_SEC_MULTIPLE 0.5 +#define REBIND_SEC_MULTIPLE 0.875 #define TIME_INTERVAL_MAX 1 #define TIMEOUT_TIMES_MAX 6 #define TIMEOUT_WAIT_SEC 1 @@ -56,6 +58,11 @@ extern "C" { #define DEFAULT_UMASK 027 #define DIR_MAX_LEN 256 #define INFNAME_SIZE 16 /* Length of interface name */ +#define RWMODE 0600 +#define MAX_MSG_SIZE 1500 + +#define STRING_MAX_LEN 1024 +#define EVENT_GET_IPV4 "usual.event.wifi.dhcp.GET_IPV4" /* UDP port numbers for BOOTP */ #define BOOTP_SERVER 67 @@ -84,8 +91,10 @@ enum EnumDhcpStateCode { DHCP_STATE_BOUND, DHCP_STATE_RENEWING, DHCP_STATE_REBINDING, + DHCP_STATE_INITREBOOT, DHCP_STATE_RELEASED, DHCP_STATE_RENEWED, + DHCP_STATE_DECLINE }; /* dhcp return code */ @@ -177,6 +186,14 @@ enum DHCP_OPTION_DATA_TYPE { DHCP_OPTION_DATA_IP_STRING }; +/* publish event code */ +enum EnumPublishEventCode { + /* success */ + PUBLISH_CODE_SUCCESS = 0, + /* failed */ + PUBLISH_CODE_FAILED = -1 +}; + /* Sizes for DhcpPacket Fields */ #define DHCP_CHADDR_MAX_BYTES 16 #define DHCP_SNAME_MAX_BYTES 64 diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_ipv4.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_ipv4.h index 18ac401f5..96d544a80 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_ipv4.h +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_ipv4.h @@ -26,6 +26,7 @@ extern "C" { int SetIpv4State(int state); int InitSignalHandle(void); +int PublishDhcpResultEvent(const char *ifname, const int code, struct DhcpResult *result); int GetPacketHeaderInfo(struct DhcpPacket *packet, uint8_t type); int GetPacketCommonInfo(struct DhcpPacket *packet); int DhcpDiscover(uint32_t transid, uint32_t requestip); @@ -34,6 +35,8 @@ int DhcpRenew(uint32_t transid, uint32_t clientip, uint32_t serverip); int DhcpRelease(uint32_t clientip, uint32_t serverip); int StartIpv4(void); +int *GetSignalPipeFD(void); + #ifdef __cplusplus } #endif diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_api.cpp b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_api.cpp new file mode 100644 index 000000000..68abe33f9 --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_api.cpp @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 "dhcp_api.h" + +#include "securec.h" +#include "common_event.h" +#include "common_event_data.h" +#include "common_event_manager.h" + +#undef LOG_TAG +#define LOG_TAG "WifiDhcpApi" + +using namespace OHOS::EventFwk; + +static bool PublishDhcpEvent(const char *action, const int code, const char *data) +{ + Want want; + want.SetAction(action); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + if (!CommonEventManager::PublishCommonEvent(commonData)) { + LOGE("PublishDhcpEvent() PublishCommonEvent failed, action:%{public}s, code:%{public}d, data:%{public}s.", + action, code, data); + return false; + } + LOGI("PublishDhcpEvent() PublishCommonEvent success, action:%{public}s, code:%{public}d, data:%{private}s.", + action, code, data); + return true; +} + +bool PublishDhcpIpv4ResultEvent(const int code, const char *data, const char *ifname) +{ + char strAction[STRING_MAX_LEN] = {0}; + if (ifname == NULL) { + if (strncpy_s(strAction, sizeof(strAction), EVENT_GET_IPV4, strlen(EVENT_GET_IPV4)) != EOK) { + LOGE("PublishDhcpIpv4ResultEvent() strncpy_s %{public}s failed!", EVENT_GET_IPV4); + return false; + } + } else { + if (snprintf_s(strAction, STRING_MAX_LEN, STRING_MAX_LEN - 1, "%s.%s", EVENT_GET_IPV4, ifname) < 0) { + LOGE("PublishDhcpIpv4ResultEvent() snprintf_s %{public}s error:%{public}s!", ifname, strerror(errno)); + return false; + } + } + return PublishDhcpEvent(strAction, code, data); +} diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_client.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_client.c index 69f15390f..a858a9cb3 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_client.c +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_client.c @@ -30,7 +30,7 @@ #define LOG_TAG "WifiDhcpClient" /* Default options. */ -static struct DhcpClientCfg g_clientCfg = {"", "", "", "", "", 0, 0, DHCP_IP_TYPE_NONE, {'\0'}, NULL, false}; +static struct DhcpClientCfg g_clientCfg = {"", "", "", "", "", 0, 0, DHCP_IP_TYPE_NONE, {'\0'}, NULL, false, "", "", 0}; struct DhcpClientCfg *GetDhcpClientCfg(void) { @@ -39,15 +39,11 @@ struct DhcpClientCfg *GetDhcpClientCfg(void) int StartProcess(void) { - LOGI("StartProcess() begin.\n"); + LOGI("StartProcess() begin."); if (InitSignalHandle() != DHCP_OPT_SUCCESS) { return DHCP_OPT_FAILED; } - if ((g_clientCfg.getMode == DHCP_IP_TYPE_ALL) || (g_clientCfg.getMode == DHCP_IP_TYPE_V6)) { - /* Handle dhcp v6. */ - } - if ((g_clientCfg.getMode == DHCP_IP_TYPE_ALL) || (g_clientCfg.getMode == DHCP_IP_TYPE_V4)) { /* Handle dhcp v4. */ StartIpv4(); @@ -57,21 +53,21 @@ int StartProcess(void) int StopProcess(const char *pidFile) { - LOGI("StopProcess() begin, pidFile:%{public}s.\n", pidFile); + LOGI("StopProcess() begin, pidFile:%{public}s.", pidFile); pid_t pid = GetPID(pidFile); if (pid <= 0) { - LOGW("StopProcess() GetPID pidFile:%{public}s, pid == -1!\n", pidFile); + LOGW("StopProcess() GetPID pidFile:%{public}s, pid == -1!", pidFile); return DHCP_OPT_SUCCESS; } - LOGI("StopProcess() sending signal SIGTERM to process:%{public}d.\n", pid); + LOGI("StopProcess() sending signal SIGTERM to process:%{public}d.", pid); if (-1 == kill(pid, SIGTERM)) { if (ESRCH == errno) { - LOGW("StopProcess() pidFile:%{public}s,pid:%{public}d is not exist.\n", pidFile, pid); + LOGW("StopProcess() pidFile:%{public}s,pid:%{public}d is not exist.", pidFile, pid); unlink(pidFile); return DHCP_OPT_SUCCESS; } - LOGE("StopProcess() cmd: [kill %{public}d] failed, kill error:%{public}s!\n", pid, strerror(errno)); + LOGE("StopProcess() cmd: [kill %{public}d] failed, kill error:%{public}s!", pid, strerror(errno)); return DHCP_OPT_FAILED; } @@ -83,9 +79,9 @@ int GetProStatus(const char *pidFile) { pid_t pid = GetPID(pidFile); if (pid <= 0) { - LOGI("GetProStatus() %{public}s pid:%{public}d, %{public}s is not running.\n", pidFile, pid, DHCPC_NAME); + LOGI("GetProStatus() %{public}s pid:%{public}d, %{public}s is not running.", pidFile, pid, DHCPC_NAME); return 0; } - LOGI("GetProStatus() %{public}s pid:%{public}d, %{public}s is running.\n", pidFile, pid, DHCPC_NAME); + LOGI("GetProStatus() %{public}s pid:%{public}d, %{public}s is running.", pidFile, pid, DHCPC_NAME); return 1; } diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_function.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_function.c index c29f4f5ad..294201df5 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_function.c +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_function.c @@ -41,18 +41,18 @@ bool Ip4StrConToInt(const char *strIp, uint32_t *uIp, bool bHost) { if ((strIp == NULL) || (strlen(strIp) == 0)) { - LOGE("Ip4StrConToInt failed, strIp == NULL or \"\"!\n"); + LOGE("Ip4StrConToInt failed, strIp == NULL or \"\"!"); return false; } struct in_addr addr4; int nRet = inet_pton(AF_INET, strIp, &addr4); if (nRet != 1) { - LOGE("Ip4StrConToInt strIp:%{private}s failed, inet_pton nRet:%{public}d!\n", strIp, nRet); + LOGE("Ip4StrConToInt strIp:%{private}s failed, inet_pton nRet:%{public}d!", strIp, nRet); if (nRet == 0) { - LOGE("Ip4StrConToInt strIp:%{private}s not in presentation format!\n", strIp); + LOGE("Ip4StrConToInt strIp:%{private}s not in presentation format!", strIp); } else { - LOGE("Ip4StrConToInt strIp:%{private}s inet_pton does not contain a valid address family!\n", strIp); + LOGE("Ip4StrConToInt strIp:%{private}s inet_pton does not contain a valid address family!", strIp); } return false; } @@ -77,17 +77,17 @@ char *Ip4IntConToStr(uint32_t uIp, bool bHost) } const char *p = inet_ntop(AF_INET, &addr4, bufIp4, INET_ADDRSTRLEN); if (p == NULL) { - LOGE("Ip4IntConToStr uIp:%{private}u failed, inet_ntop p == NULL!\n", uIp); + LOGE("Ip4IntConToStr uIp:%{private}u failed, inet_ntop p == NULL!", uIp); return NULL; } char *strIp = (char *)malloc(INET_ADDRSTRLEN); if (strIp == NULL) { - LOGE("Ip4IntConToStr uIp:%{private}u failed, strIp malloc failed!\n", uIp); + LOGE("Ip4IntConToStr uIp:%{private}u failed, strIp malloc failed!", uIp); return NULL; } if (strncpy_s(strIp, INET_ADDRSTRLEN, bufIp4, strlen(bufIp4)) != EOK) { - LOGE("Ip4IntConToStr uIp:%{private}u failed, strIp strncpy_s failed!\n", uIp); + LOGE("Ip4IntConToStr uIp:%{private}u failed, strIp strncpy_s failed!", uIp); free(strIp); return NULL; } @@ -98,7 +98,7 @@ char *Ip4IntConToStr(uint32_t uIp, bool bHost) bool Ip6StrConToChar(const char *strIp, uint8_t chIp[], size_t chlen) { if ((strIp == NULL) || (strlen(strIp) == 0)) { - LOGE("Ip6StrConToChar failed, strIp == NULL or \"\"!\n"); + LOGE("Ip6StrConToChar failed, strIp == NULL or \"\"!"); return false; } @@ -108,18 +108,18 @@ bool Ip6StrConToChar(const char *strIp, uint8_t chIp[], size_t chlen) } int nRet = inet_pton(AF_INET6, strIp, &addr6); if (nRet != 1) { - LOGE("Ip6StrConToChar strIp:%{private}s failed, inet_pton nRet:%{public}d!\n", strIp, nRet); + LOGE("Ip6StrConToChar strIp:%{private}s failed, inet_pton nRet:%{public}d!", strIp, nRet); if (nRet == 0) { - LOGE("Ip6StrConToChar strIp:%{private}s not in presentation format!\n", strIp); + LOGE("Ip6StrConToChar strIp:%{private}s not in presentation format!", strIp); } else { - LOGE("Ip6StrConToChar strIp:%{private}s inet_pton does not contain a valid address family!\n", strIp); + LOGE("Ip6StrConToChar strIp:%{private}s inet_pton does not contain a valid address family!", strIp); } return false; } - LOGI("Ip6StrConToChar strIp:%{private}s -> \n", strIp); + LOGI("Ip6StrConToChar strIp:%{private}s -> ", strIp); for (size_t i = 0; i < chlen; i++) { - LOGI("Ip6StrConToChar addr6.s6_addr: %{private}zu - %{private}02x\n", i, addr6.s6_addr[i]); + LOGI("Ip6StrConToChar addr6.s6_addr: %{private}zu - %{private}02x", i, addr6.s6_addr[i]); chIp[i] = addr6.s6_addr[i]; } @@ -129,12 +129,12 @@ bool Ip6StrConToChar(const char *strIp, uint8_t chIp[], size_t chlen) const char *MacChConToMacStr(const unsigned char *pChMac, size_t chLen, char *pStrMac, size_t strLen) { if ((pChMac == NULL) || (chLen == 0)) { - LOGE("MacChConToMacStr failed, pChMac == NULL or chLen == 0!\n"); + LOGE("MacChConToMacStr failed, pChMac == NULL or chLen == 0!"); return NULL; } if ((pStrMac == NULL) || (strLen < (chLen * MAC_ADDR_CHAR_NUM))) { - LOGE("MacChConToMacStr failed, pStrMac == NULL or strLen:%{public}d error!\n", (int)strLen); + LOGE("MacChConToMacStr failed, pStrMac == NULL or strLen:%{public}d error!", (int)strLen); return NULL; } @@ -156,7 +156,7 @@ const char *MacChConToMacStr(const unsigned char *pChMac, size_t chLen, char *pS int GetLocalInterface(const char *ifname, int *ifindex, unsigned char *hwaddr, uint32_t *ifaddr4) { if ((ifname == NULL) || (strlen(ifname) == 0)) { - LOGE("GetLocalInterface() failed, ifname == NULL or \"\"!\n"); + LOGE("GetLocalInterface() failed, ifname == NULL or \"\"!"); return DHCP_OPT_FAILED; } @@ -165,42 +165,39 @@ int GetLocalInterface(const char *ifname, int *ifindex, unsigned char *hwaddr, u struct sockaddr_in *pSockIn = NULL; if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { - LOGE("GetLocalInterface() ifname:%{public}s failed, socket err:%{public}s!\n", ifname, strerror(errno)); + LOGE("GetLocalInterface() ifname:%{public}s failed, socket err:%{public}s!", ifname, strerror(errno)); return DHCP_OPT_FAILED; } if (memset_s(&iface, sizeof(iface), 0, sizeof(iface)) != EOK) { - close(fd); - LOGE("GetLocalInterface() ifname:%{public}s failed, memset_s error!\n", ifname); + LOGE("GetLocalInterface() ifname:%{public}s failed, memset_s error!", ifname); return DHCP_OPT_FAILED; } if (strncpy_s(iface.ifr_name, sizeof(iface.ifr_name), ifname, strlen(ifname)) != EOK) { - close(fd); - LOGE("GetLocalInterface() ifname:%{public}s failed, strncpy_s error!\n", ifname); + LOGE("GetLocalInterface() ifname:%{public}s failed, strncpy_s error!", ifname); return DHCP_OPT_FAILED; } if (ioctl(fd, SIOCGIFINDEX, &iface) != 0) { + LOGE("GetLocalInterface() %{public}s failed, SIOCGIFINDEX err:%{public}s!", ifname, strerror(errno)); close(fd); - LOGE("GetLocalInterface() %{public}s failed, SIOCGIFINDEX err:%{public}s!\n", ifname, strerror(errno)); return DHCP_OPT_FAILED; } *ifindex = iface.ifr_ifindex; if (ioctl(fd, SIOCGIFHWADDR, &iface) != 0) { + LOGE("GetLocalInterface() %{public}s failed, SIOCGIFHWADDR err:%{public}s!", ifname, strerror(errno)); close(fd); - LOGE("GetLocalInterface() %{public}s failed, SIOCGIFHWADDR err:%{public}s!\n", ifname, strerror(errno)); return DHCP_OPT_FAILED; } if (memcpy_s(hwaddr, MAC_ADDR_LEN, iface.ifr_hwaddr.sa_data, MAC_ADDR_LEN) != EOK) { - close(fd); - LOGE("GetLocalInterface() ifname:%{public}s failed, memcpy_s error!\n", ifname); + LOGE("GetLocalInterface() ifname:%{public}s failed, memcpy_s error!", ifname); return DHCP_OPT_FAILED; } if (ifaddr4 != NULL) { if (ioctl(fd, SIOCGIFADDR, &iface) < 0) { - LOGE("GetLocalInterface() %{public}s failed, SIOCGIFADDR err:%{public}s!\n", ifname, strerror(errno)); + LOGE("GetLocalInterface() %{public}s failed, SIOCGIFADDR err:%{public}s!", ifname, strerror(errno)); close(fd); return DHCP_OPT_FAILED; } @@ -215,7 +212,7 @@ int GetLocalInterface(const char *ifname, int *ifindex, unsigned char *hwaddr, u int GetLocalIp(const char *ifname, uint32_t *ifaddr4) { if ((ifname == NULL) || (strlen(ifname) == 0)) { - LOGE("GetLocalIp() failed, ifname == NULL or \"\"!\n"); + LOGE("GetLocalIp() failed, ifname == NULL or \"\"!"); return DHCP_OPT_FAILED; } @@ -225,7 +222,7 @@ int GetLocalIp(const char *ifname, uint32_t *ifaddr4) char strIp[NI_MAXHOST]; if (getifaddrs(&ifaddr) == -1) { - LOGE("GetLocalIp() ifname:%{public}s failed, getifaddrs error:%{public}s!\n", ifname, strerror(errno)); + LOGE("GetLocalIp() ifname:%{public}s failed, getifaddrs error:%{public}s!", ifname, strerror(errno)); return DHCP_OPT_FAILED; } @@ -235,7 +232,7 @@ int GetLocalIp(const char *ifname, uint32_t *ifaddr4) } if (ifa->ifa_addr == NULL) { - LOGE("GetLocalIp() ifname:%{public}s failed, ifa->ifa_addr == NULL!\n", ifname); + LOGE("GetLocalIp() ifname:%{public}s failed, ifa->ifa_addr == NULL!", ifname); continue; } @@ -250,7 +247,7 @@ int GetLocalIp(const char *ifname, uint32_t *ifaddr4) s = getnameinfo(ifa->ifa_addr, (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6), strIp, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); if (s != 0) { - LOGE("GetLocalIp() %{public}s failed, getnameinfo error:%{public}s!\n", ifname, gai_strerror(s)); + LOGE("GetLocalIp() %{public}s failed, getnameinfo error:%{public}s!", ifname, gai_strerror(s)); return DHCP_OPT_FAILED; } @@ -258,13 +255,13 @@ int GetLocalIp(const char *ifname, uint32_t *ifaddr4) if (family == AF_INET) { uint32_t hostIp = 0; if (!Ip4StrConToInt(strIp, &hostIp, true)) { - LOGE("GetLocalIp() %{public}s failed, Ip4StrConToInt strIp:%{private}s error!\n", ifname, strIp); + LOGE("GetLocalIp() %{public}s failed, Ip4StrConToInt strIp:%{private}s error!", ifname, strIp); return DHCP_OPT_FAILED; } - LOGI("GetLocalIp() %{public}s, AF_INET str:%{private}s -> host:%{private}u.\n", ifname, strIp, hostIp); + LOGI("GetLocalIp() %{public}s, AF_INET str:%{private}s -> host:%{private}u.", ifname, strIp, hostIp); *ifaddr4 = hostIp; } else { - LOGI("GetLocalIp() %{public}s, AF_INET6 strIp:%{private}s.\n", ifname, strIp); + LOGI("GetLocalIp() %{public}s, AF_INET6 strIp:%{private}s.", ifname, strIp); } } @@ -275,16 +272,16 @@ int GetLocalIp(const char *ifname, uint32_t *ifaddr4) int SetLocalInterface(const char *ifname, uint32_t ifaddr4) { if ((ifname == NULL) || (strlen(ifname) == 0)) { - LOGE("SetLocalInterface() failed, ifname == NULL or \"\"!\n"); + LOGE("SetLocalInterface() failed, ifname == NULL or \"\"!"); return DHCP_OPT_FAILED; } char *cIp = Ip4IntConToStr(ifaddr4, true); if (cIp == NULL) { - LOGE("SetLocalInterface() %{public}s failed, Ip4IntConToStr addr4:%{private}u failed!\n", ifname, ifaddr4); + LOGE("SetLocalInterface() %{public}s failed, Ip4IntConToStr addr4:%{private}u failed!", ifname, ifaddr4); return DHCP_OPT_FAILED; } - LOGI("SetLocalInterface() %{public}s, ifaddr4:%{private}u -> %{private}s.\n", ifname, ifaddr4, cIp); + LOGI("SetLocalInterface() %{public}s, ifaddr4:%{private}u -> %{private}s.", ifname, ifaddr4, cIp); free(cIp); int fd; @@ -292,34 +289,30 @@ int SetLocalInterface(const char *ifname, uint32_t ifaddr4) struct sockaddr_in sin; if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { - LOGE("SetLocalInterface() ifname:%{public}s failed, socket error:%{public}s!\n", ifname, strerror(errno)); + LOGE("SetLocalInterface() ifname:%{public}s failed, socket error:%{public}s!", ifname, strerror(errno)); return DHCP_OPT_FAILED; } if (memset_s(&ifr, sizeof(ifr), 0, sizeof(ifr)) != EOK) { - close(fd); return DHCP_OPT_FAILED; } if (strncpy_s(ifr.ifr_name, sizeof(ifr.ifr_name), ifname, strlen(ifname)) != EOK) { - close(fd); return DHCP_OPT_FAILED; } if (memset_s(&sin, sizeof(sin), 0, sizeof(sin)) != EOK) { - close(fd); return DHCP_OPT_FAILED; } sin.sin_family = AF_INET; sin.sin_addr.s_addr = htonl(ifaddr4); if (memcpy_s(&ifr.ifr_addr, sizeof(ifr.ifr_addr), &sin, sizeof(struct sockaddr)) != EOK) { - close(fd); return DHCP_OPT_FAILED; } /* Similar to the system command: ifconfig ifname ifaddr4. */ if (ioctl(fd, SIOCSIFADDR, &ifr) < 0) { + LOGE("SetLocalInterface() %{public}s failed, SIOCSIFADDR err:%{public}s!", ifname, strerror(errno)); close(fd); - LOGE("SetLocalInterface() %{public}s failed, SIOCSIFADDR err:%{public}s!\n", ifname, strerror(errno)); return DHCP_OPT_FAILED; } @@ -330,36 +323,36 @@ int SetLocalInterface(const char *ifname, uint32_t ifaddr4) int InitPidfile(const char *pidDir, const char *pidFile, pid_t pid) { if ((pidDir == NULL) || (strlen(pidDir) == 0) || (pidFile == NULL) || (strlen(pidFile) == 0)) { - LOGE("InitPidfile() failed, pidDir or pidFile == NULL or \"\"!\n"); + LOGE("InitPidfile() failed, pidDir or pidFile == NULL or \"\"!"); return DHCP_OPT_FAILED; } - LOGI("InitPidfile() pidDir:%{public}s, pidFile:%{public}s.\n", pidDir, pidFile); + LOGI("InitPidfile() pidDir:%{public}s, pidFile:%{public}s.", pidDir, pidFile); unlink(pidFile); int fd; if ((fd = open(pidFile, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) { - LOGE("InitPidfile() failed, open pidFile:%{public}s error:%{public}s!\n", pidFile, strerror(errno)); + LOGE("InitPidfile() failed, open pidFile:%{public}s error:%{public}s!", pidFile, strerror(errno)); return DHCP_OPT_FAILED; } char buf[PID_MAX_LEN] = {0}; if (snprintf_s(buf, PID_MAX_LEN, PID_MAX_LEN - 1, "%d", pid) < 0) { - LOGE("InitPidfile() pidFile:%{public}s failed, snprintf_s error:%{public}s!\n", pidFile, strerror(errno)); + LOGE("InitPidfile() pidFile:%{public}s failed, snprintf_s error:%{public}s!", pidFile, strerror(errno)); close(fd); return DHCP_OPT_FAILED; } ssize_t bytes; if ((bytes = write(fd, buf, strlen(buf))) <= 0) { - LOGE("InitPidfile() failed, write pidFile:%{public}s error:%{public}s, bytes:%{public}zu!\n", + LOGE("InitPidfile() failed, write pidFile:%{public}s error:%{public}s, bytes:%{public}zu!", pidFile, strerror(errno), bytes); close(fd); return DHCP_OPT_FAILED; } - LOGI("InitPidfile() buf:%{public}s write pidFile:%{public}s, bytes:%{public}zu!\n", buf, pidFile, bytes); + LOGI("InitPidfile() buf:%{public}s write pidFile:%{public}s, bytes:%{public}zu!", buf, pidFile, bytes); close(fd); if (chdir(pidDir) != 0) { - LOGE("InitPidfile() failed, chdir pidDir:%{public}s error:%{public}s!\n", pidDir, strerror(errno)); + LOGE("InitPidfile() failed, chdir pidDir:%{public}s error:%{public}s!", pidDir, strerror(errno)); return DHCP_OPT_FAILED; } @@ -377,14 +370,14 @@ pid_t GetPID(const char *pidFile) /* Check pidFile is or not exists. */ struct stat sb; if (stat(pidFile, &sb) != 0) { - LOGW("GetPID() pidFile:%{public}s stat error:%{public}s!\n", pidFile, strerror(errno)); + LOGW("GetPID() pidFile:%{public}s stat error:%{public}s!", pidFile, strerror(errno)); return -1; } - LOGI("GetPID() pidFile:%{public}s stat st_size:%{public}d.\n", pidFile, (int)sb.st_size); + LOGI("GetPID() pidFile:%{public}s stat st_size:%{public}d.", pidFile, (int)sb.st_size); int fd; if ((fd = open(pidFile, O_RDONLY)) < 0) { - LOGE("GetPID() failed, open pidFile:%{public}s error!\n", pidFile); + LOGE("GetPID() failed, open pidFile:%{public}s error!", pidFile); return -1; } @@ -393,11 +386,11 @@ pid_t GetPID(const char *pidFile) char buf[PID_MAX_LEN] = {0}; ssize_t bytes; if ((bytes = read(fd, buf, sb.st_size)) < 0) { - LOGE("GetPID() failed, read pidFile:%{public}s error, bytes:%{public}zu!\n", pidFile, bytes); + LOGE("GetPID() failed, read pidFile:%{public}s error, bytes:%{public}zu!", pidFile, bytes); close(fd); return -1; } - LOGI("GetPID() read pidFile:%{public}s, buf:%{public}s, bytes:%{public}zu.\n", pidFile, buf, bytes); + LOGI("GetPID() read pidFile:%{public}s, buf:%{public}s, bytes:%{public}zu.", pidFile, buf, bytes); close(fd); return atoi(buf); @@ -406,23 +399,23 @@ pid_t GetPID(const char *pidFile) int CreateDirs(const char *dirs, int mode) { if ((dirs == NULL) || (strlen(dirs) == 0) || (strlen(dirs) >= DIR_MAX_LEN)) { - LOGE("CreateDirs() dirs:%{public}s error!\n", dirs); + LOGE("CreateDirs() dirs:%{public}s error!", dirs); return DHCP_OPT_FAILED; } int nSrcLen = (int)strlen(dirs); char strDir[DIR_MAX_LEN] = {0}; if (strncpy_s(strDir, sizeof(strDir), dirs, strlen(dirs)) != EOK) { - LOGE("CreateDirs() strncpy_s dirs:%{public}s failed!\n", dirs); + LOGE("CreateDirs() strncpy_s dirs:%{public}s failed!", dirs); return DHCP_OPT_FAILED; } if (strDir[nSrcLen - 1] != '/') { if (nSrcLen == (DIR_MAX_LEN - 1)) { - LOGE("CreateDirs() dirs:%{public}s len:%{public}d error!\n", dirs, nSrcLen); + LOGE("CreateDirs() dirs:%{public}s len:%{public}d error!", dirs, nSrcLen); return DHCP_OPT_FAILED; } if (strcat_s(strDir, sizeof(strDir), "/") != EOK) { - LOGE("CreateDirs() strcat_s strDir:%{public}s failed!\n", strDir); + LOGE("CreateDirs() strcat_s strDir:%{public}s failed!", strDir); return DHCP_OPT_FAILED; } nSrcLen++; @@ -433,12 +426,12 @@ int CreateDirs(const char *dirs, int mode) if (strDir[i] == '/') { strDir[i] = 0; if ((access(strDir, F_OK) != 0) && (mkdir(strDir, mode) != 0)) { - LOGE("CreateDirs() mkdir %{public}s %{public}.4o failed:%{public}s!\n", strDir, mode, strerror(errno)); + LOGE("CreateDirs() mkdir %{public}s %{public}.4o failed:%{public}s!", strDir, mode, strerror(errno)); return DHCP_OPT_FAILED; } strDir[i] = '/'; } } - LOGI("CreateDirs() %{public}s %{public}.4o success.\n", dirs, mode); + LOGI("CreateDirs() %{public}s %{public}.4o success.", dirs, mode); return DHCP_OPT_SUCCESS; } diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_ipv4.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_ipv4.c index 26451ee48..60c3a939b 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_ipv4.c +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_ipv4.c @@ -28,6 +28,8 @@ #include #include #include +#include +#include #include "securec.h" #include "dhcp_client.h" @@ -38,6 +40,17 @@ #undef LOG_TAG #define LOG_TAG "WifiDhcpIpv4" + +struct ArpPacket { + struct ethhdr ethh; /* Ethernet header */ + struct arphdr arph; /* Arp header */ + u_char sHaddr[6]; /* sender's hardware address */ + u_char sInaddr[4]; /* sender's IP address */ + u_char tHaddr[6]; /* target's hardware address */ + u_char tInaddr[4]; /* target's IP address */ + u_char pad[18]; /* pad for min. Ethernet payload (60 bytes) */ +}; + /* static defined */ static int g_dhcp4State = DHCP_STATE_INIT; static int g_sockFd = -1; @@ -54,6 +67,41 @@ static uint32_t g_socketMode = SOCKET_MODE_INVALID; static uint32_t g_transID = 0; static struct DhcpClientCfg *g_cltCnf; +static int g_signalPipe[NUMBER_TWO]; + +int *GetSignalPipeFD(void) +{ + return g_signalPipe; +} + +static int Decline(time_t timestamp) +{ + LOGI("Decline() enter, requestip:%{private}u, serverid:%{private}u", g_requestedIp4, g_serverIp4); + + struct DhcpPacket packet; + if (memset_s(&packet, sizeof(struct DhcpPacket), 0, sizeof(struct DhcpPacket)) != EOK) { + return -1; + } + + /* Get packet header and common info. */ + if (GetPacketHeaderInfo(&packet, DHCP_DECLINE) != DHCP_OPT_SUCCESS) { + return -1; + } + + if (memcpy_s(packet.chaddr, sizeof(packet.chaddr), g_cltCnf->ifaceMac, MAC_ADDR_LEN) != EOK) { + LOGE("Decline() failed, memcpy_s error!"); + return -1; + } + + /* Get packet not common info. */ + packet.xid = g_transID; + AddOptValueToOpts(packet.options, DHO_IPADDRESS, g_requestedIp4); + AddOptValueToOpts(packet.options, DHO_SERVERID, g_serverIp4); + g_sentPacketNum++; + g_timeoutTimestamp = timestamp + 1; + + return SendToDhcpPacket(&packet, INADDR_ANY, INADDR_BROADCAST, g_cltCnf->ifaceIndex, (uint8_t *)MAC_BCAST_ADDR); +} /* Send signals. */ static void SignalHandler(int signum) @@ -66,6 +114,7 @@ static void SignalHandler(int signum) case SIGUSR2: /* Send signal SIGUSR2. */ send(g_sigSockFds[1], &signum, sizeof(signum), MSG_DONTWAIT); + send(g_signalPipe[1], &signum, sizeof(signum), MSG_DONTWAIT); break; default: break; @@ -78,7 +127,7 @@ static void SetSocketMode(uint32_t mode) close(g_sockFd); g_sockFd = -1; g_socketMode = mode; - LOGI("SetSocketMode() the socket mode %{public}s.\n", (mode == SOCKET_MODE_RAW) ? "raw" + LOGI("SetSocketMode() the socket mode %{public}s.", (mode == SOCKET_MODE_RAW) ? "raw" : ((mode == SOCKET_MODE_KERNEL) ? "kernel" : "not valid")); } @@ -98,7 +147,7 @@ static void ExecDhcpRelease(void) /* Ensure that the function select() is always blocked and don't need to receive ip from dhcp server. */ g_timeoutTimestamp = SIGNED_INTEGER_MAX; - LOGI("ExecDhcpRelease() enter released state...\n"); + LOGI("ExecDhcpRelease() enter released state..."); } /* Execution dhcp renew. */ @@ -108,12 +157,12 @@ static void ExecDhcpRenew(void) switch (g_dhcp4State) { case DHCP_STATE_INIT: case DHCP_STATE_SELECTING: - LOGI("ExecDhcpRenew() dhcp ipv4 old state:%{public}d, no need change state.\n", g_dhcp4State); + LOGI("ExecDhcpRenew() dhcp ipv4 old state:%{public}d, no need change state.", g_dhcp4State); break; case DHCP_STATE_REQUESTING: case DHCP_STATE_RELEASED: case DHCP_STATE_RENEWED: - LOGI("ExecDhcpRenew() dhcp ipv4 old state:%{public}d, init state:INIT.\n", g_dhcp4State); + LOGI("ExecDhcpRenew() dhcp ipv4 old state:%{public}d, init state:INIT.", g_dhcp4State); /* Init socket mode and dhcp ipv4 state. */ g_dhcp4State = DHCP_STATE_INIT; SetSocketMode(SOCKET_MODE_RAW); @@ -123,7 +172,7 @@ static void ExecDhcpRenew(void) SetSocketMode(SOCKET_MODE_KERNEL); case DHCP_STATE_RENEWING: case DHCP_STATE_REBINDING: - LOGI("ExecDhcpRenew() dhcp ipv4 old state:%{public}d, set state:RENEWED.\n", g_dhcp4State); + LOGI("ExecDhcpRenew() dhcp ipv4 old state:%{public}d, set state:RENEWED.", g_dhcp4State); /* Set dhcp ipv4 state, send request packet. */ g_dhcp4State = DHCP_STATE_RENEWED; break; @@ -135,7 +184,7 @@ static void ExecDhcpRenew(void) g_sentPacketNum = 0; g_timeoutTimestamp = 0; - LOGI("ExecDhcpRenew() a dhcp renew is executed...\n"); + LOGI("ExecDhcpRenew() a dhcp renew is executed..."); } /* Add dhcp option paramater request list. */ @@ -169,19 +218,19 @@ static void InitSocketFd(void) if (g_socketMode == SOCKET_MODE_RAW) { if ((CreateRawSocket(&g_sockFd) != SOCKET_OPT_SUCCESS) || (BindRawSocket(g_sockFd, g_cltCnf->ifaceIndex, NULL) != SOCKET_OPT_SUCCESS)) { - LOGE("InitSocketFd() fd:%{public}d,index:%{public}d failed!\n", g_sockFd, g_cltCnf->ifaceIndex); + LOGE("InitSocketFd() fd:%{public}d,index:%{public}d failed!", g_sockFd, g_cltCnf->ifaceIndex); bInitSuccess = false; } } else { if ((CreateKernelSocket(&g_sockFd) != SOCKET_OPT_SUCCESS) || (BindKernelSocket(g_sockFd, g_cltCnf->ifaceName, INADDR_ANY, BOOTP_CLIENT, true) != SOCKET_OPT_SUCCESS)) { - LOGE("InitSocketFd() fd:%{public}d,ifname:%{public}s failed!\n", g_sockFd, g_cltCnf->ifaceName); + LOGE("InitSocketFd() fd:%{public}d,ifname:%{public}s failed!", g_sockFd, g_cltCnf->ifaceName); bInitSuccess = false; } } if (!bInitSuccess || (g_sockFd < 0)) { - LOGE("InitSocketFd() %{public}d err:%{public}s, couldn't listen on socket!\n", g_sockFd, strerror(errno)); + LOGE("InitSocketFd() %{public}d err:%{public}s, couldn't listen on socket!", g_sockFd, strerror(errno)); unlink(g_cltCnf->pidFile); unlink(g_cltCnf->resultFile); exit(EXIT_SUCCESS); @@ -197,14 +246,14 @@ static uint32_t GetTransId(void) unsigned int uSeed = 0; int nFd = -1; if ((nFd = open("/dev/urandom", 0)) == -1) { - LOGE("GetTransId() open /dev/urandom failed, error:%{public}s!\n", strerror(errno)); + LOGE("GetTransId() open /dev/urandom failed, error:%{public}s!", strerror(errno)); uSeed = time(NULL); } else { if (read(nFd, &uSeed, sizeof(uSeed)) == -1) { - LOGE("GetTransId() read /dev/urandom failed, error:%{public}s!\n", strerror(errno)); + LOGE("GetTransId() read /dev/urandom failed, error:%{public}s!", strerror(errno)); uSeed = time(NULL); } - LOGI("GetTransId() read /dev/urandom uSeed:%{public}u.\n", uSeed); + LOGI("GetTransId() read /dev/urandom uSeed:%{public}u.", uSeed); close(nFd); } srandom(uSeed); @@ -217,7 +266,7 @@ static void InitSelecting(time_t timestamp) { if (g_sentPacketNum > TIMEOUT_TIMES_MAX) { /* Send packet timed out, now exit process. */ - LOGW("InitSelecting() send packet timed out %{public}u times, now exit process!\n", g_sentPacketNum); + LOGW("InitSelecting() send packet timed out %{public}u times, now exit process!", g_sentPacketNum); g_timeoutTimestamp = timestamp + TIMEOUT_MORE_WAIT_SEC; g_sentPacketNum = 0; g_cltCnf->timeoutExit = true; @@ -236,7 +285,7 @@ static void InitSelecting(time_t timestamp) uint32_t uTimeoutSec = TIMEOUT_WAIT_SEC << g_sentPacketNum; g_timeoutTimestamp = timestamp + uTimeoutSec; - LOGI("InitSelecting() DhcpDiscover g_sentPacketNum:%{public}u,timeoutSec:%{public}u,timestamp:%{public}u.\n", + LOGI("InitSelecting() DhcpDiscover g_sentPacketNum:%{public}u,timeoutSec:%{public}u,timestamp:%{public}u.", g_sentPacketNum, uTimeoutSec, g_timeoutTimestamp); @@ -244,6 +293,171 @@ static void InitSelecting(time_t timestamp) g_sentPacketNum++; } +static struct DhcpPacket *ReadLease() +{ + if (g_cltCnf->leaseFile[0] == '\0') { + return NULL; + } + + int fd; + struct DhcpPacket *dhcp = NULL; + ssize_t rBytes; + + fd = open(g_cltCnf->leaseFile, O_RDONLY); + if (fd < 0) { + return NULL; + } + + dhcp = calloc(1, sizeof(*dhcp)); + if (dhcp == NULL) { + close(fd); + return NULL; + } + + rBytes = read(fd, (uint8_t *)dhcp, sizeof(*dhcp)); + close(fd); + if (rBytes <= 0 || (size_t)rBytes < offsetof(struct DhcpPacket, options)) { + free(dhcp); + return NULL; + } + + return dhcp; +} + +static ssize_t WriteLease(struct DhcpPacket *pkt) +{ + if (pkt == NULL) { + return -1; + } + + if (g_cltCnf->leaseFile[0] == '\0') { + return -1; + } + + int fd; + ssize_t wBytes; + + fd = open(g_cltCnf->leaseFile, O_WRONLY | O_CREAT | O_TRUNC, RWMODE); + if (fd < 0) { + return -1; + } + + wBytes = write(fd, (uint8_t *)pkt, sizeof(*pkt)); + close(fd); + return wBytes; +} + +static void AddParamaterRebootList(struct DhcpPacket *packet) +{ + int end = GetEndOptionIndex(packet->options); + int i; + int len = 0; + uint8_t arrReqCode[DHCP_REQ_CODE_NUM] = { + DHO_SUBNETMASK, DHO_STATICROUTE, DHO_ROUTER, DHO_BROADCAST, DHO_LEASETIME, DHO_RENEWALTIME, DHO_REBINDTIME}; + + packet->options[end + DHCP_OPT_CODE_INDEX] = DHO_PARAMETERREQUESTLIST; + for (i = 0; i < DHCP_REQ_CODE_NUM; i++) { + if ((arrReqCode[i] > DHO_PAD) && (arrReqCode[i] < DHO_END)) { + packet->options[end + DHCP_OPT_DATA_INDEX + len++] = arrReqCode[i]; + } + } + packet->options[end + DHCP_OPT_LEN_INDEX] = len; + packet->options[end + DHCP_OPT_DATA_INDEX + len] = DHO_END; +} + +static int DhcpReboot(uint32_t transid, uint32_t reqip) +{ + LOGI("DhcpReboot() enter"); + struct DhcpPacket packet; + if (memset_s(&packet, sizeof(struct DhcpPacket), 0, sizeof(struct DhcpPacket)) != EOK) { + return -1; + } + + /* Get packet header and common info. */ + if (GetPacketHeaderInfo(&packet, DHCP_REQUEST) != DHCP_OPT_SUCCESS) { + return -1; + } + + if (memcpy_s(packet.chaddr, sizeof(packet.chaddr), g_cltCnf->ifaceMac, MAC_ADDR_LEN) != EOK) { + LOGE("DhcpReboot() failed, memcpy_s error!"); + return -1; + } + + /* Get packet not common info. */ + packet.xid = transid; + AddOptValueToOpts(packet.options, DHO_IPADDRESS, reqip); + AddOptValueToOpts(packet.options, DHO_MAXMESSAGESIZE, MAX_MSG_SIZE); + AddOptValueToOpts(packet.options, DHO_FORCERENEW_NONCE, 1); + AddParamaterRebootList(&packet); + + /* Begin broadcast dhcp request packet. */ + char *pReqIp = Ip4IntConToStr(reqip, false); + if (pReqIp != NULL) { + LOGI("DhcpReboot() broadcast req packet, reqip: host %{private}u->%{private}s.", ntohl(reqip), pReqIp); + free(pReqIp); + } + return SendToDhcpPacket(&packet, INADDR_ANY, INADDR_BROADCAST, g_cltCnf->ifaceIndex, (uint8_t *)MAC_BCAST_ADDR); +} + +static void SendReboot(struct DhcpPacket *p, time_t timestamp) +{ + if (p == NULL) { + return; + } + + g_requestedIp4 = p->yiaddr; + + free(p); + + g_transID = GetTransId(); + g_dhcp4State = DHCP_STATE_INITREBOOT; + g_sentPacketNum = 0; + g_timeoutTimestamp = timestamp + g_renewalSec; + DhcpReboot(g_transID, g_requestedIp4); +} + +static void Reboot(time_t timestamp) +{ + struct DhcpPacket *pkt = ReadLease(); + if (pkt == NULL) { + return; + } + + uint32_t leaseTime; + uint32_t renewalTime; + uint32_t rebindTime; + uint32_t interval; + struct stat st; + if (!GetDhcpOptionUint32(pkt, DHO_LEASETIME, &leaseTime)) { + leaseTime = ~0U; + } + + if (leaseTime != ~0U && stat(g_cltCnf->leaseFile, &st) == 0) { + if (timestamp == (time_t)-1 || (time_t)leaseTime < timestamp - st.st_mtime) { + LOGI("Reboot read lease file leaseTime expire"); + free(pkt); + return; + } else { + interval = timestamp - st.st_mtime; + leaseTime -= interval; + renewalTime = leaseTime * RENEWAL_SEC_MULTIPLE; + rebindTime = leaseTime * REBIND_SEC_MULTIPLE; + LOGI("Reboot read lease file leaseTime:%{public}u, renewalTime:%{public}u, rebindTime:%{public}u", + leaseTime, renewalTime, rebindTime); + } + } else { + LOGI("Reboot read lease file leaseTime option not found"); + free(pkt); + return; + } + + g_leaseTime = leaseTime; + g_renewalSec = renewalTime; + g_rebindSec = rebindTime; + + SendReboot(pkt, timestamp); +} + static void Requesting(time_t timestamp) { if (g_sentPacketNum > TIMEOUT_TIMES_MAX) { @@ -265,7 +479,7 @@ static void Requesting(time_t timestamp) uint32_t uTimeoutSec = TIMEOUT_WAIT_SEC << g_sentPacketNum; g_timeoutTimestamp = timestamp + uTimeoutSec; - LOGI("Requesting() DhcpRequest g_sentPacketNum:%{public}u,timeoutSec:%{public}u,g_timeoutTimestamp:%{public}u.\n", + LOGI("Requesting() DhcpRequest g_sentPacketNum:%{public}u,timeoutSec:%{public}u,g_timeoutTimestamp:%{public}u.", g_sentPacketNum, uTimeoutSec, g_timeoutTimestamp); @@ -283,7 +497,7 @@ static void Renewing(time_t timestamp) g_renewalSec += (g_rebindSec - g_renewalSec) / NUMBER_TWO; g_timeoutTimestamp = g_renewalTimestamp + g_renewalSec; LOGI("Renewing() DhcpRenew unicast renewalTime:%{public}u,renewal:%{public}u,timeoutTime:%{public}u, " - "rebind:%{public}u.\n", + "rebind:%{public}u.", g_renewalTimestamp, g_renewalSec, g_timeoutTimestamp, @@ -291,9 +505,9 @@ static void Renewing(time_t timestamp) } else { /* Cur time reaches rebind time, now enter rebinding state. */ g_dhcp4State = DHCP_STATE_REBINDING; - LOGI("Renewing() cur time reaches rebind time, now enter rebinding state...\n"); + LOGI("Renewing() cur time reaches rebind time, now enter rebinding state..."); g_timeoutTimestamp = timestamp + (g_rebindSec - g_renewalSec); - LOGI("Renewing() timestamp:%{public}d,rebind:%{public}u,renewal:%{public}u, timeoutTime:%{public}u.\n", + LOGI("Renewing() timestamp:%{public}d,rebind:%{public}u,renewal:%{public}u, timeoutTime:%{public}u.", (int)timestamp, g_rebindSec, g_renewalSec, g_timeoutTimestamp); } } @@ -308,14 +522,14 @@ static void Rebinding(time_t timestamp) g_rebindSec += (g_leaseTime - g_rebindSec) / NUMBER_TWO; g_timeoutTimestamp = g_renewalTimestamp + g_rebindSec; LOGI("Rebinding() DhcpRenew broadcast renewalTime:%{public}u,rebind:%{public}u,timeoutTime:%{public}u, " - "lease:%{public}u.\n", + "lease:%{public}u.", g_renewalTimestamp, g_rebindSec, g_timeoutTimestamp, g_leaseTime); } else { /* Cur time reaches lease time, send packet timed out, now enter init state. */ - LOGI("Rebinding() 555 cur time reaches lease time, now enter init state...\n"); + LOGI("Rebinding() 555 cur time reaches lease time, now enter init state..."); g_dhcp4State = DHCP_STATE_INIT; SetSocketMode(SOCKET_MODE_RAW); g_sentPacketNum = 0; @@ -337,7 +551,7 @@ static void DhcpRequestHandle(time_t timestamp) break; case DHCP_STATE_BOUND: /* Now the renewal time run out, ready to enter renewing state. */ - LOGI("DhcpRequestHandle() 333 the renewal time run out, ready to enter renewing state...\n"); + LOGI("DhcpRequestHandle() 333 the renewal time run out, ready to enter renewing state..."); g_dhcp4State = DHCP_STATE_RENEWING; SetSocketMode(SOCKET_MODE_KERNEL); case DHCP_STATE_RENEWING: @@ -350,6 +564,16 @@ static void DhcpRequestHandle(time_t timestamp) /* Ensure that the function select() is always blocked and don't need to receive ip from dhcp server. */ g_timeoutTimestamp = SIGNED_INTEGER_MAX; break; + case DHCP_STATE_DECLINE: + if (g_sentPacketNum > 0 && g_sentPacketNum < NUMBER_FIVE) { + g_sentPacketNum++; + g_timeoutTimestamp = timestamp + 1; + } else if (g_sentPacketNum >= NUMBER_FIVE) { + g_dhcp4State = DHCP_STATE_INIT; + } else { + Decline(timestamp); + } + break; default: break; } @@ -358,18 +582,18 @@ static void DhcpRequestHandle(time_t timestamp) static void DhcpOfferPacketHandle(uint8_t type, const struct DhcpPacket *packet, time_t timestamp) { if (type != DHCP_OFFER) { - LOGE("DhcpOfferPacketHandle() type:%{public}d error!\n", type); + LOGE("DhcpOfferPacketHandle() type:%{public}d error!", type); return; } if (packet == NULL) { - LOGE("DhcpOfferPacketHandle() type:%{public}d error, packet == NULL!\n", type); + LOGE("DhcpOfferPacketHandle() type:%{public}d error, packet == NULL!", type); return; } uint32_t u32Data = 0; if (!GetDhcpOptionUint32(packet, DHO_SERVERID, &u32Data)) { - LOGE("DhcpOfferPacketHandle() type:%{public}d error, GetDhcpOptionUint32 DHO_SERVERID failed!\n", type); + LOGE("DhcpOfferPacketHandle() type:%{public}d error, GetDhcpOptionUint32 DHO_SERVERID failed!", type); return; } @@ -380,7 +604,7 @@ static void DhcpOfferPacketHandle(uint8_t type, const struct DhcpPacket *packet, char *pReqIp = Ip4IntConToStr(g_requestedIp4, false); if (pReqIp != NULL) { LOGI( - "DhcpOfferPacketHandle() receive DHCP_OFFER, xid:%{public}u, requestIp: host %{private}u->%{private}s.\n", + "DhcpOfferPacketHandle() receive DHCP_OFFER, xid:%{public}u, requestIp: host %{private}u->%{private}s.", g_transID, ntohl(g_requestedIp4), pReqIp); @@ -388,7 +612,7 @@ static void DhcpOfferPacketHandle(uint8_t type, const struct DhcpPacket *packet, } char *pSerIp = Ip4IntConToStr(g_serverIp4, false); if (pSerIp != NULL) { - LOGI("DhcpOfferPacketHandle() receive DHCP_OFFER, serverIp: host %{private}u->%{private}s.\n", + LOGI("DhcpOfferPacketHandle() receive DHCP_OFFER, serverIp: host %{private}u->%{private}s.", ntohl(g_serverIp4), pSerIp); free(pSerIp); @@ -403,7 +627,7 @@ static void DhcpOfferPacketHandle(uint8_t type, const struct DhcpPacket *packet, static void ParseOtherNetworkInfo(const struct DhcpPacket *packet, struct DhcpResult *result) { if ((packet == NULL) || (result == NULL)) { - LOGE("ParseOtherNetworkInfo() error, packet == NULL or result == NULL!\n"); + LOGE("ParseOtherNetworkInfo() error, packet == NULL or result == NULL!"); return; } @@ -412,7 +636,7 @@ static void ParseOtherNetworkInfo(const struct DhcpPacket *packet, struct DhcpRe if (GetDhcpOptionUint32n(packet, DHO_DNSSERVER, &u32Data, &u32Data2)) { char *pDnsIp = Ip4IntConToStr(u32Data, true); if (pDnsIp != NULL) { - LOGI("ParseOtherNetworkInfo() recv DHCP_ACK 6, dns1: %{private}u->%{private}s.\n", u32Data, pDnsIp); + LOGI("ParseOtherNetworkInfo() recv DHCP_ACK 6, dns1: %{private}u->%{private}s.", u32Data, pDnsIp); if (strncpy_s(result->strOptDns1, INET_ADDRSTRLEN, pDnsIp, INET_ADDRSTRLEN - 1) != EOK) { free(pDnsIp); return; @@ -421,7 +645,7 @@ static void ParseOtherNetworkInfo(const struct DhcpPacket *packet, struct DhcpRe pDnsIp = NULL; } if ((u32Data2 > 0) && ((pDnsIp = Ip4IntConToStr(u32Data2, true)) != NULL)) { - LOGI("ParseOtherNetworkInfo() recv DHCP_ACK 6, dns2: %{private}u->%{private}s.\n", u32Data2, pDnsIp); + LOGI("ParseOtherNetworkInfo() recv DHCP_ACK 6, dns2: %{private}u->%{private}s.", u32Data2, pDnsIp); if (strncpy_s(result->strOptDns2, INET_ADDRSTRLEN, pDnsIp, INET_ADDRSTRLEN - 1) != EOK) { free(pDnsIp); return; @@ -434,15 +658,25 @@ static void ParseOtherNetworkInfo(const struct DhcpPacket *packet, struct DhcpRe static void ParseNetworkInfo(const struct DhcpPacket *packet, struct DhcpResult *result) { if ((packet == NULL) || (result == NULL)) { - LOGE("ParseNetworkInfo() error, packet == NULL or result == NULL!\n"); + LOGE("ParseNetworkInfo() error, packet == NULL or result == NULL!"); return; } + char *pReqIp = Ip4IntConToStr(g_requestedIp4, false); + if (pReqIp != NULL) { + LOGI("ParseNetworkInfo() recv DHCP_ACK yiaddr: %{private}u->%{private}s.", ntohl(g_requestedIp4), pReqIp); + if (strncpy_s(result->strYiaddr, INET_ADDRSTRLEN, pReqIp, INET_ADDRSTRLEN - 1) != EOK) { + free(pReqIp); + return; + } + free(pReqIp); + } + uint32_t u32Data = 0; if (GetDhcpOptionUint32(packet, DHO_SUBNETMASK, &u32Data)) { char *pSubIp = Ip4IntConToStr(u32Data, true); if (pSubIp != NULL) { - LOGI("ParseNetworkInfo() recv DHCP_ACK 1, subnetmask: %{private}u->%{private}s.\n", u32Data, pSubIp); + LOGI("ParseNetworkInfo() recv DHCP_ACK 1, subnetmask: %{private}u->%{private}s.", u32Data, pSubIp); if (strncpy_s(result->strOptSubnet, INET_ADDRSTRLEN, pSubIp, INET_ADDRSTRLEN - 1) != EOK) { free(pSubIp); return; @@ -456,7 +690,7 @@ static void ParseNetworkInfo(const struct DhcpPacket *packet, struct DhcpResult if (GetDhcpOptionUint32n(packet, DHO_ROUTER, &u32Data, &u32Data2)) { char *pRouterIp = Ip4IntConToStr(u32Data, true); if (pRouterIp != NULL) { - LOGI("ParseNetworkInfo() recv DHCP_ACK 3, router1: %{private}u->%{private}s.\n", u32Data, pRouterIp); + LOGI("ParseNetworkInfo() recv DHCP_ACK 3, router1: %{private}u->%{private}s.", u32Data, pRouterIp); if (strncpy_s(result->strOptRouter1, INET_ADDRSTRLEN, pRouterIp, INET_ADDRSTRLEN - 1) != EOK) { free(pRouterIp); return; @@ -465,7 +699,7 @@ static void ParseNetworkInfo(const struct DhcpPacket *packet, struct DhcpResult pRouterIp = NULL; } if ((u32Data2 > 0) && ((pRouterIp = Ip4IntConToStr(u32Data2, true)) != NULL)) { - LOGI("ParseNetworkInfo() recv DHCP_ACK 3, router2: %{private}u->%{private}s.\n", u32Data2, pRouterIp); + LOGI("ParseNetworkInfo() recv DHCP_ACK 3, router2: %{private}u->%{private}s.", u32Data2, pRouterIp); if (strncpy_s(result->strOptRouter2, INET_ADDRSTRLEN, pRouterIp, INET_ADDRSTRLEN - 1) != EOK) { free(pRouterIp); return; @@ -480,7 +714,7 @@ static void ParseNetworkInfo(const struct DhcpPacket *packet, struct DhcpResult static void FormatString(struct DhcpResult *result) { if (result == NULL) { - LOGE("FormatString() error, result == NULL!\n"); + LOGE("FormatString() error, result == NULL!"); return; } @@ -526,34 +760,37 @@ static void FormatString(struct DhcpResult *result) } } -static void WriteDhcpResult(struct DhcpResult *result) +static int WriteDhcpResult(struct DhcpResult *result) { if (result == NULL) { - LOGE("WriteDhcpResult() error, result == NULL!\n"); - return; + LOGE("WriteDhcpResult() error, result == NULL!"); + return DHCP_OPT_FAILED; } /* Format dhcp result. */ FormatString(result); uint32_t curTime = (uint32_t)time(NULL); + if ((time_t)curTime == (time_t)-1) { + return DHCP_OPT_FAILED; + } LOGI("WriteDhcpResult() " "result->strYiaddr:%{private}s,strOptServerId:%{private}s,strOptSubnet:%{private}s,uOptLeasetime:%{public}u," - " curTime:%{public}u.\n", + " curTime:%{public}u.", result->strYiaddr, result->strOptServerId, result->strOptSubnet, result->uOptLeasetime, curTime); FILE *pFile = fopen(g_cltCnf->resultFile, "w+"); if (pFile == NULL) { - LOGE("WriteDhcpResult fopen %{public}s err:%{public}s!\n", g_cltCnf->resultFile, strerror(errno)); - return; + LOGE("WriteDhcpResult fopen %{public}s err:%{public}s!", g_cltCnf->resultFile, strerror(errno)); + return DHCP_OPT_FAILED; } /* Lock the writing file. */ if (flock(fileno(pFile), LOCK_EX) != 0) { - LOGE("WriteDhcpResult() flock file:%{public}s LOCK_EX failed, error:%{public}s!\n", + LOGE("WriteDhcpResult() flock file:%{public}s LOCK_EX failed, error:%{public}s!", g_cltCnf->resultFile, strerror(errno)); fclose(pFile); - return; + return DHCP_OPT_FAILED; } /* Format: IP4 timestamp cliIp servIp subnet dns1 dns2 router1 router2 vendor lease. */ @@ -562,63 +799,79 @@ static void WriteDhcpResult(struct DhcpResult *result) curTime, result->strYiaddr, result->strOptServerId, result->strOptSubnet, result->strOptDns1, result->strOptDns2, result->strOptRouter1, result->strOptRouter2, result->strOptVendor, result->uOptLeasetime); if (nBytes <= 0) { - LOGE("WriteDhcpResult() fprintf %{public}s error:%{public}s!\n", g_cltCnf->resultFile, strerror(errno)); + LOGE("WriteDhcpResult() fprintf %{public}s error:%{public}s!", g_cltCnf->resultFile, strerror(errno)); fclose(pFile); - return; + return DHCP_OPT_FAILED; } - LOGI("WriteDhcpResult() fprintf %{public}s success, nBytes:%{public}d.\n", g_cltCnf->resultFile, nBytes); /* Unlock the writing file. */ if (flock(fileno(pFile), LOCK_UN) != 0) { - LOGE("WriteDhcpResult() flock file:%{public}s LOCK_UN failed, error:%{public}s!\n", + LOGE("WriteDhcpResult() flock file:%{public}s LOCK_UN failed, error:%{public}s!", g_cltCnf->resultFile, strerror(errno)); fclose(pFile); - return; + return DHCP_OPT_FAILED; } if (fclose(pFile) != 0) { - LOGE("WriteDhcpResult() fclose %{public}s error:%{public}s!\n", g_cltCnf->resultFile, strerror(errno)); - return; + LOGE("WriteDhcpResult() fclose %{public}s error:%{public}s!", g_cltCnf->resultFile, strerror(errno)); + return DHCP_OPT_FAILED; } + LOGI("WriteDhcpResult() fprintf %{public}s success, nBytes:%{public}d.", g_cltCnf->resultFile, nBytes); + return DHCP_OPT_SUCCESS; } -static void SyncDhcpResult(const struct DhcpPacket *packet, struct DhcpResult *result) +static int SyncDhcpResult(const struct DhcpPacket *packet, struct DhcpResult *result) { if ((packet == NULL) || (result == NULL)) { - LOGE("SyncDhcpResult() error, packet == NULL or result == NULL!\n"); - return; + LOGE("SyncDhcpResult() error, packet == NULL or result == NULL!"); + return DHCP_OPT_FAILED; } char *pVendor = GetDhcpOptionString(packet, DHO_VENDOR); if (pVendor == NULL) { - LOGW("SyncDhcpResult() recv DHCP_ACK 43, pVendor is NULL!\n"); + LOGW("SyncDhcpResult() recv DHCP_ACK 43, pVendor is NULL!"); } else { - LOGI("SyncDhcpResult() recv DHCP_ACK 43, pVendor is %{public}s.\n", pVendor); + LOGI("SyncDhcpResult() recv DHCP_ACK 43, pVendor is %{public}s.", pVendor); if (strncpy_s(result->strOptVendor, DHCP_FILE_MAX_BYTES, pVendor, DHCP_FILE_MAX_BYTES - 1) != EOK) { + LOGE("SyncDhcpResult() error, strncpy_s pVendor failed!"); free(pVendor); - return; + return DHCP_OPT_FAILED; } free(pVendor); } /* Set the specified client process interface network info. */ if (SetLocalInterface(g_cltCnf->ifaceName, ntohl(g_requestedIp4)) != DHCP_OPT_SUCCESS) { - LOGE("SyncDhcpResult() error, SetLocalInterface yiaddr:%{private}s failed!\n", result->strYiaddr); - return; + LOGE("SyncDhcpResult() error, SetLocalInterface yiaddr:%{private}s failed!", result->strYiaddr); + return DHCP_OPT_FAILED; } /* Wirte to the file. */ - WriteDhcpResult(result); + if (WriteDhcpResult(result) != DHCP_OPT_SUCCESS) { + LOGE("SyncDhcpResult() error, WriteDhcpResult result failed!"); + return DHCP_OPT_FAILED; + } + + /* Publish dhcp success result event. */ + if (PublishDhcpResultEvent(g_cltCnf->ifaceName, PUBLISH_CODE_SUCCESS, result) != DHCP_OPT_SUCCESS) { + LOGE("SyncDhcpResult() error, PublishDhcpResultEvent result failed!"); + return DHCP_OPT_FAILED; + } + + LOGI("SyncDhcpResult() handle dhcp result success, ifaceName:%{public}s.", g_cltCnf->ifaceName); + return DHCP_OPT_SUCCESS; } static void ParseDhcpAckPacket(const struct DhcpPacket *packet, time_t timestamp) { if (packet == NULL) { + LOGE("ParseDhcpAckPacket() error, packet == NULL!"); return; } struct DhcpResult dhcpResult; if (memset_s(&dhcpResult, sizeof(struct DhcpResult), 0, sizeof(struct DhcpResult)) != EOK) { + LOGE("ParseDhcpAckPacket() error, memset_s failed!"); return; } @@ -628,45 +881,38 @@ static void ParseDhcpAckPacket(const struct DhcpPacket *packet, time_t timestamp uint32_t u32Data = 0; if (GetDhcpOptionUint32(packet, DHO_LEASETIME, &u32Data)) { g_leaseTime = u32Data; - LOGI("ParseDhcpAckPacket() recv DHCP_ACK 51, lease:%{public}u.\n", g_leaseTime); + LOGI("ParseDhcpAckPacket() recv DHCP_ACK 51, lease:%{public}u.", g_leaseTime); } - g_renewalSec = g_leaseTime * T1; /* First renewal seconds. */ - g_rebindSec = g_leaseTime * T2; /* Second rebind seconds. */ + g_renewalSec = g_leaseTime * RENEWAL_SEC_MULTIPLE; /* First renewal seconds. */ + g_rebindSec = g_leaseTime * REBIND_SEC_MULTIPLE; /* Second rebind seconds. */ g_renewalTimestamp = timestamp; /* Record begin renewing or rebinding timestamp. */ dhcpResult.uOptLeasetime = g_leaseTime; + LOGI("Last get lease:%{public}u,renewal:%{public}u,rebind:%{public}u.", g_leaseTime, g_renewalSec, g_rebindSec); - u32Data = 0; if (!GetDhcpOptionUint32(packet, DHO_SERVERID, &u32Data)) { - LOGW("ParseDhcpAckPacket() GetDhcpOptionUint32 DHO_SERVERID failed!\n"); + LOGE("ParseDhcpAckPacket() GetDhcpOptionUint32 DHO_SERVERID failed!"); } else { g_serverIp4 = htonl(u32Data); - } - - LOGI("recv ACK 51 lease:%{public}u,new:%{public}u,bind:%{public}u.\n", g_leaseTime, g_renewalSec, g_rebindSec); - char *pReqIp = Ip4IntConToStr(g_requestedIp4, false); - if (pReqIp != NULL) { - LOGI("ParseDhcpAckPacket() recv DHCP_ACK yiaddr: %{private}u->%{private}s.\n", ntohl(g_requestedIp4), pReqIp); - if (strncpy_s(dhcpResult.strYiaddr, INET_ADDRSTRLEN, pReqIp, INET_ADDRSTRLEN - 1) != EOK) { - free(pReqIp); - return; - } - free(pReqIp); - } - char *pSerIp = Ip4IntConToStr(g_serverIp4, false); - if (pSerIp != NULL) { - LOGI("ParseDhcpAckPacket() recv DHCP_ACK 54, serid: %{private}u->%{private}s.\n", ntohl(g_serverIp4), pSerIp); - if (strncpy_s(dhcpResult.strOptServerId, INET_ADDRSTRLEN, pSerIp, INET_ADDRSTRLEN - 1) != EOK) { + char *pSerIp = Ip4IntConToStr(g_serverIp4, false); + if (pSerIp != NULL) { + LOGI("ParseDhcpAckPacket() recv DHCP_ACK 54, serid: %{private}u->%{private}s.", u32Data, pSerIp); + if (strncpy_s(dhcpResult.strOptServerId, INET_ADDRSTRLEN, pSerIp, INET_ADDRSTRLEN - 1) != EOK) { + free(pSerIp); + return; + } free(pSerIp); - return; } - free(pSerIp); } /* Parse the specified client process interface network info. */ ParseNetworkInfo(packet, &dhcpResult); /* Sync the specified client process interface network info to the file. */ - SyncDhcpResult(packet, &dhcpResult); + if (SyncDhcpResult(packet, &dhcpResult) != DHCP_OPT_SUCCESS) { + /* Publish dhcp failed result event. */ + PublishDhcpResultEvent(g_cltCnf->ifaceName, PUBLISH_CODE_FAILED, NULL); + return; + } /* Receive dhcp ack packet finished, g_leaseTime * T1 later enter renewing state. */ g_dhcp4State = DHCP_STATE_BOUND; @@ -677,18 +923,18 @@ static void ParseDhcpAckPacket(const struct DhcpPacket *packet, time_t timestamp static void DhcpAckOrNakPacketHandle(uint8_t type, struct DhcpPacket *packet, time_t timestamp) { if ((type != DHCP_ACK) && (type != DHCP_NAK)) { - LOGE("DhcpAckOrNakPacketHandle() type:%{public}d error!\n", type); + LOGE("DhcpAckOrNakPacketHandle() type:%{public}d error!", type); return; } if (packet == NULL) { - LOGE("DhcpAckOrNakPacketHandle() type:%{public}d error, packet == NULL!\n", type); + LOGE("DhcpAckOrNakPacketHandle() type:%{public}d error, packet == NULL!", type); return; } if (type == DHCP_NAK) { /* If receive dhcp nak packet, init g_dhcp4State, resend dhcp discover packet. */ - LOGI("DhcpAckOrNakPacketHandle() receive DHCP_NAK 53, init g_dhcp4State, resend dhcp discover packet!\n"); + LOGI("DhcpAckOrNakPacketHandle() receive DHCP_NAK 53, init g_dhcp4State, resend dhcp discover packet!"); g_dhcp4State = DHCP_STATE_INIT; SetSocketMode(SOCKET_MODE_RAW); g_requestedIp4 = 0; @@ -696,15 +942,20 @@ static void DhcpAckOrNakPacketHandle(uint8_t type, struct DhcpPacket *packet, ti g_timeoutTimestamp = timestamp; /* Avoid excessive network traffic. */ - LOGI("DhcpAckOrNakPacketHandle() receive DHCP_NAK 53, avoid excessive network traffic, need sleep!\n"); + LOGI("DhcpAckOrNakPacketHandle() receive DHCP_NAK 53, avoid excessive network traffic, need sleep!"); sleep(NUMBER_THREE); return; } - LOGI("DhcpAckOrNakPacketHandle() recv DHCP_ACK 53.\n"); + LOGI("DhcpAckOrNakPacketHandle() recv DHCP_ACK 53."); /* Parse received dhcp ack packet. */ ParseDhcpAckPacket(packet, timestamp); + + /* ack packet success. */ + if (g_dhcp4State == DHCP_STATE_BOUND) { + WriteLease(packet); + } } static void DhcpResponseHandle(time_t timestamp) @@ -714,29 +965,29 @@ static void DhcpResponseHandle(time_t timestamp) uint8_t u8Message = 0; if (memset_s(&packet, sizeof(packet), 0, sizeof(packet)) != EOK) { - LOGE("DhcpResponseHandle() memset_s packet failed!\n"); + LOGE("DhcpResponseHandle() memset_s packet failed!"); return; } getLen = (g_socketMode == SOCKET_MODE_RAW) ? GetDhcpRawPacket(&packet, g_sockFd) : GetDhcpKernelPacket(&packet, g_sockFd); if (getLen < 0) { if ((getLen == SOCKET_OPT_ERROR) && (errno != EINTR)) { - LOGE("DhcpResponseHandle() get packet read error, reopening socket!\n"); + LOGE("DhcpResponseHandle() get packet read error, reopening socket!"); /* Reopen g_sockFd. */ SetSocketMode(g_socketMode); } - LOGE("DhcpResponseHandle() get packet failed, error:%{public}s!\n", strerror(errno)); + LOGE("DhcpResponseHandle() get packet failed, error:%{public}s!", strerror(errno)); return; } - LOGI("DhcpResponseHandle() get packet success, getLen:%{public}d.\n", getLen); + LOGI("DhcpResponseHandle() get packet success, getLen:%{public}d.", getLen); /* Check packet data. */ if (packet.xid != g_transID) { - LOGW("DhcpResponseHandle() get xid:%{public}u and g_transID:%{public}u not same!\n", packet.xid, g_transID); + LOGW("DhcpResponseHandle() get xid:%{public}u and g_transID:%{public}u not same!", packet.xid, g_transID); return; } if (!GetDhcpOptionUint8(&packet, DHO_MESSAGETYPE, &u8Message)) { - LOGE("DhcpResponseHandle() GetDhcpOptionUint8 DHO_MESSAGETYPE failed!\n"); + LOGE("DhcpResponseHandle() GetDhcpOptionUint8 DHO_MESSAGETYPE failed!"); return; } @@ -747,12 +998,17 @@ static void DhcpResponseHandle(time_t timestamp) case DHCP_STATE_REQUESTING: case DHCP_STATE_RENEWING: case DHCP_STATE_REBINDING: + case DHCP_STATE_INITREBOOT: case DHCP_STATE_RENEWED: DhcpAckOrNakPacketHandle(u8Message, &packet, timestamp); break; case DHCP_STATE_BOUND: case DHCP_STATE_RELEASED: - LOGW("DhcpResponseHandle() g_dhcp4State is BOUND or RELEASED, ignore all packets!\n"); + LOGW("DhcpResponseHandle() g_dhcp4State is BOUND or RELEASED, ignore all packets!"); + break; + case DHCP_STATE_DECLINE: + g_timeoutTimestamp = timestamp + NUMBER_FIVE; + g_dhcp4State = DHCP_STATE_INIT; break; default: break; @@ -764,25 +1020,26 @@ static void SignalReceiver(void) { int signum; if (read(g_sigSockFds[0], &signum, sizeof(signum)) < 0) { - LOGE("SignalReceiver() failed, g_sigSockFds[0]:%{public}d read error:%{public}s!\n", + LOGE("SignalReceiver() failed, g_sigSockFds[0]:%{public}d read error:%{public}s!", g_sigSockFds[0], strerror(errno)); return; } switch (signum) { case SIGTERM: - LOGW("SignalReceiver() SIGTERM!\n"); + LOGW("SignalReceiver() SIGTERM!"); SetSocketMode(SOCKET_MODE_INVALID); unlink(g_cltCnf->pidFile); unlink(g_cltCnf->resultFile); + unlink(g_cltCnf->result6File); exit(EXIT_SUCCESS); break; case SIGUSR1: - LOGW("SignalReceiver() SIGUSR1!\n"); + LOGW("SignalReceiver() SIGUSR1!"); ExecDhcpRelease(); break; case SIGUSR2: - LOGW("SignalReceiver() SIGUSR2!\n"); + LOGW("SignalReceiver() SIGUSR2!"); ExecDhcpRenew(); break; default: @@ -795,7 +1052,7 @@ static void SignalReceiver(void) int SetIpv4State(int state) { if (state < 0) { - LOGE("SetIpv4State() failed, state:%{public}d!\n", state); + LOGE("SetIpv4State() failed, state:%{public}d!", state); return DHCP_OPT_FAILED; } @@ -808,39 +1065,81 @@ int InitSignalHandle(void) { /* Create signal socket fd. */ if (socketpair(AF_UNIX, SOCK_STREAM, 0, g_sigSockFds) != 0) { - LOGE("InitSignalHandle() failed, socketpair error str:%{public}s!\n", strerror(errno)); + LOGE("InitSignalHandle() failed, socketpair error str:%{public}s!", strerror(errno)); return DHCP_OPT_FAILED; } /* Register signal handlers. */ if (signal(SIGTERM, SignalHandler) == SIG_ERR) { - LOGE("InitSignalHandle() failed, signal SIGTERM error str:%{public}s!\n", strerror(errno)); + LOGE("InitSignalHandle() failed, signal SIGTERM error str:%{public}s!", strerror(errno)); return DHCP_OPT_FAILED; } if (signal(SIGUSR1, SignalHandler) == SIG_ERR) { - LOGE("InitSignalHandle() failed, signal SIGUSR1 error str:%{public}s!\n", strerror(errno)); + LOGE("InitSignalHandle() failed, signal SIGUSR1 error str:%{public}s!", strerror(errno)); return DHCP_OPT_FAILED; } if (signal(SIGUSR2, SignalHandler) == SIG_ERR) { - LOGE("InitSignalHandle() failed, signal SIGUSR2 error str:%{public}s!\n", strerror(errno)); + LOGE("InitSignalHandle() failed, signal SIGUSR2 error str:%{public}s!", strerror(errno)); return DHCP_OPT_FAILED; } return DHCP_OPT_SUCCESS; } +extern bool PublishDhcpIpv4ResultEvent(const int code, const char *data, const char *ifname); +int PublishDhcpResultEvent(const char *ifname, const int code, struct DhcpResult *result) +{ + if (ifname == NULL) { + LOGE("PublishDhcpResultEvent() failed, ifname == NULL!"); + return DHCP_OPT_FAILED; + } + if ((code != PUBLISH_CODE_SUCCESS) && (code != PUBLISH_CODE_FAILED)) { + LOGE("PublishDhcpResultEvent() ifname:%{public}s failed, code:%{public}d error!", ifname, code); + return DHCP_OPT_FAILED; + } + if ((code == PUBLISH_CODE_SUCCESS) && (result == NULL)) { + LOGE("PublishDhcpResultEvent() ifname:%{public}s,code:%{public}d failed, result == NULL!", ifname, code); + return DHCP_OPT_FAILED; + } + + /* Data format - ipv4:ifname,time,cliIp,lease,servIp,subnet,dns1,dns2,router1,router2,vendor */ + int nBytes; + uint32_t curTime = (uint32_t)time(NULL); + char strData[STRING_MAX_LEN] = {0}; + if (code == PUBLISH_CODE_SUCCESS) { + nBytes = snprintf_s(strData, STRING_MAX_LEN, STRING_MAX_LEN - 1, "ipv4:%s,%u,%s,%u,%s,%s,%s,%s,%s,%s,%s", + ifname, curTime, result->strYiaddr, result->uOptLeasetime, result->strOptServerId, result->strOptSubnet, + result->strOptDns1, result->strOptDns2, result->strOptRouter1, result->strOptRouter2, result->strOptVendor); + } else { + nBytes = snprintf_s(strData, STRING_MAX_LEN, STRING_MAX_LEN - 1, "ipv4:%s,%u,*,*,*,*,*,*,*,*,*", + ifname, curTime); + } + if (nBytes < 0) { + LOGE("PublishDhcpResultEvent() failed, snprintf_s %{public}s error:%{public}s!", ifname, strerror(errno)); + return DHCP_OPT_FAILED; + } + + if (!PublishDhcpIpv4ResultEvent(code, strData, ifname)) { + LOGE("PublishDhcpResultEvent() PublishDhcpIpv4ResultEvent %{public}d %{public}s failed!", code, strData); + return DHCP_OPT_FAILED; + } + LOGI("PublishDhcpResultEvent() PublishDhcpIpv4ResultEvent %{public}d %{private}s success.", code, strData); + return DHCP_OPT_SUCCESS; +} + int GetPacketHeaderInfo(struct DhcpPacket *packet, uint8_t type) { if (packet == NULL) { - LOGE("GetPacketHeaderInfo() failed, packet == NULL!\n"); + LOGE("GetPacketHeaderInfo() failed, packet == NULL!"); return DHCP_OPT_FAILED; } switch (type) { case DHCP_DISCOVER: case DHCP_REQUEST: + case DHCP_DECLINE: case DHCP_RELEASE: case DHCP_INFORM: packet->op = BOOT_REQUEST; @@ -865,13 +1164,13 @@ int GetPacketHeaderInfo(struct DhcpPacket *packet, uint8_t type) int GetPacketCommonInfo(struct DhcpPacket *packet) { if (packet == NULL) { - LOGE("GetPacketCommonInfo() failed, packet == NULL!\n"); + LOGE("GetPacketCommonInfo() failed, packet == NULL!"); return DHCP_OPT_FAILED; } /* Add packet client_cfg info. */ if (memcpy_s(packet->chaddr, sizeof(packet->chaddr), g_cltCnf->ifaceMac, MAC_ADDR_LEN) != EOK) { - LOGE("GetPacketCommonInfo() failed, memcpy_s error!\n"); + LOGE("GetPacketCommonInfo() failed, memcpy_s error!"); return DHCP_OPT_FAILED; } int nClientIdLen = DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + g_cltCnf->pOptClientId[DHCP_OPT_LEN_INDEX]; @@ -888,14 +1187,14 @@ int GetPacketCommonInfo(struct DhcpPacket *packet) DHCPC_NAME, DHCPC_VERSION); if (nRes < 0) { - LOGE("GetPacketCommonInfo() failed, snprintf_s res:%{public}d error!\n", nRes); + LOGE("GetPacketCommonInfo() failed, snprintf_s res:%{public}d error!", nRes); return DHCP_OPT_FAILED; } pVendorId[DHCP_OPT_CODE_INDEX] = DHO_VENDOR; pVendorId[DHCP_OPT_LEN_INDEX] = strlen(buf); if (strncpy_s((char *)pVendorId + DHCP_OPT_DATA_INDEX, VENDOR_MAX_LEN - DHCP_OPT_DATA_INDEX, buf, strlen(buf)) != EOK) { - LOGE("GetPacketCommonInfo() failed, strncpy_s error!\n"); + LOGE("GetPacketCommonInfo() failed, strncpy_s error!"); return DHCP_OPT_FAILED; } if (strlen((char *)vendorId) > 0) { @@ -909,7 +1208,7 @@ int GetPacketCommonInfo(struct DhcpPacket *packet) /* Broadcast dhcp discover packet, discover dhcp servers that can provide ip address. */ int DhcpDiscover(uint32_t transid, uint32_t requestip) { - LOGI("DhcpDiscover() enter, transid:%{public}u,requestip:%{private}u.\n", transid, requestip); + LOGI("DhcpDiscover() enter, transid:%{public}u,requestip:%{private}u.", transid, requestip); struct DhcpPacket packet; if (memset_s(&packet, sizeof(struct DhcpPacket), 0, sizeof(struct DhcpPacket)) != EOK) { @@ -930,14 +1229,14 @@ int DhcpDiscover(uint32_t transid, uint32_t requestip) AddParamaterRequestList(&packet); /* Begin broadcast dhcp discover packet. */ - LOGI("DhcpDiscover() discover, begin broadcast discover packet...\n"); + LOGI("DhcpDiscover() discover, begin broadcast discover packet..."); return SendToDhcpPacket(&packet, INADDR_ANY, INADDR_BROADCAST, g_cltCnf->ifaceIndex, (uint8_t *)MAC_BCAST_ADDR); } /* Broadcast dhcp request packet, tell dhcp servers that which ip address to choose. */ int DhcpRequest(uint32_t transid, uint32_t reqip, uint32_t servip) { - LOGI("DhcpRequest() enter, transid:%{public}u,reqip:%{private}u.\n", transid, reqip); + LOGI("DhcpRequest() enter, transid:%{public}u,reqip:%{private}u.", transid, reqip); struct DhcpPacket packet; if (memset_s(&packet, sizeof(struct DhcpPacket), 0, sizeof(struct DhcpPacket)) != EOK) { @@ -959,12 +1258,12 @@ int DhcpRequest(uint32_t transid, uint32_t reqip, uint32_t servip) /* Begin broadcast dhcp request packet. */ char *pReqIp = Ip4IntConToStr(reqip, false); if (pReqIp != NULL) { - LOGI("DhcpRequest() broadcast req packet, reqip: host %{private}u->%{private}s.\n", ntohl(reqip), pReqIp); + LOGI("DhcpRequest() broadcast req packet, reqip: host %{private}u->%{private}s.", ntohl(reqip), pReqIp); free(pReqIp); } char *pSerIp = Ip4IntConToStr(servip, false); if (pSerIp != NULL) { - LOGI("DhcpRequest() broadcast req packet, servIp: host %{private}u->%{private}s.\n", ntohl(servip), pSerIp); + LOGI("DhcpRequest() broadcast req packet, servIp: host %{private}u->%{private}s.", ntohl(servip), pSerIp); free(pSerIp); } return SendToDhcpPacket(&packet, INADDR_ANY, INADDR_BROADCAST, g_cltCnf->ifaceIndex, (uint8_t *)MAC_BCAST_ADDR); @@ -973,7 +1272,7 @@ int DhcpRequest(uint32_t transid, uint32_t reqip, uint32_t servip) /* Unicast or broadcast dhcp request packet, request to extend the lease from the dhcp server. */ int DhcpRenew(uint32_t transid, uint32_t clientip, uint32_t serverip) { - LOGI("DhcpRenew() enter, transid:%{public}u,clientip:%{private}u.\n", transid, clientip); + LOGI("DhcpRenew() enter, transid:%{public}u,clientip:%{private}u.", transid, clientip); struct DhcpPacket packet; if (memset_s(&packet, sizeof(struct DhcpPacket), 0, sizeof(struct DhcpPacket)) != EOK) { @@ -995,17 +1294,17 @@ int DhcpRenew(uint32_t transid, uint32_t clientip, uint32_t serverip) struct in_addr serverAddr; serverAddr.s_addr = serverip; if (serverip == 0) { - LOGI("DhcpRenew() rebind, begin broadcast req packet, serverip:%{private}s...\n", inet_ntoa(serverAddr)); + LOGI("DhcpRenew() rebind, begin broadcast req packet, serverip:%{private}s...", inet_ntoa(serverAddr)); return SendToDhcpPacket(&packet, INADDR_ANY, INADDR_BROADCAST, g_cltCnf->ifaceIndex, (uint8_t *)MAC_BCAST_ADDR); } - LOGI("DhcpRenew() renew, begin unicast request packet, serverip:%{private}s...\n", inet_ntoa(serverAddr)); + LOGI("DhcpRenew() renew, begin unicast request packet, serverip:%{private}s...", inet_ntoa(serverAddr)); return SendDhcpPacket(&packet, clientip, serverip); } /* Unicast dhcp release packet, releasing an ip address in Use from the dhcp server. */ int DhcpRelease(uint32_t clientip, uint32_t serverip) { - LOGI("DhcpRelease() enter, clientip:%{private}u.\n", clientip); + LOGI("DhcpRelease() enter, clientip:%{private}u.", clientip); struct DhcpPacket packet; if (memset_s(&packet, sizeof(struct DhcpPacket), 0, sizeof(struct DhcpPacket)) != EOK) { @@ -1028,10 +1327,27 @@ int DhcpRelease(uint32_t clientip, uint32_t serverip) requestAddr.s_addr = clientip; serverAddr.s_addr = serverip; LOGI("DhcpRelease() release, begin unicast release packet, clientip:%{private}s,", inet_ntoa(requestAddr)); - LOGI("serverip:%{private}s...\n", inet_ntoa(serverAddr)); + LOGI("serverip:%{private}s...", inet_ntoa(serverAddr)); return SendDhcpPacket(&packet, clientip, serverip); } +static void DhcpInit(void) +{ + g_cltCnf = GetDhcpClientCfg(); + + /* Init dhcp ipv4 state. */ + g_dhcp4State = DHCP_STATE_INIT; + SetSocketMode(SOCKET_MODE_RAW); + + InitSocketFd(); + + time_t t = time(NULL); + if (t == (time_t)-1) { + return; + } + Reboot(t); +} + int StartIpv4(void) { int nRet, nMaxFds; @@ -1039,15 +1355,11 @@ int StartIpv4(void) struct timeval timeout; time_t curTimestamp; - g_cltCnf = GetDhcpClientCfg(); - - /* Init dhcp ipv4 state. */ - g_dhcp4State = DHCP_STATE_INIT; - SetSocketMode(SOCKET_MODE_RAW); + DhcpInit(); for (; ;) { if (g_cltCnf->timeoutExit) { - LOGW("StartIpv4() send packet timed out, now break!\n"); + LOGW("StartIpv4() send packet timed out, now break!"); break; } @@ -1063,18 +1375,18 @@ int StartIpv4(void) FD_SET(g_sigSockFds[0], &exceptfds); if (timeout.tv_sec <= 0) { - LOGI("StartIpv4() already timed out, need send or resend packet...\n"); + LOGI("StartIpv4() already timed out, need send or resend packet..."); nRet = 0; } else { - LOGI("StartIpv4() waiting on select...\n"); + LOGI("StartIpv4() waiting on select..."); nMaxFds = (g_sigSockFds[0] > g_sockFd) ? g_sigSockFds[0] : g_sockFd; nRet = select(nMaxFds + 1, &exceptfds, NULL, NULL, &timeout); } if (nRet < 0) { if ((nRet == -1) && (errno == EINTR)) { - LOGW("StartIpv4() select err:%{public}s, a signal was caught!\n", strerror(errno)); + LOGW("StartIpv4() select err:%{public}s, a signal was caught!", strerror(errno)); } else { - LOGE("StartIpv4() failed, select maxFds:%{public}d error:%{public}s!\n", nMaxFds, strerror(errno)); + LOGE("StartIpv4() failed, select maxFds:%{public}d error:%{public}s!", nMaxFds, strerror(errno)); } continue; } @@ -1087,7 +1399,7 @@ int StartIpv4(void) } else if (FD_ISSET(g_sigSockFds[0], &exceptfds)) { SignalReceiver(); } else { - LOGW("StartIpv4() nRet:%{public}d, g_socketMode:%{public}d, continue select...\n", nRet, g_socketMode); + LOGW("StartIpv4() nRet:%{public}d, g_socketMode:%{public}d, continue select...", nRet, g_socketMode); } } return g_cltCnf->timeoutExit ? StopProcess(g_cltCnf->pidFile) : DHCP_OPT_SUCCESS; diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_main.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_main.c index 045d2c3f8..cad92ae81 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_main.c +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_main.c @@ -52,11 +52,10 @@ static int Usage(void) printf(" help - displays usage info, INTERFACE is optional\n"); printf(" ver - displays client version, INTERFACE is optional\n"); printf(" INTERFACE = ifname, eg: wlan0\n"); - printf(" OPTION = -w |-a or -4 or -6\n"); + printf(" OPTION = -w |-a or -4\n"); printf(" -w - specify the client's working directory\n"); printf(" -a - handle dhcp v4 and v6\n"); printf(" -4 - only handle dhcp v4\n"); - printf(" -6 - only handle dhcp v6\n"); printf("\n========== running process operate ==========\n"); printf(" send dhcp release packet = kill -USR1 \n"); printf(" send dhcp renew packet = kill -USR2 \n\n"); @@ -66,12 +65,12 @@ static int Usage(void) static int RunChildProcess(void) { if (setpgrp() == -1) { - LOGE("RunChildProcess() can not change process group, return!\n"); + LOGE("RunChildProcess() can not change process group, return!"); return DHCP_OPT_FAILED; } if (signal(SIGHUP, SIG_IGN) == SIG_ERR) { - LOGE("RunChildProcess() signal SIGHUP SIG_ERR, return!\n"); + LOGE("RunChildProcess() signal SIGHUP SIG_ERR, return!"); return DHCP_OPT_FAILED; } @@ -79,7 +78,7 @@ static int RunChildProcess(void) pid_t childPid; switch (childPid = fork()) { case -1: - LOGE("RunChildProcess() fork grandchild failed, return!\n"); + LOGE("RunChildProcess() fork grandchild failed, return!"); return DHCP_OPT_FAILED; case 0: /* Grandchild process continue run. */ @@ -88,32 +87,32 @@ static int RunChildProcess(void) /* Child process exit now. */ exit(EXIT_SUCCESS); } - LOGI("RunChildProcess() child: fork grand suc, childPid:%{public}d,pid():%{public}d,ppid():%{public}d.\n", + LOGI("RunChildProcess() child: fork grand suc, childPid:%{public}d,pid():%{public}d,ppid():%{public}d.", childPid, getpid(), getppid()); return DHCP_OPT_SUCCESS; } static int CreateDaemon(void) { - LOGI("CreateDaemon() enter, pid:%{public}d, ppid:%{public}d.\n", getpid(), getppid()); + LOGI("CreateDaemon() enter, pid:%{public}d, ppid:%{public}d.", getpid(), getppid()); /* A daemon process need close all open files. */ if (fclose(stdin) != 0) { - LOGE("CreateDaemon() fclose stdin error:%{public}s!\n", strerror(errno)); + LOGE("CreateDaemon() fclose stdin error:%{public}s!", strerror(errno)); return DHCP_OPT_FAILED; } if (fclose(stdout) != 0) { - LOGE("CreateDaemon() fclose stdout error:%{public}s!\n", strerror(errno)); + LOGE("CreateDaemon() fclose stdout error:%{public}s!", strerror(errno)); return DHCP_OPT_FAILED; } if (fclose(stderr) != 0) { - LOGE("CreateDaemon() fclose stderr error:%{public}s!\n", strerror(errno)); + LOGE("CreateDaemon() fclose stderr error:%{public}s!", strerror(errno)); return DHCP_OPT_FAILED; } /* Ensure that the process is not a fork subprocess, init process id is 1. */ if (getppid() == 1) { - LOGI("CreateDaemon() getppid() == 1, the process's parent is already init process!\n"); + LOGI("CreateDaemon() getppid() == 1, the process's parent is already init process!"); /* Set default permissions for files and directories. */ umask(DEFAULT_UMASK); return DHCP_OPT_SUCCESS; @@ -122,11 +121,11 @@ static int CreateDaemon(void) pid_t pid; switch (pid = fork()) { case -1: - LOGE("CreateDaemon() fork first child failed, return!\n"); + LOGE("CreateDaemon() fork first child failed, return!"); return DHCP_OPT_FAILED; case 0: if (RunChildProcess() != DHCP_OPT_SUCCESS) { - LOGE("CreateDaemon() RunChildProcess failed, return!\n"); + LOGE("CreateDaemon() RunChildProcess failed, return!"); return DHCP_OPT_FAILED; }; /* Child process continue run. */ @@ -137,7 +136,7 @@ static int CreateDaemon(void) } /* We have forked, setpgrp, forked once more, from now on, we are a daemon process. */ - LOGI("CreateDaemon() grandchild continue run, pid:%{public}d,getpid():%{public}d,getppid():%{public}d.\n", + LOGI("CreateDaemon() grandchild continue run, pid:%{public}d,getpid():%{public}d,getppid():%{public}d.", pid, getpid(), getppid()); umask(DEFAULT_UMASK); return DHCP_OPT_SUCCESS; @@ -183,7 +182,7 @@ static int GetClientOption(int argc, char *argv[]) while ((ch = getopt(argc - NUMBER_TWO, argv + NUMBER_TWO, "w:a46")) != -1) { switch (ch) { case 'w': /* Specify the client's working directory. */ - LOGI("GetClientOption() cur workDir:%{public}s, optarg:%{public}s\n", g_cltCfg->workDir, optarg); + LOGI("GetClientOption() cur workDir:%{public}s, optarg:%{public}s", g_cltCfg->workDir, optarg); if (strncpy_s(g_cltCfg->workDir, sizeof(g_cltCfg->workDir), optarg, DIR_MAX_LEN - 1) != EOK) { return -1; } @@ -192,7 +191,7 @@ static int GetClientOption(int argc, char *argv[]) g_cltCfg->getMode = DHCP_IP_TYPE_ALL; break; case '4': /* Only handle dhcp v4. */ - LOGI("GetClientOption() cur getMode:%{public}u, optarg:%{public}s\n", g_cltCfg->getMode, optarg); + LOGI("GetClientOption() cur getMode:%{public}u, optarg:%{public}s", g_cltCfg->getMode, optarg); g_cltCfg->getMode = DHCP_IP_TYPE_V4; break; case '6': /* Only handle dhcp v6. */ @@ -216,16 +215,16 @@ static int InitSpecifiedClientCfg(int argc, char *argv[]) } g_cltCfg->getMode = DHCP_IP_TYPE_ALL; if ((argc > NUMBER_THREE) && (GetClientOption(argc, argv) != 0)) { - LOGE("InitSpecifiedClientCfg() GetClientOption failed!\n"); + LOGE("InitSpecifiedClientCfg() GetClientOption failed!"); return DHCP_OPT_FAILED; } if (strlen(g_cltCfg->workDir) == 0) { - LOGE("InitSpecifiedClientCfg() g_cltCfg->workDir:%{public}s error!\n", g_cltCfg->workDir); + LOGE("InitSpecifiedClientCfg() g_cltCfg->workDir:%{public}s error!", g_cltCfg->workDir); return DHCP_OPT_FAILED; } if (CreateDirs(g_cltCfg->workDir, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != DHCP_OPT_SUCCESS) { - LOGE("InitSpecifiedClientCfg() CreateDirs %{public}s failed!\n", g_cltCfg->workDir); + LOGE("InitSpecifiedClientCfg() CreateDirs %{public}s failed!", g_cltCfg->workDir); return DHCP_OPT_FAILED; } @@ -242,9 +241,14 @@ static int InitSpecifiedClientCfg(int argc, char *argv[]) if (n < 0) { return DHCP_OPT_FAILED; } + n = snprintf_s( + g_cltCfg->leaseFile, DIR_MAX_LEN, DIR_MAX_LEN - 1, "%s"DHCPC_LEASE, g_cltCfg->workDir, g_cltCfg->ifaceName); + if (n < 0) { + return DHCP_OPT_FAILED; + } LOGI("InitSpecifiedClientCfg() " "g_cltCfg->workDir:%{public}s,confFile:%{public}s,pidFile:%{public}s,resultFile:%{public}s, " - "getMode:%{public}d\n", + "getMode:%{public}d", g_cltCfg->workDir, g_cltCfg->confFile, g_cltCfg->pidFile, @@ -258,9 +262,9 @@ static int ExecClientProAction(const char *action) /* Stop the specified network interface service. */ if (strncasecmp(action, "stop", NUMBER_FOUR) == 0) { if (StopProcess(g_cltCfg->pidFile) != DHCP_OPT_SUCCESS) { - LOGI("ExecClientProAction() StopProcess pidFile:%{public}s not success.\n", g_cltCfg->pidFile); + LOGI("ExecClientProAction() StopProcess pidFile:%{public}s not success.", g_cltCfg->pidFile); } else { - LOGI("ExecClientProAction() StopProcess pidFile:%{public}s success.\n", g_cltCfg->pidFile); + LOGI("ExecClientProAction() StopProcess pidFile:%{public}s success.", g_cltCfg->pidFile); } return 1; } @@ -268,30 +272,30 @@ static int ExecClientProAction(const char *action) /* Get the specified client process running status. */ int proStatus = GetProStatus(g_cltCfg->pidFile); if (strncasecmp(action, "status", NUMBER_FIVE) == 0) { - LOGI("ExecClientProAction() action:%{public}s GetProStatus proStatus:%{public}d.\n", action, proStatus); + LOGI("ExecClientProAction() action:%{public}s GetProStatus proStatus:%{public}d.", action, proStatus); return 1; } /* Check the specified client process param ACTION. */ if (strncasecmp(action, "start", NUMBER_FIVE) != 0) { - LOGE("ExecClientProAction() argv[1]:%{public}s error, please input valid ACTION!\n", action); + LOGE("ExecClientProAction() argv[1]:%{public}s error, please input valid ACTION!", action); Usage(); return -1; } if (proStatus == 1) { - LOGI("ExecClientProAction() the specified client process is already started!\n"); + LOGI("ExecClientProAction() the specified client process is already started!"); return 1; } /* Create a daemon process. */ if (CreateDaemon() != DHCP_OPT_SUCCESS) { - LOGE("ExecClientProAction() CreateDaemon failed!\n"); + LOGE("ExecClientProAction() CreateDaemon failed!"); return -1; } /* Init the specified client process id info. */ if (InitPidfile(g_cltCfg->workDir, g_cltCfg->pidFile, getpid()) != DHCP_OPT_SUCCESS) { - LOGE("ExecClientProAction() InitPidfile failed, ifaceName:%{public}s.\n", g_cltCfg->ifaceName); + LOGE("ExecClientProAction() InitPidfile failed, ifaceName:%{public}s.", g_cltCfg->ifaceName); return -1; } @@ -301,7 +305,7 @@ static int ExecClientProAction(const char *action) static int GetClientNetworkInfo(void) { if (GetLocalInterface(g_cltCfg->ifaceName, &g_cltCfg->ifaceIndex, g_cltCfg->ifaceMac, NULL) != DHCP_OPT_SUCCESS) { - LOGE("GetClientNetworkInfo() GetLocalInterface failed, ifaceName:%{public}s.\n", g_cltCfg->ifaceName); + LOGE("GetClientNetworkInfo() GetLocalInterface failed, ifaceName:%{public}s.", g_cltCfg->ifaceName); return DHCP_OPT_FAILED; } char macAddr[MAC_ADDR_LEN * MAC_ADDR_CHAR_NUM]; @@ -309,19 +313,19 @@ static int GetClientNetworkInfo(void) return DHCP_OPT_FAILED; } MacChConToMacStr(g_cltCfg->ifaceMac, MAC_ADDR_LEN, macAddr, sizeof(macAddr)); - LOGI("GetClientNetworkInfo() g_cltCfg->ifaceName:%{public}s -> ifaceIndex:%{private}d,ifaceMac:%{private}s.\n", + LOGI("GetClientNetworkInfo() g_cltCfg->ifaceName:%{public}s -> ifaceIndex:%{private}d,ifaceMac:%{private}s.", g_cltCfg->ifaceName, g_cltCfg->ifaceIndex, macAddr); if (GetLocalIp(g_cltCfg->ifaceName, &g_cltCfg->ifaceIpv4) != DHCP_OPT_SUCCESS) { - LOGE("GetClientNetworkInfo() failed, g_cltCfg->ifaceName:%{public}s.\n", g_cltCfg->ifaceName); + LOGE("GetClientNetworkInfo() failed, g_cltCfg->ifaceName:%{public}s.", g_cltCfg->ifaceName); return DHCP_OPT_FAILED; } char *cIp = Ip4IntConToStr(g_cltCfg->ifaceIpv4, true); if (cIp == NULL) { - LOGE("GetClientNetworkInfo() Ip4IntConToStr g_cltCfg->ifaceIpv4 failed!\n"); + LOGE("GetClientNetworkInfo() Ip4IntConToStr g_cltCfg->ifaceIpv4 failed!"); return DHCP_OPT_FAILED; } - LOGI("GetClientNetworkInfo() GetLocalIp ifaceName:%{public}s -> ifaceIpv4:%{private}u - %{private}s.\n", + LOGI("GetClientNetworkInfo() GetLocalIp ifaceName:%{public}s -> ifaceIpv4:%{private}u - %{private}s.", g_cltCfg->ifaceName, g_cltCfg->ifaceIpv4, cIp); free(cIp); @@ -329,7 +333,7 @@ static int GetClientNetworkInfo(void) if (g_cltCfg->pOptClientId == NULL) { g_cltCfg->pOptClientId = malloc(DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + MAC_ADDR_LEN + 1); if (g_cltCfg->pOptClientId == NULL) { - LOGE("GetClientNetworkInfo() g_cltCfg->pOptClientId malloc failed!\n"); + LOGE("GetClientNetworkInfo() g_cltCfg->pOptClientId malloc failed!"); return DHCP_OPT_FAILED; } g_cltCfg->pOptClientId[DHCP_OPT_CODE_INDEX] = DHO_CLIENTID; @@ -357,7 +361,7 @@ int main(int argc, char *argv[]) /* Init the specified client process config. */ if (InitSpecifiedClientCfg(argc, argv) != DHCP_OPT_SUCCESS) { - LOGE("main() InitSpecifiedClientCfg failed!\n"); + LOGE("main() InitSpecifiedClientCfg failed!"); return EXIT_FAILURE; } @@ -370,16 +374,16 @@ int main(int argc, char *argv[]) /* Get the specified client process interface network info. */ if (GetClientNetworkInfo() != DHCP_OPT_SUCCESS) { - LOGE("main() GetClientNetworkInfo failed!\n"); + LOGE("main() GetClientNetworkInfo failed!"); return EXIT_FAILURE; } /* Start the specified network interface service. */ if (StartProcess() != DHCP_OPT_SUCCESS) { - LOGE("main() StartProcess failed!\n"); + LOGE("main() StartProcess failed!"); return EXIT_FAILURE; } - LOGI("main() end, argc:%{public}d.\n", argc); + LOGI("main() end, argc:%{public}d.", argc); return EXIT_SUCCESS; } diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_options.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_options.c index a477a2839..3958d4f0f 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_options.c +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_options.c @@ -27,13 +27,13 @@ static bool CheckOptSoverloaded(const struct DhcpPacket *packet, int code, int maxLen, int *over, int *index) { if (packet == NULL) { - LOGE("CheckOptSoverloaded failed, packet == NULL!\n"); + LOGE("CheckOptSoverloaded failed, packet == NULL!"); return false; } const uint8_t *pOption = packet->options; if (*index + DHCP_OPT_LEN_INDEX + pOption[*index + DHCP_OPT_LEN_INDEX] >= maxLen) { - LOGW("CheckOptSoverloaded code:%{public}d,*index:%{public}d more than max bytes:%{public}d!\n", + LOGW("CheckOptSoverloaded code:%{public}d,*index:%{public}d more than max bytes:%{public}d!", code, *index, maxLen); return false; } @@ -46,12 +46,12 @@ static bool CheckOptSoverloaded(const struct DhcpPacket *packet, int code, int m static int CheckOptionsData(const struct DhcpPacket *packet, int code, int index, int maxLen) { if (packet == NULL) { - LOGE("CheckOptionsData failed, packet == NULL!\n"); + LOGE("CheckOptionsData failed, packet == NULL!"); return DHCP_OPT_FAILED; } if (index >= maxLen) { - LOGW("CheckOptionsData code:%{public}d,index:%{public}d more than max bytes:%{public}d!\n", + LOGW("CheckOptionsData code:%{public}d,index:%{public}d more than max bytes:%{public}d!", code, index, maxLen); return DHCP_OPT_FAILED; } @@ -62,7 +62,7 @@ static int CheckOptionsData(const struct DhcpPacket *packet, int code, int index } if (index + DHCP_OPT_LEN_INDEX + pOption[index + DHCP_OPT_LEN_INDEX] >= maxLen) { - LOGW("CheckOptionsData failed, options data too long, code:%{public}d,index:%{public}d!\n", code, index); + LOGW("CheckOptionsData failed, options data too long, code:%{public}d,index:%{public}d!", code, index); return DHCP_OPT_FAILED; } @@ -73,16 +73,18 @@ static int CheckOptionsData(const struct DhcpPacket *packet, int code, int index static uint8_t GetDhcpOptionCodeType(const uint8_t code) { if ((code <= DHO_PAD) || (code >= DHO_END)) { - LOGE("GetDhcpOptionCodeType error, code:%{public}d is error!\n", code); + LOGE("GetDhcpOptionCodeType error, code:%{public}d is error!", code); return DHCP_OPTION_DATA_INVALID; } uint8_t nDataType = DHCP_OPTION_DATA_INVALID; switch (code) { case DHO_MESSAGETYPE: + case DHO_FORCERENEW_NONCE: nDataType = DHCP_OPTION_DATA_U8; break; case DHO_MTU: + case DHO_MAXMESSAGESIZE: nDataType = DHCP_OPTION_DATA_U16; break; case DHO_LEASETIME: @@ -105,7 +107,7 @@ static uint8_t GetDhcpOptionCodeType(const uint8_t code) nDataType = DHCP_OPTION_DATA_IP_STRING; break; default: - LOGE("GetDhcpOptionCodeType failed, code:%{public}d is invalid!\n", code); + LOGE("GetDhcpOptionCodeType failed, code:%{public}d is invalid!", code); break; } @@ -117,7 +119,7 @@ uint8_t GetDhcpOptionDataLen(const uint8_t code) { uint8_t nDataType = GetDhcpOptionCodeType(code); if (nDataType == DHCP_OPTION_DATA_INVALID) { - LOGE("GetDhcpOptionDataLen code:%{public}d error, GetDhcpOptionCodeType invalid!\n", code); + LOGE("GetDhcpOptionDataLen code:%{public}d error, GetDhcpOptionCodeType invalid!", code); return 0; } @@ -139,7 +141,7 @@ uint8_t GetDhcpOptionDataLen(const uint8_t code) nDataLen = DHCP_UINT32_DOUBLE_BYTES; break; default: - LOGE("GetDhcpOptionDataLen code:%{public}d failed, nDataType:%{public}d is invalid!\n", + LOGE("GetDhcpOptionDataLen code:%{public}d failed, nDataType:%{public}d is invalid!", code, nDataType); break; } @@ -152,7 +154,7 @@ const uint8_t *GetDhcpOption(const struct DhcpPacket *packet, int code, size_t * { *length = 0; if (packet == NULL) { - LOGE("GetDhcpOption failed, packet == NULL!\n"); + LOGE("GetDhcpOption failed, packet == NULL!"); return NULL; } @@ -196,7 +198,7 @@ const uint8_t *GetDhcpOption(const struct DhcpPacket *packet, int code, size_t * break; } } - LOGW("GetDhcpOption options no find code:%{public}d, nIndex:%{public}d!\n", code, nIndex); + LOGW("GetDhcpOption options no find code:%{public}d, nIndex:%{public}d!", code, nIndex); return NULL; } @@ -206,15 +208,15 @@ bool GetDhcpOptionUint8(const struct DhcpPacket *packet, int code, uint8_t *data size_t len = 0; const uint8_t *p = GetDhcpOption(packet, code, &len); if (p == NULL) { - LOGW("GetDhcpOptionUint8 GetDhcpOption NULL, code:%{public}d!\n", code); + LOGW("GetDhcpOptionUint8 GetDhcpOption NULL, code:%{public}d!", code); return false; } if (len < (ssize_t)sizeof(uint8_t)) { - LOGE("GetDhcpOptionUint8 failed, len:%{public}zu less data:%{public}zu, code:%{public}d!\n", + LOGE("GetDhcpOptionUint8 failed, len:%{public}zu less data:%{public}zu, code:%{public}d!", len, sizeof(uint8_t), code); return false; } - if (memcpy_s(data, sizeof(data), p, sizeof(uint8_t)) != EOK) { + if (memcpy_s(data, sizeof(uint8_t), p, sizeof(uint8_t)) != EOK) { return false; } return true; @@ -226,12 +228,12 @@ bool GetDhcpOptionUint32(const struct DhcpPacket *packet, int code, uint32_t *da size_t len = 0; const uint8_t *p = GetDhcpOption(packet, code, &len); if (p == NULL) { - LOGW("GetDhcpOptionUint32 GetDhcpOption NULL, code:%{public}d!\n", code); + LOGW("GetDhcpOptionUint32 GetDhcpOption NULL, code:%{public}d!", code); return false; } uint32_t uData = 0; if (len < (ssize_t)sizeof(uData)) { - LOGE("GetDhcpOptionUint32 failed, len:%{public}zu less uData:%{public}zu, code:%{public}d!\n", + LOGE("GetDhcpOptionUint32 failed, len:%{public}zu less uData:%{public}zu, code:%{public}d!", len, sizeof(uData), code); return false; } @@ -250,12 +252,12 @@ bool GetDhcpOptionUint32n(const struct DhcpPacket *packet, int code, uint32_t *d size_t len = 0; const uint8_t *p = GetDhcpOption(packet, code, &len); if (p == NULL) { - LOGW("GetDhcpOptionUint32n GetDhcpOption NULL, code:%{public}d!\n", code); + LOGW("GetDhcpOptionUint32n GetDhcpOption NULL, code:%{public}d!", code); return false; } uint32_t uData = 0; if ((len < (ssize_t)sizeof(uData)) || (len % (ssize_t)sizeof(uData) != 0)) { - LOGE("GetDhcpOptionUint32n failed, len:%{public}zu is not %{public}zu * n, code:%{public}d!\n", + LOGE("GetDhcpOptionUint32n failed, len:%{public}zu is not %{public}zu * n, code:%{public}d!", len, sizeof(uData), code); return false; } @@ -284,11 +286,11 @@ char *GetDhcpOptionString(const struct DhcpPacket *packet, int code) size_t len; const uint8_t *p = GetDhcpOption(packet, code, &len); if ((p == NULL) || (*p == '\0')) { - LOGW("GetDhcpOptionString GetDhcpOption NULL, code:%{public}d!\n", code); + LOGW("GetDhcpOptionString GetDhcpOption NULL, code:%{public}d!", code); return NULL; } if (len < (ssize_t)sizeof(uint8_t)) { - LOGE("GetDhcpOptionString failed, len:%{public}zu less data:%{public}zu, code:%{public}d!\n", + LOGE("GetDhcpOptionString failed, len:%{public}zu less data:%{public}zu, code:%{public}d!", len, sizeof(uint8_t), code); return NULL; } @@ -323,18 +325,18 @@ int AddOptStrToOpts(uint8_t *pOpts, uint8_t *pOpt, int nOptLen) { int optStrLen = DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + pOpt[DHCP_OPT_LEN_INDEX]; if (nOptLen != optStrLen) { - LOGE("AddOptStrToOpts() code:%{public}u nOptLen:%{public}d no equal optStrLen:%{public}d!\n", + LOGE("AddOptStrToOpts() code:%{public}u nOptLen:%{public}d no equal optStrLen:%{public}d!", pOpt[DHCP_OPT_CODE_INDEX], nOptLen, optStrLen); return 0; } int nEndIndex = GetEndOptionIndex(pOpts); if ((nEndIndex + nOptLen + 1) >= DHCP_OPT_MAX_BYTES) { - LOGE("AddOptStrToOpts() code:%{public}u did not fit into the packet!\n", pOpt[DHCP_OPT_CODE_INDEX]); + LOGE("AddOptStrToOpts() code:%{public}u did not fit into the packet!", pOpt[DHCP_OPT_CODE_INDEX]); return 0; } - LOGI("AddOptStrToOpts() adding option code %{public}u.\n", pOpt[DHCP_OPT_CODE_INDEX]); + LOGI("AddOptStrToOpts() adding option code %{public}u.", pOpt[DHCP_OPT_CODE_INDEX]); if (memcpy_s(pOpts + nEndIndex, nOptLen + 1, pOpt, nOptLen) != EOK) { return 0; } @@ -347,7 +349,7 @@ int AddOptValueToOpts(uint8_t *pOpts, uint8_t code, uint32_t value) { uint8_t uLen = GetDhcpOptionDataLen(code); if (uLen == 0) { - LOGE("AddOptValueToOpts() code:%{public}d failed, GetDhcpOptionDataLen uLen:0!\n", code); + LOGE("AddOptValueToOpts() code:%{public}d failed, GetDhcpOptionDataLen uLen:0!", code); return 0; } @@ -366,7 +368,7 @@ int AddOptValueToOpts(uint8_t *pOpts, uint8_t code, uint32_t value) *pUint32 = value; break; default: - LOGE("AddOptValueToOpts() uLen:%{public}u error, break!\n", uLen); + LOGE("AddOptValueToOpts() uLen:%{public}u error, break!", uLen); break; } diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_socket.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_socket.c index 322d132b4..5241f5de7 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_socket.c +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_socket.c @@ -60,7 +60,7 @@ int CreateRawSocket(int *rawFd) { int sockFd = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP)); if (sockFd == -1) { - LOGE("CreateRawSocket() failed, socket error:%{public}s.\n", strerror(errno)); + LOGE("CreateRawSocket() failed, socket error:%{public}s.", strerror(errno)); return SOCKET_OPT_FAILED; } *rawFd = sockFd; @@ -72,7 +72,7 @@ int CreateKernelSocket(int *sockFd) { int nFd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); if (nFd == -1) { - LOGE("CreateKernelSocket() failed, socket error:%{public}s.\n", strerror(errno)); + LOGE("CreateKernelSocket() failed, socket error:%{public}s.", strerror(errno)); return SOCKET_OPT_FAILED; } *sockFd = nFd; @@ -82,13 +82,13 @@ int CreateKernelSocket(int *sockFd) int BindRawSocket(const int rawFd, const int ifaceIndex, const uint8_t *ifaceAddr) { if (rawFd < 0) { - LOGE("BindRawSocket() failed, rawFd:%{public}d error!\n", rawFd); + LOGE("BindRawSocket() failed, rawFd:%{public}d error!", rawFd); return SOCKET_OPT_FAILED; } struct sockaddr_ll rawAddr; if (memset_s(&rawAddr, sizeof(rawAddr), 0, sizeof(rawAddr)) != EOK) { - LOGE("BindRawSocket() failed, memset_s rawAddr error!\n"); + LOGE("BindRawSocket() failed, memset_s rawAddr error!"); close(rawFd); return SOCKET_OPT_FAILED; } @@ -98,14 +98,14 @@ int BindRawSocket(const int rawFd, const int ifaceIndex, const uint8_t *ifaceAdd if (ifaceAddr != NULL) { rawAddr.sll_halen = MAC_ADDR_LEN; if (memcpy_s(rawAddr.sll_addr, sizeof(rawAddr.sll_addr), ifaceAddr, MAC_ADDR_LEN) != EOK) { - LOGE("BindRawSocket() failed, memcpy_s rawAddr.sll_addr error!\n"); + LOGE("BindRawSocket() failed, memcpy_s rawAddr.sll_addr error!"); close(rawFd); return SOCKET_OPT_FAILED; } } int nRet = bind(rawFd, (struct sockaddr *)&rawAddr, sizeof(rawAddr)); if (nRet == -1) { - LOGE("BindRawSocket() index:%{public}d failed, bind error:%{public}s.\n", ifaceIndex, strerror(errno)); + LOGE("BindRawSocket() index:%{public}d failed, bind error:%{public}s.", ifaceIndex, strerror(errno)); close(rawFd); return SOCKET_OPT_FAILED; } @@ -116,19 +116,19 @@ int BindRawSocket(const int rawFd, const int ifaceIndex, const uint8_t *ifaceAdd int BindKernelSocket(const int sockFd, const char *ifaceName, const uint32_t sockIp, const int sockPort, bool bCast) { if (sockFd < 0) { - LOGE("BindKernelSocket() failed, sockFd:%{public}d error!\n", sockFd); + LOGE("BindKernelSocket() failed, sockFd:%{public}d error!", sockFd); return SOCKET_OPT_FAILED; } /* Bind the specified interface. */ if (ifaceName != NULL) { struct ifreq ifaceReq; - if (strncpy_s(ifaceReq.ifr_name, sizeof(ifaceReq.ifr_name), ifaceName, IFNAMSIZ) != EOK) { + if (strncpy_s(ifaceReq.ifr_name, sizeof(ifaceReq.ifr_name), ifaceName, strlen(ifaceName)) != EOK) { close(sockFd); return SOCKET_OPT_FAILED; } if (setsockopt(sockFd, SOL_SOCKET, SO_BINDTODEVICE, (char *)&ifaceReq, sizeof(ifaceReq)) == -1) { - LOGE("BindKernelSocket() %{public}s SO_BINDTODEVICE error:%{public}s.\n", ifaceName, strerror(errno)); + LOGE("BindKernelSocket() %{public}s SO_BINDTODEVICE error:%{public}s.", ifaceName, strerror(errno)); close(sockFd); return SOCKET_OPT_FAILED; } @@ -137,16 +137,16 @@ int BindKernelSocket(const int sockFd, const char *ifaceName, const uint32_t soc /* Set the broadcast feature of the data sent by the socket. */ if (bCast) { if (setsockopt(sockFd, SOL_SOCKET, SO_BROADCAST, (const char *)&bCast, sizeof(bool)) == -1) { - LOGE("BindKernelSocket() sockFd:%{public}d SO_BROADCAST error:%{public}s.\n", sockFd, strerror(errno)); + LOGE("BindKernelSocket() sockFd:%{public}d SO_BROADCAST error:%{public}s.", sockFd, strerror(errno)); close(sockFd); return SOCKET_OPT_FAILED; } } /* Allow multiple sockets to use the same port number. */ - bool bReuseaddr = true; - if (setsockopt(sockFd, SOL_SOCKET, SO_REUSEADDR, (const char *)&bReuseaddr, sizeof(bool)) == -1) { - LOGE("BindKernelSocket() sockFd:%{public}d SO_REUSEADDR error:%{public}s.\n", sockFd, strerror(errno)); + int bReuseaddr = 1; + if (setsockopt(sockFd, SOL_SOCKET, SO_REUSEADDR, (const char *)&bReuseaddr, sizeof(bReuseaddr)) == -1) { + LOGE("BindKernelSocket() sockFd:%{public}d SO_REUSEADDR error:%{public}s.", sockFd, strerror(errno)); close(sockFd); return SOCKET_OPT_FAILED; } @@ -161,7 +161,7 @@ int BindKernelSocket(const int sockFd, const char *ifaceName, const uint32_t soc kernelAddr.sin_family = AF_INET; int nRet = bind(sockFd, (struct sockaddr *)&kernelAddr, sizeof(kernelAddr)); if (nRet == -1) { - LOGE("BindKernelSocket() sockFd:%{public}d failed, bind error:%{public}s.\n", sockFd, strerror(errno)); + LOGE("BindKernelSocket() sockFd:%{public}d failed, bind error:%{public}s.", sockFd, strerror(errno)); close(sockFd); return SOCKET_OPT_FAILED; } @@ -178,16 +178,16 @@ int SendToDhcpPacket( } struct sockaddr_ll rawAddr; + if ((memset_s(&rawAddr, sizeof(rawAddr), 0, sizeof(rawAddr)) != EOK) || + (memcpy_s(rawAddr.sll_addr, sizeof(rawAddr.sll_addr), destHwaddr, MAC_ADDR_LEN) != EOK)) { + close(nFd); + return SOCKET_OPT_FAILED; + } rawAddr.sll_ifindex = destIndex; rawAddr.sll_protocol = htons(ETH_P_IP); rawAddr.sll_family = AF_PACKET; rawAddr.sll_halen = MAC_ADDR_LEN; - if (memcpy_s(rawAddr.sll_addr, sizeof(rawAddr.sll_addr), destHwaddr, MAC_ADDR_LEN) != EOK) { - close(nFd); - return SOCKET_OPT_FAILED; - } if (bind(nFd, (struct sockaddr *)&rawAddr, sizeof(rawAddr)) == -1) { - LOGE("SendToDhcpPacket() index:%{public}d failed, bind error:%{public}s.\n", destIndex, strerror(errno)); close(nFd); return SOCKET_OPT_FAILED; } @@ -218,9 +218,9 @@ int SendToDhcpPacket( ssize_t nBytes = sendto(nFd, &udpPackets, sizeof(udpPackets), 0, (struct sockaddr *)&rawAddr, sizeof(rawAddr)); if (nBytes <= 0) { - LOGE("SendToDhcpPacket() fd:%{public}d failed, sendto error:%{public}s.\n", nFd, strerror(errno)); + LOGE("SendToDhcpPacket() fd:%{public}d failed, sendto error:%{public}s.", nFd, strerror(errno)); } else { - LOGI("SendToDhcpPacket() fd:%{public}d, index:%{public}d, bytes:%{public}d.\n", nFd, destIndex, (int)nBytes); + LOGI("SendToDhcpPacket() fd:%{public}d, index:%{public}d, bytes:%{public}d.", nFd, destIndex, (int)nBytes); } close(nFd); return (nBytes <= 0) ? SOCKET_OPT_FAILED : SOCKET_OPT_SUCCESS; @@ -231,7 +231,7 @@ int SendDhcpPacket(struct DhcpPacket *sendPacket, uint32_t srcIp, uint32_t destI int nFd = -1; if ((CreateKernelSocket(&nFd) != SOCKET_OPT_SUCCESS) || (BindKernelSocket(nFd, NULL, srcIp, BOOTP_CLIENT, false) != SOCKET_OPT_SUCCESS)) { - LOGE("SendDhcpPacket() fd:%{public}d,srcIp:%{private}u failed!\n", nFd, srcIp); + LOGE("SendDhcpPacket() fd:%{public}d,srcIp:%{private}u failed!", nFd, srcIp); return SOCKET_OPT_FAILED; } @@ -245,16 +245,16 @@ int SendDhcpPacket(struct DhcpPacket *sendPacket, uint32_t srcIp, uint32_t destI kernelAddr.sin_family = AF_INET; int nRet = connect(nFd, (struct sockaddr *)&kernelAddr, sizeof(kernelAddr)); if (nRet == -1) { - LOGE("SendDhcpPacket() nFd:%{public}d failed, connect error:%{public}s.\n", nFd, strerror(errno)); + LOGE("SendDhcpPacket() nFd:%{public}d failed, connect error:%{public}s.", nFd, strerror(errno)); close(nFd); return SOCKET_OPT_FAILED; } ssize_t nBytes = write(nFd, sendPacket, sizeof(struct DhcpPacket)); if (nBytes <= 0) { - LOGE("SendDhcpPacket() fd:%{public}d failed, write error:%{public}s.\n", nFd, strerror(errno)); + LOGE("SendDhcpPacket() fd:%{public}d failed, write error:%{public}s.", nFd, strerror(errno)); } else { - LOGI("SendDhcpPacket() fd:%{public}d, srcIp:%{private}u, bytes:%{public}d.\n", nFd, srcIp, (int)nBytes); + LOGI("SendDhcpPacket() fd:%{public}d, srcIp:%{private}u, bytes:%{public}d.", nFd, srcIp, (int)nBytes); } close(nFd); return (nBytes <= 0) ? SOCKET_OPT_FAILED : SOCKET_OPT_SUCCESS; @@ -263,7 +263,7 @@ int SendDhcpPacket(struct DhcpPacket *sendPacket, uint32_t srcIp, uint32_t destI int CheckReadBytes(const int count, const int totLen) { if (count < 0) { - LOGE("CheckReadBytes() couldn't read on raw listening socket, count:%{public}d, error:%{public}s!\n", + LOGE("CheckReadBytes() couldn't read on raw listening socket, count:%{public}d, error:%{public}s!", count, strerror(errno)); /* The specified network interface service may be down. */ sleep(NUMBER_ONE); @@ -272,55 +272,55 @@ int CheckReadBytes(const int count, const int totLen) int nCommonSize = sizeof(struct iphdr) + sizeof(struct udphdr); if (count < nCommonSize) { - LOGE("CheckReadBytes() read size:%{public}d less than common size:%{public}d!\n", count, nCommonSize); + LOGE("CheckReadBytes() read size:%{public}d less than common size:%{public}d!", count, nCommonSize); return SOCKET_OPT_FAILED; } if (count < totLen) { - LOGE("CheckReadBytes() count:%{public}d less than totLen:%{public}d, packet is Truncated!\n", count, totLen); + LOGE("CheckReadBytes() count:%{public}d less than totLen:%{public}d, packet is Truncated!", count, totLen); return SOCKET_OPT_FAILED; } - LOGI("CheckReadBytes() count:%{public}d, tot:%{public}d, common:%{public}d.\n", count, totLen, nCommonSize); + LOGI("CheckReadBytes() count:%{public}d, tot:%{public}d, common:%{public}d.", count, totLen, nCommonSize); return SOCKET_OPT_SUCCESS; } int CheckUdpPacket(struct UdpDhcpPacket *pPacket, const int totLen) { if (pPacket == NULL) { - LOGE("CheckUdpPacket() failed, pPacket == NULL!\n"); + LOGE("CheckUdpPacket() failed, pPacket == NULL!"); return SOCKET_OPT_FAILED; } if (totLen > (int)sizeof(struct UdpDhcpPacket)) { - LOGE("CheckUdpPacket() totLen:%{public}d more than %{public}d!\n", totLen, (int)sizeof(struct UdpDhcpPacket)); + LOGE("CheckUdpPacket() totLen:%{public}d more than %{public}d!", totLen, (int)sizeof(struct UdpDhcpPacket)); return SOCKET_OPT_FAILED; } if ((pPacket->ip.protocol != IPPROTO_UDP) || (pPacket->ip.version != IPVERSION)) { - LOGE("CheckUdpPacket() failed, pPacket->ip.protocol:%{public}d or version:%{public}u error!\n", + LOGE("CheckUdpPacket() failed, pPacket->ip.protocol:%{public}d or version:%{public}u error!", pPacket->ip.protocol, pPacket->ip.version); return SOCKET_OPT_FAILED; } uint32_t uIhl = (uint32_t)(sizeof(pPacket->ip) >> DHCP_UINT16_BYTES); if (pPacket->ip.ihl != uIhl) { - LOGE("CheckUdpPacket() failed, pPacket->ip.ihl:%{public}u error, uIhl:%{public}u!\n", pPacket->ip.ihl, uIhl); + LOGE("CheckUdpPacket() failed, pPacket->ip.ihl:%{public}u error, uIhl:%{public}u!", pPacket->ip.ihl, uIhl); return SOCKET_OPT_FAILED; } if (pPacket->udp.dest != htons(BOOTP_CLIENT)) { - LOGE("CheckUdpPacket() failed, pPacket->udp.dest:%{public}d error, htons:%{public}d!\n", + LOGE("CheckUdpPacket() failed, pPacket->udp.dest:%{public}d error, htons:%{public}d!", pPacket->udp.dest, htons(BOOTP_CLIENT)); return SOCKET_OPT_FAILED; } uint16_t uLen = (uint16_t)(totLen - (int)sizeof(pPacket->ip)); if (ntohs(pPacket->udp.len) != uLen) { - LOGE("CheckUdpPacket() failed, pPacket->udp.len:%{public}d error, uLen:%{public}d!\n", pPacket->udp.len, uLen); + LOGE("CheckUdpPacket() failed, pPacket->udp.len:%{public}d error, uLen:%{public}d!", pPacket->udp.len, uLen); return SOCKET_OPT_FAILED; } - LOGI("CheckUdpPacket() success, totLen:%{public}d.\n", totLen); + LOGI("CheckUdpPacket() success, totLen:%{public}d.", totLen); return SOCKET_OPT_SUCCESS; } @@ -340,17 +340,17 @@ int CheckPacketIpSum(struct UdpDhcpPacket *pPacket, const int bytes) pPacket->ip.check = 0; uint16_t uCheckSum = GetCheckSum((uint16_t *)&(pPacket->ip), sizeof(pPacket->ip)); if (uCheck != uCheckSum) { - LOGE("CheckPacketIpSum() failed, ip.check:%{public}d, uCheckSum:%{public}d!\n", uCheck, uCheckSum); + LOGE("CheckPacketIpSum() failed, ip.check:%{public}d, uCheckSum:%{public}d!", uCheck, uCheckSum); return SOCKET_OPT_ERROR; } - LOGI("CheckPacketIpSum() success, bytes:%{public}d.\n", bytes); + LOGI("CheckPacketIpSum() success, bytes:%{public}d.", bytes); return SOCKET_OPT_SUCCESS; } int CheckPacketUdpSum(struct UdpDhcpPacket *pPacket, const int bytes) { if (pPacket == NULL) { - LOGE("CheckPacketUdpSum() failed, pPacket == NULL!\n"); + LOGE("CheckPacketUdpSum() failed, pPacket == NULL!"); return SOCKET_OPT_FAILED; } @@ -360,7 +360,7 @@ int CheckPacketUdpSum(struct UdpDhcpPacket *pPacket, const int bytes) u_int32_t source = pPacket->ip.saddr; u_int32_t dest = pPacket->ip.daddr; if (memset_s(&pPacket->ip, sizeof(pPacket->ip), 0, sizeof(pPacket->ip)) != EOK) { - LOGE("CheckPacketUdpSum() failed, memset_s ERROR!\n"); + LOGE("CheckPacketUdpSum() failed, memset_s ERROR!"); return SOCKET_OPT_FAILED; } pPacket->ip.protocol = IPPROTO_UDP; @@ -369,10 +369,10 @@ int CheckPacketUdpSum(struct UdpDhcpPacket *pPacket, const int bytes) pPacket->ip.tot_len = pPacket->udp.len; uint16_t uCheckSum = GetCheckSum((uint16_t *)pPacket, bytes); if (uCheck && (uCheck != uCheckSum)) { - LOGE("CheckPacketUdpSum() failed, udp.check:%{public}d, uCheckSum:%{public}d!\n", uCheck, uCheckSum); + LOGE("CheckPacketUdpSum() failed, udp.check:%{public}d, uCheckSum:%{public}d!", uCheck, uCheckSum); return SOCKET_OPT_FAILED; } - LOGI("CheckPacketUdpSum() success, bytes:%{public}d.\n", bytes); + LOGI("CheckPacketUdpSum() success, bytes:%{public}d.", bytes); return SOCKET_OPT_SUCCESS; } @@ -403,11 +403,11 @@ int GetDhcpRawPacket(struct DhcpPacket *getPacket, int rawFd) int nDhcpPacket = nBytes - (int)(sizeof(udpPackets.ip) + sizeof(udpPackets.udp)); if (memcpy_s(getPacket, sizeof(struct DhcpPacket), &(udpPackets.data), nDhcpPacket) != EOK) { - LOGE("GetDhcpRawPacket() memcpy_s packet.data failed!\n"); + LOGE("GetDhcpRawPacket() memcpy_s packet.data failed!"); return SOCKET_OPT_FAILED; } if (ntohl(getPacket->cookie) != MAGIC_COOKIE) { - LOGE("GetDhcpRawPacket() cook:%{public}x error, COOK:%{public}x!\n", ntohl(getPacket->cookie), MAGIC_COOKIE); + LOGE("GetDhcpRawPacket() cook:%{public}x error, COOK:%{public}x!", ntohl(getPacket->cookie), MAGIC_COOKIE); return SOCKET_OPT_FAILED; } return nDhcpPacket; @@ -421,12 +421,12 @@ int GetDhcpKernelPacket(struct DhcpPacket *getPacket, int sockFd) int nBytes = -1; if ((nBytes = read(sockFd, getPacket, sizeof(struct DhcpPacket))) == -1) { - LOGE("GetDhcpKernelPacket() couldn't read on kernel listening socket, error:%{public}s!\n", strerror(errno)); + LOGE("GetDhcpKernelPacket() couldn't read on kernel listening socket, error:%{public}s!", strerror(errno)); return SOCKET_OPT_ERROR; } if (ntohl(getPacket->cookie) != MAGIC_COOKIE) { - LOGE("GetDhcpKernelPacket() cook:%{public}x error, COOK:%{public}x!\n", ntohl(getPacket->cookie), MAGIC_COOKIE); + LOGE("GetDhcpKernelPacket() cook:%{public}x error, COOK:%{public}x!", ntohl(getPacket->cookie), MAGIC_COOKIE); return SOCKET_OPT_FAILED; } return nBytes; diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/BUILD.gn b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/BUILD.gn index 82cb36785..98e55e545 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/BUILD.gn +++ b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/BUILD.gn @@ -12,40 +12,49 @@ # limitations under the License. import("//build/ohos.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +################################################################################ ohos_shared_library("dhcp_manager_service") { install_enable = true sources = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_service.cpp", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_client_service_impl.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_event_subscriber.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_func.cpp", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_server_service_impl.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_func.cpp" + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_service.cpp", ] include_dirs = [ "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", - "//utils/native/base/include" + "//utils/native/base/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", ] deps = [ - "//utils/native/base:utils" + "${aafwk_path}/interfaces/innerkits/base:base", + "${aafwk_path}/interfaces/innerkits/want:want", + "//utils/native/base:utils", ] - cflags_cc = [ "-std=c++17", - "-Wall", + cflags_cc = [ + "-std=c++17", + "-Wall", ] external_deps = [ - "hiviewdfx_hilog_native:libhilog" + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", ] ldflags = [ - "-fPIC", - "-Wl,-E", + "-fPIC", + "-Wl,-E", ] part_name = "wifi_standard" subsystem_name = "communication" } - diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_client_service_impl.h b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_client_service_impl.h index c33262e71..9250f135f 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_client_service_impl.h +++ b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_client_service_impl.h @@ -112,16 +112,7 @@ public: * @param ifname - interface name, eg:wlan0 [in] * @Return : success - DHCP_OPT_SUCCESS, failed - others. */ - int ReleaseDhcpClient(const std::string& ifname) override; - - /** - * @Description : Handle dhcp packet info. - * - * @param ifname - interface name, eg:wlan0 [in] - * @param packetResult - dhcp packet result [in] - * @param success - get success is true, get failed is false [in] - */ - void DhcpPacketInfoHandle(const std::string& ifname, struct DhcpPacketResult &packetResult, bool success = true); + int ReleaseDhcpClient(const std::string &ifname) override; /** * @Description : Handle dhcp result. @@ -136,7 +127,37 @@ public: * @param ifname - interface name, eg:wlan0 [in] * @Return : The dhcp client process pid. */ - pid_t GetDhcpClientProPid(const std::string& ifname); + pid_t GetDhcpClientProPid(const std::string &ifname); + + /** + * @Description : Get dhcp event success ipv4 result. + * + * @param splits - dhcp event result vector [in] + * @Return : success - DHCP_OPT_SUCCESS, failed - others. + */ + static int GetSuccessIpv4Result(const std::vector &splits); + + /** + * @Description : Get dhcp event ipv4 result. + * + * @param code - dhcp event result code [in] + * @param splits - dhcp event result vector [in] + * @Return : success - DHCP_OPT_SUCCESS, failed - others. + */ + static int GetDhcpEventIpv4Result(const int code, const std::vector &splits); + + /** + * @Description : Handle dhcp event result string. + * + * @param code - dhcp event result code [in] + * @param data - dhcp event result string [in] + * @Return : success - DHCP_OPT_SUCCESS, failed - others. + */ + static int DhcpEventResultHandle(const int code, const std::string &data); + +public: + static std::map m_mapDhcpResult; + static std::map m_mapDhcpInfo; private: /** @@ -160,12 +181,6 @@ private: * */ void RunDhcpResultHandleThreadFunc(); - /** - * @Description : Dhcp recv msg threads execution function. - * - * @param ifname - interface name, eg:wlan0 [in] - */ - void RunDhcpRecvMsgThreadFunc(const std::string& ifname); /** * @Description : Fork child process function for start or stop dhcp process. * @@ -185,13 +200,9 @@ private: private: std::mutex mResultNotifyMutex; - std::mutex mRecvMsgThreadMutex; bool isExitDhcpResultHandleThread; std::thread *pDhcpResultHandleThread; - std::map m_mapDhcpRecvMsgThread; - std::map m_mapDhcpInfo; - std::map m_mapDhcpResult; std::map> m_mapDhcpResultNotify; }; } // namespace Wifi diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_define.h b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_define.h index 4d0a677b6..ef05979b0 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_define.h +++ b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_define.h @@ -35,13 +35,18 @@ const int ETH_MAC_ADDR_CHAR_NUM = 3; const int IP_SIZE = 18; const int LEASETIME_DEFAULT = 12; const int RECEIVER_TIMEOUT = 6; -const int DHCP_RESULT_NUM = 11; -const int DHCP_NUMBER_ONE = 1; -const int DHCP_NUMBER_TWO = 2; -const int DHCP_NUMBER_THREE = 3; -const int DHCP_NUMBER_FOUR = 4; -const int DHCP_NUMBER_FIVE = 5; -const int DHCP_NUMBER_EIGHT = 8; +const int EVENT_DATA_NUM = 11; +const int DHCP_NUM_ZERO = 0; +const int DHCP_NUM_ONE = 1; +const int DHCP_NUM_TWO = 2; +const int DHCP_NUM_THREE = 3; +const int DHCP_NUM_FOUR = 4; +const int DHCP_NUM_FIVE = 5; +const int DHCP_NUM_SIX = 6; +const int DHCP_NUM_SEVEN = 7; +const int DHCP_NUM_EIGHT = 8; +const int DHCP_NUM_NINE = 9; +const int DHCP_NUM_TEN = 10; const int DHCP_FILE_MAX_BYTES = 128; const int FILE_LINE_MAX_SIZE = 1024; const int DHCP_SER_ARGSNUM = 6; @@ -54,6 +59,10 @@ const int DIR_MAX_LEN = 256; const int DIR_DEFAULT_MODE = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH; const std::string IP4_SEPARATOR("."); const std::string IP6_SEPARATOR(":"); +const std::string INVALID_STRING("*"); +const std::string EVENT_DATA_DELIMITER(","); +const std::string EVENT_DATA_IPV4("ipv4"); +const std::string EVENT_DATA_IPV6("ipv6"); const std::string DHCP_WORK_DIR("/data/dhcp/"); const std::string DHCP_CLIENT_PID_FILETYPE(".pid"); const std::string DHCP_RESULT_FILETYPE(".result"); @@ -64,6 +73,7 @@ const std::string DHCP_SERVER_CONFIG_DIR("/data/dhcp/dhcpd.d/"); const std::string DHCP_SERVER_LEASES_FILE("/data/dhcp/dhcpd.leases"); const std::string DHCP_SERVER_CFG_IPV4("#ipv4"); const std::string DHCP_SERVER_CFG_IPV6("#ipv6"); +const std::string COMMON_EVENT_DHCP_GET_IPV4 = "usual.event.wifi.dhcp.GET_IPV4"; typedef enum enumErrCode { /* success */ @@ -78,6 +88,14 @@ typedef enum enumErrCode { DHCP_OPT_ERROR, } DhcpErrCode; +/* publish event code */ +typedef enum enumPublishEventCode { + /* success */ + PUBLISH_CODE_SUCCESS = 0, + /* failed */ + PUBLISH_CODE_FAILED = -1 +} DhcpEventCode; + struct DhcpResult { int iptype; /* 0-ipv4,1-ipv6 */ diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_event_subscriber.h b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_event_subscriber.h new file mode 100644 index 000000000..56f614513 --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_event_subscriber.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef OHOS_DHCP_EVENT_SUBSCRIBER_H +#define OHOS_DHCP_EVENT_SUBSCRIBER_H + +#include +#include "common_event_subscriber.h" +#include "common_event_data.h" + +namespace OHOS { +namespace Wifi { +class DhcpEventSubscriber : public OHOS::EventFwk::CommonEventSubscriber { +public: + explicit DhcpEventSubscriber(const OHOS::EventFwk::CommonEventSubscribeInfo &subscribeInfo) + : CommonEventSubscriber(subscribeInfo) + {} + + ~DhcpEventSubscriber() + {} + void OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data) override; + +private: + std::mutex onReceivedLock_; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_func.h b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_func.h index 2b541cf99..792898dda 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_func.h +++ b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_func.h @@ -26,6 +26,11 @@ #include "dhcp_define.h" +#include "common_event_subscriber.h" +#include "common_event.h" +#include "common_event_data.h" +#include "common_event_manager.h" + namespace OHOS { namespace Wifi { @@ -51,10 +56,20 @@ public: static bool DelFileLineData(const std::string& filename, const std::string& linedata); static bool ModifyFileLineData(const std::string& filename, const std::string& srcdata, const std::string& dstdata); static int FormatString(struct DhcpPacketResult &result); - static int GetDhcpPacketResult(const std::string& filename, struct DhcpPacketResult &result); static int InitPidfile(const std::string& piddir, const std::string& pidfile); static pid_t GetPID(const std::string& pidfile); static int CreateDirs(const std::string dirs, int mode = DIR_DEFAULT_MODE); + static bool SplitString( + const std::string src, const std::string delim, const int count, std::vector &splits); + + static bool SubscribeDhcpCommonEvent( + const std::shared_ptr &subscriber); + static int SubscribeDhcpEvent(const std::string action, int timeouts = RECEIVER_TIMEOUT); + static bool UnsubscribeDhcpCommonEvent( + const std::shared_ptr &subscriber); + static int UnsubscribeDhcpEvent(const std::string action, int timeouts = RECEIVER_TIMEOUT); + + static bool PublishDhcpEvent(const std::string action, const int code, const std::string data); }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_client_service_impl.cpp b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_client_service_impl.cpp index 085d09b3a..f43b326f4 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_client_service_impl.cpp +++ b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_client_service_impl.cpp @@ -27,18 +27,16 @@ DEFINE_WIFILOG_DHCP_LABEL("DhcpClientServiceImpl"); namespace OHOS { namespace Wifi { +std::map DhcpClientServiceImpl::m_mapDhcpResult; +std::map DhcpClientServiceImpl::m_mapDhcpInfo; DhcpClientServiceImpl::DhcpClientServiceImpl() { isExitDhcpResultHandleThread = false; pDhcpResultHandleThread = nullptr; - m_mapDhcpRecvMsgThread.clear(); - m_mapDhcpInfo.clear(); - m_mapDhcpResult.clear(); m_mapDhcpResultNotify.clear(); InitDhcpMgrThread(); - DhcpFunc::CreateDirs(DHCP_WORK_DIR); } @@ -51,7 +49,7 @@ int DhcpClientServiceImpl::InitDhcpMgrThread() { pDhcpResultHandleThread = new std::thread(&DhcpClientServiceImpl::RunDhcpResultHandleThreadFunc, this); if (pDhcpResultHandleThread == nullptr) { - WIFI_LOGE("DhcpClientServiceImpl::InitDhcpMgrThread() init pDhcpResultHandleThread failed!\n"); + WIFI_LOGE("DhcpClientServiceImpl::InitDhcpMgrThread() init pDhcpResultHandleThread failed!"); return DHCP_OPT_FAILED; } @@ -69,18 +67,9 @@ void DhcpClientServiceImpl::ExitDhcpMgrThread() } if (!m_mapDhcpResultNotify.empty()) { - WIFI_LOGE("ExitDhcpMgrThread() error, m_mapDhcpResultNotify is not empty!\n"); + WIFI_LOGE("ExitDhcpMgrThread() error, m_mapDhcpResultNotify is not empty!"); m_mapDhcpResultNotify.clear(); } - - if (!m_mapDhcpRecvMsgThread.empty()) { - WIFI_LOGE("ExitDhcpMgrThread() error, m_mapDhcpRecvMsgThread is not empty!\n"); - for (auto &mapThread : m_mapDhcpRecvMsgThread) { - int nStatus = GetDhcpStatus(mapThread.first); - WIFI_LOGE("ExitDhcpMgrThread() ifname:%{public}s, status:%{public}d!\n", - (mapThread.first).c_str(), nStatus); - } - } } void DhcpClientServiceImpl::CheckTimeout() @@ -89,20 +78,20 @@ void DhcpClientServiceImpl::CheckTimeout() uint32_t curTime = (uint32_t)time(NULL); for (auto &itemNotify : m_mapDhcpResultNotify) { std::string ifname = itemNotify.first; - WIFI_LOGI("CheckTimeout() ifname:%{public}s, notify1 second size:%{public}d.\n", + WIFI_LOGI("CheckTimeout() ifname:%{public}s, notify1 second size:%{public}d.", ifname.c_str(), (int)itemNotify.second.size()); auto iterReq = itemNotify.second.begin(); while (iterReq != itemNotify.second.end()) { if ((*iterReq == nullptr) || ((*iterReq)->pResultNotify == nullptr)) { - WIFI_LOGE("DhcpClientServiceImpl::CheckTimeout() error, *iterReq or pResultNotify is nullptr!\n"); + WIFI_LOGE("DhcpClientServiceImpl::CheckTimeout() error, *iterReq or pResultNotify is nullptr!"); return; } tempTime = (*iterReq)->getTimestamp + (*iterReq)->timeouts; if (tempTime <= curTime) { /* get dhcp result timeout */ WIFI_LOGW("CheckTimeout() ifname:%{public}s get timeout, getTime:%{public}u,timeout:%{public}d, " - "curTime:%{public}u!\n", + "curTime:%{public}u!", ifname.c_str(), (*iterReq)->getTimestamp, (*iterReq)->timeouts, @@ -133,14 +122,14 @@ void DhcpClientServiceImpl::DhcpResultHandle(uint32_t &second) std::string ifname = iterNotify->first; if (iterNotify->second.size() <= 0) { iterNotify = m_mapDhcpResultNotify.erase(iterNotify); - WIFI_LOGI("DhcpResultHandle() ifname:%{public}s, dhcp result notify size:0, erase!\n", ifname.c_str()); + WIFI_LOGI("DhcpResultHandle() ifname:%{public}s, dhcp result notify size:0, erase!", ifname.c_str()); continue; } /* Check dhcp result */ - auto iterDhcpResult = m_mapDhcpResult.find(ifname); - if (iterDhcpResult == m_mapDhcpResult.end()) { - WIFI_LOGI("DhcpResultHandle() ifname:%{public}s, dhcp result is getting...\n", ifname.c_str()); + auto iterDhcpResult = DhcpClientServiceImpl::m_mapDhcpResult.find(ifname); + if (iterDhcpResult == DhcpClientServiceImpl::m_mapDhcpResult.end()) { + WIFI_LOGI("DhcpResultHandle() ifname:%{public}s, dhcp result is getting...", ifname.c_str()); ++iterNotify; continue; } @@ -148,21 +137,21 @@ void DhcpClientServiceImpl::DhcpResultHandle(uint32_t &second) auto iterReq = iterNotify->second.begin(); while (iterReq != iterNotify->second.end()) { if ((*iterReq == nullptr) || ((*iterReq)->pResultNotify == nullptr)) { - WIFI_LOGE("DhcpResultHandle() %{public}s iterReq or pResultNotify is nullptr!\n", ifname.c_str()); + WIFI_LOGE("DhcpResultHandle() %{public}s iterReq or pResultNotify is nullptr!", ifname.c_str()); second = SLEEP_TIME_500_MS; return; } /* Handle dhcp result notify */ - WIFI_LOGI("DhcpResultHandle() ifname:%{public}s, isOptSuc:%{public}d.\n", + WIFI_LOGI("DhcpResultHandle() ifname:%{public}s, isOptSuc:%{public}d.", ifname.c_str(), (iterDhcpResult->second).isOptSuc); if ((iterDhcpResult->second).isOptSuc) { /* get dhcp result success */ - WIFI_LOGI("DhcpResultHandle() ifname:%{public}s get dhcp result success!\n", ifname.c_str()); + WIFI_LOGI("DhcpResultHandle() ifname:%{public}s get dhcp result success!", ifname.c_str()); (*iterReq)->pResultNotify->OnSuccess(DHCP_OPT_SUCCESS, ifname, iterDhcpResult->second); } else { /* get dhcp result failed */ - WIFI_LOGE("DhcpResultHandle() ifname:%{public}s get dhcp result failed!\n", ifname.c_str()); + WIFI_LOGE("DhcpResultHandle() ifname:%{public}s get dhcp result failed!", ifname.c_str()); (*iterReq)->pResultNotify->OnFailed(DHCP_OPT_FAILED, ifname, "get dhcp result failed!"); } delete *iterReq; @@ -172,7 +161,7 @@ void DhcpClientServiceImpl::DhcpResultHandle(uint32_t &second) ++iterNotify; } - WIFI_LOGI("DhcpResultHandle() dhcp result notify finished.\n"); + WIFI_LOGI("DhcpResultHandle() dhcp result notify finished."); second = SLEEP_TIME_500_MS; } @@ -180,7 +169,7 @@ void DhcpClientServiceImpl::RunDhcpResultHandleThreadFunc() { for (; ;) { if (isExitDhcpResultHandleThread) { - WIFI_LOGI("RunDhcpResultHandleThreadFunc() isExitDhcpResultHandleThread:1, break!\n"); + WIFI_LOGI("RunDhcpResultHandleThreadFunc() isExitDhcpResultHandleThread:1, break!"); break; } @@ -189,113 +178,7 @@ void DhcpClientServiceImpl::RunDhcpResultHandleThreadFunc() usleep(uSleepSec); } - WIFI_LOGI("DhcpClientServiceImpl::RunDhcpResultHandleThreadFunc() end!\n"); -} - -void DhcpClientServiceImpl::RunDhcpRecvMsgThreadFunc(const std::string &ifname) -{ - if (ifname.empty()) { - WIFI_LOGE("DhcpClientServiceImpl::RunDhcpRecvMsgThreadFunc() error, ifname is empty!\n"); - return; - } - - struct DhcpPacketResult result; - std::string strResultFile = DHCP_WORK_DIR + ifname + DHCP_RESULT_FILETYPE; - for (; ;) { - /* Check break condition. */ - auto iter = this->m_mapDhcpInfo.find(ifname); - if ((iter != this->m_mapDhcpInfo.end()) && ((iter->second).clientRunStatus) != 1) { - WIFI_LOGI("RunDhcpRecvMsgThreadFunc() Status != 1, need break, ifname:%{public}s.\n", ifname.c_str()); - break; - } - - /* Check dhcp result file is or not exist. */ - if (!DhcpFunc::IsExistFile(strResultFile)) { - usleep(SLEEP_TIME_200_MS); - continue; - } - - if (memset_s(&result, sizeof(result), 0, sizeof(result)) != EOK) { - return; - } - int nGetRet = DhcpFunc::GetDhcpPacketResult(strResultFile, result); - if (nGetRet == DHCP_OPT_SUCCESS) { - /* Get success, add or reload dhcp packet info. */ - this->DhcpPacketInfoHandle(ifname, result); - usleep(SLEEP_TIME_500_MS); - } else if (nGetRet == DHCP_OPT_FAILED) { - /* Get failed, print dhcp packet info. */ - this->DhcpPacketInfoHandle(ifname, result, false); - usleep(SLEEP_TIME_500_MS); - } else { - /* Get null, continue get dhcp packet info. */ - WIFI_LOGI("RunDhcpRecvMsgThreadFunc() GetDhcpPacketResult NULL, ifname:%{public}s.\n", ifname.c_str()); - usleep(SLEEP_TIME_200_MS); - } - - continue; - } -} - -void DhcpClientServiceImpl::DhcpPacketInfoHandle( - const std::string &ifname, struct DhcpPacketResult &packetResult, bool success) -{ - if (ifname.empty()) { - WIFI_LOGE("DhcpClientServiceImpl::DhcpPacketInfoHandle() error, ifname is empty!\n"); - return; - } - - DhcpResult result; - auto iterResult = m_mapDhcpResult.find(ifname); - if (!success) { - /* get failed */ - if (iterResult != m_mapDhcpResult.end()) { - iterResult->second = result; - } else { - m_mapDhcpResult.emplace(std::make_pair(ifname, result)); - } - return; - } - - /* Check dhcp result add time */ - if ((iterResult != m_mapDhcpResult.end()) && ((iterResult->second).uAddTime == packetResult.uAddTime)) { - return; - } - WIFI_LOGI("DhcpPacketInfoHandle() DhcpResult %{public}s old %{public}u no equal new %{public}u, need update...\n", - ifname.c_str(), (iterResult->second).uAddTime, packetResult.uAddTime); - - /* get success, add or reload dhcp packet info */ - auto iterInfo = m_mapDhcpInfo.find(ifname); - if (iterInfo != m_mapDhcpInfo.end()) { - m_mapDhcpInfo[ifname].serverIp = packetResult.strOptServerId; - WIFI_LOGI("DhcpPacketInfoHandle() m_mapDhcpInfo find ifname:%{public}s.\n", ifname.c_str()); - } - - result.iptype = 0; - result.isOptSuc = true; - result.strYourCli = packetResult.strYiaddr; - result.strServer = packetResult.strOptServerId; - result.strSubnet = packetResult.strOptSubnet; - result.strDns1 = packetResult.strOptDns1; - result.strDns2 = packetResult.strOptDns2; - result.strRouter1 = packetResult.strOptRouter1; - result.strRouter2 = packetResult.strOptRouter2; - result.strVendor = packetResult.strOptVendor; - result.uLeaseTime = packetResult.uOptLeasetime; - result.uAddTime = packetResult.uAddTime; - result.uGetTime = (uint32_t)time(NULL); - - if (iterResult != m_mapDhcpResult.end()) { - iterResult->second = result; - } else { - m_mapDhcpResult.emplace(std::make_pair(ifname, result)); - } - WIFI_LOGI("DhcpPacketInfoHandle %{public}s, type:%{public}d, opt:%{public}d, cli:%{private}s, server:%{private}s, " - "strSubnet:%{private}s, strDns1:%{private}s, Dns2:%{private}s, strRouter1:%{private}s, Router2:%{private}s, " - "strVendor:%{public}s, uLeaseTime:%{public}u, uAddTime:%{public}u, uGetTime:%{public}u.\n", - ifname.c_str(), result.iptype, result.isOptSuc, result.strYourCli.c_str(), result.strServer.c_str(), - result.strSubnet.c_str(), result.strDns1.c_str(), result.strDns2.c_str(), result.strRouter1.c_str(), - result.strRouter2.c_str(), result.strVendor.c_str(), result.uLeaseTime, result.uAddTime, result.uGetTime); + WIFI_LOGI("DhcpClientServiceImpl::RunDhcpResultHandleThreadFunc() end!"); } int DhcpClientServiceImpl::ForkExecChildProcess(const std::string &ifname, bool bIpv6, bool bStart) @@ -305,13 +188,13 @@ int DhcpClientServiceImpl::ForkExecChildProcess(const std::string &ifname, bool if (bStart) { const char *args[DHCP_CLI_ARGSNUM] = {DHCP_CLIENT_FILE.c_str(), "start", ifname.c_str(), "-a", nullptr}; if (execv(args[0], const_cast(args)) == -1) { - WIFI_LOGE("execv start v4 v6 failed,strerror(errno):%{public}s,ifname:%{public}s\n", + WIFI_LOGE("execv start v4 v6 failed,strerror(errno):%{public}s,ifname:%{public}s", strerror(errno), ifname.c_str()); } } else { const char *args[DHCP_CLI_ARGSNUM] = {DHCP_CLIENT_FILE.c_str(), "stop", ifname.c_str(), "-a", nullptr}; if (execv(args[0], const_cast(args)) == -1) { - WIFI_LOGE("execv stop v4 v6 failed,strerror(errno):%{public}s,ifname:%{public}s\n", + WIFI_LOGE("execv stop v4 v6 failed,strerror(errno):%{public}s,ifname:%{public}s", strerror(errno), ifname.c_str()); } } @@ -320,13 +203,13 @@ int DhcpClientServiceImpl::ForkExecChildProcess(const std::string &ifname, bool if (bStart) { const char *args[DHCP_CLI_ARGSNUM] = {DHCP_CLIENT_FILE.c_str(), "start", ifname.c_str(), "-4", nullptr}; if (execv(args[0], const_cast(args)) == -1) { - WIFI_LOGE("execv start v4 failed,strerror(errno):%{public}s,ifname:%{public}s\n", + WIFI_LOGE("execv start v4 failed,strerror(errno):%{public}s,ifname:%{public}s", strerror(errno), ifname.c_str()); } } else { const char *args[DHCP_CLI_ARGSNUM] = {DHCP_CLIENT_FILE.c_str(), "stop", ifname.c_str(), "-4", nullptr}; if (execv(args[0], const_cast(args)) == -1) { - WIFI_LOGE("execv stop v4 failed,strerror(errno):%{public}s,ifname:%{public}s\n", + WIFI_LOGE("execv stop v4 failed,strerror(errno):%{public}s,ifname:%{public}s", strerror(errno), ifname.c_str()); } } @@ -337,99 +220,246 @@ int DhcpClientServiceImpl::ForkExecChildProcess(const std::string &ifname, bool int DhcpClientServiceImpl::ForkExecParentProcess(const std::string &ifname, bool bIpv6, bool bStart, pid_t pid) { if (bStart) { - /* check and new receive dhcp packet msg thread */ - std::unique_lock lock(mRecvMsgThreadMutex); - auto iterRecvMsgThread = m_mapDhcpRecvMsgThread.find(ifname); - if (iterRecvMsgThread != m_mapDhcpRecvMsgThread.end()) { - WIFI_LOGE("ForkExecParentProcess() RecvMsgThread exist ifname:%{public}s, need erase!\n", ifname.c_str()); - return DHCP_OPT_FAILED; - } - std::thread *pThread = new std::thread(&DhcpClientServiceImpl::RunDhcpRecvMsgThreadFunc, this, ifname); - if (pThread == nullptr) { - WIFI_LOGE("ForkExecParentProcess() init pThread failed, ifname:%{public}s.\n", ifname.c_str()); + /* Subscribe dhcp event. */ + std::string strAction = OHOS::Wifi::COMMON_EVENT_DHCP_GET_IPV4 + "." + ifname; + if (DhcpFunc::SubscribeDhcpEvent(strAction) != DHCP_OPT_SUCCESS) { + WIFI_LOGE("ForkExecParentProcess() SubscribeDhcpEvent %{public}s failed!", strAction.c_str()); return DHCP_OPT_FAILED; } - m_mapDhcpRecvMsgThread.emplace(std::make_pair(ifname, pThread)); + /* normal started, update dhcp client service running status */ - auto iter = m_mapDhcpInfo.find(ifname); - if (iter != m_mapDhcpInfo.end()) { - m_mapDhcpInfo[ifname].enableIPv6 = bIpv6; - m_mapDhcpInfo[ifname].clientRunStatus = 1; - m_mapDhcpInfo[ifname].clientProPid = pid; + auto iter = DhcpClientServiceImpl::m_mapDhcpInfo.find(ifname); + if (iter != DhcpClientServiceImpl::m_mapDhcpInfo.end()) { + DhcpClientServiceImpl::m_mapDhcpInfo[ifname].enableIPv6 = bIpv6; + DhcpClientServiceImpl::m_mapDhcpInfo[ifname].clientRunStatus = 1; + DhcpClientServiceImpl::m_mapDhcpInfo[ifname].clientProPid = pid; } else { DhcpServiceInfo dhcpInfo; dhcpInfo.enableIPv6 = bIpv6; dhcpInfo.clientRunStatus = 1; dhcpInfo.clientProPid = pid; - m_mapDhcpInfo.emplace(std::make_pair(ifname, dhcpInfo)); + DhcpClientServiceImpl::m_mapDhcpInfo.emplace(std::make_pair(ifname, dhcpInfo)); } } else { - /* destroy recv msg thread */ - auto iter = m_mapDhcpInfo.find(ifname); - if (iter != m_mapDhcpInfo.end()) { + /* Unsubscribe dhcp event. */ + std::string strAction = OHOS::Wifi::COMMON_EVENT_DHCP_GET_IPV4 + "." + ifname; + if (DhcpFunc::UnsubscribeDhcpEvent(strAction) != DHCP_OPT_SUCCESS) { + WIFI_LOGE("ForkExecParentProcess() UnsubscribeDhcpEvent %{public}s failed!", strAction.c_str()); + return DHCP_OPT_FAILED; + } + + auto iter = DhcpClientServiceImpl::m_mapDhcpInfo.find(ifname); + if (iter != DhcpClientServiceImpl::m_mapDhcpInfo.end()) { /* not start */ - m_mapDhcpInfo[ifname].clientRunStatus = 0; - m_mapDhcpInfo[ifname].clientProPid = 0; - std::unique_lock lock(mRecvMsgThreadMutex); - auto iterRecvMsgThreadMap = m_mapDhcpRecvMsgThread.find(ifname); - if (iterRecvMsgThreadMap == m_mapDhcpRecvMsgThread.end()) { - WIFI_LOGI("ForkExecParentProcess() RecvMsgThread already del ifname:%{public}s.\n", ifname.c_str()); - return DHCP_OPT_SUCCESS; - } - if (iterRecvMsgThreadMap->second != nullptr) { - iterRecvMsgThreadMap->second->join(); - delete iterRecvMsgThreadMap->second; - iterRecvMsgThreadMap->second = nullptr; - WIFI_LOGI("ForkExecParentProcess() destroy RecvThread success, ifname:%{public}s.\n", ifname.c_str()); + DhcpClientServiceImpl::m_mapDhcpInfo[ifname].clientRunStatus = 0; + DhcpClientServiceImpl::m_mapDhcpInfo[ifname].clientProPid = 0; + + auto iterResult = DhcpClientServiceImpl::m_mapDhcpResult.find(ifname); + if (iterResult != DhcpClientServiceImpl::m_mapDhcpResult.end()) { + DhcpClientServiceImpl::m_mapDhcpResult.erase(iterResult); + WIFI_LOGI("ForkExecParentProcess() m_mapDhcpResult erase ifname:%{public}s success.", ifname.c_str()); } - WIFI_LOGI("ForkExecParentProcess() m_mapDhcpRecvMsgThread erase ifname:%{public}s.\n", ifname.c_str()); - m_mapDhcpRecvMsgThread.erase(iterRecvMsgThreadMap); } } return DHCP_OPT_SUCCESS; } -pid_t DhcpClientServiceImpl::GetDhcpClientProPid(const std::string& ifname) +pid_t DhcpClientServiceImpl::GetDhcpClientProPid(const std::string &ifname) { if (ifname.empty()) { - WIFI_LOGE("GetDhcpClientProPid() error, ifname is empty!\n"); + WIFI_LOGE("GetDhcpClientProPid() error, ifname is empty!"); return 0; } - auto iter = m_mapDhcpInfo.find(ifname); - if (iter == m_mapDhcpInfo.end()) { - WIFI_LOGI("GetDhcpClientProPid() m_mapDhcpInfo no find ifname:%{public}s.\n", ifname.c_str()); + auto iter = DhcpClientServiceImpl::m_mapDhcpInfo.find(ifname); + if (iter == DhcpClientServiceImpl::m_mapDhcpInfo.end()) { + WIFI_LOGI("GetDhcpClientProPid() m_mapDhcpInfo no find ifname:%{public}s.", ifname.c_str()); return 0; } std::string pidFile = DHCP_WORK_DIR + ifname + DHCP_CLIENT_PID_FILETYPE; pid_t newPid = DhcpFunc::GetPID(pidFile); if ((newPid > 0) && (newPid != (iter->second).clientProPid)) { - WIFI_LOGI("GetDhcpClientProPid() GetPID %{public}s new pid:%{public}d, old pid:%{public}d, need update.\n", + WIFI_LOGI("GetDhcpClientProPid() GetPID %{public}s new pid:%{public}d, old pid:%{public}d, need update.", pidFile.c_str(), newPid, (iter->second).clientProPid); - m_mapDhcpInfo[ifname].clientProPid = newPid; + DhcpClientServiceImpl::m_mapDhcpInfo[ifname].clientProPid = newPid; } - WIFI_LOGI("GetDhcpClientProPid() m_mapDhcpInfo find ifname:%{public}s, pid:%{public}d.\n", - ifname.c_str(), m_mapDhcpInfo[ifname].clientProPid); - return m_mapDhcpInfo[ifname].clientProPid; + WIFI_LOGI("GetDhcpClientProPid() m_mapDhcpInfo find ifname:%{public}s, pid:%{public}d.", + ifname.c_str(), DhcpClientServiceImpl::m_mapDhcpInfo[ifname].clientProPid); + return DhcpClientServiceImpl::m_mapDhcpInfo[ifname].clientProPid; +} + +int DhcpClientServiceImpl::GetSuccessIpv4Result(const std::vector &splits) +{ + /* Result format - ifname,time,cliIp,lease,servIp,subnet,dns1,dns2,router1,router2,vendor */ + if (splits.size() != EVENT_DATA_NUM) { + WIFI_LOGE("GetSuccessIpv4Result() splits.size:%{public}d error!", (int)splits.size()); + return DHCP_OPT_FAILED; + } + + /* Check field cliIp. */ + if (splits[DHCP_NUM_TWO] == INVALID_STRING) { + WIFI_LOGE("GetSuccessIpv4Result() cliIp:%{public}s error!", splits[DHCP_NUM_TWO].c_str()); + return DHCP_OPT_FAILED; + } + + DhcpResult result; + result.uAddTime = std::stoi(splits[DHCP_NUM_ONE]); + std::string ifname = splits[DHCP_NUM_ZERO]; + auto iter = DhcpClientServiceImpl::m_mapDhcpResult.find(ifname); + if ((iter != DhcpClientServiceImpl::m_mapDhcpResult.end()) && ((iter->second).uAddTime == result.uAddTime)) { + WIFI_LOGI("GetSuccessIpv4Result() %{public}s old %{public}u equal new %{public}u, no need update.", + ifname.c_str(), (iter->second).uAddTime, result.uAddTime); + return DHCP_OPT_SUCCESS; + } + WIFI_LOGI("GetSuccessIpv4Result() DhcpResult %{public}s old %{public}u no equal new %{public}u, need update...", + ifname.c_str(), (iter->second).uAddTime, result.uAddTime); + + /* Reload dhcp packet info. */ + auto iterInfo = DhcpClientServiceImpl::m_mapDhcpInfo.find(ifname); + if (iterInfo != DhcpClientServiceImpl::m_mapDhcpInfo.end()) { + WIFI_LOGI("GetSuccessIpv4Result() m_mapDhcpInfo find ifname:%{public}s.", ifname.c_str()); + DhcpClientServiceImpl::m_mapDhcpInfo[ifname].serverIp = splits[DHCP_NUM_FOUR]; + } + + result.iptype = 0; + result.isOptSuc = true; + result.strYourCli = splits[DHCP_NUM_TWO]; + result.uLeaseTime = std::stoi(splits[DHCP_NUM_THREE]); + result.strServer = splits[DHCP_NUM_FOUR]; + result.strSubnet = splits[DHCP_NUM_FIVE]; + result.strDns1 = splits[DHCP_NUM_SIX]; + result.strDns2 = splits[DHCP_NUM_SEVEN]; + result.strRouter1 = splits[DHCP_NUM_EIGHT]; + result.strRouter2 = splits[DHCP_NUM_NINE]; + result.strVendor = splits[DHCP_NUM_TEN]; + result.uGetTime = (uint32_t)time(NULL); + if (iter != DhcpClientServiceImpl::m_mapDhcpResult.end()) { + iter->second = result; + } else { + DhcpClientServiceImpl::m_mapDhcpResult.emplace(std::make_pair(ifname, result)); + } + WIFI_LOGI("GetSuccessIpv4Result() %{public}s, %{public}d, opt:%{public}d, cli:%{private}s, server:%{private}s, " + "strSubnet:%{private}s, strDns1:%{private}s, Dns2:%{private}s, strRouter1:%{private}s, Router2:%{private}s, " + "strVendor:%{public}s, uLeaseTime:%{public}u, uAddTime:%{public}u, uGetTime:%{public}u.", + ifname.c_str(), result.iptype, result.isOptSuc, result.strYourCli.c_str(), result.strServer.c_str(), + result.strSubnet.c_str(), result.strDns1.c_str(), result.strDns2.c_str(), result.strRouter1.c_str(), + result.strRouter2.c_str(), result.strVendor.c_str(), result.uLeaseTime, result.uAddTime, result.uGetTime); + return DHCP_OPT_SUCCESS; +} + +int DhcpClientServiceImpl::GetDhcpEventIpv4Result(const int code, const std::vector &splits) +{ + /* Result format - ifname,time,cliIp,lease,servIp,subnet,dns1,dns2,router1,router2,vendor */ + if (splits.size() != EVENT_DATA_NUM) { + WIFI_LOGE("GetDhcpEventIpv4Result() splits.size:%{public}d error!", (int)splits.size()); + return DHCP_OPT_FAILED; + } + + /* Check field ifname and time. */ + if (splits[DHCP_NUM_ZERO].empty() || splits[DHCP_NUM_ONE].empty()) { + WIFI_LOGE("GetDhcpEventIpv4Result() ifname or time is empty!"); + return DHCP_OPT_FAILED; + } + + /* Check field cliIp. */ + if (((code == PUBLISH_CODE_SUCCESS) && (splits[DHCP_NUM_TWO] == INVALID_STRING)) + || ((code == PUBLISH_CODE_FAILED) && (splits[DHCP_NUM_TWO] != INVALID_STRING))) { + WIFI_LOGE("GetDhcpEventIpv4Result() code:%{public}d,%{public}s error!", code, splits[DHCP_NUM_TWO].c_str()); + return DHCP_OPT_FAILED; + } + + std::string ifname = splits[DHCP_NUM_ZERO]; + if (code == PUBLISH_CODE_FAILED) { + /* Get failed. */ + DhcpResult result; + result.iptype = 0; + result.isOptSuc = false; + result.uAddTime = std::stoi(splits[DHCP_NUM_ONE]); + auto iterResult = DhcpClientServiceImpl::m_mapDhcpResult.find(ifname); + if (iterResult != DhcpClientServiceImpl::m_mapDhcpResult.end()) { + iterResult->second = result; + } else { + m_mapDhcpResult.emplace(std::make_pair(ifname, result)); + } + WIFI_LOGI("GetDhcpEventIpv4Result() ifname:%{public}s result.isOptSuc:false!", ifname.c_str()); + return DHCP_OPT_SUCCESS; + } + + /* Get success. */ + if (GetSuccessIpv4Result(splits) != DHCP_OPT_SUCCESS) { + WIFI_LOGE("GetDhcpEventIpv4Result() GetSuccessIpv4Result failed!"); + return DHCP_OPT_FAILED; + } + WIFI_LOGI("GetDhcpEventIpv4Result() ifname:%{public}s result.isOptSuc:true!", ifname.c_str()); + return DHCP_OPT_SUCCESS; +} + +int DhcpClientServiceImpl::DhcpEventResultHandle(const int code, const std::string &data) +{ + if (data.empty()) { + WIFI_LOGE("DhcpClientServiceImpl::DhcpEventResultHandle() error, data is empty!"); + return DHCP_OPT_FAILED; + } + WIFI_LOGI("Enter DhcpEventResultHandle() code:%{public}d,data:%{private}s.", code, data.c_str()); + + /* Data format - ipv4:ifname,time,cliIp,lease,servIp,subnet,dns1,dns2,router1,router2,vendor */ + std::string strData(data); + std::string strFlag; + std::string strResult; + if (strData.find(EVENT_DATA_IPV4) != std::string::npos) { + strFlag = strData.substr(0, (int)EVENT_DATA_IPV4.size()); + if (strFlag != EVENT_DATA_IPV4) { + WIFI_LOGE("DhcpEventResultHandle() %{public}s ipv4flag:%{public}s error!", data.c_str(), strFlag.c_str()); + return DHCP_OPT_FAILED; + } + /* Skip separator ":" */ + strResult = strData.substr((int)EVENT_DATA_IPV4.size() + 1); + } else if (strData.find(EVENT_DATA_IPV6) != std::string::npos) { + strFlag = strData.substr(0, (int)EVENT_DATA_IPV6.size()); + if (strFlag != EVENT_DATA_IPV6) { + WIFI_LOGE("DhcpEventResultHandle() %{public}s ipv6flag:%{public}s error!", data.c_str(), strFlag.c_str()); + return DHCP_OPT_FAILED; + } + strResult = strData.substr((int)EVENT_DATA_IPV6.size() + 1); + } else { + WIFI_LOGE("DhcpEventResultHandle() data:%{public}s error, no find ipflag!", data.c_str()); + return DHCP_OPT_FAILED; + } + WIFI_LOGI("DhcpEventResultHandle() flag:%{public}s, result:%{private}s.", strFlag.c_str(), strResult.c_str()); + + if (strFlag == EVENT_DATA_IPV4) { + std::vector vecSplits; + if (!DhcpFunc::SplitString(strResult, EVENT_DATA_DELIMITER, EVENT_DATA_NUM, vecSplits)) { + WIFI_LOGE("DhcpEventResultHandle() SplitString strResult:%{public}s failed!", strResult.c_str()); + return DHCP_OPT_FAILED; + } + + if (GetDhcpEventIpv4Result(code, vecSplits) != DHCP_OPT_SUCCESS) { + WIFI_LOGE("DhcpEventResultHandle() GetDhcpEventIpv4Result failed!"); + return DHCP_OPT_FAILED; + } + } + + return DHCP_OPT_SUCCESS; } int DhcpClientServiceImpl::StartDhcpClient(const std::string &ifname, bool bIpv6) { if (ifname.empty()) { - WIFI_LOGE("DhcpClientServiceImpl::StartDhcpClient() error, ifname is empty!\n"); + WIFI_LOGE("DhcpClientServiceImpl::StartDhcpClient() error, ifname is empty!"); return DHCP_OPT_FAILED; } - WIFI_LOGI("enter StartDhcpClient()...ifname:%{public}s, bIpv6:%{public}d.\n", ifname.c_str(), bIpv6); + WIFI_LOGI("enter StartDhcpClient()...ifname:%{public}s, bIpv6:%{public}d.", ifname.c_str(), bIpv6); /* check config */ /* check dhcp client service running status */ int nStatus = GetDhcpStatus(ifname); if (nStatus == 1) { - WIFI_LOGI("StartDhcpClient() running status:%{public}d, service already started, ifname:%{public}s.\n", + WIFI_LOGI("StartDhcpClient() running status:%{public}d, service already started, ifname:%{public}s.", nStatus, ifname.c_str()); /* reload config */ return DHCP_OPT_SUCCESS; @@ -438,7 +468,7 @@ int DhcpClientServiceImpl::StartDhcpClient(const std::string &ifname, bool bIpv6 /* start dhcp client service */ pid_t pid; if ((pid = vfork()) < 0) { - WIFI_LOGE("StartDhcpClient() vfork() failed, pid:%{public}d.\n", pid); + WIFI_LOGE("StartDhcpClient() vfork() failed, pid:%{public}d.", pid); return DHCP_OPT_FAILED; } if (pid == 0) { @@ -446,12 +476,12 @@ int DhcpClientServiceImpl::StartDhcpClient(const std::string &ifname, bool bIpv6 ForkExecChildProcess(ifname, bIpv6, true); } else { /* Parent process */ - WIFI_LOGI("StartDhcpClient() vfork %{public}d success, parent:%{public}d, begin waitpid...\n", pid, getpid()); + WIFI_LOGI("StartDhcpClient() vfork %{public}d success, parent:%{public}d, begin waitpid...", pid, getpid()); pid_t pidRet = waitpid(pid, nullptr, 0); if (pidRet == pid) { - WIFI_LOGI("StartDhcpClient() waitpid child:%{public}d success.\n", pid); + WIFI_LOGI("StartDhcpClient() waitpid child:%{public}d success.", pid); } else { - WIFI_LOGE("StartDhcpClient() waitpid child:%{public}d failed, pidRet:%{public}d!\n", pid, pidRet); + WIFI_LOGE("StartDhcpClient() waitpid child:%{public}d failed, pidRet:%{public}d!", pid, pidRet); } return ForkExecParentProcess(ifname, bIpv6, true, pid); @@ -463,29 +493,29 @@ int DhcpClientServiceImpl::StartDhcpClient(const std::string &ifname, bool bIpv6 int DhcpClientServiceImpl::StopDhcpClient(const std::string &ifname, bool bIpv6) { if (ifname.empty()) { - WIFI_LOGE("DhcpClientServiceImpl::StopDhcpClient() error, ifname is empty!\n"); + WIFI_LOGE("DhcpClientServiceImpl::StopDhcpClient() error, ifname is empty!"); return DHCP_OPT_FAILED; } - WIFI_LOGI("enter StopDhcpClient()...ifname:%{public}s, bIpv6:%{public}d.\n", ifname.c_str(), bIpv6); + WIFI_LOGI("enter StopDhcpClient()...ifname:%{public}s, bIpv6:%{public}d.", ifname.c_str(), bIpv6); /* check dhcp client service running status */ bool bExecParentProcess = true; int nStatus = GetDhcpStatus(ifname); if (nStatus == 0) { - WIFI_LOGI("StopDhcpClient() status:%{public}d, service already stopped, ifname:%{public}s.\n", + WIFI_LOGI("StopDhcpClient() status:%{public}d, service already stopped, ifname:%{public}s.", nStatus, ifname.c_str()); return DHCP_OPT_SUCCESS; } else if (nStatus == -1) { WIFI_LOGI("StopDhcpClient() status:%{public}d, service not start or started, not need ExecParentProcess, " - "ifname:%{public}s.\n", nStatus, ifname.c_str()); + "ifname:%{public}s.", nStatus, ifname.c_str()); bExecParentProcess = false; } /* stop dhcp client service */ pid_t pid; if ((pid = vfork()) < 0) { - WIFI_LOGE("StopDhcpClient() vfork() failed, pid:%{public}d.\n", pid); + WIFI_LOGE("StopDhcpClient() vfork() failed, pid:%{public}d.", pid); return DHCP_OPT_FAILED; } if (pid == 0) { @@ -494,12 +524,12 @@ int DhcpClientServiceImpl::StopDhcpClient(const std::string &ifname, bool bIpv6) return DHCP_OPT_SUCCESS; } else { /* Parent process */ - WIFI_LOGI("StopDhcpClient() vfork %{public}d success, parent:%{public}d, begin waitpid...\n", pid, getpid()); + WIFI_LOGI("StopDhcpClient() vfork %{public}d success, parent:%{public}d, begin waitpid...", pid, getpid()); pid_t pidRet = waitpid(pid, nullptr, 0); if (pidRet == pid) { - WIFI_LOGI("StopDhcpClient() waitpid child:%{public}d success.\n", pid); + WIFI_LOGI("StopDhcpClient() waitpid child:%{public}d success.", pid); } else { - WIFI_LOGE("StopDhcpClient() waitpid child:%{public}d failed, pidRet:%{public}d!\n", pid, pidRet); + WIFI_LOGE("StopDhcpClient() waitpid child:%{public}d failed, pidRet:%{public}d!", pid, pidRet); } return bExecParentProcess ? ForkExecParentProcess(ifname, bIpv6) : DHCP_OPT_SUCCESS; @@ -509,17 +539,17 @@ int DhcpClientServiceImpl::StopDhcpClient(const std::string &ifname, bool bIpv6) int DhcpClientServiceImpl::GetDhcpStatus(const std::string &ifname) { if (ifname.empty()) { - WIFI_LOGE("DhcpClientServiceImpl::GetDhcpStatus() error, ifname is empty!\n"); + WIFI_LOGE("DhcpClientServiceImpl::GetDhcpStatus() error, ifname is empty!"); return -1; } - auto iter = m_mapDhcpInfo.find(ifname); - if (iter == m_mapDhcpInfo.end()) { - WIFI_LOGI("DhcpClientServiceImpl::GetDhcpStatus() m_mapDhcpInfo no find ifname:%{public}s.\n", ifname.c_str()); + auto iter = DhcpClientServiceImpl::m_mapDhcpInfo.find(ifname); + if (iter == DhcpClientServiceImpl::m_mapDhcpInfo.end()) { + WIFI_LOGI("DhcpClientServiceImpl::GetDhcpStatus() m_mapDhcpInfo no find ifname:%{public}s.", ifname.c_str()); return -1; } - WIFI_LOGI("GetDhcpStatus() m_mapDhcpInfo find ifname:%{public}s, clientRunStatus:%{public}d.\n", + WIFI_LOGI("GetDhcpStatus() m_mapDhcpInfo find ifname:%{public}s, clientRunStatus:%{public}d.", ifname.c_str(), (iter->second).clientRunStatus); return (iter->second).clientRunStatus; @@ -528,12 +558,12 @@ int DhcpClientServiceImpl::GetDhcpStatus(const std::string &ifname) int DhcpClientServiceImpl::GetDhcpResult(const std::string &ifname, IDhcpResultNotify *pResultNotify, int timeouts) { if (ifname.empty()) { - WIFI_LOGE("DhcpClientServiceImpl::GetDhcpResult() error, ifname is empty!\n"); + WIFI_LOGE("DhcpClientServiceImpl::GetDhcpResult() error, ifname is empty!"); return DHCP_OPT_FAILED; } if (pResultNotify == nullptr) { - WIFI_LOGE("GetDhcpResult() ifname:%{public}s error, pResultNotify is nullptr!\n", ifname.c_str()); + WIFI_LOGE("GetDhcpResult() ifname:%{public}s error, pResultNotify is nullptr!", ifname.c_str()); return DHCP_OPT_FAILED; } @@ -551,24 +581,22 @@ int DhcpClientServiceImpl::GetDhcpResult(const std::string &ifname, IDhcpResultN listDhcpResultReq.push_back(pResultReq); m_mapDhcpResultNotify.emplace(std::make_pair(ifname, listDhcpResultReq)); } - - WIFI_LOGI("GetDhcpResult() ifname:%{public}s,timeouts:%{public}d, result push_back!\n", ifname.c_str(), timeouts); - + WIFI_LOGI("GetDhcpResult() ifname:%{public}s,timeouts:%{public}d, result push_back!", ifname.c_str(), timeouts); return DHCP_OPT_SUCCESS; } int DhcpClientServiceImpl::GetDhcpInfo(const std::string &ifname, DhcpServiceInfo &dhcp) { if (ifname.empty()) { - WIFI_LOGE("DhcpClientServiceImpl::GetDhcpInfo() error, ifname is empty!\n"); + WIFI_LOGE("DhcpClientServiceImpl::GetDhcpInfo() error, ifname is empty!"); return DHCP_OPT_FAILED; } - auto iter = m_mapDhcpInfo.find(ifname); - if (iter != m_mapDhcpInfo.end()) { + auto iter = DhcpClientServiceImpl::m_mapDhcpInfo.find(ifname); + if (iter != DhcpClientServiceImpl::m_mapDhcpInfo.end()) { dhcp = iter->second; } else { - WIFI_LOGE("GetDhcpInfo() failed, m_mapDhcpInfo no find ifname:%{public}s.\n", ifname.c_str()); + WIFI_LOGE("GetDhcpInfo() failed, m_mapDhcpInfo no find ifname:%{public}s.", ifname.c_str()); } return DHCP_OPT_SUCCESS; @@ -576,55 +604,55 @@ int DhcpClientServiceImpl::GetDhcpInfo(const std::string &ifname, DhcpServiceInf int DhcpClientServiceImpl::RenewDhcpClient(const std::string &ifname) { - WIFI_LOGI("enter DhcpClientServiceImpl::RenewDhcpClient()...ifname:%{public}s.\n", ifname.c_str()); + WIFI_LOGI("enter DhcpClientServiceImpl::RenewDhcpClient()...ifname:%{public}s.", ifname.c_str()); int nStatus = GetDhcpStatus(ifname); if (nStatus != 1) { - WIFI_LOGW("RenewDhcpClient() dhcp client service not started, now start ifname:%{public}s.\n", ifname.c_str()); + WIFI_LOGW("RenewDhcpClient() dhcp client service not started, now start ifname:%{public}s.", ifname.c_str()); /* Start dhcp client service */ - return StartDhcpClient(ifname, m_mapDhcpInfo[ifname].enableIPv6); + return StartDhcpClient(ifname, DhcpClientServiceImpl::m_mapDhcpInfo[ifname].enableIPv6); } /* Send dhcp renew packet : kill -USR2 */ pid_t pid = GetDhcpClientProPid(ifname); if (pid <= 0) { - WIFI_LOGW("RenewDhcpClient() dhcp client process pid:%{public}d error, ifname:%{public}s!\n", + WIFI_LOGW("RenewDhcpClient() dhcp client process pid:%{public}d error, ifname:%{public}s!", pid, ifname.c_str()); return DHCP_OPT_FAILED; } if (kill(pid, SIGUSR2) == -1) { - WIFI_LOGE("RenewDhcpClient() kill [%{public}d] failed:%{public}s, ifname:%{public}s!\n", + WIFI_LOGE("RenewDhcpClient() kill [%{public}d] failed:%{public}s, ifname:%{public}s!", pid, strerror(errno), ifname.c_str()); return DHCP_OPT_FAILED; } - WIFI_LOGI("RenewDhcpClient() kill [%{public}d] success, ifname:%{public}s.\n", pid, ifname.c_str()); + WIFI_LOGI("RenewDhcpClient() kill [%{public}d] success, ifname:%{public}s.", pid, ifname.c_str()); return DHCP_OPT_SUCCESS; } int DhcpClientServiceImpl::ReleaseDhcpClient(const std::string &ifname) { - WIFI_LOGI("enter DhcpClientServiceImpl::ReleaseDhcpClient()...ifname:%{public}s.\n", ifname.c_str()); + WIFI_LOGI("enter DhcpClientServiceImpl::ReleaseDhcpClient()...ifname:%{public}s.", ifname.c_str()); int nStatus = GetDhcpStatus(ifname); if (nStatus != 1) { - WIFI_LOGE("ReleaseDhcpClient() failed, dhcp client service not started, ifname:%{public}s!\n", ifname.c_str()); + WIFI_LOGE("ReleaseDhcpClient() failed, dhcp client service not started, ifname:%{public}s!", ifname.c_str()); return DHCP_OPT_FAILED; } /* Send dhcp release packet : kill -USR1 */ pid_t pid = GetDhcpClientProPid(ifname); if (pid <= 0) { - WIFI_LOGW("ReleaseDhcpClient() dhcp client process pid:%{public}d error, ifname:%{public}s!\n", + WIFI_LOGW("ReleaseDhcpClient() dhcp client process pid:%{public}d error, ifname:%{public}s!", pid, ifname.c_str()); return DHCP_OPT_FAILED; } if (kill(pid, SIGUSR1) == -1) { - WIFI_LOGE("ReleaseDhcpClient() kill [%{public}d] failed:%{public}s, ifname:%{public}s!\n", + WIFI_LOGE("ReleaseDhcpClient() kill [%{public}d] failed:%{public}s, ifname:%{public}s!", pid, strerror(errno), ifname.c_str()); return DHCP_OPT_FAILED; } - WIFI_LOGI("ReleaseDhcpClient() kill [%{public}d] success, ifname:%{public}s.\n", pid, ifname.c_str()); + WIFI_LOGI("ReleaseDhcpClient() kill [%{public}d] success, ifname:%{public}s.", pid, ifname.c_str()); return DHCP_OPT_SUCCESS; } } // namespace Wifi diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_event_subscriber.cpp b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_event_subscriber.cpp new file mode 100644 index 000000000..ac1d5859e --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_event_subscriber.cpp @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 "dhcp_event_subscriber.h" + +#include "wifi_logger.h" +#include "dhcp_client_service_impl.h" + +DEFINE_WIFILOG_DHCP_LABEL("DhcpEventSubscriber"); + +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace Wifi { +void DhcpEventSubscriber::OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data) +{ + std::lock_guard lock(onReceivedLock_); + int code = data.GetCode(); + std::string strData = data.GetData(); + WIFI_LOGI("OnReceiveEvent() GetCode:%{public}d, GetData:%{private}s.", code, strData.c_str()); + if (DhcpClientServiceImpl::DhcpEventResultHandle(code, strData) != DHCP_OPT_SUCCESS) { + WIFI_LOGE("OnReceiveEvent() DhcpEventResultHandle failed!"); + return; + } +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_func.cpp b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_func.cpp index 4b5b826a7..e3f9cba53 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_func.cpp +++ b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_func.cpp @@ -23,6 +23,7 @@ #include "securec.h" #include "wifi_logger.h" +#include "dhcp_event_subscriber.h" DEFINE_WIFILOG_DHCP_LABEL("DhcpFunc"); @@ -49,24 +50,24 @@ unsigned int DhcpFunc::IPtoInt(const std::string& strIp) bool DhcpFunc::Ip4StrConToInt(const std::string& strIp, uint32_t& uIp) { if (strIp.empty()) { - WIFI_LOGE("Ip4StrConToInt error, strIp is empty()!\n"); + WIFI_LOGE("Ip4StrConToInt error, strIp is empty()!"); return false; } struct in_addr addr4; int nRet = inet_pton(AF_INET, strIp.c_str(), &addr4); if (nRet != 1) { - WIFI_LOGE("Ip4StrConToInt strIp:%{private}s failed, nRet:%{public}d!\n", strIp.c_str(), nRet); + WIFI_LOGE("Ip4StrConToInt strIp:%{private}s failed, nRet:%{public}d!", strIp.c_str(), nRet); if (nRet == 0) { - WIFI_LOGE("Ip4StrConToInt strIp:%{private}s not in presentation format!\n", strIp.c_str()); + WIFI_LOGE("Ip4StrConToInt strIp:%{private}s not in presentation format!", strIp.c_str()); } else { - WIFI_LOGE("Ip4StrConToInt strIp:%{private}s inet_pton not contain a valid address!\n", strIp.c_str()); + WIFI_LOGE("Ip4StrConToInt strIp:%{private}s inet_pton not contain a valid address!", strIp.c_str()); } return false; } uIp = ntohl(addr4.s_addr); - WIFI_LOGI("Ip4StrConToInt strIp:%{private}s -> uIp:%{private}u.\n", strIp.c_str(), uIp); + WIFI_LOGI("Ip4StrConToInt strIp:%{private}s -> uIp:%{private}u.", strIp.c_str(), uIp); return true; } @@ -74,7 +75,7 @@ bool DhcpFunc::Ip4StrConToInt(const std::string& strIp, uint32_t& uIp) std::string DhcpFunc::Ip4IntConToStr(uint32_t uIp) { if (uIp == 0) { - WIFI_LOGE("Ip4IntConToStr uIp is 0!\n"); + WIFI_LOGE("Ip4IntConToStr uIp is 0!"); return ""; } @@ -83,10 +84,10 @@ std::string DhcpFunc::Ip4IntConToStr(uint32_t uIp) struct in_addr addr4; addr4.s_addr = htonl(uIp); if (inet_ntop(AF_INET, &addr4, bufIp4, INET_ADDRSTRLEN) == NULL) { - WIFI_LOGE("Ip4IntConToStr uIp:%{private}u failed, inet_ntop NULL!\n", uIp); + WIFI_LOGE("Ip4IntConToStr uIp:%{private}u failed, inet_ntop NULL!", uIp); } else { strIp = bufIp4; - WIFI_LOGI("Ip4IntConToStr uIp:%{private}u -> strIp:%{private}s.\n", uIp, strIp.c_str()); + WIFI_LOGI("Ip4IntConToStr uIp:%{private}u -> strIp:%{private}s.", uIp, strIp.c_str()); } return strIp; @@ -95,7 +96,7 @@ std::string DhcpFunc::Ip4IntConToStr(uint32_t uIp) bool DhcpFunc::Ip6StrConToChar(const std::string& strIp, uint8_t chIp[], size_t uSize) { if (strIp.empty()) { - WIFI_LOGE("Ip6StrConToChar param error, strIp is empty()!\n"); + WIFI_LOGE("Ip6StrConToChar param error, strIp is empty()!"); return false; } @@ -105,11 +106,11 @@ bool DhcpFunc::Ip6StrConToChar(const std::string& strIp, uint8_t chIp[], size_t } int nRet = inet_pton(AF_INET6, strIp.c_str(), &addr6); if (nRet != 1) { - WIFI_LOGE("Ip6StrConToChar inet_pton strIp:%{private}s failed, nRet:%{public}d!\n", strIp.c_str(), nRet); + WIFI_LOGE("Ip6StrConToChar inet_pton strIp:%{private}s failed, nRet:%{public}d!", strIp.c_str(), nRet); if (nRet == 0) { - WIFI_LOGE("Ip6StrConToChar strIp:%{private}s not in presentation format!\n", strIp.c_str()); + WIFI_LOGE("Ip6StrConToChar strIp:%{private}s not in presentation format!", strIp.c_str()); } else { - WIFI_LOGE("Ip6StrConToChar strIp:%{private}s inet_pton not contain a valid address!\n", strIp.c_str()); + WIFI_LOGE("Ip6StrConToChar strIp:%{private}s inet_pton not contain a valid address!", strIp.c_str()); } return false; } @@ -124,7 +125,7 @@ bool DhcpFunc::Ip6StrConToChar(const std::string& strIp, uint8_t chIp[], size_t std::string DhcpFunc::Ip6CharConToStr(uint8_t chIp[], int size) { if (size <= 0) { - WIFI_LOGE("Ip6CharConToStr param error, size:%{public}d!\n", size); + WIFI_LOGE("Ip6CharConToStr param error, size:%{public}d!", size); return ""; } @@ -135,10 +136,10 @@ std::string DhcpFunc::Ip6CharConToStr(uint8_t chIp[], int size) return ""; } if (inet_ntop(AF_INET6, &addr6, bufIp6, INET6_ADDRSTRLEN) == NULL) { - WIFI_LOGE("Ip6CharConToStr chIp failed, inet_ntop NULL!\n"); + WIFI_LOGE("Ip6CharConToStr chIp failed, inet_ntop NULL!"); } else { strIp = bufIp6; - WIFI_LOGI("Ip6CharConToStr chIp -> strIp:%{private}s.\n", strIp.c_str()); + WIFI_LOGI("Ip6CharConToStr chIp -> strIp:%{private}s.", strIp.c_str()); } return strIp; @@ -147,7 +148,7 @@ std::string DhcpFunc::Ip6CharConToStr(uint8_t chIp[], int size) bool DhcpFunc::CheckIpStr(const std::string& strIp) { if (strIp.empty()) { - WIFI_LOGE("CheckIpStr param error, strIp is empty()!\n"); + WIFI_LOGE("CheckIpStr param error, strIp is empty()!"); return false; } @@ -162,20 +163,20 @@ bool DhcpFunc::CheckIpStr(const std::string& strIp) bIp6 = true; } if ((!bIp4 && !bIp6) || (bIp4 && bIp6)) { - WIFI_LOGE("CheckIpStr strIp:%{private}s error, bIp4:%{public}d,bIp6:%{public}d!\n", strIp.c_str(), bIp4, bIp6); + WIFI_LOGE("CheckIpStr strIp:%{private}s error, bIp4:%{public}d,bIp6:%{public}d!", strIp.c_str(), bIp4, bIp6); return false; } if (bIp4) { uint32_t uIp = 0; if (!Ip4StrConToInt(strIp, uIp)) { - WIFI_LOGE("CheckIpStr Ip4StrConToInt failed, strIp:%{private}s.\n", strIp.c_str()); + WIFI_LOGE("CheckIpStr Ip4StrConToInt failed, strIp:%{private}s.", strIp.c_str()); return false; } } else { uint8_t addr6[sizeof(struct in6_addr)] = {0}; if (!Ip6StrConToChar(strIp, addr6, sizeof(struct in6_addr))) { - WIFI_LOGE("CheckIpStr Ip6StrConToChar failed, strIp:%{private}s.\n", strIp.c_str()); + WIFI_LOGE("CheckIpStr Ip6StrConToChar failed, strIp:%{private}s.", strIp.c_str()); return false; } } @@ -191,30 +192,28 @@ int DhcpFunc::GetLocalIp(const std::string ethInf, std::string& localIp) sd = socket(AF_INET, SOCK_DGRAM, 0); if (-1 == sd) { - WIFI_LOGE("GetLocalIp socket ethInf:%{public}s,strerror:%{public}s!\n", ethInf.c_str(), strerror(errno)); + WIFI_LOGE("GetLocalIp socket ethInf:%{public}s,strerror:%{public}s!", ethInf.c_str(), strerror(errno)); return -1; } if (strncpy_s(ifr.ifr_name, IFNAMSIZ, ethInf.c_str(), IFNAMSIZ - 1) != EOK) { - close(sd); return -1; } ifr.ifr_name[IFNAMSIZ - 1] = 0; // if error: No such device if (ioctl(sd, SIOCGIFADDR, &ifr) < 0) { + WIFI_LOGE("GetLocalIp ioctl ethInf:%{public}s,strerror:%{public}s!", ethInf.c_str(), strerror(errno)); close(sd); - WIFI_LOGE("GetLocalIp ioctl ethInf:%{public}s,strerror:%{public}s!\n", ethInf.c_str(), strerror(errno)); return -1; } if (memcpy_s(&sin, sizeof(sin), &ifr.ifr_addr, sizeof(sin)) != EOK) { - close(sd); return -1; } char ip[IP_SIZE] = { 0 }; - if (snprintf_s(ip, IP_SIZE, IP_SIZE - 1, "%{public}s", inet_ntoa(sin.sin_addr)) < 0) { - WIFI_LOGE("GetLocalIp snprintf_s ethInf:%{public}s,strerror:%{public}s!\n", ethInf.c_str(), strerror(errno)); + if (snprintf_s(ip, IP_SIZE, IP_SIZE - 1, "%s", inet_ntoa(sin.sin_addr)) < 0) { + WIFI_LOGE("GetLocalIp snprintf_s ethInf:%{public}s,strerror:%{public}s!", ethInf.c_str(), strerror(errno)); close(sd); return -1; } @@ -230,17 +229,16 @@ int DhcpFunc::GetLocalMac(const std::string ethInf, std::string& ethMac) bzero(&ifr, sizeof(struct ifreq)); if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { - WIFI_LOGE("GetLocalMac socket ethInf:%{public}s,strerror:%{public}s!\n", ethInf.c_str(), strerror(errno)); + WIFI_LOGE("GetLocalMac socket ethInf:%{public}s,strerror:%{public}s!", ethInf.c_str(), strerror(errno)); return -1; } if (strncpy_s(ifr.ifr_name, IFNAMSIZ, ethInf.c_str(), IFNAMSIZ - 1) != EOK) { - close(sd); return -1; } if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0) { - WIFI_LOGE("GetLocalMac ioctl ethInf:%{public}s,strerror:%{public}s!\n", ethInf.c_str(), strerror(errno)); + WIFI_LOGE("GetLocalMac ioctl ethInf:%{public}s,strerror:%{public}s!", ethInf.c_str(), strerror(errno)); close(sd); return -1; } @@ -257,7 +255,7 @@ int DhcpFunc::GetLocalMac(const std::string ethInf, std::string& ethMac) (unsigned char)ifr.ifr_hwaddr.sa_data[ETH_MAC_ADDR_INDEX_4], (unsigned char)ifr.ifr_hwaddr.sa_data[ETH_MAC_ADDR_INDEX_5]); if (nRes < 0) { - WIFI_LOGE("GetLocalMac snprintf_s ethInf:%{public}s,strerror:%{public}s!\n", ethInf.c_str(), strerror(errno)); + WIFI_LOGE("GetLocalMac snprintf_s ethInf:%{public}s,strerror:%{public}s!", ethInf.c_str(), strerror(errno)); close(sd); return -1; } @@ -292,10 +290,10 @@ bool DhcpFunc::CreateFile(const std::string& filename, const std::string& fileda bool DhcpFunc::RemoveFile(const std::string& filename) { if (std::remove(filename.c_str()) != 0) { - WIFI_LOGE("RemoveFile filename:%{public}s failed!\n", filename.c_str()); + WIFI_LOGE("RemoveFile filename:%{public}s failed!", filename.c_str()); return false; } - WIFI_LOGI("RemoveFile filename:%{public}s success.\n", filename.c_str()); + WIFI_LOGI("RemoveFile filename:%{public}s success.", filename.c_str()); return true; } @@ -322,7 +320,7 @@ bool DhcpFunc::AddFileLineData(const std::string& filename, const std::string& p std::ofstream outFile; outFile.open(filename.c_str()); outFile.flush(); - WIFI_LOGI("AddFileLineData Reflush filename:%{public}s, strFileData:%{public}s.\n", + WIFI_LOGI("AddFileLineData Reflush filename:%{public}s, strFileData:%{public}s.", filename.c_str(), strFileData.c_str()); outFile << strFileData; outFile.close(); @@ -353,7 +351,7 @@ bool DhcpFunc::DelFileLineData(const std::string& filename, const std::string& l std::ofstream outFile; outFile.open(filename.c_str()); outFile.flush(); - WIFI_LOGI("DelFileLineData Reflush filename:%{public}s, strFileData:%{public}s.\n", + WIFI_LOGI("DelFileLineData Reflush filename:%{public}s, strFileData:%{public}s.", filename.c_str(), strFileData.c_str()); outFile << strFileData; outFile.close(); @@ -386,7 +384,7 @@ bool DhcpFunc::ModifyFileLineData(const std::string& filename, const std::string std::ofstream outFile; outFile.open(filename.c_str()); outFile.flush(); - WIFI_LOGI("ModifyFileLineData Reflush filename:%{public}s, strFileData:%{public}s.\n", + WIFI_LOGI("ModifyFileLineData Reflush filename:%{public}s, strFileData:%{public}s.", filename.c_str(), strFileData.c_str()); outFile << strFileData; outFile.close(); @@ -439,86 +437,39 @@ int DhcpFunc::FormatString(struct DhcpPacketResult &result) return 0; } -int DhcpFunc::GetDhcpPacketResult(const std::string& filename, struct DhcpPacketResult &result) -{ - FILE *pFile = fopen(filename.c_str(), "r"); - if (pFile == nullptr) { - WIFI_LOGE("GetDhcpPacketResult() fopen %{public}s fail, err:%{public}s!\n", filename.c_str(), strerror(errno)); - return DHCP_OPT_FAILED; - } - - char strIpFlag[DHCP_NUMBER_EIGHT]; - if (memset_s(strIpFlag, sizeof(strIpFlag), 0, sizeof(strIpFlag)) != EOK) { - fclose(pFile); - return DHCP_OPT_FAILED; - } - /* Format: IpFlag AddTime cliIp servIp subnet dns1 dns2 router1 router2 vendor lease */ - int nRes = fscanf_s(pFile, "%s %u %s %s %s %s %s %s %s %s %u\n", strIpFlag, DHCP_NUMBER_EIGHT, &result.uAddTime, - result.strYiaddr, INET_ADDRSTRLEN, result.strOptServerId, INET_ADDRSTRLEN, result.strOptSubnet, INET_ADDRSTRLEN, - result.strOptDns1, INET_ADDRSTRLEN, result.strOptDns2, INET_ADDRSTRLEN, result.strOptRouter1, INET_ADDRSTRLEN, - result.strOptRouter2, INET_ADDRSTRLEN, result.strOptVendor, DHCP_FILE_MAX_BYTES, &result.uOptLeasetime); - if (nRes == EOF) { - WIFI_LOGE("GetDhcpPacketResult() fscanf %{public}s err:%{public}s!\n", filename.c_str(), strerror(errno)); - fclose(pFile); - return DHCP_OPT_FAILED; - } else if (nRes == 0) { - WIFI_LOGW("GetDhcpPacketResult() fscanf file:%{public}s nRes:0 NULL!\n", filename.c_str()); - fclose(pFile); - return DHCP_OPT_NULL; - } else if (nRes != DHCP_RESULT_NUM) { - WIFI_LOGE("GetDhcpPacketResult() fscanf file:%{public}s nRes:%{public}d ERROR!\n", filename.c_str(), nRes); - fclose(pFile); - return DHCP_OPT_FAILED; - } - - if (fclose(pFile) != 0) { - WIFI_LOGE("GetDhcpPacketResult() fclose file:%{public}s failed, error:%{public}s!\n", - filename.c_str(), strerror(errno)); - return DHCP_OPT_FAILED; - } - - /* Format dhcp packet result */ - if (FormatString(result) != 0) { - WIFI_LOGE("GetDhcpPacketResult() file:%{public}s failed, FormatString result error!\n", filename.c_str()); - return DHCP_OPT_FAILED; - } - - return DHCP_OPT_SUCCESS; -} - int DhcpFunc::InitPidfile(const std::string& piddir, const std::string& pidfile) { if (piddir.empty() || pidfile.empty()) { - WIFI_LOGE("InitPidfile() failed, piddir or pidfile is empty!\n"); + WIFI_LOGE("InitPidfile() failed, piddir or pidfile is empty!"); return DHCP_OPT_FAILED; } - WIFI_LOGI("InitPidfile() piddir:%{public}s, pidfile:%{public}s.\n", piddir.c_str(), pidfile.c_str()); + WIFI_LOGI("InitPidfile() piddir:%{public}s, pidfile:%{public}s.", piddir.c_str(), pidfile.c_str()); unlink(pidfile.c_str()); int fd; if ((fd = open(pidfile.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) { - WIFI_LOGE("InitPidfile() failed, open pidfile:%{public}s err:%{public}s!\n", pidfile.c_str(), strerror(errno)); + WIFI_LOGE("InitPidfile() failed, open pidfile:%{public}s err:%{public}s!", pidfile.c_str(), strerror(errno)); return DHCP_OPT_FAILED; } char buf[PID_MAX_LEN] = {0}; if (snprintf_s(buf, PID_MAX_LEN, PID_MAX_LEN - 1, "%d", getpid()) < 0) { - WIFI_LOGE("InitPidfile() %{public}s failed, snprintf_s error:%{public}s!\n", pidfile.c_str(), strerror(errno)); + WIFI_LOGE("InitPidfile() %{public}s failed, snprintf_s error:%{public}s!", pidfile.c_str(), strerror(errno)); close(fd); return DHCP_OPT_FAILED; } ssize_t bytes; if ((bytes = write(fd, buf, strlen(buf))) <= 0) { - WIFI_LOGE("InitPidfile() failed, write pidfile:%{public}s error:%{public}s, bytes:%{public}zu!\n", + WIFI_LOGE("InitPidfile() failed, write pidfile:%{public}s error:%{public}s, bytes:%{public}zu!", pidfile.c_str(), strerror(errno), bytes); close(fd); return DHCP_OPT_FAILED; } - WIFI_LOGI("InitPidfile() pid:%{public}s write %{public}s, bytes:%{public}zu!\n", buf, pidfile.c_str(), bytes); + WIFI_LOGI("InitPidfile() pid:%{public}s write %{public}s, bytes:%{public}zu!", buf, pidfile.c_str(), bytes); close(fd); if (chdir(piddir.c_str()) != 0) { - WIFI_LOGE("InitPidfile() failed, chdir piddir:%{public}s err:%{public}s!\n", piddir.c_str(), strerror(errno)); + WIFI_LOGE("InitPidfile() failed, chdir piddir:%{public}s err:%{public}s!", piddir.c_str(), strerror(errno)); return DHCP_OPT_FAILED; } @@ -536,14 +487,14 @@ pid_t DhcpFunc::GetPID(const std::string& pidfile) /* Check pidfile is or not exists. */ struct stat sb; if (stat(pidfile.c_str(), &sb) != 0) { - WIFI_LOGW("GetPID() pidfile:%{public}s stat:%{public}s!\n", pidfile.c_str(), strerror(errno)); + WIFI_LOGW("GetPID() pidfile:%{public}s stat:%{public}s!", pidfile.c_str(), strerror(errno)); return -1; } - WIFI_LOGI("GetPID() pidfile:%{public}s stat st_size:%{public}d.\n", pidfile.c_str(), (int)sb.st_size); + WIFI_LOGI("GetPID() pidfile:%{public}s stat st_size:%{public}d.", pidfile.c_str(), (int)sb.st_size); int fd; if ((fd = open(pidfile.c_str(), O_RDONLY)) < 0) { - WIFI_LOGE("GetPID() failed, open pidfile:%{public}s error!\n", pidfile.c_str()); + WIFI_LOGE("GetPID() failed, open pidfile:%{public}s error!", pidfile.c_str()); return -1; } @@ -552,11 +503,11 @@ pid_t DhcpFunc::GetPID(const std::string& pidfile) char buf[PID_MAX_LEN] = {0}; ssize_t bytes; if ((bytes = read(fd, buf, sb.st_size)) < 0) { - WIFI_LOGE("GetPID() failed, read pidfile:%{public}s error, bytes:%{public}zu!\n", pidfile.c_str(), bytes); + WIFI_LOGE("GetPID() failed, read pidfile:%{public}s error, bytes:%{public}zu!", pidfile.c_str(), bytes); close(fd); return -1; } - WIFI_LOGI("GetPID() read pidfile:%{public}s, buf:%{public}s, bytes:%{public}zu.\n", pidfile.c_str(), buf, bytes); + WIFI_LOGI("GetPID() read pidfile:%{public}s, buf:%{public}s, bytes:%{public}zu.", pidfile.c_str(), buf, bytes); close(fd); return atoi(buf); @@ -565,23 +516,23 @@ pid_t DhcpFunc::GetPID(const std::string& pidfile) int DhcpFunc::CreateDirs(const std::string dirs, int mode) { if (dirs.empty() || (dirs.size() >= DIR_MAX_LEN)) { - WIFI_LOGE("CreateDirs() dirs:%{public}s error!\n", dirs.c_str()); + WIFI_LOGE("CreateDirs() dirs:%{public}s error!", dirs.c_str()); return DHCP_OPT_FAILED; } int nSrcLen = (int)dirs.size(); char strDir[DIR_MAX_LEN] = {0}; if (strncpy_s(strDir, sizeof(strDir), dirs.c_str(), dirs.size()) != EOK) { - WIFI_LOGE("CreateDirs() strncpy_s dirs:%{public}s failed!\n", dirs.c_str()); + WIFI_LOGE("CreateDirs() strncpy_s dirs:%{public}s failed!", dirs.c_str()); return DHCP_OPT_FAILED; } if (strDir[nSrcLen - 1] != '/') { if (nSrcLen == (DIR_MAX_LEN - 1)) { - WIFI_LOGE("CreateDirs() dirs:%{public}s len:%{public}d error!\n", dirs.c_str(), nSrcLen); + WIFI_LOGE("CreateDirs() dirs:%{public}s len:%{public}d error!", dirs.c_str(), nSrcLen); return DHCP_OPT_FAILED; } if (strcat_s(strDir, sizeof(strDir), "/") != EOK) { - WIFI_LOGE("CreateDirs() strcat_s strDir:%{public}s failed!\n", strDir); + WIFI_LOGE("CreateDirs() strcat_s strDir:%{public}s failed!", strDir); return DHCP_OPT_FAILED; } nSrcLen++; @@ -592,13 +543,101 @@ int DhcpFunc::CreateDirs(const std::string dirs, int mode) if (strDir[i] == '/') { strDir[i] = 0; if ((access(strDir, F_OK) != 0) && (mkdir(strDir, mode) != 0)) { - WIFI_LOGE("CreateDirs() mkdir %{public}s %{public}.4o %{public}s!\n", strDir, mode, strerror(errno)); + WIFI_LOGE("CreateDirs() mkdir %{public}s %{public}.4o %{public}s!", strDir, mode, strerror(errno)); return DHCP_OPT_FAILED; } strDir[i] = '/'; } } - WIFI_LOGI("CreateDirs() %{public}s %{public}.4o success.\n", dirs.c_str(), mode); + WIFI_LOGI("CreateDirs() %{public}s %{public}.4o success.", dirs.c_str(), mode); + return DHCP_OPT_SUCCESS; +} + +bool DhcpFunc::SplitString( + const std::string src, const std::string delim, const int count, std::vector &splits) +{ + if (src.empty() || delim.empty()) { + WIFI_LOGE("SplitString() error, src or delim is empty!"); + return false; + } + + splits.clear(); + + std::string strData(src); + int nDelim = 0; + char *pSave = NULL; + char *pTok = strtok_r(const_cast(strData.c_str()), delim.c_str(), &pSave); + while (pTok != NULL) { + splits.push_back(std::string(pTok)); + nDelim++; + pTok = strtok_r(NULL, delim.c_str(), &pSave); + } + if (nDelim != count) { + WIFI_LOGE("SplitString() %{public}s failed, nDelim:%{public}d,count:%{public}d!", src.c_str(), nDelim, count); + return false; + } + WIFI_LOGI("SplitString() %{private}s success, delim:%{public}s, count:%{public}d, splits.size():%{public}d.", + src.c_str(), delim.c_str(), count, (int)splits.size()); + return true; +} + +bool DhcpFunc::SubscribeDhcpCommonEvent( + const std::shared_ptr &subscriber) +{ + return OHOS::EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber); +} + +int DhcpFunc::SubscribeDhcpEvent(const std::string action, int timeouts) +{ + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(action); + EventFwk::CommonEventSubscribeInfo subInfo(matchingSkills); + std::shared_ptr dhcpSubscriber = + std::make_shared(subInfo); + if (!DhcpFunc::SubscribeDhcpCommonEvent(dhcpSubscriber)) { + WIFI_LOGE("SubscribeDhcpEvent() SubscribeDhcpCommonEvent %{public}s failed!", action.c_str()); + return DHCP_OPT_FAILED; + } + WIFI_LOGI("SubscribeDhcpEvent() SubscribeDhcpCommonEvent %{public}s success.", action.c_str()); + return DHCP_OPT_SUCCESS; +} + +bool DhcpFunc::UnsubscribeDhcpCommonEvent( + const std::shared_ptr &subscriber) +{ + return OHOS::EventFwk::CommonEventManager::UnSubscribeCommonEvent(subscriber); +} + +int DhcpFunc::UnsubscribeDhcpEvent(const std::string action, int timeouts) +{ + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(action); + EventFwk::CommonEventSubscribeInfo subInfo(matchingSkills); + std::shared_ptr dhcpSubscriber = + std::make_shared(subInfo); + if (!DhcpFunc::UnsubscribeDhcpCommonEvent(dhcpSubscriber)) { + WIFI_LOGE("UnsubscribeDhcpEvent() UnsubscribeDhcpCommonEvent %{public}s failed!", action.c_str()); + return DHCP_OPT_FAILED; + } + WIFI_LOGI("UnsubscribeDhcpEvent() UnsubscribeDhcpCommonEvent %{public}s success.", action.c_str()); + return DHCP_OPT_SUCCESS; +} + +bool DhcpFunc::PublishDhcpEvent(const std::string action, const int code, const std::string data) +{ + OHOS::EventFwk::Want want; + want.SetAction(action); + OHOS::EventFwk::CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + if (!OHOS::EventFwk::CommonEventManager::PublishCommonEvent(commonData)) { + WIFI_LOGE("PublishDhcpEvent() PublishCommonEvent failed, action:%{public}s, code:%{public}d, data:%{public}s.", + action.c_str(), code, data.c_str()); + return DHCP_OPT_FAILED; + } + WIFI_LOGI("PublishDhcpEvent() PublishCommonEvent success, action:%{public}s, code:%{public}d, data:%{private}s.", + action.c_str(), code, data.c_str()); return DHCP_OPT_SUCCESS; } } // namespace Wifi diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_server_service_impl.cpp b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_server_service_impl.cpp index a87fb20ff..2bab9ca2f 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_server_service_impl.cpp +++ b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_server_service_impl.cpp @@ -30,7 +30,7 @@ pid_t DhcpServerServiceImpl::mPidDhcpServer = 0; DhcpServerServiceImpl::DhcpServerServiceImpl() { - WIFI_LOGI("DhcpServerServiceImpl::DhcpServerServiceImpl()...\n"); + WIFI_LOGI("DhcpServerServiceImpl::DhcpServerServiceImpl()..."); m_setInterfaces.clear(); m_mapTagDhcpRange.clear(); m_mapInfDhcpRange.clear(); @@ -43,13 +43,13 @@ DhcpServerServiceImpl::DhcpServerServiceImpl() DhcpServerServiceImpl::~DhcpServerServiceImpl() { - WIFI_LOGI("DhcpServerServiceImpl::~DhcpServerServiceImpl()...\n"); + WIFI_LOGI("DhcpServerServiceImpl::~DhcpServerServiceImpl()..."); auto iterInterfaces = m_setInterfaces.begin(); while (iterInterfaces != m_setInterfaces.end()) { if (StopDhcpServer(*iterInterfaces) != DHCP_OPT_SUCCESS) { - WIFI_LOGE("~StartDhcpServer() StopDhcpServer ifname:%{public}s failed!\n", (*iterInterfaces).c_str()); + WIFI_LOGE("~StartDhcpServer() StopDhcpServer ifname:%{public}s failed!", (*iterInterfaces).c_str()); } else { - WIFI_LOGW("~StartDhcpServer() StopDhcpServer ifname:%{public}s success.\n", (*iterInterfaces).c_str()); + WIFI_LOGW("~StartDhcpServer() StopDhcpServer ifname:%{public}s success.", (*iterInterfaces).c_str()); } m_setInterfaces.erase(iterInterfaces++); } @@ -60,21 +60,21 @@ DhcpServerServiceImpl::~DhcpServerServiceImpl() int DhcpServerServiceImpl::StartDhcpServer(const std::string &ifname) { if (ifname.empty()) { - WIFI_LOGE("DhcpServerServiceImpl::StartDhcpServer() error, ifname is empty!\n"); + WIFI_LOGE("DhcpServerServiceImpl::StartDhcpServer() error, ifname is empty!"); return DHCP_OPT_FAILED; } - WIFI_LOGI("enter DhcpServerServiceImpl::StartDhcpServer()...ifname:%{public}s.\n", ifname.c_str()); + WIFI_LOGI("enter DhcpServerServiceImpl::StartDhcpServer()...ifname:%{public}s.", ifname.c_str()); /* check and update interface config file */ if (CheckAndUpdateConf(ifname) != DHCP_OPT_SUCCESS) { - WIFI_LOGE("StartDhcpServer() CheckAndUpdateConf failed, ifname:%{public}s.\n", ifname.c_str()); + WIFI_LOGE("StartDhcpServer() CheckAndUpdateConf failed, ifname:%{public}s.", ifname.c_str()); return DHCP_OPT_FAILED; } /* Add the specified interface. */ if (AddSpecifiedInterface(ifname) != DHCP_OPT_SUCCESS) { - WIFI_LOGE("StartDhcpServer() AddSpecifiedInterface failed, ifname:%{public}s.\n", ifname.c_str()); + WIFI_LOGE("StartDhcpServer() AddSpecifiedInterface failed, ifname:%{public}s.", ifname.c_str()); return DHCP_OPT_FAILED; } @@ -91,7 +91,7 @@ int DhcpServerServiceImpl::StartDhcpServer(const std::string &ifname) /* start dhcp server process */ pid_t pid_server; if ((pid_server = vfork()) < 0) { - WIFI_LOGE("StartDhcpServer() vfork() failed, pid_server:%{public}d!\n", pid_server); + WIFI_LOGE("StartDhcpServer() vfork() failed, pid_server:%{public}d!", pid_server); return DHCP_OPT_FAILED; } if (pid_server == 0) { @@ -111,11 +111,11 @@ int DhcpServerServiceImpl::StartDhcpServer(const std::string &ifname) int DhcpServerServiceImpl::StopDhcpServer(const std::string &ifname) { if (ifname.empty()) { - WIFI_LOGE("StopDhcpServer() error, ifname is empty!\n"); + WIFI_LOGE("StopDhcpServer() error, ifname is empty!"); return DHCP_OPT_FAILED; } if (mPidDhcpServer == 0) { - WIFI_LOGI("StopDhcpServer() %{public}s, %{public}s already stop.\n", ifname.c_str(), DHCP_SERVER_FILE.c_str()); + WIFI_LOGI("StopDhcpServer() %{public}s, %{public}s already stop.", ifname.c_str(), DHCP_SERVER_FILE.c_str()); return DHCP_OPT_SUCCESS; } bool bStopDhcpServer = false; @@ -127,12 +127,12 @@ int DhcpServerServiceImpl::StopDhcpServer(const std::string &ifname) if (iterRangeMap != m_mapInfDhcpRange.end()) { std::string strInfFile = DHCP_SERVER_CONFIG_DIR + ifname + ".conf"; if (DeleteInfConf(strInfFile) != DHCP_OPT_SUCCESS) { - WIFI_LOGE("StopDhcpServer() DeleteInfConf failed, ifname:%{public}s.\n", ifname.c_str()); + WIFI_LOGE("StopDhcpServer() DeleteInfConf failed, ifname:%{public}s.", ifname.c_str()); return DHCP_OPT_FAILED; } if (m_mapInfDhcpRange.size() == 1) { - WIFI_LOGI("StopDhcpServer() ifname:%{public}s, only the if service, now StopServer.\n", ifname.c_str()); + WIFI_LOGI("StopDhcpServer() ifname:%{public}s, only the if service, now StopServer.", ifname.c_str()); bStopDhcpServer = true; } else { bReloadServerCfg = true; @@ -151,7 +151,7 @@ int DhcpServerServiceImpl::StopDhcpServer(const std::string &ifname) } else { /* reload dhcp server config */ if (bReloadServerCfg && (ReConf() != DHCP_OPT_SUCCESS)) { - WIFI_LOGE("StopDhcpServer() ReConf failed, ifname:%{public}s.\n", ifname.c_str()); + WIFI_LOGE("StopDhcpServer() ReConf failed, ifname:%{public}s.", ifname.c_str()); return DHCP_OPT_FAILED; } } @@ -166,22 +166,22 @@ int DhcpServerServiceImpl::StopDhcpServer(const std::string &ifname) int DhcpServerServiceImpl::GetServerStatus() { if (mPidDhcpServer == 0) { - WIFI_LOGI("GetServerStatus() pro:%{public}s not start.\n", DHCP_SERVER_FILE.c_str()); + WIFI_LOGI("GetServerStatus() pro:%{public}s not start.", DHCP_SERVER_FILE.c_str()); return 0; } - WIFI_LOGI("GetServerStatus() pro:%{public}s normal started.\n", DHCP_SERVER_FILE.c_str()); + WIFI_LOGI("GetServerStatus() pro:%{public}s normal started.", DHCP_SERVER_FILE.c_str()); return 1; } int DhcpServerServiceImpl::PutDhcpRange(const std::string &tagName, const DhcpRange &range) { if (tagName.empty()) { - WIFI_LOGE("DhcpServerServiceImpl::PutDhcpRange() error, tagName is empty!\n"); + WIFI_LOGE("DhcpServerServiceImpl::PutDhcpRange() error, tagName is empty!"); return DHCP_OPT_FAILED; } if ((range.iptype == -1) || range.strStartip.empty() || range.strEndip.empty()) { WIFI_LOGE("PutDhcpRange() tagName:%{public}s failed, range.iptype:%{public}d or strStartip:%{private}s or " - "strEndip:%{private}s error!\n", + "strEndip:%{private}s error!", tagName.c_str(), range.iptype, range.strStartip.c_str(), @@ -189,11 +189,11 @@ int DhcpServerServiceImpl::PutDhcpRange(const std::string &tagName, const DhcpRa return DHCP_OPT_FAILED; } - WIFI_LOGI("enter PutDhcpRange() tagName:%{public}s.\n", tagName.c_str()); + WIFI_LOGI("enter PutDhcpRange() tagName:%{public}s.", tagName.c_str()); /* check invalid and already exist in dhcp range */ if (!CheckIpAddrRange(range)) { - WIFI_LOGE("PutDhcpRange() CheckIpAddrRange failed, tagName:%{public}s!\n", tagName.c_str()); + WIFI_LOGE("PutDhcpRange() CheckIpAddrRange failed, tagName:%{public}s!", tagName.c_str()); return DHCP_OPT_FAILED; } @@ -204,7 +204,7 @@ int DhcpServerServiceImpl::PutDhcpRange(const std::string &tagName, const DhcpRa if ((iterRange.iptype == range.iptype) && (iterRange.strStartip == range.strStartip) && (iterRange.strEndip == range.strEndip)) { WIFI_LOGE("PutDhcpRange() tagName:%{public}s failed, " - "range.iptype:%{public}d,strStartip:%{private}s,strEndip:%{private}s already exist!\n", + "range.iptype:%{public}d,strStartip:%{private}s,strEndip:%{private}s already exist!", tagName.c_str(), range.iptype, range.strStartip.c_str(), @@ -213,12 +213,12 @@ int DhcpServerServiceImpl::PutDhcpRange(const std::string &tagName, const DhcpRa } } iterRangeMap->second.push_back(range); - WIFI_LOGI("PutDhcpRange() m_mapTagDhcpRange find tagName:%{public}s, need push_back.\n", tagName.c_str()); + WIFI_LOGI("PutDhcpRange() m_mapTagDhcpRange find tagName:%{public}s, need push_back.", tagName.c_str()); } else { std::list listDhcpRange; listDhcpRange.push_back(range); m_mapTagDhcpRange.emplace(std::make_pair(tagName, listDhcpRange)); - WIFI_LOGI("PutDhcpRange() m_mapTagDhcpRange no find tagName:%{public}s, need emplace.\n", tagName.c_str()); + WIFI_LOGI("PutDhcpRange() m_mapTagDhcpRange no find tagName:%{public}s, need emplace.", tagName.c_str()); } return DHCP_OPT_SUCCESS; @@ -227,12 +227,12 @@ int DhcpServerServiceImpl::PutDhcpRange(const std::string &tagName, const DhcpRa int DhcpServerServiceImpl::RemoveDhcpRange(const std::string &tagName, const DhcpRange &range) { if (tagName.empty()) { - WIFI_LOGE("DhcpServerServiceImpl::RemoveDhcpRange() error, tagName is empty!\n"); + WIFI_LOGE("DhcpServerServiceImpl::RemoveDhcpRange() error, tagName is empty!"); return DHCP_OPT_FAILED; } if ((range.iptype == -1) || range.strStartip.empty() || range.strEndip.empty()) { WIFI_LOGE("RemoveDhcpRange() tagName:%{public}s failed, range.iptype:%{public}d or strStartip:%{private}s or " - "strEndip:%{private}s error!\n", + "strEndip:%{private}s error!", tagName.c_str(), range.iptype, range.strStartip.c_str(), @@ -249,7 +249,7 @@ int DhcpServerServiceImpl::RemoveDhcpRange(const std::string &tagName, const Dhc (iterRange->strEndip == range.strEndip)) { m_mapTagDhcpRange[tagName].erase(iterRange++); WIFI_LOGI("RemoveDhcpRange() find tagName:%{public}s, " - "range.iptype:%{public}d,strStartip:%{private}s,strEndip:%{private}s, erase.\n", + "range.iptype:%{public}d,strStartip:%{private}s,strEndip:%{private}s, erase.", tagName.c_str(), range.iptype, range.strStartip.c_str(), @@ -258,9 +258,9 @@ int DhcpServerServiceImpl::RemoveDhcpRange(const std::string &tagName, const Dhc } iterRange++; } - WIFI_LOGE("RemoveDhcpRange() find tagName:%{public}s, second no find range, erase failed!\n", tagName.c_str()); + WIFI_LOGE("RemoveDhcpRange() find tagName:%{public}s, second no find range, erase failed!", tagName.c_str()); } else { - WIFI_LOGE("RemoveDhcpRange no find tagName:%{public}s, erase failed!\n", tagName.c_str()); + WIFI_LOGE("RemoveDhcpRange no find tagName:%{public}s, erase failed!", tagName.c_str()); } return DHCP_OPT_FAILED; @@ -269,7 +269,7 @@ int DhcpServerServiceImpl::RemoveDhcpRange(const std::string &tagName, const Dhc int DhcpServerServiceImpl::RemoveAllDhcpRange(const std::string &tagName) { if (tagName.empty()) { - WIFI_LOGE("DhcpServerServiceImpl::RemoveAllDhcpRange() error, tagName is empty!\n"); + WIFI_LOGE("DhcpServerServiceImpl::RemoveAllDhcpRange() error, tagName is empty!"); return DHCP_OPT_FAILED; } @@ -277,9 +277,9 @@ int DhcpServerServiceImpl::RemoveAllDhcpRange(const std::string &tagName) auto iterRangeMap = m_mapTagDhcpRange.find(tagName); if (iterRangeMap != m_mapTagDhcpRange.end()) { m_mapTagDhcpRange.erase(iterRangeMap); - WIFI_LOGI("RemoveAllDhcpRange() find tagName:%{public}s, erase success.\n", tagName.c_str()); + WIFI_LOGI("RemoveAllDhcpRange() find tagName:%{public}s, erase success.", tagName.c_str()); } else { - WIFI_LOGI("RemoveAllDhcpRange() no find tagName:%{public}s, not need erase!\n", tagName.c_str()); + WIFI_LOGI("RemoveAllDhcpRange() no find tagName:%{public}s, not need erase!", tagName.c_str()); } return DHCP_OPT_SUCCESS; @@ -288,12 +288,12 @@ int DhcpServerServiceImpl::RemoveAllDhcpRange(const std::string &tagName) int DhcpServerServiceImpl::SetDhcpRange(const std::string &ifname, const DhcpRange &range) { if (ifname.empty()) { - WIFI_LOGE("DhcpServerServiceImpl::SetDhcpRange() error, ifname is empty!\n"); + WIFI_LOGE("DhcpServerServiceImpl::SetDhcpRange() error, ifname is empty!"); return DHCP_OPT_FAILED; } if ((range.iptype == -1) || range.strStartip.empty() || range.strEndip.empty()) { WIFI_LOGE("SetDhcpRange() ifname:%{public}s failed, range.iptype:%{public}d or strStartip:%{private}s or " - "strEndip:%{private}s error!\n", + "strEndip:%{private}s error!", ifname.c_str(), range.iptype, range.strStartip.c_str(), range.strEndip.c_str()); return DHCP_OPT_FAILED; } @@ -301,13 +301,13 @@ int DhcpServerServiceImpl::SetDhcpRange(const std::string &ifname, const DhcpRan /* check dhcp server service status */ int nStatus = GetServerStatus(); if (nStatus != 1) { - WIFI_LOGE("SetDhcpRange() ifname:%{public}s failed, dhcp status:%{public}d error!\n", ifname.c_str(), nStatus); + WIFI_LOGE("SetDhcpRange() ifname:%{public}s failed, dhcp status:%{public}d error!", ifname.c_str(), nStatus); return DHCP_OPT_FAILED; } /* put dhcp range */ if (PutDhcpRange(ifname, range) != DHCP_OPT_SUCCESS) { - WIFI_LOGE("SetDhcpRange() PutDhcpRange failed, ifname:%{public}s.\n", ifname.c_str()); + WIFI_LOGE("SetDhcpRange() PutDhcpRange failed, ifname:%{public}s.", ifname.c_str()); return DHCP_OPT_FAILED; } @@ -318,23 +318,23 @@ int DhcpServerServiceImpl::SetDhcpRange(const std::string &ifname, const DhcpRan if ((iterRange.iptype == range.iptype) && (iterRange.strStartip == range.strStartip) && (iterRange.strEndip == range.strEndip)) { WIFI_LOGE("SetDhcpRange() ifname:%{public}s failed, " - "range.iptype:%{public}d,strStartip:%{private}s,strEndip:%{private}s already exist!\n", + "range.iptype:%{public}d,strStartip:%{private}s,strEndip:%{private}s already exist!", ifname.c_str(), range.iptype, range.strStartip.c_str(), range.strEndip.c_str()); return DHCP_OPT_FAILED; } } iterRangeMap->second.push_back(range); - WIFI_LOGI("SetDhcpRange() m_mapInfDhcpRange find ifname:%{public}s, second need push_back.\n", ifname.c_str()); + WIFI_LOGI("SetDhcpRange() m_mapInfDhcpRange find ifname:%{public}s, second need push_back.", ifname.c_str()); } else { std::list listDhcpRange; listDhcpRange.push_back(range); m_mapInfDhcpRange.emplace(std::make_pair(ifname, listDhcpRange)); - WIFI_LOGI("SetDhcpRange() m_mapInfDhcpRange no find ifname:%{public}s, need emplace.\n", ifname.c_str()); + WIFI_LOGI("SetDhcpRange() m_mapInfDhcpRange no find ifname:%{public}s, need emplace.", ifname.c_str()); } /* update or reload interface config file */ if (CheckAndUpdateConf(ifname) != DHCP_OPT_SUCCESS) { - WIFI_LOGE("SetDhcpRange() CheckAndUpdateConf failed, ifname:%{public}s.\n", ifname.c_str()); + WIFI_LOGE("SetDhcpRange() CheckAndUpdateConf failed, ifname:%{public}s.", ifname.c_str()); return DHCP_OPT_FAILED; } @@ -345,23 +345,23 @@ int DhcpServerServiceImpl::SetDhcpRange(const std::string &ifname, const DhcpRan int DhcpServerServiceImpl::SetDhcpRange(const std::string &ifname, const std::string &tagName) { if (ifname.empty() || tagName.empty()) { - WIFI_LOGE("SetDhcpRange() failed, ifname or tagName is empty!\n"); + WIFI_LOGE("SetDhcpRange() failed, ifname or tagName is empty!"); return DHCP_OPT_FAILED; } auto iterTag = m_mapTagDhcpRange.find(tagName); if (iterTag == m_mapTagDhcpRange.end()) { - WIFI_LOGE("SetDhcpRange() failed, m_mapTagDhcpRange no find tagName:%{public}s.\n", tagName.c_str()); + WIFI_LOGE("SetDhcpRange() failed, m_mapTagDhcpRange no find tagName:%{public}s.", tagName.c_str()); return DHCP_OPT_FAILED; } if ((iterTag->second).empty()) { - WIFI_LOGE("SetDhcpRange() failed, m_mapTagDhcpRange second is empty, tagName:%{public}s.\n", tagName.c_str()); + WIFI_LOGE("SetDhcpRange() failed, m_mapTagDhcpRange second is empty, tagName:%{public}s.", tagName.c_str()); return DHCP_OPT_FAILED; } /* check dhcp server service status */ int nStatus = GetServerStatus(); if (nStatus != 1) { - WIFI_LOGE("SetDhcpRange() ifname:%{public}s,tagName:%{public}s failed,dhcp status:%{public}d!\n", + WIFI_LOGE("SetDhcpRange() ifname:%{public}s,tagName:%{public}s failed,dhcp status:%{public}d!", ifname.c_str(), tagName.c_str(), nStatus); return DHCP_OPT_FAILED; } @@ -371,25 +371,25 @@ int DhcpServerServiceImpl::SetDhcpRange(const std::string &ifname, const std::st if (iterRangeMap != m_mapInfDhcpRange.end()) { /* check dhcp range is already exist */ if (CheckTagDhcpRange(iterTag->second, iterRangeMap->second)) { - WIFI_LOGE("SetDhcpRange() ifname:%{public}s,tagName:%{public}s failed, dhcp range is same!\n", + WIFI_LOGE("SetDhcpRange() ifname:%{public}s,tagName:%{public}s failed, dhcp range is same!", ifname.c_str(), tagName.c_str()); return DHCP_OPT_FAILED; } for (auto iterTagValue : iterTag->second) { iterRangeMap->second.push_back(iterTagValue); - WIFI_LOGI("SetDhcpRange() find ifname:%{public}s, second need push tagName:%{public}s.\n", + WIFI_LOGI("SetDhcpRange() find ifname:%{public}s, second need push tagName:%{public}s.", ifname.c_str(), tagName.c_str()); } } else { m_mapInfDhcpRange.emplace(std::make_pair(ifname, iterTag->second)); - WIFI_LOGI("SetDhcpRange() no find ifname:%{public}s,tagName:%{public}s, need emplace.\n", + WIFI_LOGI("SetDhcpRange() no find ifname:%{public}s,tagName:%{public}s, need emplace.", ifname.c_str(), tagName.c_str()); } /* update or reload interface config file */ if (CheckAndUpdateConf(ifname) != DHCP_OPT_SUCCESS) { - WIFI_LOGE("SetDhcpRange() CheckAndUpdateConf failed, ifname:%{public}s,tagName:%{public}s!\n", + WIFI_LOGE("SetDhcpRange() CheckAndUpdateConf failed, ifname:%{public}s,tagName:%{public}s!", ifname.c_str(), tagName.c_str()); return DHCP_OPT_FAILED; } @@ -401,7 +401,7 @@ int DhcpServerServiceImpl::SetDhcpRange(const std::string &ifname, const std::st int DhcpServerServiceImpl::GetLeases(std::vector &leases) { if (!DhcpFunc::IsExistFile(DHCP_SERVER_LEASES_FILE)) { - WIFI_LOGE("GetLeases() failed, dhcp leasefile:%{public}s no exist!\n", DHCP_SERVER_LEASES_FILE.c_str()); + WIFI_LOGE("GetLeases() failed, dhcp leasefile:%{public}s no exist!", DHCP_SERVER_LEASES_FILE.c_str()); return DHCP_OPT_FAILED; } @@ -417,37 +417,37 @@ int DhcpServerServiceImpl::GetLeases(std::vector &leases) } inFile.close(); - WIFI_LOGI("GetLeases() leases.size:%{public}d.\n", (int)leases.size()); + WIFI_LOGI("GetLeases() leases.size:%{public}d.", (int)leases.size()); return DHCP_OPT_SUCCESS; } int DhcpServerServiceImpl::GetDhcpSerProExit(const std::string &ifname, IDhcpResultNotify *pResultNotify) { if (ifname.empty()) { - WIFI_LOGE("DhcpServerServiceImpl::GetDhcpSerProExit() error, ifname is empty!\n"); + WIFI_LOGE("DhcpServerServiceImpl::GetDhcpSerProExit() error, ifname is empty!"); return DHCP_OPT_FAILED; } if (pResultNotify == nullptr) { - WIFI_LOGE("DhcpServerServiceImpl::GetDhcpSerProExit() error, pResultNotify = nullptr!\n"); + WIFI_LOGE("DhcpServerServiceImpl::GetDhcpSerProExit() error, pResultNotify = nullptr!"); return DHCP_OPT_FAILED; } auto iterExitNotify = m_mapDhcpSerExitNotify.find(ifname); if (iterExitNotify == m_mapDhcpSerExitNotify.end()) { - WIFI_LOGI("GetDhcpSerProExit() SerExitNotify no find ifname:%{public}s, need emplace.\n", ifname.c_str()); + WIFI_LOGI("GetDhcpSerProExit() SerExitNotify no find ifname:%{public}s, need emplace.", ifname.c_str()); m_mapDhcpSerExitNotify.emplace(std::make_pair(ifname, pResultNotify)); } else { - WIFI_LOGW("GetDhcpSerProExit() SerExitNotify find ifname:%{public}s, not need emplace!\n", ifname.c_str()); + WIFI_LOGW("GetDhcpSerProExit() SerExitNotify find ifname:%{public}s, not need emplace!", ifname.c_str()); } if (pDhcpSerProExitThread == nullptr) { pDhcpSerProExitThread = new std::thread(&DhcpServerServiceImpl::RunDhcpSerProExitThreadFunc, this); if (pDhcpSerProExitThread == nullptr) { - WIFI_LOGE("DhcpServerServiceImpl::GetDhcpSerProExit() init pDhcpSerProExitThread failed!\n"); + WIFI_LOGE("DhcpServerServiceImpl::GetDhcpSerProExit() init pDhcpSerProExitThread failed!"); return DHCP_OPT_FAILED; } - WIFI_LOGI("DhcpServerServiceImpl::GetDhcpSerProExit() init pDhcpSerProExitThread success.\n"); + WIFI_LOGI("DhcpServerServiceImpl::GetDhcpSerProExit() init pDhcpSerProExitThread success."); } return DHCP_OPT_SUCCESS; @@ -456,26 +456,26 @@ int DhcpServerServiceImpl::GetDhcpSerProExit(const std::string &ifname, IDhcpRes int DhcpServerServiceImpl::ReConf() { if (mPidDhcpServer == 0) { - WIFI_LOGE("ReConf() failed, %{public}s not start, config can not reload!\n", DHCP_SERVER_FILE.c_str()); + WIFI_LOGE("ReConf() failed, %{public}s not start, config can not reload!", DHCP_SERVER_FILE.c_str()); return DHCP_OPT_FAILED; } - WIFI_LOGI("enter ReConf(), now restart server:[ %{public}s ], mPidDhcpServer:%{public}d.\n", + WIFI_LOGI("enter ReConf(), now restart server:[ %{public}s ], mPidDhcpServer:%{public}d.", DHCP_SERVER_FILE.c_str(), mPidDhcpServer); /* stop dhcp server process */ if (StopServer(mPidDhcpServer) != DHCP_OPT_SUCCESS) { - WIFI_LOGE("ReConf() failed, StopServer mPidDhcpServer:%{public}d error!\n", mPidDhcpServer); + WIFI_LOGE("ReConf() failed, StopServer mPidDhcpServer:%{public}d error!", mPidDhcpServer); return DHCP_OPT_FAILED; } mPidDhcpServer = 0; - sleep(DHCP_NUMBER_ONE); + sleep(DHCP_NUM_ONE); /* restart dhcp server process for load config */ pid_t pid_server; if ((pid_server = vfork()) < 0) { - WIFI_LOGE("ReConf() failed, vfork() pid_server:%{public}d error!\n", pid_server); + WIFI_LOGE("ReConf() failed, vfork() pid_server:%{public}d error!", pid_server); return DHCP_OPT_FAILED; } if (pid_server == 0) { @@ -494,7 +494,7 @@ int DhcpServerServiceImpl::ReConf() int DhcpServerServiceImpl::ForkParentProcess() { - WIFI_LOGI("enter ForkParentProcess() server:[ %{public}s ], mPidDhcpServer:%{public}d.\n", + WIFI_LOGI("enter ForkParentProcess() server:[ %{public}s ], mPidDhcpServer:%{public}d.", DHCP_SERVER_FILE.c_str(), mPidDhcpServer); RegisterSignal(); return DHCP_OPT_SUCCESS; @@ -502,7 +502,7 @@ int DhcpServerServiceImpl::ForkParentProcess() int DhcpServerServiceImpl::ForkExecProcess(const std::string &ifname) { - WIFI_LOGI("enter ForkExecProcess() server:[ %{public}s ], ifname:%{public}s.\n", + WIFI_LOGI("enter ForkExecProcess() server:[ %{public}s ], ifname:%{public}s.", DHCP_SERVER_FILE.c_str(), ifname.c_str()); const char *args[DHCP_SER_ARGSNUM] = { DHCP_SERVER_FILE.c_str(), @@ -513,10 +513,10 @@ int DhcpServerServiceImpl::ForkExecProcess(const std::string &ifname) nullptr }; if (execv(args[0], const_cast(args)) == -1) { - WIFI_LOGE("execv start failed,errno:%{public}d,strerror(errno):%{public}s,ifname:%{public}s!\n", + WIFI_LOGE("execv start failed,errno:%{public}d,strerror(errno):%{public}s,ifname:%{public}s!", errno, strerror(errno), ifname.c_str()); } else { - WIFI_LOGI("execv start success, ifname:%{public}s!\n", ifname.c_str()); + WIFI_LOGI("execv start success, ifname:%{public}s!", ifname.c_str()); } _exit(-1); @@ -530,33 +530,33 @@ int DhcpServerServiceImpl::StopServer(const pid_t &server_pid) if (kill(server_pid, SIGTERM) == -1) { if (ESRCH == errno) { /* Normal. The subprocess is dead. The SIGCHLD signal triggers the stop hotspot. */ - WIFI_LOGI("StopServer() kill [%{public}d] success, pro pid no exist, pro:%{public}s.\n", + WIFI_LOGI("StopServer() kill [%{public}d] success, pro pid no exist, pro:%{public}s.", server_pid, DHCP_SERVER_FILE.c_str()); return DHCP_OPT_SUCCESS; } - WIFI_LOGE("StopServer() kill [%{public}d] failed, strerror(errno):%{public}s!\n", server_pid, strerror(errno)); + WIFI_LOGE("StopServer() kill [%{public}d] failed, strerror(errno):%{public}s!", server_pid, strerror(errno)); return DHCP_OPT_FAILED; } if (waitpid(server_pid, nullptr, 0) == -1) { - WIFI_LOGE("StopServer() waitpid [%{public}d] failed, strerror(errno):%{public}s!\n", + WIFI_LOGE("StopServer() waitpid [%{public}d] failed, strerror(errno):%{public}s!", server_pid, strerror(errno)); return DHCP_OPT_FAILED; } - WIFI_LOGI("StopServer() waitpid [%{public}d] success, pro:%{public}s!\n", server_pid, DHCP_SERVER_FILE.c_str()); + WIFI_LOGI("StopServer() waitpid [%{public}d] success, pro:%{public}s!", server_pid, DHCP_SERVER_FILE.c_str()); return DHCP_OPT_SUCCESS; } int DhcpServerServiceImpl::CheckAndUpdateConf(const std::string &ifname) { if (ifname.empty()) { - WIFI_LOGE("DhcpServerServiceImpl::CheckAndUpdateConf() error, ifname is empty!\n"); + WIFI_LOGE("DhcpServerServiceImpl::CheckAndUpdateConf() error, ifname is empty!"); return DHCP_OPT_FAILED; } /* delete temp interface config */ std::string strInfFile = DHCP_SERVER_CONFIG_DIR + ifname + ".conf"; if (DeleteInfConf(strInfFile) != DHCP_OPT_SUCCESS) { - WIFI_LOGE("CheckAndUpdateConf() DeleteInfConf failed, ifname:%{public}s!\n", ifname.c_str()); + WIFI_LOGE("CheckAndUpdateConf() DeleteInfConf failed, ifname:%{public}s!", ifname.c_str()); return DHCP_OPT_FAILED; } @@ -567,7 +567,7 @@ int DhcpServerServiceImpl::CheckAndUpdateConf(const std::string &ifname) std::string strMac = ""; if (DhcpFunc::GetLocalMac(ifname.c_str(), strMac) != 0) { - WIFI_LOGE("CheckAndUpdateConf() ifname:%{public}s failed, GetLocalMac error!\n", ifname.c_str()); + WIFI_LOGE("CheckAndUpdateConf() ifname:%{public}s failed, GetLocalMac error!", ifname.c_str()); return DHCP_OPT_FAILED; } @@ -578,7 +578,7 @@ int DhcpServerServiceImpl::CheckAndUpdateConf(const std::string &ifname) if (((iterRange.iptype != 0) && (iterRange.iptype != 1)) || (iterRange.leaseHours <= 0) || (iterRange.strStartip.size() == 0) || (iterRange.strEndip.size() == 0)) { WIFI_LOGE("CheckAndUpdateConf() failed, " - "iptype:%{public}d,leaseHours:%{public}d,strStartip:%{private}s,strEndip:%{private}s error!\n", + "iptype:%{public}d,leaseHours:%{public}d,strStartip:%{private}s,strEndip:%{private}s error!", iterRange.iptype, iterRange.leaseHours, iterRange.strStartip.c_str(), iterRange.strEndip.c_str()); continue; } @@ -610,20 +610,20 @@ int DhcpServerServiceImpl::CheckAndUpdateConf(const std::string &ifname) int DhcpServerServiceImpl::DeleteInfConf(const std::string &if_filename) { if (if_filename.empty()) { - WIFI_LOGE("DhcpServerServiceImpl::DeleteInfConf() error, if_filename is empty!\n"); + WIFI_LOGE("DhcpServerServiceImpl::DeleteInfConf() error, if_filename is empty!"); return DHCP_OPT_FAILED; } if (DhcpFunc::IsExistFile(if_filename)) { return DhcpFunc::RemoveFile(if_filename) ? DHCP_OPT_SUCCESS : DHCP_OPT_FAILED; } - WIFI_LOGI("DeleteInfConf() if_filename:%{public}s no exist, not need delete.\n", if_filename.c_str()); + WIFI_LOGI("DeleteInfConf() if_filename:%{public}s no exist, not need delete.", if_filename.c_str()); return DHCP_OPT_SUCCESS; } bool DhcpServerServiceImpl::CheckIpAddrRange(const DhcpRange &range) { if (((range.iptype != 0) && (range.iptype != 1)) || range.strStartip.empty() || range.strEndip.empty()) { - WIFI_LOGE("CheckIpAddrRange() range.iptype:%{public}d,strStartip:%{private}s,strEndip:%{private}s error!\n", + WIFI_LOGE("CheckIpAddrRange() range.iptype:%{public}d,strStartip:%{private}s,strEndip:%{private}s error!", range.iptype, range.strStartip.c_str(), range.strEndip.c_str()); return false; } @@ -631,20 +631,19 @@ bool DhcpServerServiceImpl::CheckIpAddrRange(const DhcpRange &range) if (range.iptype == 0) { uint32_t uStartIp = 0; if (!DhcpFunc::Ip4StrConToInt(range.strStartip, uStartIp)) { - WIFI_LOGE("CheckIpAddrRange() Ip4StrConToInt failed, range.iptype:%{public}d,strStartip:%{private}s!\n", + WIFI_LOGE("CheckIpAddrRange() Ip4StrConToInt failed, range.iptype:%{public}d,strStartip:%{private}s!", range.iptype, range.strStartip.c_str()); return false; } uint32_t uEndIp = 0; if (!DhcpFunc::Ip4StrConToInt(range.strEndip, uEndIp)) { - WIFI_LOGE("CheckIpAddrRange() Ip4StrConToInt failed, range.iptype:%{public}d,strEndip:%{private}s!\n", + WIFI_LOGE("CheckIpAddrRange() Ip4StrConToInt failed, range.iptype:%{public}d,strEndip:%{private}s!", range.iptype, range.strEndip.c_str()); return false; } /* check ip4 start and end ip */ if (uStartIp >= uEndIp) { - WIFI_LOGE( - "CheckIpAddrRange() failed, uStartIp:%{private}u not less uEndIp:%{private}u!\n", uStartIp, uEndIp); + WIFI_LOGE("CheckIpAddrRange() failed, start:%{private}u not less end:%{private}u!", uStartIp, uEndIp); return false; } } else { @@ -667,7 +666,7 @@ bool DhcpServerServiceImpl::CheckIpAddrRange(const DhcpRange &range) } if (CheckDhcpRangeConflict(dhcpRange, range)) { - WIFI_LOGE("CheckIpAddrRange() Conflict yes, type:%{public}d,Start:%{private}s,End:%{private}s error!\n", + WIFI_LOGE("CheckIpAddrRange() Conflict yes, type:%{public}d,Start:%{private}s,End:%{private}s error!", range.iptype, range.strStartip.c_str(), range.strEndip.c_str()); return false; } @@ -680,7 +679,7 @@ bool DhcpServerServiceImpl::CheckIpAddrRange(const DhcpRange &range) bool DhcpServerServiceImpl::CheckDhcpRangeConflict(const DhcpRange &srcRange, const DhcpRange &addRange) { if (srcRange.iptype != addRange.iptype) { - WIFI_LOGI("CheckDhcpRangeConflict() no, src:%{public}d,add:%{public}d.\n", srcRange.iptype, addRange.iptype); + WIFI_LOGI("CheckDhcpRangeConflict() no, src:%{public}d,add:%{public}d.", srcRange.iptype, addRange.iptype); return false; } @@ -695,36 +694,36 @@ bool DhcpServerServiceImpl::CheckDhcpRangeConflict(const DhcpRange &srcRange, co return false; } if (uSrcStartIp >= uSrcEndIp) { - WIFI_LOGE("CheckDhcpRangeConflict() Start:%{private}u not less End:%{private}u!\n", uSrcStartIp, uSrcEndIp); + WIFI_LOGE("CheckDhcpRangeConflict() Start:%{private}u not less End:%{private}u!", uSrcStartIp, uSrcEndIp); return false; } uint32_t uAddStartIp = 0; if (!DhcpFunc::Ip4StrConToInt(addRange.strStartip, uAddStartIp)) { - WIFI_LOGE("CheckDhcpRangeConflict() Ip4StrConToInt failed, iptype:%{public}d,strStartip:%{private}s!\n", + WIFI_LOGE("CheckDhcpRangeConflict() Ip4StrConToInt failed, iptype:%{public}d,strStartip:%{private}s!", addRange.iptype, addRange.strStartip.c_str()); return false; } uint32_t uAddEndIp = 0; if (!DhcpFunc::Ip4StrConToInt(addRange.strEndip, uAddEndIp)) { - WIFI_LOGE("CheckDhcpRangeConflict() Ip4StrConToInt failed, iptype:%{public}d,strEndip:%{private}s!\n", + WIFI_LOGE("CheckDhcpRangeConflict() Ip4StrConToInt failed, iptype:%{public}d,strEndip:%{private}s!", addRange.iptype, addRange.strEndip.c_str()); return false; } if (uAddStartIp >= uAddEndIp) { - WIFI_LOGE("CheckDhcpRangeConflict() Start:%{private}u not less End:%{private}u!\n", uAddStartIp, uAddEndIp); + WIFI_LOGE("CheckDhcpRangeConflict() Start:%{private}u not less End:%{private}u!", uAddStartIp, uAddEndIp); return false; } if (!((uAddStartIp > uSrcEndIp) || (uAddEndIp < uSrcStartIp))) { WIFI_LOGI("CheckDhcpRangeConflict yes,srcRange.iptype:%{public}d, " "strStartip:%{private}s-uSrcStartIp:%{private}u, strEndip:%{private}s-uSrcEndIp:%{private}u, " - "addRange.strStartip:%{private}s->%{private}u, strEndip:%{private}s->%{private}u.\n", + "addRange.strStartip:%{private}s->%{private}u, strEndip:%{private}s->%{private}u.", srcRange.iptype, srcRange.strStartip.c_str(), uSrcStartIp, srcRange.strEndip.c_str(), uSrcEndIp, addRange.strStartip.c_str(), uAddStartIp, addRange.strEndip.c_str(), uAddEndIp); return true; } - WIFI_LOGI("CheckDhcpRangeConflict() no, srcRange.iptype:%{public}d.\n", srcRange.iptype); + WIFI_LOGI("CheckDhcpRangeConflict() no, srcRange.iptype:%{public}d.", srcRange.iptype); } else { /* check ip6 */ } @@ -739,7 +738,7 @@ bool DhcpServerServiceImpl::CheckTagDhcpRange(std::list &tagRange, st if ((iterInfValue.iptype == iterTagValue.iptype) && (iterInfValue.strStartip == iterTagValue.strStartip) && (iterInfValue.strEndip == iterTagValue.strEndip)) { WIFI_LOGE("CheckTagDhcpRange() failed, iterTagValue.iptype:%{public}d, strStartip:%{private}s, " - "strEndip:%{private}s already exist!\n", + "strEndip:%{private}s already exist!", iterTagValue.iptype, iterTagValue.strStartip.c_str(), iterTagValue.strEndip.c_str()); @@ -754,11 +753,11 @@ void DhcpServerServiceImpl::RunDhcpSerProExitThreadFunc() { for (;;) { if (bDhcpSerProExitThread) { - WIFI_LOGI("RunDhcpSerProExitThreadFunc() bDhcpSerProExitThread:true, break!\n"); + WIFI_LOGI("RunDhcpSerProExitThreadFunc() bDhcpSerProExitThread:true, break!"); break; } if (m_mapDhcpSerExitNotify.empty()) { - sleep(DHCP_NUMBER_ONE); + sleep(DHCP_NUM_ONE); continue; } if (!mProExitSig || mStopServer) { @@ -767,28 +766,28 @@ void DhcpServerServiceImpl::RunDhcpSerProExitThreadFunc() } /* If the dhcp server process exits abnormally, notify other modules. */ - WIFI_LOGI("RunDhcpSerProExitThreadFunc() other modules have notify reqs, now begin notify...\n"); + WIFI_LOGI("RunDhcpSerProExitThreadFunc() other modules have notify reqs, now begin notify..."); auto iterNotify = m_mapDhcpSerExitNotify.begin(); while (iterNotify != m_mapDhcpSerExitNotify.end()) { std::string ifname = iterNotify->first; if (iterNotify->second == nullptr) { - WIFI_LOGE("RunDhcpSerProExitThreadFunc() ifname:%{public}s error, ptr is nullptr!\n", ifname.c_str()); + WIFI_LOGE("RunDhcpSerProExitThreadFunc() ifname:%{public}s error, ptr is nullptr!", ifname.c_str()); iterNotify = m_mapDhcpSerExitNotify.erase(iterNotify); continue; } /* notify other modules */ - WIFI_LOGI("RunDhcpSerProExitThreadFunc() notify other modules.\n"); + WIFI_LOGI("RunDhcpSerProExitThreadFunc() notify other modules."); iterNotify->second->OnSerExitNotify(ifname); iterNotify = m_mapDhcpSerExitNotify.erase(iterNotify); } - WIFI_LOGI("RunDhcpSerProExitThreadFunc() dhcp ser pro exit notify finished.\n"); - sleep(DHCP_NUMBER_ONE); + WIFI_LOGI("RunDhcpSerProExitThreadFunc() dhcp ser pro exit notify finished."); + sleep(DHCP_NUM_ONE); continue; } - WIFI_LOGI("DhcpServerServiceImpl::RunDhcpSerProExitThreadFunc() end!\n"); + WIFI_LOGI("DhcpServerServiceImpl::RunDhcpSerProExitThreadFunc() end!"); } void DhcpServerServiceImpl::ExitDhcpMgrThreadFunc() @@ -846,15 +845,15 @@ void DhcpServerServiceImpl::UnregisterSignal() const int DhcpServerServiceImpl::AddSpecifiedInterface(const std::string& ifname) { if (ifname.empty()) { - WIFI_LOGE("AddSpecifiedInterface() error, ifname is empty!\n"); + WIFI_LOGE("AddSpecifiedInterface() error, ifname is empty!"); return DHCP_OPT_FAILED; } if (m_setInterfaces.find(ifname) == m_setInterfaces.end()) { m_setInterfaces.insert(ifname); - WIFI_LOGI("AddSpecifiedInterface() m_setInterfaces add ifname:%{public}s success.\n", ifname.c_str()); + WIFI_LOGI("AddSpecifiedInterface() m_setInterfaces add ifname:%{public}s success.", ifname.c_str()); } else { - WIFI_LOGI("AddSpecifiedInterface() m_setInterfaces already exists ifname:%{public}s.\n", ifname.c_str()); + WIFI_LOGI("AddSpecifiedInterface() m_setInterfaces already exists ifname:%{public}s.", ifname.c_str()); } return DHCP_OPT_SUCCESS; @@ -863,16 +862,16 @@ int DhcpServerServiceImpl::AddSpecifiedInterface(const std::string& ifname) int DhcpServerServiceImpl::DelSpecifiedInterface(const std::string& ifname) { if (ifname.empty()) { - WIFI_LOGE("DelSpecifiedInterface() error, ifname is empty!\n"); + WIFI_LOGE("DelSpecifiedInterface() error, ifname is empty!"); return DHCP_OPT_FAILED; } auto iterInterfaces = m_setInterfaces.find(ifname); if (iterInterfaces != m_setInterfaces.end()) { m_setInterfaces.erase(iterInterfaces); - WIFI_LOGI("DelSpecifiedInterface() m_setInterfaces del ifname:%{public}s success.\n", ifname.c_str()); + WIFI_LOGI("DelSpecifiedInterface() m_setInterfaces del ifname:%{public}s success.", ifname.c_str()); } else { - WIFI_LOGI("DelSpecifiedInterface() m_setInterfaces not exists ifname:%{public}s.\n", ifname.c_str()); + WIFI_LOGI("DelSpecifiedInterface() m_setInterfaces not exists ifname:%{public}s.", ifname.c_str()); } return DHCP_OPT_SUCCESS; diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_service.cpp b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_service.cpp index e25d94fd9..bdce8096e 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_service.cpp +++ b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_service.cpp @@ -22,12 +22,16 @@ namespace OHOS { namespace Wifi { DhcpService::DhcpService() : m_pClientService(nullptr), m_pServerService(nullptr) { - WIFI_LOGI("DhcpService::DhcpService()...\n"); + WIFI_LOGI("DhcpService::DhcpService()..."); + DhcpClientServiceImpl::m_mapDhcpResult.clear(); + DhcpClientServiceImpl::m_mapDhcpInfo.clear(); } DhcpService::~DhcpService() { - WIFI_LOGI("DhcpService::~DhcpService()...\n"); + WIFI_LOGI("DhcpService::~DhcpService()..."); + DhcpClientServiceImpl::m_mapDhcpResult.clear(); + DhcpClientServiceImpl::m_mapDhcpInfo.clear(); } int DhcpService::StartDhcpClient(const std::string& ifname, bool bIpv6) @@ -35,7 +39,7 @@ int DhcpService::StartDhcpClient(const std::string& ifname, bool bIpv6) if (m_pClientService == nullptr) { m_pClientService = std::make_unique(); if (m_pClientService == nullptr) { - WIFI_LOGE("DhcpService::StartDhcpClient() std::make_unique() failed!\n"); + WIFI_LOGE("DhcpService::StartDhcpClient() std::make_unique() failed!"); return DHCP_OPT_FAILED; } } @@ -48,7 +52,7 @@ int DhcpService::StopDhcpClient(const std::string& ifname, bool bIpv6) if (m_pClientService == nullptr) { m_pClientService = std::make_unique(); if (m_pClientService == nullptr) { - WIFI_LOGE("DhcpService::StopDhcpClient() std::make_unique() failed!\n"); + WIFI_LOGE("DhcpService::StopDhcpClient() std::make_unique() failed!"); return DHCP_OPT_FAILED; } } @@ -59,7 +63,7 @@ int DhcpService::StopDhcpClient(const std::string& ifname, bool bIpv6) int DhcpService::GetDhcpResult(const std::string& ifname, IDhcpResultNotify *pResultNotify, int timeouts) { if (m_pClientService == nullptr) { - WIFI_LOGE("DhcpService::GetDhcpResult() error, m_pClientService = nullptr!\n"); + WIFI_LOGE("DhcpService::GetDhcpResult() error, m_pClientService = nullptr!"); return DHCP_OPT_FAILED; } @@ -69,7 +73,7 @@ int DhcpService::GetDhcpResult(const std::string& ifname, IDhcpResultNotify *pRe int DhcpService::GetDhcpInfo(const std::string& ifname, DhcpServiceInfo& dhcp) { if (m_pClientService == nullptr) { - WIFI_LOGE("DhcpService::GetDhcpInfo() error, m_pClientService = nullptr!\n"); + WIFI_LOGE("DhcpService::GetDhcpInfo() error, m_pClientService = nullptr!"); return DHCP_OPT_FAILED; } @@ -79,7 +83,7 @@ int DhcpService::GetDhcpInfo(const std::string& ifname, DhcpServiceInfo& dhcp) int DhcpService::RenewDhcpClient(const std::string& ifname) { if (m_pClientService == nullptr) { - WIFI_LOGE("DhcpService::RenewDhcpClient() error, m_pClientService = nullptr!\n"); + WIFI_LOGE("DhcpService::RenewDhcpClient() error, m_pClientService = nullptr!"); return DHCP_OPT_FAILED; } @@ -89,7 +93,7 @@ int DhcpService::RenewDhcpClient(const std::string& ifname) int DhcpService::ReleaseDhcpClient(const std::string& ifname) { if (m_pClientService == nullptr) { - WIFI_LOGE("DhcpService::ReleaseDhcpClient() error, m_pClientService = nullptr!\n"); + WIFI_LOGE("DhcpService::ReleaseDhcpClient() error, m_pClientService = nullptr!"); return DHCP_OPT_FAILED; } @@ -101,7 +105,7 @@ int DhcpService::StartDhcpServer(const std::string& ifname) if (m_pServerService == nullptr) { m_pServerService = std::make_unique(); if (m_pServerService == nullptr) { - WIFI_LOGE("DhcpService::StartDhcpServer() std::make_unique() failed!\n"); + WIFI_LOGE("DhcpService::StartDhcpServer() std::make_unique() failed!"); return DHCP_OPT_FAILED; } } @@ -114,7 +118,7 @@ int DhcpService::StopDhcpServer(const std::string& ifname) if (m_pServerService == nullptr) { m_pServerService = std::make_unique(); if (m_pServerService == nullptr) { - WIFI_LOGE("DhcpService::StopDhcpServer() std::make_unique() failed!\n"); + WIFI_LOGE("DhcpService::StopDhcpServer() std::make_unique() failed!"); return DHCP_OPT_FAILED; } } @@ -125,7 +129,7 @@ int DhcpService::StopDhcpServer(const std::string& ifname) int DhcpService::GetServerStatus() { if (m_pServerService == nullptr) { - WIFI_LOGE("DhcpService::GetServerStatus() error, m_pServerService = nullptr!\n"); + WIFI_LOGE("DhcpService::GetServerStatus() error, m_pServerService = nullptr!"); return DHCP_OPT_FAILED; } @@ -135,7 +139,7 @@ int DhcpService::GetServerStatus() int DhcpService::PutDhcpRange(const std::string& tagName, const DhcpRange& range) { if (m_pServerService == nullptr) { - WIFI_LOGE("DhcpService::PutDhcpRange() error, m_pServerService = nullptr!\n"); + WIFI_LOGE("DhcpService::PutDhcpRange() error, m_pServerService = nullptr!"); return DHCP_OPT_FAILED; } @@ -145,7 +149,7 @@ int DhcpService::PutDhcpRange(const std::string& tagName, const DhcpRange& range int DhcpService::RemoveDhcpRange(const std::string& tagName, const DhcpRange& range) { if (m_pServerService == nullptr) { - WIFI_LOGE("DhcpService::RemoveDhcpRange() error, m_pServerService = nullptr!\n"); + WIFI_LOGE("DhcpService::RemoveDhcpRange() error, m_pServerService = nullptr!"); return DHCP_OPT_FAILED; } @@ -155,7 +159,7 @@ int DhcpService::RemoveDhcpRange(const std::string& tagName, const DhcpRange& ra int DhcpService::RemoveAllDhcpRange(const std::string& tagName) { if (m_pServerService == nullptr) { - WIFI_LOGE("DhcpService::RemoveAllDhcpRange() error, m_pServerService = nullptr!\n"); + WIFI_LOGE("DhcpService::RemoveAllDhcpRange() error, m_pServerService = nullptr!"); return DHCP_OPT_FAILED; } @@ -165,7 +169,7 @@ int DhcpService::RemoveAllDhcpRange(const std::string& tagName) int DhcpService::SetDhcpRange(const std::string& ifname, const DhcpRange& range) { if (m_pServerService == nullptr) { - WIFI_LOGE("DhcpService::SetDhcpRange() error, m_pServerService = nullptr!\n"); + WIFI_LOGE("DhcpService::SetDhcpRange() error, m_pServerService = nullptr!"); return DHCP_OPT_FAILED; } @@ -175,7 +179,7 @@ int DhcpService::SetDhcpRange(const std::string& ifname, const DhcpRange& range) int DhcpService::SetDhcpRange(const std::string& ifname, const std::string& tagName) { if (m_pServerService == nullptr) { - WIFI_LOGE("DhcpService::SetDhcpRange() error, m_pServerService = nullptr!\n"); + WIFI_LOGE("DhcpService::SetDhcpRange() error, m_pServerService = nullptr!"); return DHCP_OPT_FAILED; } @@ -185,7 +189,7 @@ int DhcpService::SetDhcpRange(const std::string& ifname, const std::string& tagN int DhcpService::GetLeases(std::vector& leases) { if (m_pServerService == nullptr) { - WIFI_LOGE("DhcpService::GetLeases() error, m_pServerService = nullptr!\n"); + WIFI_LOGE("DhcpService::GetLeases() error, m_pServerService = nullptr!"); return DHCP_OPT_FAILED; } @@ -195,7 +199,7 @@ int DhcpService::GetLeases(std::vector& leases) int DhcpService::GetDhcpSerProExit(const std::string& ifname, IDhcpResultNotify *pResultNotify) { if (m_pServerService == nullptr) { - WIFI_LOGE("DhcpService::GetDhcpSerProExit() error, m_pServerService = nullptr!\n"); + WIFI_LOGE("DhcpService::GetDhcpSerProExit() error, m_pServerService = nullptr!"); return DHCP_OPT_FAILED; } diff --git a/services/wifi_standard/wifi_framework/wifi_manage/BUILD.gn b/services/wifi_standard/wifi_framework/wifi_manage/BUILD.gn index cd3189d97..35e3a8cd2 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/BUILD.gn +++ b/services/wifi_standard/wifi_framework/wifi_manage/BUILD.gn @@ -15,6 +15,7 @@ import("//build/ohos.gni") import("//build/ohos/sa_profile/sa_profile.gni") import("//build/ohos_var.gni") import("//foundation/appexecfwk/standard/appexecfwk.gni") + ################################################################################ config("wifi_manager_service_header") { @@ -35,6 +36,9 @@ config("wifi_manager_service_header") { "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", "${aafwk_path}/interfaces/innerkits/want/include", "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", @@ -113,10 +117,10 @@ ohos_shared_library("wifi_manager_service") { "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/network_interface.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils/wifi_common_event_helper.cpp", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.cpp", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_helper.cpp", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_utils.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils/wifi_common_event_helper.cpp", "wifi_auth_center.cpp", "wifi_config_center.cpp", "wifi_internal_event_dispatcher.cpp", @@ -125,13 +129,13 @@ ohos_shared_library("wifi_manager_service") { ] deps = [ + "${aafwk_path}/interfaces/innerkits/base:base", + "${aafwk_path}/interfaces/innerkits/want:want", "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", "//foundation/communication/wifi/services/wifi_standard/etc/init:etc", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//utils/native/base:utils", - "${aafwk_path}/interfaces/innerkits/base:base", - "${aafwk_path}/interfaces/innerkits/want:want", ] defines = [ @@ -143,7 +147,7 @@ ohos_shared_library("wifi_manager_service") { external_deps = [ "ces_standard:cesfwk_innerkits", - "ipc:ipc_core", + "ipc:ipc_core", ] part_name = "wifi_standard" diff --git a/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp b/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp index 115194585..24efbf7f0 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp @@ -214,7 +214,7 @@ void StateMachine::MessageExecutedLater(InternalMessage *msg, int64_t delayTimeM void StateMachine::StartTimer(int timerName, int64_t interval) { - LOGD("Enter StateMachine::StartTimer, timerName is %{public}d, interval is %" PRIu64 "", timerName, interval); + LOGD("Enter StateMachine::StartTimer, timerName is %{public}d, interval is %" PRIu64 ".", timerName, interval); MessageExecutedLater(timerName, interval); return; } @@ -631,4 +631,4 @@ void StateMachineHandler::CallTreeStateEnters(int index) mSwitchingStateFlag = false; } } // namespace Wifi -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.c b/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.c index 03876ce86..eac0fb109 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.c +++ b/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.c @@ -137,29 +137,6 @@ WifiErrorNo GetStaInfos(char *infos, int32_t *size) return result; } -WifiErrorNo ConfigHotspot(uint32_t chan, const char *mscb) -{ - RpcClient *client = GetApRpcClient(); - LockRpcClient(client); - Context *context = client->context; - WriteBegin(context, 0); - WriteFunc(context, "ConfigHotspot"); - WriteInt(context, chan); - WriteStr(context, mscb); - WriteEnd(context); - int ret = RemoteCall(client); - if (ret < 0) { - LOGE("remote call failed!"); - UnlockRpcClient(client); - return WIFI_IDL_OPT_FAILED; - } - int result = WIFI_IDL_OPT_FAILED; - ReadInt(context, &result); - ReadClientEnd(client); - UnlockRpcClient(client); - return result; -} - WifiErrorNo SetMacFilter(unsigned char *mac, int lenMac) { RpcClient *client = GetApRpcClient(); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.h b/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.h index 50ec00769..366620f4e 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.h @@ -72,15 +72,6 @@ WifiErrorNo SetHostapdConfig(HostsapdConfig *config); */ WifiErrorNo GetStaInfos(char *infos, int32_t *size); -/** - * @Description Configuring the Wi-Fi hotspot channel and maximum number of connections. - * - * @param chan - * @param mscb - * @return WifiErrorNo - */ -WifiErrorNo ConfigHotspot(uint32_t chan, const char *mscb); - /** * @Description To set the blocklist filtering in AP mode to prohibit the MAC * address connection. @@ -111,8 +102,7 @@ WifiErrorNo DelMacFilter(unsigned char *mac, int lenMac); WifiErrorNo DisassociateSta(unsigned char *mac, int lenMac); /** - * @Description Obtains the hotspot frequency supported by a specified - * frequency band. + * @Description Obtains the hotspot frequency supported by a specified frequency band. * * @param band - Band type. * @param frequencies - Numeric group pointer of the int type. diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.cpp b/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.cpp index a9954b30e..a8e888eb0 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.cpp @@ -63,11 +63,6 @@ WifiErrorNo WifiApHalInterface::GetStationList(std::vector &result) return mIdlClient->GetStationList(result); } -WifiErrorNo WifiApHalInterface::SetHotspotConfig(int channel, const std::string &mscb) -{ - return mIdlClient->SetHotspotConfig(channel, mscb); -} - WifiErrorNo WifiApHalInterface::AddBlockByMac(const std::string &mac) { return mIdlClient->AddBlockByMac(mac); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.h b/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.h index fca3ef449..5c8d60561 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.h @@ -63,16 +63,6 @@ public: */ WifiErrorNo GetStationList(std::vector &result); - /** - * @Description Configuring the Wi-Fi hotspot channel and maximum number of - * connections, mscb Need to define. - * - * @param channel - * @param mscb - * @return WifiErrorNo - */ - WifiErrorNo SetHotspotConfig(int channel, const std::string &mscb); - /** * @Description To set the blocklist filtering in AP mode to prohibit * the MAC address connection. diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.cpp b/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.cpp index d4c383eb3..d99b89e9f 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.cpp @@ -781,14 +781,6 @@ WifiErrorNo WifiIdlClient::GetStationList(std::vector &result) return WIFI_IDL_OPT_OK; } -WifiErrorNo WifiIdlClient::SetHotspotConfig(int channel, const std::string &mscb) -{ - if (pRpcClient == nullptr) { - return WIFI_IDL_OPT_FAILED; - } - return ConfigHotspot(channel, mscb.c_str()); -} - WifiErrorNo WifiIdlClient::AddBlockByMac(const std::string &mac) { if (pRpcClient == nullptr) { @@ -1101,4 +1093,4 @@ WifiErrorNo WifiIdlClient::ReWpaBlocklistClear(void) return WpaBlocklistClear(); } } // namespace Wifi -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.h b/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.h index 2a0768520..e1f7d6bfd 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.h @@ -352,16 +352,6 @@ public: */ WifiErrorNo GetStationList(std::vector &result); - /** - * @Description Configuring the Wi-Fi hotspot channel and maximum number of connections. - * - * @param channel - * @param mscb - * @return WifiErrorNo - */ - - WifiErrorNo SetHotspotConfig(int channel, const std::string &mscb); - /** * @Description To set the blocklist filtering in AP mode to prohibit the MAC * address connection. diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use.h index 3313ea1ac..1f09c7e19 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use.h @@ -24,7 +24,6 @@ namespace OHOS { namespace Wifi { -constexpr int AP_CHANNEL_DEFAULT = 6; constexpr int FREP_2G_MIN = 2412; constexpr int FREP_2G_MAX = 2472; constexpr int FREP_5G_MIN = 5170; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_interface.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_interface.cpp index 05be8ab7b..e87b834aa 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_interface.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_interface.cpp @@ -42,21 +42,63 @@ ApInterface::~ApInterface() ApService::DeleteInstance(); } -int ApInterface::Init(WifiMessageQueue *mqUp) +extern "C" IApService *Create(void) { - return ApService::GetInstance().Init(mqUp); + return new ApInterface(); } -int ApInterface::PushMsg(WifiRequestMsgInfo *msg) +extern "C" void Destroy(IApService *pservice) { - return ApService::GetInstance().PushMsg(msg); + delete pservice; +} +ErrCode ApInterface::EnableHotspot() +{ + return ApService::GetInstance().EnableHotspot(); } -int ApInterface::UnInit(void) +ErrCode ApInterface::DisableHotspot() { - return ApService::GetInstance().UnInit(); + return ApService::GetInstance().DisableHotspot(); } -DECLARE_INIT_SERVICE(ApInterface); +ErrCode ApInterface::AddBlockList(const StationInfo &stationInfo) +{ + return ApService::GetInstance().AddBlockList(stationInfo); +} + +ErrCode ApInterface::DelBlockList(const StationInfo &stationInfo) +{ + return ApService::GetInstance().DelBlockList(stationInfo); +} + +ErrCode ApInterface::SetHotspotConfig(const HotspotConfig &hotspotConfig) +{ + return ApService::GetInstance().SetHotspotConfig(hotspotConfig); +} + +ErrCode ApInterface::DisconnetStation(const StationInfo &stationInfo) +{ + return ApService::GetInstance().DisconnetStation(stationInfo); +} + +ErrCode ApInterface::GetStationList(std::vector &result) +{ + return ErrCode::WIFI_OPT_FAILED; +} + +ErrCode ApInterface::GetValidBands(std::vector &bands) +{ + return ErrCode::WIFI_OPT_FAILED; +} + +ErrCode ApInterface::GetValidChannels(BandType band, std::vector &validchannel) +{ + return ErrCode::WIFI_OPT_FAILED; +} + +ErrCode ApInterface::RegisterApServiceCallbacks(const IApServiceCallbacks &callbacks) +{ + return ApService::GetInstance().RegisterApServiceCallbacks(callbacks); +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_interface.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_interface.h index 101eafe48..139aebf4e 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_interface.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_interface.h @@ -16,11 +16,11 @@ #define OHOS_AP_INTERFACE_H #include "ap_define.h" -#include "base_service.h" +#include "ap_service.h" namespace OHOS { namespace Wifi { -class ApInterface : public BaseService { +class ApInterface : public IApService { public: /** * @Description construction method @@ -35,24 +35,81 @@ public: */ ~ApInterface(); +public: /** - * @Description This command is invoked after the AP dynamic library file is loaded. - * @param mqUp - MO message - * @return success: 0 failed: -1 + * @Description Enable hotspot. + * @param None + * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE */ - virtual int Init(WifiMessageQueue *mqUp); + virtual ErrCode EnableHotspot() override; + /** - * @Description This interface is invoked when an MO message is sent to the AP. - * @param msg - delivered message - * @return success: 0 failed: -1 + * @Description Disable hotspot. + * @param None + * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE */ - virtual int PushMsg(WifiRequestMsgInfo *msg); + virtual ErrCode DisableHotspot() override; + /** - * @Description This command is invoked before the AP dynamic library file is uninstalled. - * @param None - * @return None + * @Description Add block list from station information. + * @param stationInfo - station information. + * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE */ - virtual int UnInit(void); + virtual ErrCode AddBlockList(const StationInfo &stationInfo) override; + + /** + * @Description Del block list from station information. + * @param stationInfo - station information. + * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE + */ + virtual ErrCode DelBlockList(const StationInfo &stationInfo) override; + + /** + * @Description Set hotspot configure. + * @param hotspotConfig - hotspot configure. + * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE + */ + virtual ErrCode SetHotspotConfig(const HotspotConfig &hotspotConfig) override; + + /** + * @Description Disconnet Station connect from station information. + * @param stationInfo - station information. + * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE + */ + virtual ErrCode DisconnetStation(const StationInfo &stationInfo) override; + + /** + * @Description Get the Station List object. + * + * @param result - current connected station info + * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE + */ + virtual ErrCode GetStationList(std::vector &result) override; + + /** + * @Description Sets the callback function for the state machine. + * @param callbacks - callbacks list. + * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE + */ + virtual ErrCode RegisterApServiceCallbacks(const IApServiceCallbacks &callbacks) override; + + /** + * @Description Get valid bands. + * + * @param bands - return valid bands + * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE + */ + virtual ErrCode GetValidBands(std::vector &bands) override; + + /** + * @Description Get valid channels. + * + * @param band - input band + * @param validchannel - band's valid channel + * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE + */ + virtual ErrCode GetValidChannels(BandType band, std::vector &validchannel) override; + }; /* ApInterface */ } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.cpp index 726b82f91..928081b4e 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.cpp @@ -30,146 +30,54 @@ ApService &ApService::GetInstance() void ApService::DeleteInstance() {} -ApService::ApService() : mMsgQueueUp(nullptr) +ApService::ApService() {} -int ApService::Init(WifiMessageQueue *mqUp) -{ - if (mqUp == nullptr) { - WIFI_LOGE("fatal error!"); - return -1; - } - mMsgQueueUp = mqUp; - EnableHotspot(); - return 0; -} - -int ApService::UnInit(void) const -{ - DisableHotspot(); - return 0; -} - -int ApService::PushMsg(const WifiRequestMsgInfo *msg) const -{ - if (msg == nullptr) { - WIFI_LOGE("fatal error!"); - return -1; - } - WIFI_LOGI("Receive a message from the ServiceManager. msgCode = [%{public}d]", msg->msgCode); - switch (static_cast(msg->msgCode)) { - case WifiInternalMsgCode::AP_ADD_BLOCK_LIST_REQ: { - AddBlockList(msg->params.stationInfo); - break; - } - case WifiInternalMsgCode::AP_DEL_BLOCK_LIST_REQ: { - DelBlockList(msg->params.stationInfo); - break; - } - case WifiInternalMsgCode::AP_SET_HOTSPOT_CONFIG_REQ: { - SetHotspotConfig(msg->params.hotspotConfig); - break; - } - case WifiInternalMsgCode::AP_DISCCONECT_STA_BY_MAC_REQ: { - DisconnetStation(msg->params.stationInfo); - break; - } - default: - return -1; - break; - } - - return 0; -} - -void ApService::BroadcastMsg(const WifiResponseMsgInfo &upMsg) const -{ - mMsgQueueUp->Push(upMsg); - return; -} - -void ApService::OnApStateChange(const ApState &state) const -{ - if (WifiSettings::GetInstance().SetHotspotState(static_cast(state))) { - WIFI_LOGE("WifiSetting change state failed"); - } - switch (state) { - case ApState::AP_STATE_IDLE: { - WifiResponseMsgInfo msg; - msg.msgCode = WifiInternalMsgCode::AP_CLOSE_RES; - BroadcastMsg(msg); - break; - } - case ApState::AP_STATE_STARTED: { - WifiResponseMsgInfo msg; - msg.msgCode = WifiInternalMsgCode::AP_OPEN_RES; - BroadcastMsg(msg); - break; - } - default: /* don't update other state */ - break; - } - return; -} - -void ApService::OnHotspotStaJoin(const StationInfo &info) const -{ - WifiResponseMsgInfo msgInfo; - msgInfo.params.staInfo = info; - msgInfo.msgCode = AP_JOIN_RES; - WIFI_LOGI("OnHotspotStaJoin:,%{public}d,%s,%s,%s", - msgInfo.msgCode, - msgInfo.params.staInfo.bssid.c_str(), - msgInfo.params.staInfo.deviceName.c_str(), - msgInfo.params.staInfo.ipAddr.c_str()); - BroadcastMsg(msgInfo); -} - -void ApService::OnHotspotStaLeave(const StationInfo &info) const -{ - WifiResponseMsgInfo msgInfo; - msgInfo.params.staInfo = info; - msgInfo.msgCode = AP_LEAVE_RES; - WIFI_LOGI("OnHotspotStaleave:,%{public}d,%s,%s,%s", - msgInfo.msgCode, - msgInfo.params.staInfo.bssid.c_str(), - msgInfo.params.staInfo.deviceName.c_str(), - msgInfo.params.staInfo.ipAddr.c_str()); - BroadcastMsg(msgInfo); -} +ApService::~ApService() +{} -void ApService::EnableHotspot() const +ErrCode ApService::EnableHotspot() const { ApStateMachine::GetInstance().SendMessage(static_cast(ApStatemachineEvent::CMD_START_HOTSPOT)); + return ErrCode::WIFI_OPT_SUCCESS; } -void ApService::DisableHotspot() const +ErrCode ApService::DisableHotspot() const { ApStateMachine::GetInstance().SendMessage(static_cast(ApStatemachineEvent::CMD_STOP_HOTSPOT)); + return ErrCode::WIFI_OPT_SUCCESS; } -void ApService::SetHotspotConfig(const HotspotConfig &cfg) const +ErrCode ApService::SetHotspotConfig(const HotspotConfig &cfg) const { ApStateMachine::GetInstance().SetHotspotConfig(cfg); - return; + return ErrCode::WIFI_OPT_SUCCESS; } -void ApService::AddBlockList(const StationInfo &stationInfo) const +ErrCode ApService::AddBlockList(const StationInfo &stationInfo) const { ApStateMachine::GetInstance().AddBlockList(stationInfo); - return; + return ErrCode::WIFI_OPT_SUCCESS; } -void ApService::DelBlockList(const StationInfo &stationInfo) const +ErrCode ApService::DelBlockList(const StationInfo &stationInfo) const { ApStateMachine::GetInstance().DelBlockList(stationInfo); - return; + return ErrCode::WIFI_OPT_SUCCESS; } -void ApService::DisconnetStation(const StationInfo &stationInfo) const +ErrCode ApService::DisconnetStation(const StationInfo &stationInfo) const { ApStateMachine::GetInstance().DisconnetStation(stationInfo); - return; + return ErrCode::WIFI_OPT_SUCCESS; +} + +ErrCode ApService::RegisterApServiceCallbacks(const IApServiceCallbacks &callbacks) +{ + WIFI_LOGI("RegisterApServiceCallbacks."); + ApStateMachine::GetInstance().RegisterApServiceCallbacks(callbacks); + return ErrCode::WIFI_OPT_SUCCESS; } + } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.h index 7a3a662c3..b5ff3f96d 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.h @@ -17,123 +17,91 @@ #include "ap_define.h" #include "wifi_internal_msg.h" -#include "wifi_message_queue.h" #include "wifi_settings.h" +#include "i_ap_service.h" +#include "i_ap_service_callbacks.h" namespace OHOS { namespace Wifi { class ApService { -public: - /** - * @Description Obtains a single g_instance. - * @param None - * @return Reference to singleton objects - */ - static ApService &GetInstance(); +private: /** - * @Description Delete a single g_instance. + * @Description construction method. * @param None * @return None */ - static void DeleteInstance(); - - /** - * @Description Called after the AP dynamic library file is loaded. - * @param mqUp - message queue to response - * @return 0: success -1: failed - */ - int Init(WifiMessageQueue *mqUp); - /** - * @Description Called when public module send message to AP - * @param msg - delivered message - * @return 0: success -1: failed - */ - int PushMsg(const WifiRequestMsgInfo *msg) const; + ApService(); /** - * @Description Called before the AP dynamic library file is uninstalled. + * @Description destructor method. * @param None * @return None */ - int UnInit(void) const; - - /** - * @Description Broadcasting the AP module status change - * @param state - current status - * @return None - */ - void OnApStateChange(const ApState &state) const; - - /** - * @Description A new STA connection is reported. - * @param info - detailed information about the connected STA - * @return None - */ - void OnHotspotStaJoin(const StationInfo &info) const; - + ~ApService(); + DISALLOW_COPY_AND_ASSIGN(ApService) +public: /** - * @Description Broadcasting the STA disconnection information. - * @param info - detailed information about the disconnected STA - * @return None + * @Description Obtains a single g_instance. + * @param None + * @return Reference to singleton objects */ - void OnHotspotStaLeave(const StationInfo &info) const; - -private: - ApService(); - ~ApService() = default; - DISALLOW_COPY_AND_ASSIGN(ApService) - + static ApService &GetInstance(); /** - * @Description Sending response messages to the Service Management Module - * @param upMsg - structure of response messages + * @Description Delete a single g_instance. + * @param None * @return None */ - void BroadcastMsg(const WifiResponseMsgInfo &upMsg) const; + static void DeleteInstance(); /** * @Description open hotspot * @param None - * @return None + * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE */ - void EnableHotspot() const; + ErrCode EnableHotspot() const; /** * @Description close hotspot * @param None - * @return None + * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE */ - void DisableHotspot() const; + ErrCode DisableHotspot() const; /** * @Description set ap config * @param cfg - ap config - * @return None + * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE */ - void SetHotspotConfig(const HotspotConfig &cfg) const; + ErrCode SetHotspotConfig(const HotspotConfig &cfg) const; /** * @Description add block list * @param stationInfo - sta infos - * @return None + * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE */ - void AddBlockList(const StationInfo &stationInfo) const; + ErrCode AddBlockList(const StationInfo &stationInfo) const; /** * @Description delete block list * @param stationInfo - sta infos - * @return None + * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE */ - void DelBlockList(const StationInfo &stationInfo) const; + ErrCode DelBlockList(const StationInfo &stationInfo) const; /** * @Description Disconnect a specified STA * @param stationInfo - sta infos - * @return None + * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE */ - void DisconnetStation(const StationInfo &stationInfo) const; + ErrCode DisconnetStation(const StationInfo &stationInfo) const; -private: - WifiMessageQueue *mMsgQueueUp; + /** + * @Description Sets the callback function for the state machine. + * + * @param callbacks - callbacks list. + * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE + */ + ErrCode RegisterApServiceCallbacks(const IApServiceCallbacks &callbacks); }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state.cpp index fcf8ec448..35657991e 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state.cpp @@ -174,7 +174,7 @@ bool ApStartedState::StopAp() const void ApStartedState::OnApStateChange(const ApState &state) const { - ApService::GetInstance().OnApStateChange(state); + ApStateMachine::GetInstance().OnApStateChange(state); } void ApStartedState::StartMonitor() const diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.cpp index 0fbd2b394..8410b17ca 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.cpp @@ -128,6 +128,45 @@ void ApStateMachine::DisconnetStation(const StationInfo &staInfo) SendMessage(msg); } +void ApStateMachine::OnApStateChange(ApState state) +{ + if (WifiSettings::GetInstance().SetHotspotState(static_cast(state))) { + WIFI_LOGE("WifiSetting change state fail."); + } + + if (m_Callbacks.OnApStateChangedEvent != nullptr && + (state == ApState::AP_STATE_IDLE || state == ApState::AP_STATE_STARTED || state == ApState::AP_STATE_STARTING || + state == ApState::AP_STATE_CLOSING)) { + m_Callbacks.OnApStateChangedEvent(state); + } + return; +} + +ErrCode ApStateMachine::RegisterApServiceCallbacks(const IApServiceCallbacks &callbacks) +{ + m_Callbacks = callbacks; + return ErrCode::WIFI_OPT_SUCCESS; +} + +void ApStateMachine::BroadCastStationChange(const StationInfo &staInfo, ApStatemachineEvent act) +{ + switch (act) { + case ApStatemachineEvent::CMD_STATION_JOIN: + if (m_Callbacks.OnHotspotStaJoinEvent) { + m_Callbacks.OnHotspotStaJoinEvent(staInfo); + } + break; + case ApStatemachineEvent::CMD_STATION_LEAVE: + if (m_Callbacks.OnHotspotStaLeaveEvent) { + m_Callbacks.OnHotspotStaLeaveEvent(staInfo); + } + break; + default: + WIFI_LOGW("error BroadCastStation msg %{public}d.", act); + break; + } +} + void ApStateMachine::UpdateHotspotConfigResult(const bool result) { SendMessage(static_cast(ApStatemachineEvent::CMD_UPDATE_HOTSPOTCONFIG_RESULT), result ? 1 : 0); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.h index 2c4b37c97..19fff9f9a 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.h @@ -16,6 +16,7 @@ #define OHOS_AP_STATE_MACHINE_H #include "ap_define.h" +#include "i_ap_service.h" #include "ap_idle_state.h" #include "ap_root_state.h" #include "ap_started_state.h" @@ -42,6 +43,27 @@ public: * @return None */ static void DeleteInstance(); + /** + * @Description Reporting New State. + * @param state - the state. + * @return None + */ + void OnApStateChange(ApState state); + + /** + * @Description Reporting station change msg. + * @param staInfo - station information + * @param act - action event + * @return None + */ + void BroadCastStationChange(const StationInfo &staInfo, ApStatemachineEvent act); + + /** + * @Description Register callback list to reporting msg. + * @param callbacks - callback list + * @return None + */ + ErrCode RegisterApServiceCallbacks(const IApServiceCallbacks &callbacks); /** * @Description Wrap and send messages. * @param staInfo - joined sta info @@ -93,6 +115,7 @@ private: private: static ApStateMachine *g_instance; + IApServiceCallbacks m_Callbacks; /* STA Manager */ ApStationsManager mApStationsManager; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.cpp index b856b4108..b250f0196 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.cpp @@ -13,12 +13,13 @@ * limitations under the License. */ #include "ap_stations_manager.h" -#include "ap_service.h" +#include "ap_state_machine.h" #include "log_helper.h" #include "unistd.h" #include "wifi_logger.h" DEFINE_WIFILOG_HOTSPOT_LABEL("ApStationsManager"); + namespace OHOS { namespace Wifi { ApStationsManager::ApStationsManager() @@ -97,7 +98,7 @@ void ApStationsManager::StationLeave(const std::string &mac) const break; } } - ApService::GetInstance().OnHotspotStaLeave(staInfo); + ApStateMachine::GetInstance().BroadCastStationChange(staInfo, ApStatemachineEvent::CMD_STATION_LEAVE); return; } @@ -126,7 +127,7 @@ void ApStationsManager::StationJoin(const StationInfo &staInfo) const } if (it == results.end() || it->ipAddr != staInfo.ipAddr) { - ApService::GetInstance().OnHotspotStaJoin(staInfoTemp); + ApStateMachine::GetInstance().BroadCastStationChange(staInfoTemp, ApStatemachineEvent::CMD_STATION_JOIN); } return; } diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/i_ap_service.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/i_ap_service.h new file mode 100644 index 000000000..db88d4db9 --- /dev/null +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/i_ap_service.h @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ +#ifndef OHOS_IAP_SERVICE_H +#define OHOS_IAP_SERVICE_H + +#include "wifi_errcode.h" +#include "wifi_msg.h" +#include "i_ap_service_callbacks.h" + +namespace OHOS { +namespace Wifi { +class IApService { +public: + /** + * @DescriptionDestroy the IApService object. + * + */ + virtual ~IApService() = default; + virtual ErrCode EnableHotspot() = 0; + virtual ErrCode DisableHotspot() = 0; + virtual ErrCode AddBlockList(const StationInfo &stationInfo) = 0; + virtual ErrCode DelBlockList(const StationInfo &stationInfo) = 0; + virtual ErrCode SetHotspotConfig(const HotspotConfig &hotspotConfig) = 0; + virtual ErrCode DisconnetStation(const StationInfo &stationInfo) = 0; + virtual ErrCode GetStationList(std::vector &result) = 0; + virtual ErrCode GetValidBands(std::vector &bands) = 0; + virtual ErrCode GetValidChannels(BandType band, std::vector &validchannel) = 0; + + /** + * @Description - Registers all callbacks provided by the P2P service. + * @param callbacks - All callbacks + * @return ErrCode + */ + virtual ErrCode RegisterApServiceCallbacks(const IApServiceCallbacks &callbacks) = 0; +}; +} // namespace Wifi +} // namespace OHOS +#endif diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/i_ap_service_callbacks.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/i_ap_service_callbacks.h new file mode 100644 index 000000000..9f65af377 --- /dev/null +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/i_ap_service_callbacks.h @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef OHOS_IAP_SERVICE_CALLBACK_H +#define OHOS_IAP_SERVICE_CALLBACK_H + +#include +#include "wifi_errcode.h" +#include "wifi_msg.h" + +namespace OHOS { +namespace Wifi { +/* All callbacks provided by the AP service */ +class IApServiceCallbacks { +public: + std::function OnApStateChangedEvent; + std::function OnHotspotStaJoinEvent; // STA device join event. + std::function OnHotspotStaLeaveEvent; // STA device leaving event. +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.cpp index 83856cbad..5ee7016ed 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.cpp @@ -14,9 +14,11 @@ */ #include "wifi_config_center.h" +#include "wifi_global_func.h" +#include "wifi_ap_hal_interface.h" #include "wifi_log.h" #undef LOG_TAG -#define LOG_TAG "OHWIFI_MANAGER_CONFIG_CENTER" +#define LOG_TAG "WifiConfigCenter" namespace OHOS { namespace Wifi { @@ -31,6 +33,7 @@ WifiConfigCenter::WifiConfigCenter() mStaMidState = WifiOprMidState::CLOSED; mApMidState = WifiOprMidState::CLOSED; mScanMidState = WifiOprMidState::CLOSED; + mWifiOpenedWhenAirplane = false; } WifiConfigCenter::~WifiConfigCenter() @@ -146,6 +149,7 @@ WifiOprMidState WifiConfigCenter::GetApMidState() { return mApMidState.load(); } + bool WifiConfigCenter::SetApMidState(WifiOprMidState expState, WifiOprMidState state) { return mApMidState.compare_exchange_strong(expState, state); @@ -206,6 +210,31 @@ int WifiConfigCenter::GetValidChannels(ChannelsTable &channelsInfo) return WifiSettings::GetInstance().GetValidChannels(channelsInfo); } +bool WifiConfigCenter::GetSupportedBandChannel() +{ + std::vector allowed5GFreq, allowed2GFreq; + std::vector allowed5GChan, allowed2GChan; + if (WifiApHalInterface::GetInstance().GetFrequenciesByBand(static_cast(BandType::BAND_2GHZ), allowed2GFreq)) { + LOGW("fail to get 2.4G channel"); + } + if (WifiApHalInterface::GetInstance().GetFrequenciesByBand(static_cast(BandType::BAND_5GHZ), allowed5GFreq)) { + LOGW("fail to get 5G channel"); + } + + TransformFrequencyIntoChannel(allowed5GFreq, allowed5GChan); + TransformFrequencyIntoChannel(allowed2GFreq, allowed2GChan); + + ChannelsTable ChanTbs; + ChanTbs[BandType::BAND_2GHZ] = allowed2GChan; + ChanTbs[BandType::BAND_5GHZ] = allowed5GChan; + + if (WifiSettings::GetInstance().SetValidChannels(ChanTbs)) { + LOGE("fail to SetValidChannels"); + return false; + } + return true; +} + WifiOprMidState WifiConfigCenter::GetScanMidState() { return mScanMidState.load(); @@ -231,9 +260,19 @@ bool WifiConfigCenter::GetCanUseStaWhenAirplaneMode() return WifiSettings::GetInstance().GetCanUseStaWhenAirplaneMode(); } -int WifiConfigCenter::SetCanUseStaWhenAirplaneMode(bool bCan) +bool WifiConfigCenter::GetCanOpenStaWhenAirplaneMode() +{ + return WifiSettings::GetInstance().GetCanOpenStaWhenAirplaneMode(); +} + +bool WifiConfigCenter::GetWifiStateWhenAirplaneMode() +{ + return mWifiOpenedWhenAirplane; +} + +void WifiConfigCenter::SetWifiStateWhenAirplaneMode(bool bState) { - return WifiSettings::GetInstance().SetCanUseStaWhenAirplaneMode(bCan); + mWifiOpenedWhenAirplane = bState; } bool WifiConfigCenter::GetStaLastRunState() diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.h index 9a99e0e99..ed92d70b8 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.h @@ -297,6 +297,11 @@ public: */ int GetValidChannels(ChannelsTable &channelsInfo); + /** + * @Description request to chip for initation current vaild bands and channels + */ + bool GetSupportedBandChannel(); + /** * @Description Get current scan service middle state * @@ -346,6 +351,29 @@ public: */ int SetCanUseStaWhenAirplaneMode(bool bCan); + /** + * @Description Get the config whether can open sta when airplane mode opened + * + * @return true - can open + * @return false - can't open + */ + bool GetCanOpenStaWhenAirplaneMode(); + + /** + * @Description when last airplane mode, get sta state, open or close + * + * @return true - when in airplane mode, we open sta + * @return false - when in airplane mode, we close sta + */ + bool GetWifiStateWhenAirplaneMode(); + + /** + * @Description when in airplane mode, set sta state + * + * @param bState - open or close + */ + void SetWifiStateWhenAirplaneMode(bool bState); + /** * @Description Get the STA service last running state * @@ -424,6 +452,7 @@ private: std::atomic mScanMidState; /* Time interval for disabling and re-enabling the STA */ std::chrono::steady_clock::time_point mWifiCloseTime; + bool mWifiOpenedWhenAirplane; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_callback_proxy.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_callback_proxy.cpp index 86eb13bfe..59ce431dc 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_callback_proxy.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_callback_proxy.cpp @@ -56,18 +56,18 @@ void WifiDeviceCallBackProxy::OnWifiConnectionChanged(int state, const WifiLinke data.WriteInt32(0); data.WriteInt32(state); data.WriteInt32(info.networkId); - data.WriteString16(Str8ToStr16(info.ssid)); - data.WriteString16(Str8ToStr16(info.bssid)); + data.WriteCString(info.ssid.c_str()); + data.WriteCString(info.bssid.c_str()); data.WriteInt32(info.rssi); data.WriteInt32(info.band); data.WriteInt32(info.frequency); data.WriteInt32(info.linkSpeed); - data.WriteString16(Str8ToStr16(info.macAddress)); + data.WriteCString(info.macAddress.c_str()); data.WriteInt32(info.ipAddress); data.WriteInt32((int)info.connState); data.WriteBool(info.ifHiddenSSID); - data.WriteString16(Str8ToStr16(info.rxLinkSpeed)); - data.WriteString16(Str8ToStr16(info.txLinkSpeed)); + data.WriteCString(info.rxLinkSpeed.c_str()); + data.WriteCString(info.txLinkSpeed.c_str()); data.WriteInt32(info.chload); data.WriteInt32(info.snr); data.WriteInt32((int)info.supplicantState); @@ -80,7 +80,7 @@ void WifiDeviceCallBackProxy::OnWifiConnectionChanged(int state, const WifiLinke } int exception = reply.ReadInt32(); if (exception) { - WIFI_LOGE("notify wifi state change failed!"); + WIFI_LOGE("notify wifi connection change failed!"); } return; } @@ -113,7 +113,7 @@ void WifiDeviceCallBackProxy::OnWifiWpsStateChanged(int state, const std::string MessageParcel reply; data.WriteInt32(0); data.WriteInt32(state); - data.WriteString16(Str8ToStr16(pinCode)); + data.WriteCString(pinCode.c_str()); int error = Remote()->SendRequest(WIFI_CBK_CMD_WPS_STATE_CHANGE, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_CBK_CMD_WPS_STATE_CHANGE, error); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_death_recipient.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_death_recipient.h index ad7c4c34c..e4dbe6d43 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_death_recipient.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_death_recipient.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_WIFI_SCAN_CALLBACK_DEATH_H -#define OHOS_WIFI_SCAN_CALLBACK_DEATH_H +#ifndef OHOS_WIFI_DEVICE_DEATH_RECIPIENT_H +#define OHOS_WIFI_DEVICE_DEATH_RECIPIENT_H #include "iremote_object.h" namespace OHOS { diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_service_impl.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_service_impl.cpp index 75ed20043..f6c8b5260 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_service_impl.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_service_impl.cpp @@ -37,7 +37,7 @@ sptr WifiDeviceServiceImpl::GetInstance() if (g_instance == nullptr) { std::lock_guard autoLock(g_instanceLock); if (g_instance == nullptr) { - auto service = new WifiDeviceServiceImpl; + auto service = new (std::nothrow) WifiDeviceServiceImpl; g_instance = service; } } @@ -109,32 +109,37 @@ ErrCode WifiDeviceServiceImpl::EnableWifi() return WIFI_OPT_OPEN_SUCC_WHEN_OPENED; } - bool bflag = false; + errCode = WIFI_OPT_FAILED; do { if (WifiServiceManager::GetInstance().CheckAndEnforceService(WIFI_SERVICE_STA) < 0) { - WIFI_LOGE("Load wifi device service failed!"); + WIFI_LOGE("Load %{public}s service failed!", WIFI_SERVICE_STA); break; } - WifiMessageQueue *mqUp = WifiManager::GetInstance().GetMessageQueue(); - auto srvInst = WifiServiceManager::GetInstance().GetServiceInst(WIFI_SERVICE_STA); - if (srvInst == nullptr) { - WIFI_LOGE("Failed to get service instance!"); + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr) { + WIFI_LOGE("Create %{public}s service failed!", WIFI_SERVICE_STA); break; } - int ret = srvInst->Init(mqUp); - if (ret < 0) { - WIFI_LOGE("Init wifi device service failed!"); - WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_STA); + + errCode = pService->RegisterStaServiceCallback(WifiManager::GetInstance().GetStaCallback()); + if (errCode != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Register sta service callback failed!"); + break; + } + + errCode = pService->EnableWifi(); + if (errCode != WIFI_OPT_SUCCESS) { + WIFI_LOGE("service enable sta failed, ret %{public}d!", static_cast(errCode)); break; } - bflag = true; } while (false); - if (!bflag) { + if (errCode != WIFI_OPT_SUCCESS) { WifiConfigCenter::GetInstance().SetWifiMidState(WifiOprMidState::OPENING, WifiOprMidState::CLOSED); - return WIFI_OPT_FAILED; - } else { - return WIFI_OPT_SUCCESS; + WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_STA); + return errCode; } + + return WIFI_OPT_SUCCESS; } ErrCode WifiDeviceServiceImpl::DisableWifi() @@ -157,18 +162,19 @@ ErrCode WifiDeviceServiceImpl::DisableWifi() WIFI_LOGI("set wifi mid state opening failed! may be other activity has been operated"); return WIFI_OPT_CLOSE_SUCC_WHEN_CLOSED; } - auto srvInst = WifiServiceManager::GetInstance().GetServiceInst(WIFI_SERVICE_STA); - if (srvInst == nullptr) { - WIFI_LOGE("Failed to get service instance!"); - return WIFI_OPT_FAILED; + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr) { + WifiConfigCenter::GetInstance().SetWifiMidState(WifiOprMidState::CLOSED); + WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_STA); + return WIFI_OPT_SUCCESS; } - int ret = srvInst->UnInit(); - if (ret < 0) { - WIFI_LOGE("UnInit wifi device service failed!"); + ErrCode ret = pService->DisableWifi(); + if (ret != WIFI_OPT_SUCCESS) { WifiConfigCenter::GetInstance().SetWifiMidState(WifiOprMidState::CLOSING, WifiOprMidState::RUNNING); - return WIFI_OPT_FAILED; + } else { + WifiConfigCenter::GetInstance().SetStaLastRunState(false); } - return WIFI_OPT_SUCCESS; + return ret; } ErrCode WifiDeviceServiceImpl::AddDeviceConfig(const WifiDeviceConfig &config, int &result) @@ -178,11 +184,19 @@ ErrCode WifiDeviceServiceImpl::AddDeviceConfig(const WifiDeviceConfig &config, i return WIFI_OPT_PERMISSION_DENIED; } - int ret = WifiManager::GetInstance().AddDeviceConfig(config, result); - if (ret < 0) { - WIFI_LOGE("Add wifi device config failed!"); + if (!IsStaServiceRunning()) { + return WIFI_OPT_STA_NOT_OPENED; + } + + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_STA_NOT_OPENED; + } + int retNetworkId = pService->AddDeviceConfig(config); + if (retNetworkId < 0) { return WIFI_OPT_FAILED; } + result = retNetworkId; return WIFI_OPT_SUCCESS; } @@ -197,14 +211,11 @@ ErrCode WifiDeviceServiceImpl::RemoveDevice(int networkId) return WIFI_OPT_STA_NOT_OPENED; } - WifiRequestMsgInfo msg; - msg.msgCode = WifiInternalMsgCode::STA_REMOVE_DEVICE_REQ; - msg.params.argInt = networkId; - if (WifiManager::GetInstance().PushMsg(WIFI_SERVICE_STA, msg) < 0) { - WIFI_LOGE("send remove device config msg failed!"); - return WIFI_OPT_FAILED; + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_STA_NOT_OPENED; } - return WIFI_OPT_SUCCESS; + return pService->RemoveDevice(networkId); } ErrCode WifiDeviceServiceImpl::RemoveAllDevice() @@ -218,13 +229,11 @@ ErrCode WifiDeviceServiceImpl::RemoveAllDevice() return WIFI_OPT_STA_NOT_OPENED; } - WifiRequestMsgInfo msg; - msg.msgCode = WifiInternalMsgCode::STA_REMOVE_ALL_DEVICE_REQ; - if (WifiManager::GetInstance().PushMsg(WIFI_SERVICE_STA, msg) < 0) { - WIFI_LOGE("send remove device config msg failed!"); - return WIFI_OPT_FAILED; + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_STA_NOT_OPENED; } - return WIFI_OPT_SUCCESS; + return pService->RemoveAllDevice(); } ErrCode WifiDeviceServiceImpl::GetDeviceConfigs(std::vector &result) @@ -245,13 +254,15 @@ ErrCode WifiDeviceServiceImpl::EnableDeviceConfig(int networkId, bool attemptEna return WIFI_OPT_PERMISSION_DENIED; } - int ret = - WifiConfigCenter::GetInstance().SetDeviceState(networkId, (int)WifiDeviceConfigStatus::ENABLED, attemptEnable); - if (ret < 0) { - WIFI_LOGE("Enable device config failed! networkid is %{public}d", networkId); - return WIFI_OPT_FAILED; + if (!IsStaServiceRunning()) { + return WIFI_OPT_STA_NOT_OPENED; } - return WIFI_OPT_SUCCESS; + + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_STA_NOT_OPENED; + } + return pService->EnableDeviceConfig(networkId, attemptEnable); } ErrCode WifiDeviceServiceImpl::DisableDeviceConfig(int networkId) @@ -261,12 +272,15 @@ ErrCode WifiDeviceServiceImpl::DisableDeviceConfig(int networkId) return WIFI_OPT_PERMISSION_DENIED; } - int ret = WifiConfigCenter::GetInstance().SetDeviceState(networkId, (int)WifiDeviceConfigStatus::DISABLED); - if (ret < 0) { - WIFI_LOGE("Disable Wi-Fi device configuration. failed! networkid is %{public}d", networkId); - return WIFI_OPT_FAILED; + if (!IsStaServiceRunning()) { + return WIFI_OPT_STA_NOT_OPENED; } - return WIFI_OPT_SUCCESS; + + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_STA_NOT_OPENED; + } + return pService->DisableDeviceConfig(networkId); } ErrCode WifiDeviceServiceImpl::ConnectToNetwork(int networkId) @@ -280,14 +294,11 @@ ErrCode WifiDeviceServiceImpl::ConnectToNetwork(int networkId) return WIFI_OPT_STA_NOT_OPENED; } - WifiRequestMsgInfo msg; - msg.msgCode = WifiInternalMsgCode::STA_CONNECT_REQ; - msg.params.argInt = networkId; - if (WifiManager::GetInstance().PushMsg(WIFI_SERVICE_STA, msg) < 0) { - WIFI_LOGE("send connect network msg failed!"); - return WIFI_OPT_FAILED; + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_STA_NOT_OPENED; } - return WIFI_OPT_SUCCESS; + return pService->ConnectToNetwork(networkId); } ErrCode WifiDeviceServiceImpl::ConnectToDevice(const WifiDeviceConfig &config) @@ -301,14 +312,11 @@ ErrCode WifiDeviceServiceImpl::ConnectToDevice(const WifiDeviceConfig &config) return WIFI_OPT_STA_NOT_OPENED; } - WifiRequestMsgInfo msg; - msg.msgCode = WifiInternalMsgCode::STA_CONNECT_REQ; - msg.params.deviceConfig = config; - if (WifiManager::GetInstance().PushMsg(WIFI_SERVICE_STA, msg) < 0) { - WIFI_LOGE("send connect with device config msg failed!"); - return WIFI_OPT_FAILED; + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_STA_NOT_OPENED; } - return WIFI_OPT_SUCCESS; + return pService->ConnectToDevice(config); } ErrCode WifiDeviceServiceImpl::ReConnect() @@ -326,13 +334,11 @@ ErrCode WifiDeviceServiceImpl::ReConnect() return WIFI_OPT_SCAN_NOT_OPENED; } - WifiRequestMsgInfo msg; - msg.msgCode = WifiInternalMsgCode::SCAN_RECONNECT_REQ; - if (WifiManager::GetInstance().PushMsg(WIFI_SERVICE_SCAN, msg) < 0) { - WIFI_LOGE("send scan msg failed!"); - return WIFI_OPT_FAILED; + IScanService *pService = WifiServiceManager::GetInstance().GetScanServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_SCAN_NOT_OPENED; } - return WIFI_OPT_SUCCESS; + return pService->Scan(false); } ErrCode WifiDeviceServiceImpl::ReAssociate(void) @@ -346,13 +352,11 @@ ErrCode WifiDeviceServiceImpl::ReAssociate(void) return WIFI_OPT_STA_NOT_OPENED; } - WifiRequestMsgInfo msg; - msg.msgCode = WifiInternalMsgCode::STA_REASSOCIATE_REQ; - if (WifiManager::GetInstance().PushMsg(WIFI_SERVICE_STA, msg) < 0) { - WIFI_LOGE("send disconnect msg failed!"); - return WIFI_OPT_FAILED; + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_STA_NOT_OPENED; } - return WIFI_OPT_SUCCESS; + return pService->ReAssociate(); } ErrCode WifiDeviceServiceImpl::Disconnect(void) @@ -366,13 +370,11 @@ ErrCode WifiDeviceServiceImpl::Disconnect(void) return WIFI_OPT_STA_NOT_OPENED; } - WifiRequestMsgInfo msg; - msg.msgCode = WifiInternalMsgCode::STA_DISCONNECT_REQ; - if (WifiManager::GetInstance().PushMsg(WIFI_SERVICE_STA, msg) < 0) { - WIFI_LOGE("send disconnect msg failed!"); - return WIFI_OPT_FAILED; + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_STA_NOT_OPENED; } - return WIFI_OPT_SUCCESS; + return pService->Disconnect(); } ErrCode WifiDeviceServiceImpl::StartWps(const WpsConfig &config) @@ -386,14 +388,11 @@ ErrCode WifiDeviceServiceImpl::StartWps(const WpsConfig &config) return WIFI_OPT_STA_NOT_OPENED; } - WifiRequestMsgInfo msg; - msg.msgCode = WifiInternalMsgCode::STA_START_WPS_REQ; - msg.params.wpsConfig = config; - if (WifiManager::GetInstance().PushMsg(WIFI_SERVICE_STA, msg) < 0) { - WIFI_LOGE("send start wps msg failed!"); - return WIFI_OPT_FAILED; + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_STA_NOT_OPENED; } - return WIFI_OPT_SUCCESS; + return pService->StartWps(config); } ErrCode WifiDeviceServiceImpl::CancelWps(void) @@ -407,19 +406,16 @@ ErrCode WifiDeviceServiceImpl::CancelWps(void) return WIFI_OPT_STA_NOT_OPENED; } - WifiRequestMsgInfo msg; - msg.msgCode = WifiInternalMsgCode::STA_CANCEL_WPS_REQ; - if (WifiManager::GetInstance().PushMsg(WIFI_SERVICE_STA, msg) < 0) { - WIFI_LOGE("send cancel wps msg failed!"); - return WIFI_OPT_FAILED; + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_STA_NOT_OPENED; } - return WIFI_OPT_SUCCESS; + return pService->CancelWps(); } ErrCode WifiDeviceServiceImpl::IsWifiActive(bool &bActive) { - WifiOprMidState curState = WifiConfigCenter::GetInstance().GetWifiMidState(); - bActive = (curState == WifiOprMidState::RUNNING); + bActive = IsStaServiceRunning(); return WIFI_OPT_SUCCESS; } @@ -468,22 +464,23 @@ ErrCode WifiDeviceServiceImpl::GetIpInfo(IpInfo &info) ErrCode WifiDeviceServiceImpl::SetCountryCode(const std::string &countryCode) { + if (countryCode.length() != WIFI_COUNTRY_CODE_LEN) { + return WIFI_OPT_INVALID_PARAM; + } if (WifiPermissionUtils::VerifyWifiConnectionPermission() == PERMISSION_DENIED) { WIFI_LOGE("SetCountryCode:VerifyWifiConnectionPermission() PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; } - WifiConfigCenter::GetInstance().SetCountryCode(countryCode); + if (!IsStaServiceRunning()) { + return WIFI_OPT_STA_NOT_OPENED; + } - if (IsStaServiceRunning()) { - WifiRequestMsgInfo msg; - msg.msgCode = WifiInternalMsgCode::STA_SET_COUNTRY_CODE; - if (WifiManager::GetInstance().PushMsg(WIFI_SERVICE_STA, msg) < 0) { - WIFI_LOGE("send set country code msg failed!"); - return WIFI_OPT_FAILED; - } + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_STA_NOT_OPENED; } - return WIFI_OPT_SUCCESS; + return pService->SetCountryCode(countryCode); } ErrCode WifiDeviceServiceImpl::GetCountryCode(std::string &countryCode) @@ -498,10 +495,9 @@ ErrCode WifiDeviceServiceImpl::GetCountryCode(std::string &countryCode) return WIFI_OPT_SUCCESS; } -ErrCode WifiDeviceServiceImpl::RegisterCallBackClient( - const std::string &name, const sptr &callback) +ErrCode WifiDeviceServiceImpl::RegisterCallBack(const sptr &callback) { - WIFI_LOGI("RegisterCallBackClient"); + WIFI_LOGI("RegisterCallBack"); if (callback == nullptr) { WIFI_LOGE("Get call back client failed!"); return WIFI_OPT_FAILED; @@ -541,6 +537,23 @@ ErrCode WifiDeviceServiceImpl::GetSupportedFeatures(long &features) return WIFI_OPT_SUCCESS; } +ErrCode WifiDeviceServiceImpl::GetDeviceMacAddress(std::string &result) +{ + WIFI_LOGI("GetDeviceMacAddress"); + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("GetDeviceMacAddress:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (WifiPermissionUtils::VerifyGetWifiLocalMacPermission() == PERMISSION_DENIED) { + WIFI_LOGE("GetDeviceMacAddress:VerifyGetWifiLocalMacPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + WifiConfigCenter::GetInstance().GetMacAddress(result); + return WIFI_OPT_SUCCESS; +} + ErrCode WifiDeviceServiceImpl::CheckCanEnableWifi(void) { if (WifiPermissionUtils::VerifySetWifiInfoPermission() == PERMISSION_DENIED) { @@ -551,7 +564,8 @@ ErrCode WifiDeviceServiceImpl::CheckCanEnableWifi(void) * when airplane mode opened, if the config "can_use_sta_when_airplanemode" * opened, then can open sta; other, return forbid. */ - if (WifiConfigCenter::GetInstance().GetAirplaneModeState() == 1 && + if (!WifiConfigCenter::GetInstance().GetCanOpenStaWhenAirplaneMode() && + WifiConfigCenter::GetInstance().GetAirplaneModeState() == 1 && !WifiConfigCenter::GetInstance().GetCanUseStaWhenAirplaneMode()) { WIFI_LOGI("current airplane mode and can not use sta, open failed!"); return WIFI_OPT_FORBID_AIRPLANE; @@ -568,8 +582,7 @@ ErrCode WifiDeviceServiceImpl::CheckCanEnableWifi(void) double interval = WifiConfigCenter::GetInstance().GetWifiStaInterval(); if (interval <= REOPEN_STA_INTERVAL) { int waitMils = REOPEN_STA_INTERVAL - int(interval) + 1; - WIFI_LOGI("open wifi too frequent, interval since last close is %lf, and wait " - "%{public}d ms", + WIFI_LOGI("open wifi too frequent, interval since last close is %{public}lf, and wait %{public}d ms", interval, waitMils); usleep(waitMils * MSEC); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_service_impl.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_service_impl.h index 250cc3cb8..f402bd63b 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_service_impl.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_service_impl.h @@ -82,12 +82,14 @@ public: ErrCode GetCountryCode(std::string &countryCode) override; - ErrCode RegisterCallBackClient(const std::string &name, const sptr &callback) override; + ErrCode RegisterCallBack(const sptr &callback) override; ErrCode GetSignalLevel(const int &rssi, const int &band, int &level) override; ErrCode GetSupportedFeatures(long &features) override; + ErrCode GetDeviceMacAddress(std::string &result) override; + private: bool Init(); ErrCode CheckCanEnableWifi(void); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub.cpp index ab783bd9d..2afaed4b8 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub.cpp @@ -56,9 +56,10 @@ void WifiDeviceStub::InitHandleMap() handleFuncMap[WIFI_SVR_CMD_GET_DHCP_INFO] = &WifiDeviceStub::OnGetIpInfo; handleFuncMap[WIFI_SVR_CMD_SET_COUNTRY_CODE] = &WifiDeviceStub::OnSetCountryCode; handleFuncMap[WIFI_SVR_CMD_GET_COUNTRY_CODE] = &WifiDeviceStub::OnGetCountryCode; - handleFuncMap[WIFI_SVR_CMD_REGISTER_CALLBACK_CLIENT] = &WifiDeviceStub::OnRegisterCallBackClient; + handleFuncMap[WIFI_SVR_CMD_REGISTER_CALLBACK_CLIENT] = &WifiDeviceStub::OnRegisterCallBack; handleFuncMap[WIFI_SVR_CMD_GET_SIGNAL_LEVEL] = &WifiDeviceStub::OnGetSignalLevel; handleFuncMap[WIFI_SVR_CMD_GET_SUPPORTED_FEATURES] = &WifiDeviceStub::OnGetSupportedFeatures; + handleFuncMap[WIFI_SVR_CMD_GET_DERVICE_MAC_ADD] = &WifiDeviceStub::OnGetDeviceMacAdd; return; } @@ -84,7 +85,7 @@ int WifiDeviceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageP void WifiDeviceStub::OnEnableWifi(uint32_t code, MessageParcel &data, MessageParcel &reply) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); - int ret = EnableWifi(); + ErrCode ret = EnableWifi(); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -94,7 +95,7 @@ void WifiDeviceStub::OnEnableWifi(uint32_t code, MessageParcel &data, MessagePar void WifiDeviceStub::OnDisableWifi(uint32_t code, MessageParcel &data, MessageParcel &reply) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); - int ret = DisableWifi(); + ErrCode ret = DisableWifi(); reply.WriteInt32(0); reply.WriteInt32(ret); return; @@ -107,7 +108,7 @@ void WifiDeviceStub::OnAddDeviceConfig(uint32_t code, MessageParcel &data, Messa ReadWifiDeviceConfig(data, config); int result = 0; - int ret = AddDeviceConfig(config, result); + ErrCode ret = AddDeviceConfig(config, result); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -229,7 +230,7 @@ void WifiDeviceStub::OnRemoveDevice(uint32_t code, MessageParcel &data, MessageP { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); int networkId = data.ReadInt32(); - int ret = RemoveDevice(networkId); + ErrCode ret = RemoveDevice(networkId); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -239,7 +240,7 @@ void WifiDeviceStub::OnRemoveDevice(uint32_t code, MessageParcel &data, MessageP void WifiDeviceStub::OnRemoveAllDevice(uint32_t code, MessageParcel &data, MessageParcel &reply) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); - int ret = RemoveAllDevice(); + ErrCode ret = RemoveAllDevice(); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -250,7 +251,7 @@ void WifiDeviceStub::OnGetDeviceConfigs(uint32_t code, MessageParcel &data, Mess { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); std::vector result; - int ret = GetDeviceConfigs(result); + ErrCode ret = GetDeviceConfigs(result); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -269,7 +270,7 @@ void WifiDeviceStub::OnEnableDeviceConfig(uint32_t code, MessageParcel &data, Me WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); int networkId = data.ReadInt32(); bool attemptEnable = data.ReadBool(); - int ret = EnableDeviceConfig(networkId, attemptEnable); + ErrCode ret = EnableDeviceConfig(networkId, attemptEnable); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -280,7 +281,7 @@ void WifiDeviceStub::OnDisableDeviceConfig(uint32_t code, MessageParcel &data, M { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); int networkId = data.ReadInt32(); - int ret = DisableDeviceConfig(networkId); + ErrCode ret = DisableDeviceConfig(networkId); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -291,7 +292,7 @@ void WifiDeviceStub::OnConnectTo(uint32_t code, MessageParcel &data, MessageParc { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); int networkId = data.ReadInt32(); - int ret = ConnectToNetwork(networkId); + ErrCode ret = ConnectToNetwork(networkId); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -303,7 +304,7 @@ void WifiDeviceStub::OnConnect2To(uint32_t code, MessageParcel &data, MessagePar WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); WifiDeviceConfig config; ReadWifiDeviceConfig(data, config); - int ret = ConnectToDevice(config); + ErrCode ret = ConnectToDevice(config); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -313,7 +314,7 @@ void WifiDeviceStub::OnConnect2To(uint32_t code, MessageParcel &data, MessagePar void WifiDeviceStub::OnReConnect(uint32_t code, MessageParcel &data, MessageParcel &reply) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); - int ret = ReConnect(); + ErrCode ret = ReConnect(); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -323,7 +324,7 @@ void WifiDeviceStub::OnReConnect(uint32_t code, MessageParcel &data, MessageParc void WifiDeviceStub::OnReAssociate(uint32_t code, MessageParcel &data, MessageParcel &reply) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); - int ret = ReAssociate(); + ErrCode ret = ReAssociate(); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -333,7 +334,7 @@ void WifiDeviceStub::OnReAssociate(uint32_t code, MessageParcel &data, MessagePa void WifiDeviceStub::OnDisconnect(uint32_t code, MessageParcel &data, MessageParcel &reply) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); - int ret = Disconnect(); + ErrCode ret = Disconnect(); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -348,7 +349,7 @@ void WifiDeviceStub::OnStartWps(uint32_t code, MessageParcel &data, MessageParce config.pin = data.ReadCString(); config.bssid = data.ReadCString(); - int ret = StartWps(config); + ErrCode ret = StartWps(config); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -358,7 +359,7 @@ void WifiDeviceStub::OnStartWps(uint32_t code, MessageParcel &data, MessageParce void WifiDeviceStub::OnCancelWps(uint32_t code, MessageParcel &data, MessageParcel &reply) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); - int ret = CancelWps(); + ErrCode ret = CancelWps(); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -369,7 +370,7 @@ void WifiDeviceStub::OnIsWifiActive(uint32_t code, MessageParcel &data, MessageP { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); bool bActive = false; - int ret = IsWifiActive(bActive); + ErrCode ret = IsWifiActive(bActive); reply.WriteInt32(0); reply.WriteInt32(ret); if (ret == WIFI_OPT_SUCCESS) { @@ -382,7 +383,7 @@ void WifiDeviceStub::OnGetWifiState(uint32_t code, MessageParcel &data, MessageP { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); int state = 0; - int ret = GetWifiState(state); + ErrCode ret = GetWifiState(state); reply.WriteInt32(0); reply.WriteInt32(ret); if (ret == WIFI_OPT_SUCCESS) { @@ -395,7 +396,7 @@ void WifiDeviceStub::OnGetLinkedInfo(uint32_t code, MessageParcel &data, Message { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); WifiLinkedInfo wifiInfo; - int ret = GetLinkedInfo(wifiInfo); + ErrCode ret = GetLinkedInfo(wifiInfo); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -426,7 +427,7 @@ void WifiDeviceStub::OnGetIpInfo(uint32_t code, MessageParcel &data, MessageParc { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); IpInfo info; - int ret = GetIpInfo(info); + ErrCode ret = GetIpInfo(info); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -447,7 +448,7 @@ void WifiDeviceStub::OnSetCountryCode(uint32_t code, MessageParcel &data, Messag { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); std::string countrycode = data.ReadCString(); - int ret = SetCountryCode(countrycode); + ErrCode ret = SetCountryCode(countrycode); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -458,7 +459,7 @@ void WifiDeviceStub::OnGetCountryCode(uint32_t code, MessageParcel &data, Messag { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); std::string countryCode; - int ret = GetCountryCode(countryCode); + ErrCode ret = GetCountryCode(countryCode); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -469,12 +470,11 @@ void WifiDeviceStub::OnGetCountryCode(uint32_t code, MessageParcel &data, Messag return; } -void WifiDeviceStub::OnRegisterCallBackClient(uint32_t code, MessageParcel &data, MessageParcel &reply) +void WifiDeviceStub::OnRegisterCallBack(uint32_t code, MessageParcel &data, MessageParcel &reply) { WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); - int ret = WIFI_OPT_FAILED; + ErrCode ret = WIFI_OPT_FAILED; do { - std::string name = data.ReadCString(); sptr remote = data.ReadRemoteObject(); if (remote == nullptr) { WIFI_LOGD("Failed to ReadRemoteObject!"); @@ -482,15 +482,15 @@ void WifiDeviceStub::OnRegisterCallBackClient(uint32_t code, MessageParcel &data } callback_ = iface_cast(remote); if (callback_ == nullptr) { - callback_ = new WifiDeviceCallBackProxy(remote); + callback_ = new (std::nothrow) WifiDeviceCallBackProxy(remote); WIFI_LOGD("create new WifiDeviceCallBackProxy!"); } if (mSingleCallback) { - ret = RegisterCallBackClient(name, callback_); + ret = RegisterCallBack(callback_); } else { if (deathRecipient_ == nullptr) { - deathRecipient_ = new WifiDeviceDeathRecipient(); + deathRecipient_ = new (std::nothrow) WifiDeviceDeathRecipient(); } if ((remote->IsProxyObject()) && (!remote->AddDeathRecipient(deathRecipient_))) { WIFI_LOGD("AddDeathRecipient!"); @@ -512,7 +512,7 @@ void WifiDeviceStub::OnGetSignalLevel(uint32_t code, MessageParcel &data, Messag int rssi = data.ReadInt32(); int band = data.ReadInt32(); int level = 0; - int ret = GetSignalLevel(rssi, band, level); + ErrCode ret = GetSignalLevel(rssi, band, level); reply.WriteInt32(0); reply.WriteInt32(ret); if (ret == WIFI_OPT_SUCCESS) { @@ -535,5 +535,19 @@ void WifiDeviceStub::OnGetSupportedFeatures(uint32_t code, MessageParcel &data, return; } + +void WifiDeviceStub::OnGetDeviceMacAdd(uint32_t code, MessageParcel &data, MessageParcel &reply) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + std::string strMacAddr; + ErrCode ret = GetDeviceMacAddress(strMacAddr); + reply.WriteInt32(0); + reply.WriteInt32(ret); + if (ret == WIFI_OPT_SUCCESS) { + reply.WriteCString(strMacAddr.c_str()); + } + + return; +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub.h index 5c0c669b8..0f2e9e240 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub.h @@ -20,7 +20,6 @@ #include "i_wifi_device.h" #include "i_wifi_device_callback.h" - namespace OHOS { namespace Wifi { class WifiDeviceStub : public IRemoteStub { @@ -36,7 +35,6 @@ public: private: void InitHandleMap(); - void InitStaHandleMap(); void OnEnableWifi(uint32_t code, MessageParcel &data, MessageParcel &reply); void OnDisableWifi(uint32_t code, MessageParcel &data, MessageParcel &reply); void OnAddDeviceConfig(uint32_t code, MessageParcel &data, MessageParcel &reply); @@ -58,9 +56,10 @@ private: void OnGetIpInfo(uint32_t code, MessageParcel &data, MessageParcel &reply); void OnSetCountryCode(uint32_t code, MessageParcel &data, MessageParcel &reply); void OnGetCountryCode(uint32_t code, MessageParcel &data, MessageParcel &reply); - void OnRegisterCallBackClient(uint32_t code, MessageParcel &data, MessageParcel &reply); + void OnRegisterCallBack(uint32_t code, MessageParcel &data, MessageParcel &reply); void OnGetSignalLevel(uint32_t code, MessageParcel &data, MessageParcel &reply); void OnGetSupportedFeatures(uint32_t code, MessageParcel &data, MessageParcel &reply); + void OnGetDeviceMacAdd(uint32_t code, MessageParcel &data, MessageParcel &reply); private: void ReadWifiDeviceConfig(MessageParcel &data, WifiDeviceConfig &config); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_callback_proxy.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_callback_proxy.cpp index 05060b82a..74a18808f 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_callback_proxy.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_callback_proxy.cpp @@ -53,9 +53,9 @@ void WifiHotspotCallbackProxy::OnHotspotStaJoin(const StationInfo &info) MessageParcel data; MessageParcel reply; data.WriteInt32(0); - data.WriteString16(Str8ToStr16(info.deviceName)); - data.WriteString16(Str8ToStr16(info.bssid)); - data.WriteString16(Str8ToStr16(info.ipAddr)); + data.WriteCString(info.deviceName.c_str()); + data.WriteCString(info.bssid.c_str()); + data.WriteCString(info.ipAddr.c_str()); int error = Remote()->SendRequest(WIFI_CBK_CMD_HOTSPOT_STATE_JOIN, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_CBK_CMD_HOTSPOT_STATE_JOIN, error); @@ -76,9 +76,9 @@ void WifiHotspotCallbackProxy::OnHotspotStaLeave(const StationInfo &info) MessageParcel data; MessageParcel reply; data.WriteInt32(0); - data.WriteString16(Str8ToStr16(info.deviceName)); - data.WriteString16(Str8ToStr16(info.bssid)); - data.WriteString16(Str8ToStr16(info.ipAddr)); + data.WriteCString(info.deviceName.c_str()); + data.WriteCString(info.bssid.c_str()); + data.WriteCString(info.ipAddr.c_str()); int error = Remote()->SendRequest(WIFI_CBK_CMD_HOTSPOT_STATE_LEAVE, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_CBK_CMD_HOTSPOT_STATE_LEAVE, error); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_death_recipient.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_death_recipient.cpp index 79bb4a3bd..f8de93325 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_death_recipient.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_death_recipient.cpp @@ -16,7 +16,7 @@ #include "wifi_hotspot_death_recipient.h" #include "wifi_logger.h" #include "wifi_internal_event_dispatcher.h" -DEFINE_WIFILOG_HOTSPOT_LABEL("WifiScanDeathRecipient"); +DEFINE_WIFILOG_HOTSPOT_LABEL("WifiHotspotDeathRecipient"); namespace OHOS { namespace Wifi { void WifiHotspotDeathRecipient::OnRemoteDied(const wptr& remoteObject) diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_death_recipient.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_death_recipient.h index 817754c76..dffa5a7ed 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_death_recipient.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_death_recipient.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_WIFI_SCAN_CALLBACK_DEATH_H -#define OHOS_WIFI_SCAN_CALLBACK_DEATH_H +#ifndef OHOS_WIFI_HOTSPOT_DEATH_RECIPIENT_H +#define OHOS_WIFI_HOTSPOT_DEATH_RECIPIENT_H #include "iremote_object.h" namespace OHOS { diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_service_impl.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_service_impl.cpp index 69f241a50..fdc93ba14 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_service_impl.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_service_impl.cpp @@ -38,7 +38,7 @@ sptr WifiHotspotServiceImpl::GetInstance() if (g_instance == nullptr) { std::lock_guard autoLock(g_instanceLock); if (g_instance == nullptr) { - auto service = new WifiHotspotServiceImpl; + auto service = new (std::nothrow) WifiHotspotServiceImpl; g_instance = service; } } @@ -91,8 +91,7 @@ bool WifiHotspotServiceImpl::Init() ErrCode WifiHotspotServiceImpl::IsHotspotActive(bool &bActive) { WIFI_LOGI("IsHotspotActive"); - WifiOprMidState curState = WifiConfigCenter::GetInstance().GetApMidState(); - bActive = (curState == WifiOprMidState::RUNNING); + bActive = IsApServiceRunning(); return WIFI_OPT_SUCCESS; } @@ -154,38 +153,25 @@ ErrCode WifiHotspotServiceImpl::SetHotspotConfig(const HotspotConfig &config) return validRetval; } + WifiLinkedInfo linkInfo; + WifiConfigCenter::GetInstance().GetLinkedInfo(linkInfo); + if (!linkInfo.ssid.empty() && linkInfo.ssid == config.GetSsid()) { + WIFI_LOGD("set ssid equal current linked ap ssid, no premission!"); + return WIFI_OPT_INVALID_PARAM; + } + if (!IsApServiceRunning()) { WifiConfigCenter::GetInstance().SetHotspotConfig(config); } else { - WifiRequestMsgInfo msg; - msg.msgCode = WifiInternalMsgCode::AP_SET_HOTSPOT_CONFIG_REQ; - msg.params.hotspotConfig = config; - if (WifiManager::GetInstance().PushMsg(WIFI_SERVICE_AP, msg) < 0) { - WIFI_LOGE("send set hotspot config msg failed!"); - return WIFI_OPT_FAILED; + IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_AP_NOT_OPENED; } + return pService->SetHotspotConfig(config); } return WIFI_OPT_SUCCESS; } -ErrCode WifiHotspotServiceImpl::GetDeviceMacAddress(std::string &result) -{ - WIFI_LOGI("GetDeviceMacAddress"); - if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { - WIFI_LOGE("GetDeviceMacAddress:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); - return WIFI_OPT_PERMISSION_DENIED; - } - - if (WifiPermissionUtils::VerifyGetWifiLocalMacPermission() == PERMISSION_DENIED) { - WIFI_LOGE("GetDeviceMacAddress:VerifyGetWifiLocalMacPermission " - "PERMISSION_DENIED!"); - return WIFI_OPT_PERMISSION_DENIED; - } - - WifiConfigCenter::GetInstance().GetMacAddress(result); - return WIFI_OPT_SUCCESS; -} - ErrCode WifiHotspotServiceImpl::GetStationList(std::vector &result) { WIFI_LOGI("GetStationList"); @@ -204,13 +190,20 @@ ErrCode WifiHotspotServiceImpl::GetStationList(std::vector &result) return WIFI_OPT_PERMISSION_DENIED; } - WifiConfigCenter::GetInstance().GetStationList(result); - return WIFI_OPT_SUCCESS; + if (!IsApServiceRunning()) { + return WIFI_OPT_AP_NOT_OPENED; + } + + IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_AP_NOT_OPENED; + } + return pService->GetStationList(result); } ErrCode WifiHotspotServiceImpl::DisassociateSta(const StationInfo &info) { - WIFI_LOGI("DisassociateSta device name [%s]", info.deviceName.c_str()); + WIFI_LOGI("DisassociateSta device name [%{private}s]", info.deviceName.c_str()); if (WifiPermissionUtils::VerifySetWifiInfoPermission() == PERMISSION_DENIED) { WIFI_LOGE("DisassociateSta:VerifySetWifiInfoPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; @@ -222,14 +215,11 @@ ErrCode WifiHotspotServiceImpl::DisassociateSta(const StationInfo &info) return WIFI_OPT_AP_NOT_OPENED; } - WifiRequestMsgInfo msg; - msg.msgCode = WifiInternalMsgCode::AP_DISCCONECT_STA_BY_MAC_REQ; - msg.params.stationInfo = info; - if (WifiManager::GetInstance().PushMsg(WIFI_SERVICE_AP, msg) < 0) { - WIFI_LOGE("send disconnect sta msg failed!"); - return WIFI_OPT_FAILED; + IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_AP_NOT_OPENED; } - return WIFI_OPT_SUCCESS; + return pService->DisconnetStation(info); } ErrCode WifiHotspotServiceImpl::CheckCanEnableHotspot(void) @@ -268,36 +258,36 @@ ErrCode WifiHotspotServiceImpl::EnableHotspot(void) } } if (!WifiConfigCenter::GetInstance().SetApMidState(curState, WifiOprMidState::OPENING)) { - WIFI_LOGI("set ap mid state opening failed! may be other activity has been " - "operated"); + WIFI_LOGI("set ap mid state opening failed! may be other activity has been operated"); return WIFI_OPT_OPEN_SUCC_WHEN_OPENED; } - bool bflag = false; + errCode = WIFI_OPT_FAILED; do { if (WifiServiceManager::GetInstance().CheckAndEnforceService(WIFI_SERVICE_AP) < 0) { WIFI_LOGE("Load %{public}s service failed!", WIFI_SERVICE_AP); break; } - WifiMessageQueue *mqUp = WifiManager::GetInstance().GetMessageQueue(); - auto srvInst = WifiServiceManager::GetInstance().GetServiceInst(WIFI_SERVICE_AP); - if (srvInst == nullptr) { - WIFI_LOGE("Failed to get service instance!"); - return WIFI_OPT_FAILED; + IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(); + if (pService == nullptr) { + WIFI_LOGE("Create %{public}s service failed!", WIFI_SERVICE_AP); + break; + } + errCode = pService->RegisterApServiceCallbacks(WifiManager::GetInstance().GetApCallback()); + if (errCode != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Register ap service callback failed!"); + break; } - int ret = srvInst->Init(mqUp); - if (ret < 0) { - WIFI_LOGE("Init %{public}s service failed!", WIFI_SERVICE_AP); - WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_AP); + errCode = pService->EnableHotspot(); + if (errCode != WIFI_OPT_SUCCESS) { + WIFI_LOGE("service enable ap failed, ret %{public}d!", static_cast(errCode)); break; } - bflag = true; } while (false); - if (!bflag) { + if (errCode != WIFI_OPT_SUCCESS) { WifiConfigCenter::GetInstance().SetApMidState(WifiOprMidState::OPENING, WifiOprMidState::CLOSED); - return WIFI_OPT_FAILED; - } else { - return WIFI_OPT_SUCCESS; + WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_AP); } + return errCode; } ErrCode WifiHotspotServiceImpl::DisableHotspot(void) @@ -318,27 +308,25 @@ ErrCode WifiHotspotServiceImpl::DisableHotspot(void) } } if (!WifiConfigCenter::GetInstance().SetApMidState(curState, WifiOprMidState::CLOSING)) { - WIFI_LOGI("set ap mid state closing failed! may be other activity has been " - "operated"); + WIFI_LOGI("set ap mid state closing failed! may be other activity has been operated"); return WIFI_OPT_CLOSE_SUCC_WHEN_CLOSED; } - auto srvInst = WifiServiceManager::GetInstance().GetServiceInst(WIFI_SERVICE_AP); - if (srvInst == nullptr) { - WIFI_LOGE("Failed to get service instance!"); - return WIFI_OPT_FAILED; + IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(); + if (pService == nullptr) { + WifiConfigCenter::GetInstance().SetApMidState(WifiOprMidState::CLOSED); + WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_AP); + return WIFI_OPT_SUCCESS; } - int ret = srvInst->UnInit(); - if (ret < 0) { + ErrCode ret = pService->DisableHotspot(); + if (ret != WIFI_OPT_SUCCESS) { WifiConfigCenter::GetInstance().SetApMidState(WifiOprMidState::CLOSING, WifiOprMidState::RUNNING); - return WIFI_OPT_FAILED; - } else { - return WIFI_OPT_SUCCESS; } + return ret; } ErrCode WifiHotspotServiceImpl::AddBlockList(const StationInfo &info) { - WIFI_LOGI("AddBlockList, device name [%s]", info.deviceName.c_str()); + WIFI_LOGI("AddBlockList, device name [%{private}s]", info.deviceName.c_str()); if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { WIFI_LOGE("AddBlockList:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; @@ -360,19 +348,16 @@ ErrCode WifiHotspotServiceImpl::AddBlockList(const StationInfo &info) WIFI_LOGE("Add block list failed!"); return WIFI_OPT_FAILED; } - WifiRequestMsgInfo msg; - msg.msgCode = WifiInternalMsgCode::AP_ADD_BLOCK_LIST_REQ; - msg.params.stationInfo = info; - if (WifiManager::GetInstance().PushMsg(WIFI_SERVICE_AP, msg) < 0) { - WIFI_LOGE("send set hotspot blocklist msg failed!"); - return WIFI_OPT_FAILED; + IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_AP_NOT_OPENED; } - return WIFI_OPT_SUCCESS; + return pService->AddBlockList(info); } ErrCode WifiHotspotServiceImpl::DelBlockList(const StationInfo &info) { - WIFI_LOGI("DelBlockList, device name [%s]", info.deviceName.c_str()); + WIFI_LOGI("DelBlockList, device name [%{private}s]", info.deviceName.c_str()); if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { WIFI_LOGE("DelBlockList:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; @@ -388,11 +373,12 @@ ErrCode WifiHotspotServiceImpl::DelBlockList(const StationInfo &info) } if (IsApServiceRunning()) { - WifiRequestMsgInfo msg; - msg.msgCode = WifiInternalMsgCode::AP_DEL_BLOCK_LIST_REQ; - msg.params.stationInfo = info; - if (WifiManager::GetInstance().PushMsg(WIFI_SERVICE_AP, msg) < 0) { - WIFI_LOGE("send del hotspot blocklist msg failed!"); + IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_AP_NOT_OPENED; + } + if (pService->DelBlockList(info) != WIFI_OPT_SUCCESS) { + WIFI_LOGE("request del hotspot blocklist failed!"); return WIFI_OPT_FAILED; } } @@ -411,13 +397,7 @@ ErrCode WifiHotspotServiceImpl::GetValidBands(std::vector &bands) return WIFI_OPT_PERMISSION_DENIED; } - if (!IsApServiceRunning()) { - WIFI_LOGE("ApService is not running!"); - return WIFI_OPT_AP_NOT_OPENED; - } - if (WifiConfigCenter::GetInstance().GetValidBands(bands) < 0) { - WIFI_LOGE("Delete block list failed!"); return WIFI_OPT_FAILED; } return WIFI_OPT_SUCCESS; @@ -431,25 +411,15 @@ ErrCode WifiHotspotServiceImpl::GetValidChannels(BandType band, std::vectorsecond; + } return WIFI_OPT_SUCCESS; } diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_service_impl.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_service_impl.h index 7c836f687..ac6379b0d 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_service_impl.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_service_impl.h @@ -71,14 +71,6 @@ public: */ ErrCode SetHotspotConfig(const HotspotConfig &config) override; - /** - * @Description Get the device MAC address - * - * @param result - Get device mac String - * @return ErrCode - operation result - */ - ErrCode GetDeviceMacAddress(std::string &result) override; - /** * @Description Get the Station List object * diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_stub.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_stub.cpp index aa75c7072..f14539957 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_stub.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_stub.cpp @@ -38,7 +38,6 @@ void WifiHotspotStub::InitHandleMap() handleFuncMap[WIFI_SVR_CMD_GETAPSTATE_WIFI] = &WifiHotspotStub::OnGetApStateWifi; handleFuncMap[WIFI_SVR_CMD_GET_HOTSPOT_CONFIG] = &WifiHotspotStub::OnGetHotspotConfig; handleFuncMap[WIFI_SVR_CMD_SETAPCONFIG_WIFI] = &WifiHotspotStub::OnSetApConfigWifi; - handleFuncMap[WIFI_SVR_CMD_GET_DERVICE_MAC_ADD] = &WifiHotspotStub::OnGetDeviceMacAdd; handleFuncMap[WIFI_SVR_CMD_GET_STATION_LIST] = &WifiHotspotStub::OnGetStationList; handleFuncMap[WIFI_SVR_CMD_ENABLE_WIFI_AP] = &WifiHotspotStub::OnEnableWifiAp; handleFuncMap[WIFI_SVR_CMD_DISABLE_WIFI_AP] = &WifiHotspotStub::OnDisableWifiAp; @@ -75,7 +74,7 @@ void WifiHotspotStub::OnIsHotspotActive(uint32_t code, MessageParcel &data, Mess { WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); bool bActive = false; - int ret = IsHotspotActive(bActive); + ErrCode ret = IsHotspotActive(bActive); reply.WriteInt32(0); reply.WriteInt32(ret); if (ret == WIFI_OPT_SUCCESS) { @@ -88,7 +87,7 @@ void WifiHotspotStub::OnGetApStateWifi(uint32_t code, MessageParcel &data, Messa { WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); int state = 0; - int ret = GetHotspotState(state); + ErrCode ret = GetHotspotState(state); reply.WriteInt32(0); reply.WriteInt32(ret); if (ret == WIFI_OPT_SUCCESS) { @@ -103,7 +102,7 @@ void WifiHotspotStub::OnGetHotspotConfig( WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); HotspotConfig hotspotConfig; - int ret = GetHotspotConfig(hotspotConfig); + ErrCode ret = GetHotspotConfig(hotspotConfig); reply.WriteInt32(0); reply.WriteInt32(ret); if (ret == WIFI_OPT_SUCCESS) { @@ -128,32 +127,18 @@ void WifiHotspotStub::OnSetApConfigWifi(uint32_t code, MessageParcel &data, Mess config.SetChannel(data.ReadInt32()); config.SetPreSharedKey(data.ReadCString()); config.SetMaxConn(data.ReadInt32()); - int ret = SetHotspotConfig(config); + ErrCode ret = SetHotspotConfig(config); reply.WriteInt32(0); reply.WriteInt32(ret); return; } -void WifiHotspotStub::OnGetDeviceMacAdd(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) -{ - WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); - std::string strMacAddr; - int ret = GetDeviceMacAddress(strMacAddr); - reply.WriteInt32(0); - reply.WriteInt32(ret); - if (ret == WIFI_OPT_SUCCESS) { - reply.WriteCString(strMacAddr.c_str()); - } - - return; -} - void WifiHotspotStub::OnGetStationList(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); std::vector result; - int ret = GetStationList(result); + ErrCode ret = GetStationList(result); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -177,7 +162,7 @@ void WifiHotspotStub::OnDisassociateSta(uint32_t code, MessageParcel &data, Mess info.deviceName = data.ReadCString(); info.bssid = data.ReadCString(); info.ipAddr = data.ReadCString(); - int ret = DisassociateSta(info); + ErrCode ret = DisassociateSta(info); reply.WriteInt32(0); reply.WriteInt32(ret); return; @@ -187,14 +172,16 @@ void WifiHotspotStub::OnGetValidBands(uint32_t code, MessageParcel &data, Messag { WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); std::vector bands; - int ret = GetValidBands(bands); + ErrCode ret = GetValidBands(bands); reply.WriteInt32(0); reply.WriteInt32(ret); - int count = bands.size(); - reply.WriteInt32(count); - for (int i = 0; i < count; i++) { - reply.WriteInt32((int)bands[i]); + if (ret == WIFI_OPT_SUCCESS) { + int count = bands.size(); + reply.WriteInt32(count); + for (int i = 0; i < count; i++) { + reply.WriteInt32((int)bands[i]); + } } return; } @@ -205,14 +192,16 @@ void WifiHotspotStub::OnGetValidChannels( WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); std::vector channels; int32_t band = data.ReadInt32(); - int ret = GetValidChannels(static_cast(band), channels); + ErrCode ret = GetValidChannels(static_cast(band), channels); reply.WriteInt32(0); reply.WriteInt32(ret); - int count = channels.size(); - reply.WriteInt32(count); - for (int i = 0; i < count; i++) { - reply.WriteInt32(channels[i]); + if (ret == WIFI_OPT_SUCCESS) { + int count = channels.size(); + reply.WriteInt32(count); + for (int i = 0; i < count; i++) { + reply.WriteInt32(channels[i]); + } } return; } @@ -220,7 +209,7 @@ void WifiHotspotStub::OnGetValidChannels( void WifiHotspotStub::OnEnableWifiAp(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); - int ret = EnableHotspot(); + ErrCode ret = EnableHotspot(); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -230,7 +219,7 @@ void WifiHotspotStub::OnEnableWifiAp(uint32_t code, MessageParcel &data, Message void WifiHotspotStub::OnDisableWifiAp(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); - int ret = DisableHotspot(); + ErrCode ret = DisableHotspot(); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -244,7 +233,7 @@ void WifiHotspotStub::OnAddBlockList(uint32_t code, MessageParcel &data, Message info.deviceName = data.ReadCString(); info.bssid = data.ReadCString(); info.ipAddr = data.ReadCString(); - int ret = AddBlockList(info); + ErrCode ret = AddBlockList(info); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -258,7 +247,7 @@ void WifiHotspotStub::OnDelBlockList(uint32_t code, MessageParcel &data, Message info.deviceName = data.ReadCString(); info.bssid = data.ReadCString(); info.ipAddr = data.ReadCString(); - int ret = DelBlockList(info); + ErrCode ret = DelBlockList(info); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -269,7 +258,7 @@ void WifiHotspotStub::OnGetBlockLists(uint32_t code, MessageParcel &data, Messag { WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); std::vector infos; - int ret = GetBlockLists(infos); + ErrCode ret = GetBlockLists(infos); reply.WriteInt32(0); reply.WriteInt32(ret); if (ret == WIFI_OPT_SUCCESS) { @@ -289,7 +278,7 @@ void WifiHotspotStub::OnRegisterCallBack( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); - int ret = WIFI_OPT_FAILED; + ErrCode ret = WIFI_OPT_FAILED; do { sptr remote = data.ReadRemoteObject(); if (remote == nullptr) { @@ -298,7 +287,7 @@ void WifiHotspotStub::OnRegisterCallBack( } sptr callback_ = iface_cast(remote); if (callback_ == nullptr) { - callback_ = new WifiHotspotCallbackProxy(remote); + callback_ = new (std::nothrow) WifiHotspotCallbackProxy(remote); WIFI_LOGD("create new WifiHotspotCallbackProxy!"); } @@ -306,7 +295,7 @@ void WifiHotspotStub::OnRegisterCallBack( ret = RegisterCallBack(callback_); } else { if (deathRecipient_ == nullptr) { - deathRecipient_ = new WifiHotspotDeathRecipient(); + deathRecipient_ = new (std::nothrow) WifiHotspotDeathRecipient(); } if ((remote->IsProxyObject()) && (!remote->AddDeathRecipient(deathRecipient_))) { WIFI_LOGD("AddDeathRecipient!"); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_stub.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_stub.h index b5950e6ad..c963af1d0 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_stub.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_stub.h @@ -43,7 +43,6 @@ private: void OnGetApStateWifi(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); void OnGetHotspotConfig(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); void OnSetApConfigWifi(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); - void OnGetDeviceMacAdd(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); void OnGetStationList(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); void OnDisassociateSta(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); void OnEnableWifiAp(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.cpp index db2f6b4f0..dbd228665 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.cpp @@ -16,6 +16,7 @@ #include "wifi_internal_event_dispatcher.h" #include "wifi_logger.h" #include "wifi_permission_helper.h" +#include "wifi_errcode.h" #include "wifi_common_event_helper.h" DEFINE_WIFILOG_LABEL("WifiInternalEventDispatcher"); @@ -28,11 +29,8 @@ WifiInternalEventDispatcher &WifiInternalEventDispatcher::GetInstance() return gWifiInternalEventDispatcher; } -WifiInternalEventDispatcher::WifiInternalEventDispatcher():mTid(0) -{ - mSystemNotifyInit = false; - mRunFlag = true; -} +WifiInternalEventDispatcher::WifiInternalEventDispatcher() : mRunFlag(true) +{} WifiInternalEventDispatcher::~WifiInternalEventDispatcher() {} @@ -41,11 +39,7 @@ int WifiInternalEventDispatcher::Init() { /* first init system notify service client here ! */ - int ret = pthread_create(&mTid, nullptr, Run, this); - if (ret != 0) { - WIFI_LOGE("Init WifiInternalEventDispatcher notify message callback thread failed!"); - return -1; - } + mBroadcastThread = std::thread(WifiInternalEventDispatcher::Run, std::ref(*this)); return 0; } @@ -211,15 +205,18 @@ int WifiInternalEventDispatcher::AddBroadCastMsg(const WifiEventCallbackMsg &msg void WifiInternalEventDispatcher::Exit() { - if (mRunFlag) { - mRunFlag = false; - mCondition.notify_one(); - pthread_join(mTid, nullptr); + if (!mRunFlag) { + return; + } + mRunFlag = false; + mCondition.notify_one(); + if (mBroadcastThread.joinable()) { + mBroadcastThread.join(); } } void WifiInternalEventDispatcher::DealStaCallbackMsg( - WifiInternalEventDispatcher *pInstance, const WifiEventCallbackMsg &msg) + WifiInternalEventDispatcher &instance, const WifiEventCallbackMsg &msg) { switch (msg.msgCode) { case WIFI_CBK_MSG_STATE_CHANGE: @@ -229,6 +226,7 @@ void WifiInternalEventDispatcher::DealStaCallbackMsg( WifiInternalEventDispatcher::PublishConnectionStateChangedEvent(msg.msgData, msg.linkInfo); break; case WIFI_CBK_MSG_RSSI_CHANGE: + WifiInternalEventDispatcher::PublishRssiValueChangedEvent(msg.msgData); break; case WIFI_CBK_MSG_STREAM_DIRECTION: break; @@ -238,7 +236,7 @@ void WifiInternalEventDispatcher::DealStaCallbackMsg( break; } - auto callback = pInstance->GetSingleStaCallback(); + auto callback = instance.GetSingleStaCallback(); if (callback != nullptr) { switch (msg.msgCode) { case WIFI_CBK_MSG_STATE_CHANGE: @@ -261,83 +259,33 @@ void WifiInternalEventDispatcher::DealStaCallbackMsg( break; } } - pInstance->InvokeDeviceCallbacks(msg); + instance.InvokeDeviceCallbacks(msg); return; } -void WifiInternalEventDispatcher::PublishConnectionStateChangedEvent(int state, const WifiLinkedInfo &info) +void WifiInternalEventDispatcher::DealScanCallbackMsg( + WifiInternalEventDispatcher &instance, const WifiEventCallbackMsg &msg) { - std::string eventData = "Other"; - switch (state) { - case int(OHOS::Wifi::ConnectionState::CONNECT_CONNECTING): - eventData = "Connecting"; - break; - case int(OHOS::Wifi::ConnectionState::CONNECT_OBTAINING_IP): - eventData = "OBtaingIp"; - break; - case int(OHOS::Wifi::ConnectionState::CONNECT_OBTAINING_IP_FAIL): - eventData = "OBtaingIpFail"; - break; - case int(OHOS::Wifi::ConnectionState::CONNECT_AP_CONNECTED): - eventData = "ApConnecting"; - break; - case int(OHOS::Wifi::ConnectionState::CONNECT_CHECK_PORTAL): - eventData = "Connecting"; - break; - case int(OHOS::Wifi::ConnectionState::CONNECT_NETWORK_ENABLED): - eventData = "NetworkEnabled"; - break; - case int(OHOS::Wifi::ConnectionState::CONNECT_NETWORK_DISABLED): - eventData = "NetworkDisabled"; - break; - case int(OHOS::Wifi::ConnectionState::DISCONNECT_DISCONNECTING): - eventData = "DisconnectDisconnecting"; - break; - case int(OHOS::Wifi::ConnectionState::DISCONNECT_DISCONNECTED): - eventData = "Disconnected"; - break; - case int(OHOS::Wifi::ConnectionState::CONNECT_PASSWORD_WRONG): - eventData = "ConnectPasswordWrong"; - break; - case int(OHOS::Wifi::ConnectionState::CONNECT_CONNECTING_TIMEOUT): - eventData = "ConnectingTimeout"; + switch (msg.msgCode) { + case WIFI_CBK_MSG_SCAN_STATE_CHANGE: + WifiCommonEventHelper::PublishScanStateChangedEvent(msg.msgData, "OnScanStateChanged"); break; - default: { - eventData = "UnknownState"; + default: + WIFI_LOGI("UnKnown msgcode %{public}d", msg.msgCode); break; - } } - if (!WifiCommonEventHelper::PublishConnectionStateChangedEvent(state, eventData)) { - WIFI_LOGE("failed to publish connection state changed event!"); - return; - } - WIFI_LOGD("publish connection state changed event."); -} -void WifiInternalEventDispatcher::PublishWifiStateChangedEvent(int state) -{ - if (!WifiCommonEventHelper::PublishPowerStateChangeEvent(state, "OnWifiPowerStateChanged")) { - WIFI_LOGE("failed to publish wifi state changed event!"); - return; - } - WIFI_LOGD("publish wifi state changed event."); -} - -void WifiInternalEventDispatcher::DealScanCallbackMsg( - WifiInternalEventDispatcher *pInstance, const WifiEventCallbackMsg &msg) -{ - auto callback = pInstance->GetSingleScanCallback(); + auto callback = instance.GetSingleScanCallback(); if (callback != nullptr) { switch (msg.msgCode) { case WIFI_CBK_MSG_SCAN_STATE_CHANGE: callback->OnWifiScanStateChanged(msg.msgData); break; default: - WIFI_LOGI("UnKnown msgcode %{public}d", msg.msgCode); break; } } - pInstance->InvokeScanCallbacks(msg); + instance.InvokeScanCallbacks(msg); return; } @@ -347,15 +295,16 @@ void WifiInternalEventDispatcher::InvokeScanCallbacks(const WifiEventCallbackMsg ScanCallbackMapType::iterator itr; for (itr = callbacks.begin(); itr != callbacks.end(); itr++) { auto callback = itr->second; - if (callback != nullptr) { - switch (msg.msgCode) { - case WIFI_CBK_MSG_SCAN_STATE_CHANGE: - callback->OnWifiScanStateChanged(msg.msgData); - break; - default: - WIFI_LOGI("UnKnown msgcode %{public}d", msg.msgCode); - break; - } + if (callback == nullptr) { + continue; + } + switch (msg.msgCode) { + case WIFI_CBK_MSG_SCAN_STATE_CHANGE: + callback->OnWifiScanStateChanged(msg.msgData); + break; + default: + WIFI_LOGI("UnKnown msgcode %{public}d", msg.msgCode); + break; } } } @@ -366,27 +315,28 @@ void WifiInternalEventDispatcher::InvokeDeviceCallbacks(const WifiEventCallbackM StaCallbackMapType::iterator itr; for (itr = callbacks.begin(); itr != callbacks.end(); itr++) { auto callback = itr->second; - if (callback != nullptr) { - switch (msg.msgCode) { - case WIFI_CBK_MSG_STATE_CHANGE: - callback->OnWifiStateChanged(msg.msgData); - break; - case WIFI_CBK_MSG_CONNECTION_CHANGE: - callback->OnWifiConnectionChanged(msg.msgData, msg.linkInfo); - break; - case WIFI_CBK_MSG_RSSI_CHANGE: - callback->OnWifiRssiChanged(msg.msgData); - break; - case WIFI_CBK_MSG_STREAM_DIRECTION: - callback->OnStreamChanged(msg.msgData); - break; - case WIFI_CBK_MSG_WPS_STATE_CHANGE: - callback->OnWifiWpsStateChanged(msg.msgData, msg.pinCode); - break; - default: - WIFI_LOGI("UnKnown msgcode %{public}d", msg.msgCode); - break; - } + if (callback == nullptr) { + continue; + } + switch (msg.msgCode) { + case WIFI_CBK_MSG_STATE_CHANGE: + callback->OnWifiStateChanged(msg.msgData); + break; + case WIFI_CBK_MSG_CONNECTION_CHANGE: + callback->OnWifiConnectionChanged(msg.msgData, msg.linkInfo); + break; + case WIFI_CBK_MSG_RSSI_CHANGE: + callback->OnWifiRssiChanged(msg.msgData); + break; + case WIFI_CBK_MSG_STREAM_DIRECTION: + callback->OnStreamChanged(msg.msgData); + break; + case WIFI_CBK_MSG_WPS_STATE_CHANGE: + callback->OnWifiWpsStateChanged(msg.msgData, msg.pinCode); + break; + default: + WIFI_LOGI("UnKnown msgcode %{public}d", msg.msgCode); + break; } } } @@ -397,29 +347,30 @@ void WifiInternalEventDispatcher::InvokeHotspotCallbacks(const WifiEventCallback HotspotCallbackMapType::iterator itr; for (itr = callbacks.begin(); itr != callbacks.end(); itr++) { auto callback = itr->second; - if (callback != nullptr) { - switch (msg.msgCode) { - case WIFI_CBK_MSG_HOTSPOT_STATE_CHANGE: - callback->OnHotspotStateChanged(msg.msgData); - break; - case WIFI_CBK_MSG_HOTSPOT_STATE_JOIN: - callback->OnHotspotStaJoin(msg.staInfo); - break; - case WIFI_CBK_MSG_HOTSPOT_STATE_LEAVE: - callback->OnHotspotStaLeave(msg.staInfo); - break; - default: - WIFI_LOGI("UnKnown msgcode %{public}d", msg.msgCode); - break; - } + if (callback == nullptr) { + continue; + } + switch (msg.msgCode) { + case WIFI_CBK_MSG_HOTSPOT_STATE_CHANGE: + callback->OnHotspotStateChanged(msg.msgData); + break; + case WIFI_CBK_MSG_HOTSPOT_STATE_JOIN: + callback->OnHotspotStaJoin(msg.staInfo); + break; + case WIFI_CBK_MSG_HOTSPOT_STATE_LEAVE: + callback->OnHotspotStaLeave(msg.staInfo); + break; + default: + WIFI_LOGI("UnKnown msgcode %{public}d", msg.msgCode); + break; } } } void WifiInternalEventDispatcher::DealHotspotCallbackMsg( - WifiInternalEventDispatcher *pInstance, const WifiEventCallbackMsg &msg) + WifiInternalEventDispatcher &instance, const WifiEventCallbackMsg &msg) { - auto callback = pInstance->GetSingleHotspotCallback(); + auto callback = instance.GetSingleHotspotCallback(); if (callback != nullptr) { switch (msg.msgCode) { case WIFI_CBK_MSG_HOTSPOT_STATE_CHANGE: @@ -436,35 +387,100 @@ void WifiInternalEventDispatcher::DealHotspotCallbackMsg( break; } } - pInstance->InvokeHotspotCallbacks(msg); + instance.InvokeHotspotCallbacks(msg); return; } -void *WifiInternalEventDispatcher::Run(void *p) +void WifiInternalEventDispatcher::PublishConnectionStateChangedEvent(int state, const WifiLinkedInfo &info) +{ + std::string eventData = "Other"; + switch (state) { + case int(OHOS::Wifi::ConnectionState::CONNECT_CONNECTING): + eventData = "Connecting"; + break; + case int(OHOS::Wifi::ConnectionState::CONNECT_OBTAINING_IP_FAILED): + eventData = "OBtaingIpFail"; + break; + case int(OHOS::Wifi::ConnectionState::CONNECT_AP_CONNECTED): + eventData = "ApConnecting"; + break; + case int(OHOS::Wifi::ConnectionState::CONNECT_CHECK_PORTAL): + eventData = "Connecting"; + break; + case int(OHOS::Wifi::ConnectionState::CONNECT_NETWORK_ENABLED): + eventData = "NetworkEnabled"; + break; + case int(OHOS::Wifi::ConnectionState::CONNECT_NETWORK_DISABLED): + eventData = "NetworkDisabled"; + break; + case int(OHOS::Wifi::ConnectionState::DISCONNECT_DISCONNECTING): + eventData = "DisconnectDisconnecting"; + break; + case int(OHOS::Wifi::ConnectionState::DISCONNECT_DISCONNECTED): + eventData = "Disconnected"; + break; + case int(OHOS::Wifi::ConnectionState::CONNECT_PASSWORD_WRONG): + eventData = "ConnectPasswordWrong"; + break; + case int(OHOS::Wifi::ConnectionState::CONNECT_CONNECTING_TIMEOUT): + eventData = "ConnectingTimeout"; + break; + default: { + eventData = "UnknownState"; + break; + } + } + if (!WifiCommonEventHelper::PublishConnectionStateChangedEvent(state, eventData)) { + WIFI_LOGE("failed to publish connection state changed event!"); + return; + } + WIFI_LOGD("publish connection state changed event."); +} + +void WifiInternalEventDispatcher::PublishRssiValueChangedEvent(int state) +{ + if (!WifiCommonEventHelper::PublishRssiValueChangedEvent(state, "OnRssiValueChanged")) { + WIFI_LOGE("failed to publish rssi value changed event!"); + return; + } + WIFI_LOGD("publish rssi value changed event."); +} + +void WifiInternalEventDispatcher::PublishWifiStateChangedEvent(int state) +{ + if (!WifiCommonEventHelper::PublishPowerStateChangeEvent(state, "OnWifiPowerStateChanged")) { + WIFI_LOGE("failed to publish wifi state changed event!"); + return; + } + WIFI_LOGD("publish wifi state changed event."); +} + +void WifiInternalEventDispatcher::Run(WifiInternalEventDispatcher &instance) { - WifiInternalEventDispatcher *pInstance = (WifiInternalEventDispatcher *)p; - while (pInstance->mRunFlag) { - std::unique_lock lock(pInstance->mMutex); - while (pInstance->mEventQue.empty() && pInstance->mRunFlag) { - pInstance->mCondition.wait(lock); + while (instance.mRunFlag) { + std::unique_lock lock(instance.mMutex); + while (instance.mEventQue.empty() && instance.mRunFlag) { + instance.mCondition.wait(lock); } - if (!pInstance->mRunFlag) { + if (!instance.mRunFlag) { break; } - WifiEventCallbackMsg msg = pInstance->mEventQue.front(); - pInstance->mEventQue.pop_front(); + WifiEventCallbackMsg msg = instance.mEventQue.front(); + instance.mEventQue.pop_front(); lock.unlock(); WIFI_LOGD("WifiInternalEventDispatcher::Run broad cast a msg %{public}d", msg.msgCode); if (msg.msgCode >= WIFI_CBK_MSG_STATE_CHANGE && msg.msgCode <= WIFI_CBK_MSG_WPS_STATE_CHANGE) { - DealStaCallbackMsg(pInstance, msg); + DealStaCallbackMsg(instance, msg); } else if (msg.msgCode == WIFI_CBK_MSG_SCAN_STATE_CHANGE) { - DealScanCallbackMsg(pInstance, msg); + DealScanCallbackMsg(instance, msg); } else if (msg.msgCode >= WIFI_CBK_MSG_HOTSPOT_STATE_CHANGE && msg.msgCode <= WIFI_CBK_MSG_HOTSPOT_STATE_LEAVE) { - DealHotspotCallbackMsg(pInstance, msg); + DealHotspotCallbackMsg(instance, msg); + } else { + WIFI_LOGI("UnKnown msgcode %{public}d", msg.msgCode); } } - return nullptr; + return; } } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.h index 5766f593a..0b131ba73 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.h @@ -22,10 +22,10 @@ #include #include #include -#include +#include #include #include -#include + #include "wifi_internal_msg.h" #include "parcel.h" #include "iremote_object.h" @@ -83,7 +83,7 @@ public: * @param p WifiInternalEventDispatcher this Object * @return void* - nullptr, not care this now */ - static void *Run(void *p); + static void Run(WifiInternalEventDispatcher &instance); static WifiInternalEventDispatcher &GetInstance(); int AddStaCallback(const sptr &remote, const sptr &callback); @@ -106,19 +106,15 @@ public: void InvokeDeviceCallbacks(const WifiEventCallbackMsg &msg); void InvokeHotspotCallbacks(const WifiEventCallbackMsg &msg); private: - static void DealStaCallbackMsg(WifiInternalEventDispatcher *pInstance, const WifiEventCallbackMsg &msg); - static void DealScanCallbackMsg(WifiInternalEventDispatcher *pInstance, const WifiEventCallbackMsg &msg); - static void DealHotspotCallbackMsg(WifiInternalEventDispatcher *pInstance, const WifiEventCallbackMsg &msg); + static void DealStaCallbackMsg(WifiInternalEventDispatcher &pInstance, const WifiEventCallbackMsg &msg); + static void DealScanCallbackMsg(WifiInternalEventDispatcher &pInstance, const WifiEventCallbackMsg &msg); + static void DealHotspotCallbackMsg(WifiInternalEventDispatcher &pInstance, const WifiEventCallbackMsg &msg); static void PublishConnectionStateChangedEvent(int state, const WifiLinkedInfo &info); - static void PublishWifiStateChangedEvent(int state); - + static void PublishRssiValueChangedEvent(int state); private: - bool mSystemNotifyInit; - /* system notify service client */ - - pthread_t mTid; + std::thread mBroadcastThread; std::atomic mRunFlag; std::mutex mMutex; std::condition_variable mCondition; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.cpp index 3a544d7f5..f1781e18f 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.cpp @@ -23,6 +23,7 @@ #include "wifi_internal_event_dispatcher.h" #include "wifi_service_manager.h" #include "wifi_settings.h" +#include "wifi_common_event_helper.h" DEFINE_WIFILOG_LABEL("WifiManager"); @@ -44,46 +45,43 @@ WifiManager &WifiManager::GetInstance() return gWifiManager; } -WifiManager::WifiManager() : mTid(0), mRunFlag(true), mInitStatus_(INIT_UNKNOWN), mSupportedFeatures(0) +WifiManager::WifiManager() : mInitStatus(INIT_UNKNOWN), mSupportedFeatures(0) {} WifiManager::~WifiManager() -{ - WIFI_LOGI("WifiManager::~WifiManager"); -} +{} int WifiManager::Init() { if (WifiConfigCenter::GetInstance().Init() < 0) { WIFI_LOGE("WifiConfigCenter Init failed!"); - mInitStatus_ = CONFIG_CENTER_INIT_FAILED; + mInitStatus = CONFIG_CENTER_INIT_FAILED; return -1; } if (WifiAuthCenter::GetInstance().Init() < 0) { WIFI_LOGE("WifiAuthCenter Init failed!"); - mInitStatus_ = AUTH_CENTER_INIT_FAILED; + mInitStatus = AUTH_CENTER_INIT_FAILED; return -1; } if (WifiServiceManager::GetInstance().Init() < 0) { WIFI_LOGE("WifiServiceManager Init failed!"); - mInitStatus_ = SERVICE_MANAGER_INIT_FAILED; + mInitStatus = SERVICE_MANAGER_INIT_FAILED; return -1; } if (WifiInternalEventDispatcher::GetInstance().Init() < 0) { WIFI_LOGE("WifiInternalEventDispatcher Init failed!"); - mInitStatus_ = EVENT_BROADCAST_INIT_FAILED; + mInitStatus = EVENT_BROADCAST_INIT_FAILED; return -1; } - mMqUp = std::make_unique>(); - - int ret = pthread_create(&mTid, nullptr, DealServiceUpMsg, this); - if (ret != 0) { - WIFI_LOGE("In WifiManager create message deal thread failed!"); - mInitStatus_ = TASK_THREAD_INIT_FAILED; - return -1; + mCloseServiceThread = std::thread(WifiManager::DealCloseServiceMsg, std::ref(*this)); + + mInitStatus = INIT_OK; + InitStaCallback(); + InitScanCallback(); + InitApCallback(); + if (!WifiConfigCenter::GetInstance().GetSupportedBandChannel()) { + WIFI_LOGE("Failed to get current chip supported band and channel!"); } - - mInitStatus_ = INIT_OK; return 0; } @@ -92,73 +90,19 @@ void WifiManager::Exit() WifiServiceManager::GetInstance().UninstallAllService(); WifiStaHalInterface::GetInstance().ExitAllIdlClient(); WifiInternalEventDispatcher::GetInstance().Exit(); - if (mTid != 0) { - mRunFlag = false; - WifiResponseMsgInfo msg; - msg.msgCode = WifiInternalMsgCode::MAIN_EXIT_CODE; - mMqUp->Push(msg); - pthread_join(mTid, nullptr); - mTid = 0; + if (mCloseServiceThread.joinable()) { + PushServiceCloseMsg(WifiCloseServiceCode::SERVICE_THREAD_EXIT); + mCloseServiceThread.join(); } return; } -int WifiManager::PushMsg(const std::string &name, const WifiRequestMsgInfo &msg) -{ - WIFI_LOGD("WifiManager::PushMsg name: %{public}s", name.c_str()); - BaseService *p = WifiServiceManager::GetInstance().GetServiceInst(name); - if (p == nullptr) { - WIFI_LOGE("Get Service %{public}s failed!", name.c_str()); - return -1; - } - p->PushMsg(const_cast(&msg)); - return 0; -} - -WifiMessageQueue *WifiManager::GetMessageQueue() +void WifiManager::PushServiceCloseMsg(WifiCloseServiceCode code) { - return mMqUp.get(); -} - -int WifiManager::AddDeviceConfig(const WifiDeviceConfig &config, int &networkId) -{ - WIFI_LOGI("Enter WifiManager::AddDeviceConfig"); - WifiDeviceConfig tempDeviceConfig; - if (WifiSettings::GetInstance().GetDeviceConfig(config.ssid, DEVICE_CONFIG_INDEX_SSID, tempDeviceConfig) == 0) { - networkId = tempDeviceConfig.networkId; - return 0; - } else { - WIFI_LOGD("Add a new device config, request wpa to create network id"); - if (WifiStaHalInterface::GetInstance().GetNextNetworkId(networkId) != WIFI_IDL_OPT_OK) { - WIFI_LOGE("Failed to GetNextNetworkId!"); - return -1; - } - tempDeviceConfig = config; - tempDeviceConfig.networkId = networkId; - } - - WifiSettings::GetInstance().AddDeviceConfig(tempDeviceConfig); - WifiSettings::GetInstance().SyncDeviceConfig(); - WifiIdlDeviceConfig idlConfig; - idlConfig.networkId = networkId; - idlConfig.ssid = config.ssid; - idlConfig.bssid = config.bssid; - idlConfig.psk = config.preSharedKey; - idlConfig.keyMgmt = config.keyMgmt; - idlConfig.priority = config.priority; - idlConfig.scanSsid = config.hiddenSSID ? 1 : 0; - idlConfig.eap = config.wifiEapConfig.eap; - idlConfig.identity = config.wifiEapConfig.identity; - idlConfig.password = config.wifiEapConfig.password; - idlConfig.wepKeyIdx = config.wepTxKeyIndex; - for (int i = 0; i < MAX_WEPKEYS_SIZE; i++) { - idlConfig.wepKeys[i] = config.wepKeys[i]; - } - - if (WifiStaHalInterface::GetInstance().SetDeviceConfig(networkId, idlConfig) != WIFI_IDL_OPT_OK) { - WIFI_LOGE("Failed to SetDeviceConfig"); - } - return 0; + std::unique_lock lock(mMutex); + mEventQue.push_back(code); + mCondition.notify_one(); + return; } void WifiManager::AddSupportedFeatures(WifiFeatures feature) @@ -187,219 +131,248 @@ int WifiManager::GetSupportedFeatures(long &features) InitStatus WifiManager::GetInitStatus() { - return mInitStatus_; + return mInitStatus; } -void *WifiManager::DealServiceUpMsg(void *p) +void WifiManager::CloseStaService(void) { - WifiManager *pInstance = (WifiManager *)p; - while (pInstance->mRunFlag) { - /* read and deal response msg */ - WifiResponseMsgInfo msg; - if (pInstance->mMqUp->Pop(msg) < 0) { - continue; - } - /* deal msg begin */ - WIFI_LOGI("receive msgcode %{public}d", msg.msgCode); - if (msg.msgCode == WifiInternalMsgCode::MAIN_EXIT_CODE) { - WIFI_LOGI("Receive thread exit msg!"); - return nullptr; - } else if (msg.msgCode > WifiInternalMsgCode::STA_START_MSG_CODE && - msg.msgCode < WifiInternalMsgCode::STA_END_MSG_CODE) { - DealStaUpMsg(pInstance, msg); - } else if (msg.msgCode > WifiInternalMsgCode::AP_START_MSG_CODE && - msg.msgCode < WifiInternalMsgCode::AP_END_MSG_CODE) { - DealApUpMsg(msg); - } else if (msg.msgCode > WifiInternalMsgCode::SCAN_START_MSG_CODE && - msg.msgCode < WifiInternalMsgCode::SCAN_END_MSG_CODE) { - DealScanUpMsg(msg); - } else { - WIFI_LOGI("not deal this msgcode %{public}d, ignore it!", msg.msgCode); - } - } - return nullptr; + WIFI_LOGD("close sta service"); + WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_STA); + WifiConfigCenter::GetInstance().SetWifiMidState(WifiOprMidState::CLOSED); + WifiConfigCenter::GetInstance().SetWifiStaCloseTime(); + return; } -void WifiManager::DealStaUpMsg(WifiManager *pInstance, const WifiResponseMsgInfo &msg) +void WifiManager::CloseApService(void) { - switch (msg.msgCode) { - case WifiInternalMsgCode::STA_OPEN_RES: { - DealStaOpenRes(pInstance, msg); - break; - } - case WifiInternalMsgCode::STA_CLOSE_RES: { - DealStaCloseRes(msg); - break; - } - case WifiInternalMsgCode::STA_CONNECT_RES: - case WifiInternalMsgCode::STA_DISCONNECT_RES: { - DealStaConnChanged(msg); - break; - } - case WifiInternalMsgCode::STA_START_WPS_RES: - case WifiInternalMsgCode::STA_CANCEL_WPS_RES: { - DealWpsChanged(msg); - break; - } - default: { - WIFI_LOGI("not deal this msgcode %{public}d, ignore it!", msg.msgCode); - break; - } - } + WIFI_LOGD("close ap service"); + WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_AP); + WifiConfigCenter::GetInstance().SetApMidState(WifiOprMidState::CLOSED); + WifiSettings::GetInstance().SetHotspotState(static_cast(ApState::AP_STATE_CLOSED)); + WifiEventCallbackMsg cbMsg; + cbMsg.msgCode = WIFI_CBK_MSG_HOTSPOT_STATE_CHANGE; + cbMsg.msgData = static_cast(ApState::AP_STATE_CLOSED); + WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); return; } -void WifiManager::DealApUpMsg(const WifiResponseMsgInfo &msg) +void WifiManager::CloseScanService(void) { - switch (msg.msgCode) { - case WifiInternalMsgCode::AP_OPEN_RES: { - DealApOpenRes(); - break; - } - case WifiInternalMsgCode::AP_CLOSE_RES: { - DealApCloseRes(); - break; - } - case WifiInternalMsgCode::AP_JOIN_RES: - case WifiInternalMsgCode::AP_LEAVE_RES: { - DealApConnChanged(msg); - break; - } - default: { - WIFI_LOGI("not deal this msgcode %{public}d, ignore it!", msg.msgCode); - break; - } - } + WIFI_LOGD("close scan service"); + WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_SCAN); + WifiConfigCenter::GetInstance().SetScanMidState(WifiOprMidState::CLOSED); return; } -void WifiManager::DealScanUpMsg(const WifiResponseMsgInfo &msg) +void WifiManager::DealCloseServiceMsg(WifiManager &manager) { - switch (msg.msgCode) { - case WifiInternalMsgCode::SCAN_START_RES: { - WifiConfigCenter::GetInstance().SetScanMidState(WifiOprMidState::OPENING, WifiOprMidState::RUNNING); - break; - } - case WifiInternalMsgCode::SCAN_STOP_RES: { - WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_SCAN); /* uninstalling scan service */ - WifiConfigCenter::GetInstance().SetScanMidState(WifiOprMidState::CLOSED); - break; - } - case WifiInternalMsgCode::SCAN_RES: - case WifiInternalMsgCode::SCAN_PARAM_RES: { - WifiEventCallbackMsg cbMsg; - cbMsg.msgCode = WIFI_CBK_MSG_SCAN_STATE_CHANGE; - cbMsg.msgData = msg.params.result; - WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); - break; - } - case WifiInternalMsgCode::SCAN_RESULT_RES: { - WifiRequestMsgInfo staMsg; - staMsg.msgCode = WifiInternalMsgCode::STA_CONNECT_MANAGE_REQ; - staMsg.params.scanInfos = msg.params.scanInfos; - WifiManager::GetInstance().PushMsg(WIFI_SERVICE_STA, staMsg); - break; + const int waitDealTime = 10 * 1000; /* 10 ms */ + while (true) { + std::unique_lock lock(manager.mMutex); + while (manager.mEventQue.empty()) { + manager.mCondition.wait(lock); } - default: { - WIFI_LOGI("not deal this msgcode %{public}d, ignore it!", msg.msgCode); - break; + WifiCloseServiceCode msg = manager.mEventQue.front(); + manager.mEventQue.pop_front(); + lock.unlock(); + usleep(waitDealTime); + switch (msg) { + case WifiCloseServiceCode::STA_SERVICE_CLOSE: + CloseStaService(); + break; + case WifiCloseServiceCode::SCAN_SERVICE_CLOSE: + CloseScanService(); + break; + case WifiCloseServiceCode::AP_SERVICE_CLOSE: + CloseApService(); + break; + case WifiCloseServiceCode::SERVICE_THREAD_EXIT: + WIFI_LOGD("DealCloseServiceMsg thread exit!"); + return; + default: + WIFI_LOGD("Unknown message code, %{public}d", static_cast(msg)); + break; } } + WIFI_LOGD("WifiManager Thread exit"); + return; +} + +void WifiManager::InitStaCallback(void) +{ + mStaCallback.OnStaOpenRes = DealStaOpenRes; + mStaCallback.OnStaCloseRes = DealStaCloseRes; + mStaCallback.OnStaConnChanged = DealStaConnChanged; + mStaCallback.OnWpsChanged = DealWpsChanged; + mStaCallback.OnStaStreamChanged = DealStreamChanged; + mStaCallback.OnStaRssiLevelChanged = DealRssiChanged; return; } -void WifiManager::UploadOpenWifiFailedEvent() +StaServiceCallback WifiManager::GetStaCallback() +{ + return mStaCallback; +} + +void WifiManager::DealStaOpenRes(OperateResState state) { - WIFI_LOGD("DealStaOpenRes:upload wifi open failed event!"); WifiEventCallbackMsg cbMsg; cbMsg.msgCode = WIFI_CBK_MSG_STATE_CHANGE; - cbMsg.msgData = static_cast(WifiState::UNKNOWN); - WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + if (state == OperateResState::OPEN_WIFI_FAILED) { + WIFI_LOGD("DealStaOpenRes:upload wifi open failed event!"); + cbMsg.msgData = static_cast(WifiState::UNKNOWN); + WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + } else if (state == OperateResState::OPEN_WIFI_OPENING) { + cbMsg.msgData = static_cast(WifiState::ENABLING); + WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + } else if (state == OperateResState::OPEN_WIFI_DISABLED) { + WIFI_LOGD("DealStaOpenRes:wifi open failed,close wifi sta service!"); + DealStaCloseRes(state); + } else { + WIFI_LOGD("DealStaOpenRes:wifi open successfully!"); + WifiConfigCenter::GetInstance().SetWifiMidState(WifiOprMidState::OPENING, WifiOprMidState::RUNNING); + WifiConfigCenter::GetInstance().SetStaLastRunState(true); + if (WifiConfigCenter::GetInstance().GetAirplaneModeState() == 1) { + WifiConfigCenter::GetInstance().SetWifiStateWhenAirplaneMode(true); + } + + cbMsg.msgData = static_cast(WifiState::ENABLED); + WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + + CheckAndStartScanService(); + } return; } -void WifiManager::UploadOpenWifiSuccessfulEvent() +void WifiManager::DealStaCloseRes(OperateResState state) { - WIFI_LOGD("DealStaOpenRes:wifi open successfully!"); - WifiConfigCenter::GetInstance().SetWifiMidState(WifiOprMidState::OPENING, WifiOprMidState::RUNNING); - WifiConfigCenter::GetInstance().SetStaLastRunState(true); - WifiEventCallbackMsg cbMsg; cbMsg.msgCode = WIFI_CBK_MSG_STATE_CHANGE; - cbMsg.msgData = static_cast(WifiState::ENABLED); + if (state == OperateResState::CLOSE_WIFI_CLOSING) { + cbMsg.msgData = static_cast(WifiState::DISABLING); + WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + return; + } + if (state == OperateResState::CLOSE_WIFI_FAILED) { + WIFI_LOGD("DealStaCloseRes:upload wifi close failed event!"); + cbMsg.msgData = static_cast(WifiState::UNKNOWN); + WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + } + + if (WifiConfigCenter::GetInstance().GetAirplaneModeState() == 1) { + WifiConfigCenter::GetInstance().SetWifiStateWhenAirplaneMode(false); + } + + cbMsg.msgData = static_cast(WifiState::DISABLED); WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + CheckAndStopScanService(); + WifiManager::GetInstance().PushServiceCloseMsg(WifiCloseServiceCode::STA_SERVICE_CLOSE); return; } -void WifiManager::DealStaOpenRes(WifiManager *pInstance, const WifiResponseMsgInfo &msg) +void WifiManager::DealStaConnChanged(OperateResState state, const WifiLinkedInfo &info) { - if (msg.params.result == (int)OperateResState::OPEN_WIFI_FAILED) { - UploadOpenWifiFailedEvent(); - } else if (msg.params.result == (int)OperateResState::OPEN_WIFI_DISABLED) { - WIFI_LOGD("DealStaOpenRes:wifi open failed,close wifi sta service!"); - DealStaCloseRes(msg); - } else { - UploadOpenWifiSuccessfulEvent(); - WifiOprMidState scanState = WifiConfigCenter::GetInstance().GetScanMidState(); - if (scanState != WifiOprMidState::CLOSED) { - return; - } + WifiEventCallbackMsg cbMsg; + cbMsg.msgCode = WIFI_CBK_MSG_CONNECTION_CHANGE; + cbMsg.msgData = static_cast(ConvertConnStateInternal(state)); + cbMsg.linkInfo = info; + WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); - bool bflag = false; - do { - if (!WifiConfigCenter::GetInstance().SetScanMidState(scanState, WifiOprMidState::OPENING)) { - WIFI_LOGD("set scan mid state opening failed! may be other activity has been operated"); - bflag = true; - break; - } - if (WifiServiceManager::GetInstance().CheckAndEnforceService(WIFI_SERVICE_SCAN) < 0) { - WIFI_LOGE("Load %{public}s service failed!", WIFI_SERVICE_SCAN); - break; - } - WifiMessageQueue *mqUp = pInstance->mMqUp.get(); - auto srvInst = WifiServiceManager::GetInstance().GetServiceInst(WIFI_SERVICE_SCAN); - if (srvInst == nullptr) { - WIFI_LOGE("Failed to get service instance!"); - break; + if (state == OperateResState::CONNECT_CONNECTING || state == OperateResState::CONNECT_AP_CONNECTED || + state == OperateResState::DISCONNECT_DISCONNECTING || state == OperateResState::DISCONNECT_DISCONNECTED || + state == OperateResState::CONNECT_OBTAINING_IP || state == OperateResState::CONNECT_ASSOCIATING || + state == OperateResState::CONNECT_ASSOCIATED) { + if (WifiConfigCenter::GetInstance().GetScanMidState() == WifiOprMidState::RUNNING) { + IScanService *pService = WifiServiceManager::GetInstance().GetScanServiceInst(); + if (pService != nullptr) { + pService->OnClientModeStatusChanged(static_cast(state)); } - int ret = srvInst->Init(mqUp); - if (ret < 0) { - WIFI_LOGE("Init %{public}s service failed!", WIFI_SERVICE_SCAN); - WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_SCAN); - break; - } - bflag = true; - } while (0); - if (!bflag) { - WifiConfigCenter::GetInstance().SetScanMidState(WifiOprMidState::OPENING, WifiOprMidState::CLOSED); } } - return; } -void WifiManager::DealStaCloseRes(const WifiResponseMsgInfo &msg) +void WifiManager::DealWpsChanged(WpsStartState state, const int pinCode) { - if (msg.params.result == (int)OperateResState::CLOSE_WIFI_FAILED) { - WIFI_LOGD("DealStaCloseRes:upload wifi close failed event!"); - WifiEventCallbackMsg cbMsg; - cbMsg.msgCode = WIFI_CBK_MSG_STATE_CHANGE; - cbMsg.msgData = static_cast(WifiState::UNKNOWN); - WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + WifiEventCallbackMsg cbMsg; + cbMsg.msgCode = WIFI_CBK_MSG_WPS_STATE_CHANGE; + cbMsg.msgData = static_cast(state); + cbMsg.pinCode = std::to_string(pinCode); + int len = cbMsg.pinCode.length(); + if (len < 8) { /* Fill in 8 digits. */ + cbMsg.pinCode = std::string(8 - len, '0') + cbMsg.pinCode; } + WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + return; +} - WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_STA); /* uninstalling sta service */ - WifiConfigCenter::GetInstance().SetWifiMidState(WifiOprMidState::CLOSED); - WifiConfigCenter::GetInstance().SetWifiStaCloseTime(); +void WifiManager::DealStreamChanged(StreamDirection direction) +{ + WifiEventCallbackMsg cbMsg; + cbMsg.msgCode = WIFI_CBK_MSG_STREAM_DIRECTION; + cbMsg.msgData = static_cast(direction); + WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + return; +} - /* Add callback message */ +void WifiManager::DealRssiChanged(int rssi) +{ WifiEventCallbackMsg cbMsg; - cbMsg.msgCode = WIFI_CBK_MSG_STATE_CHANGE; - cbMsg.msgData = static_cast(WifiState::DISABLED); + cbMsg.msgCode = WIFI_CBK_MSG_RSSI_CHANGE; + cbMsg.msgData = rssi; WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + return; +} +void WifiManager::CheckAndStartScanService(void) +{ + WifiOprMidState scanState = WifiConfigCenter::GetInstance().GetScanMidState(); + if (scanState != WifiOprMidState::CLOSED) { + /* If the scanning function is enabled when the STA is not enabled, you need to start the scheduled + scanning function immediately when the STA is enabled. */ + IScanService *pService = WifiServiceManager::GetInstance().GetScanServiceInst(); + if (pService != nullptr) { + pService->OnClientModeStatusChanged(static_cast(OperateResState::DISCONNECT_DISCONNECTED)); + } + return; + } + if (!WifiConfigCenter::GetInstance().SetScanMidState(scanState, WifiOprMidState::OPENING)) { + WIFI_LOGD("Failed to set scan mid state opening! may be other activity has been operated"); + return; + } + ErrCode errCode = WIFI_OPT_FAILED; + do { + if (WifiServiceManager::GetInstance().CheckAndEnforceService(WIFI_SERVICE_SCAN) < 0) { + WIFI_LOGE("Load %{public}s service failed!", WIFI_SERVICE_SCAN); + break; + } + IScanService *pService = WifiServiceManager::GetInstance().GetScanServiceInst(); + if (pService == nullptr) { + WIFI_LOGE("Create %{public}s service failed!", WIFI_SERVICE_SCAN); + break; + } + errCode = pService->RegisterScanCallbacks(WifiManager::GetInstance().GetScanCallback()); + if (errCode != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Register scan service callback failed!"); + break; + } + errCode = pService->Init(); + if (errCode != WIFI_OPT_SUCCESS) { + WIFI_LOGE("init scan service failed, ret %{public}d!", static_cast(errCode)); + break; + } + } while (0); + if (errCode != WIFI_OPT_SUCCESS) { + WifiConfigCenter::GetInstance().SetScanMidState(WifiOprMidState::OPENING, WifiOprMidState::CLOSED); + WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_SCAN); + } + return; +} + +void WifiManager::CheckAndStopScanService(void) +{ /** * Check unload SCAN service * When anytime scanning is enabled and the control policy allows, airplane @@ -419,85 +392,106 @@ void WifiManager::DealStaCloseRes(const WifiResponseMsgInfo &msg) } /* After check condition over, begin unload SCAN service */ if (WifiConfigCenter::GetInstance().SetScanMidState(scanState, WifiOprMidState::CLOSING)) { - BaseService *pService = WifiServiceManager::GetInstance().GetServiceInst(WIFI_SERVICE_SCAN); - if (pService != nullptr) { - pService->UnInit(); - } else { - WifiConfigCenter::GetInstance().SetScanMidState(WifiOprMidState::CLOSED); + IScanService *pService = WifiServiceManager::GetInstance().GetScanServiceInst(); + if (pService == nullptr) { + WifiManager::GetInstance().PushServiceCloseMsg(WifiCloseServiceCode::SCAN_SERVICE_CLOSE); + return; + } + ErrCode ret = pService->UnInit(); + if (ret != WIFI_OPT_SUCCESS) { + WifiConfigCenter::GetInstance().SetScanMidState(WifiOprMidState::CLOSING, scanState); } } +} - return; +void WifiManager::InitScanCallback(void) +{ + mScanCallback.OnScanStartEvent = DealScanOpenRes; + mScanCallback.OnScanStopEvent = DealScanCloseRes; + mScanCallback.OnScanFinishEvent = DealScanFinished; + mScanCallback.OnScanInfoEvent = DealScanInfoNotify; +} + +IScanSerivceCallbacks WifiManager::GetScanCallback() +{ + return mScanCallback; +} + +void WifiManager::DealScanOpenRes(void) +{ + WifiConfigCenter::GetInstance().SetScanMidState(WifiOprMidState::OPENING, WifiOprMidState::RUNNING); } -void WifiManager::DealStaConnChanged(const WifiResponseMsgInfo &msg) +void WifiManager::DealScanCloseRes(void) +{ + WifiManager::GetInstance().PushServiceCloseMsg(WifiCloseServiceCode::SCAN_SERVICE_CLOSE); +} + +void WifiManager::DealScanFinished(int state) { - /* Send Event Broadcast */ WifiEventCallbackMsg cbMsg; - cbMsg.msgCode = WIFI_CBK_MSG_CONNECTION_CHANGE; - cbMsg.msgData = static_cast(ConvertConnStateInternal(OperateResState(msg.params.result))); - cbMsg.linkInfo = msg.params.linkedInfo; + cbMsg.msgCode = WIFI_CBK_MSG_SCAN_STATE_CHANGE; + cbMsg.msgData = state; WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + WifiCommonEventHelper::PublishScanFinishedEvent(state,"OnScanFinished"); +} - /* Pushing the connection status to the scanning service */ - if (msg.params.result == static_cast(OperateResState::CONNECT_CONNECTING) || - msg.params.result == static_cast(OperateResState::CONNECT_AP_CONNECTED) || - msg.params.result == static_cast(OperateResState::DISCONNECT_DISCONNECTING) || - msg.params.result == static_cast(OperateResState::DISCONNECT_DISCONNECTED)) { - WifiRequestMsgInfo scanMsg; - scanMsg.msgCode = WifiInternalMsgCode::SCAN_NOTIFY_STA_CONN_REQ; - scanMsg.params.argInt = msg.params.result; - WifiManager::GetInstance().PushMsg(WIFI_SERVICE_SCAN, scanMsg); +void WifiManager::DealScanInfoNotify(std::vector &results) +{ + if (WifiConfigCenter::GetInstance().GetWifiMidState() == WifiOprMidState::RUNNING) { + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService != nullptr) { + pService->ConnectivityManager(results); + } } - return; } -void WifiManager::DealApOpenRes() +void WifiManager::InitApCallback(void) { - WifiConfigCenter::GetInstance().SetApMidState(WifiOprMidState::OPENING, WifiOprMidState::RUNNING); - WifiEventCallbackMsg cbMsg; - cbMsg.msgCode = WIFI_CBK_MSG_HOTSPOT_STATE_CHANGE; - cbMsg.msgData = static_cast(ApState::AP_STATE_STARTED); - WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + mApCallback.OnApStateChangedEvent = DealApStateChanged; + mApCallback.OnHotspotStaJoinEvent = DealApGetStaJoin; + mApCallback.OnHotspotStaLeaveEvent = DealApGetStaLeave; return; } -void WifiManager::DealApCloseRes() +IApServiceCallbacks WifiManager::GetApCallback() +{ + return mApCallback; +} + +void WifiManager::DealApStateChanged(ApState state) { - WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_AP); - WifiConfigCenter::GetInstance().SetApMidState(WifiOprMidState::CLOSED); WifiEventCallbackMsg cbMsg; cbMsg.msgCode = WIFI_CBK_MSG_HOTSPOT_STATE_CHANGE; - cbMsg.msgData = static_cast(ApState::AP_STATE_CLOSED); + cbMsg.msgData = static_cast(state); WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + if (state == ApState::AP_STATE_IDLE) { + WifiManager::GetInstance().PushServiceCloseMsg(WifiCloseServiceCode::AP_SERVICE_CLOSE); + } + if (state == ApState::AP_STATE_STARTED) { + WifiConfigCenter::GetInstance().SetApMidState(WifiOprMidState::OPENING, WifiOprMidState::RUNNING); + } + WifiCommonEventHelper::PublishHotspotStateChangedEvent((int)state, "OnHotspotStateChanged"); return; } -void WifiManager::DealApConnChanged(const WifiResponseMsgInfo &msg) +void WifiManager::DealApGetStaJoin(const StationInfo &info) { WifiEventCallbackMsg cbMsg; cbMsg.msgCode = WIFI_CBK_MSG_HOTSPOT_STATE_JOIN; - if (msg.msgCode == WifiInternalMsgCode::AP_LEAVE_RES) { - cbMsg.msgCode = WIFI_CBK_MSG_HOTSPOT_STATE_LEAVE; - } - cbMsg.staInfo = msg.params.staInfo; + cbMsg.staInfo = info; WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + WifiCommonEventHelper::PublishApStaJoinEvent(0, "ApStaJoined"); return; } -void WifiManager::DealWpsChanged(const WifiResponseMsgInfo &msg) +void WifiManager::DealApGetStaLeave(const StationInfo &info) { WifiEventCallbackMsg cbMsg; - cbMsg.msgCode = WIFI_CBK_MSG_WPS_STATE_CHANGE; - cbMsg.msgData = msg.params.result; - if (msg.params.argInt >= 0) { - cbMsg.pinCode = std::to_string(msg.params.argInt); - int len = cbMsg.pinCode.length(); - if (len < 8) { /* Fill in 8 digits. */ - cbMsg.pinCode = std::string(8 - len, '0') + cbMsg.pinCode; - } - } + cbMsg.msgCode = WIFI_CBK_MSG_HOTSPOT_STATE_LEAVE; + cbMsg.staInfo = info; WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + WifiCommonEventHelper::PublishApStaLeaveEvent(0, "ApStaLeaved"); return; } } // namespace Wifi diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.h index e338f6dcc..51e36ce9f 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.h @@ -16,19 +16,18 @@ #ifndef OHOS_WIFIMANAGER_H #define OHOS_WIFIMANAGER_H -#include -#include -#include -#include -#include -#include #include -#include #include -#include "wifi_internal_msg.h" -#include "wifi_message_queue.h" +#include +#include +#include +#include + #include "define.h" -#include "wifi_msg.h" +#include "wifi_internal_msg.h" +#include "sta_service_callback.h" +#include "iscan_service_callbacks.h" +#include "i_ap_service_callbacks.h" namespace OHOS { namespace Wifi { @@ -43,12 +42,19 @@ enum InitStatus { TASK_THREAD_INIT_FAILED = 5, }; +enum class WifiCloseServiceCode { + STA_SERVICE_CLOSE, + SCAN_SERVICE_CLOSE, + AP_SERVICE_CLOSE, + SERVICE_THREAD_EXIT, +}; + class WifiManager { public: WifiManager(); ~WifiManager(); /** - * @Description Initialize submodules and message processing threads + * @Description Initialize submodules and message processing threads. * 1. Initializing the Configuration Center * 2. Initialization permission management * 3. Initializing Service Management @@ -56,23 +62,12 @@ public: * 5. Initializing a Message Queue * 6. Initialize the message processing thread * - * @return int - Init result, when 0 means success, other means some fails happened + * @return int - Init result, when 0 means success, other means some fails happened. */ int Init(); /** - * @Description Send a message to a feature service - * 1. Search the service management module for the feature service based on the name - * 2. Get the object and then invoke the PushMsg method of the object - * - * @param name - Feature Service Name - * @param msg - Pushes message - * @return int - 0 success; -1 feature service not exist - */ - int PushMsg(const std::string &name, const WifiRequestMsgInfo &msg); - - /** - * @Description When exiting, the system exits each submodule and then exits the message processing thread + * @Description When exiting, the system exits each submodule and then exits the message processing thread. * 1. Uninstall each feature service * 2. Exit the event broadcast module * 3. Wait for the message processing thread to exit @@ -81,20 +76,25 @@ public: void Exit(); /** - * @Description Get message queue object + * @Description Get the sta callback object. + * + * @return StaServiceCallback - return mStaCallback + */ + StaServiceCallback GetStaCallback(void); + + /** + * @Description Get the scan callback object. * - * @return WifiMessageQueue* - message queue reference + * @return IScanSerivceCallbacks - return mScanCallback */ - WifiMessageQueue *GetMessageQueue(); + IScanSerivceCallbacks GetScanCallback(void); /** - * @Description Add a new device config + * @Description Get the ap callback object. * - * @param config device config - * @param networkId return device's network id - * @return int - operate result, 0 success -1 failed + * @return IApServiceCallbacks - return mApCallback */ - int AddDeviceConfig(const WifiDeviceConfig &config, int &networkId); + IApServiceCallbacks GetApCallback(void); /** * @Description Get supported features @@ -111,37 +111,43 @@ public: */ void AddSupportedFeatures(WifiFeatures feature); - /** - * @Description Deal message from feature service, Obtain the message and process the message - * based on the message code - * - * @param p - WifiManager object - * @return void* - nullptr, not care this return value - */ - static void *DealServiceUpMsg(void *p); static WifiManager &GetInstance(); private: - static void DealStaUpMsg(WifiManager *pInstance, const WifiResponseMsgInfo &msg); - static void DealApUpMsg(const WifiResponseMsgInfo &msg); - static void DealScanUpMsg(const WifiResponseMsgInfo &msg); - static void UploadOpenWifiFailedEvent(); - static void UploadOpenWifiSuccessfulEvent(); - static void DealStaOpenRes(WifiManager *pInstance, const WifiResponseMsgInfo &msg); - static void DealStaCloseRes(const WifiResponseMsgInfo &msg); - static void DealStaConnChanged(const WifiResponseMsgInfo &msg); - static void DealApOpenRes(); - static void DealApCloseRes(); - static void DealApConnChanged(const WifiResponseMsgInfo &msg); - static void DealWpsChanged(const WifiResponseMsgInfo &msg); - + void PushServiceCloseMsg(WifiCloseServiceCode code); + void InitStaCallback(void); + void InitScanCallback(void); + void InitApCallback(void); InitStatus GetInitStatus(); -private: - pthread_t mTid; - std::atomic mRunFlag; - std::unique_ptr> mMqUp; + static void DealCloseServiceMsg(WifiManager &manager); + static void CloseStaService(void); + static void CloseApService(void); + static void CloseScanService(void); + static void DealStaOpenRes(OperateResState state); + static void DealStaCloseRes(OperateResState state); + static void DealStaConnChanged(OperateResState state, const WifiLinkedInfo &info); + static void DealWpsChanged(WpsStartState state, const int pinCode); + static void DealStreamChanged(StreamDirection direction); + static void DealRssiChanged(int rssi); + static void CheckAndStartScanService(void); + static void CheckAndStopScanService(void); + static void DealScanOpenRes(void); + static void DealScanCloseRes(void); + static void DealScanFinished(int state); + static void DealScanInfoNotify(std::vector &results); + static void DealApStateChanged(ApState bState); + static void DealApGetStaJoin(const StationInfo &info); + static void DealApGetStaLeave(const StationInfo &info); - InitStatus mInitStatus_; +private: + std::thread mCloseServiceThread; + std::mutex mMutex; + std::condition_variable mCondition; + std::deque mEventQue; + StaServiceCallback mStaCallback; + IScanSerivceCallbacks mScanCallback; + IApServiceCallbacks mApCallback; + InitStatus mInitStatus; long mSupportedFeatures; }; } // namespace Wifi diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/iscan_service.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/iscan_service.h new file mode 100644 index 000000000..4be934564 --- /dev/null +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/iscan_service.h @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ +#ifndef OHOS_ISCAN_SERVICE_H +#define OHOS_ISCAN_SERVICE_H + +#include "wifi_errcode.h" +#include "wifi_msg.h" +#include "iscan_service_callbacks.h" + +namespace OHOS { +namespace Wifi { +class IScanService { +public: + virtual ~IScanService() = default; + /** + * @Description Scan service initialization function. + * + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED + */ + virtual ErrCode Init() = 0; + /** + * @Description Stopping the Scan Service. + * + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED + */ + virtual ErrCode UnInit() = 0; + /** + * @Description Processes interface service scan request. + * + * @param externFlag it is from an external scan[in] + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED + */ + virtual ErrCode Scan(bool externFlag) = 0; + /** + * @Description Processes interface service scan with param request. + * + * @param wifiScanParams Parameters in the scan request[in] + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED + */ + virtual ErrCode ScanWithParam(const WifiScanParams &wifiScanParams) = 0; + /** + * @Description Processes interface service screen change request. + * + * @param screenState screen state[in] + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED + */ + virtual ErrCode OnScreenStateChanged(int screenState) = 0; + /** + * @Description Processes interface service sta status change request. + * + * @param staStatus sta status[in] + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED + */ + virtual ErrCode OnClientModeStatusChanged(int staStatus) = 0; + /** + * @Description Processes interface service appMode change request. + * + * @param appMode operate app mode[in] + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED + */ + virtual ErrCode OnAppRunningModeChanged(int appMode) = 0; + /** + * @Description Processes interface service custom scene change request. + * + * @param customScene custom scene[in] + * @param customSceneStatus Enter or exit the customized scenario[in] + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED + */ + virtual ErrCode OnCustomControlStateChanged(int customScene, int customSceneStatus) = 0; + /** + * @Description Processes interface service scan control info change request. + * + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED + */ + virtual ErrCode OnControlStrategyChanged() = 0; + /** + * @Description Registers the callback function of the scanning module to the interface service. + * + * @param scanSerivceCallbacks callback function + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED + */ + virtual ErrCode RegisterScanCallbacks(const IScanSerivceCallbacks &scanSerivceCallbacks) = 0; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/iscan_service_callbacks.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/iscan_service_callbacks.h new file mode 100644 index 000000000..efe50bca5 --- /dev/null +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/iscan_service_callbacks.h @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ +#ifndef OHOS_ISCAN_SERVICE_CALLBACK_H +#define OHOS_ISCAN_SERVICE_CALLBACK_H + +#include +#include "wifi_msg.h" +#include "wifi_internal_msg.h" + +namespace OHOS { +namespace Wifi { +class IScanSerivceCallbacks { +public: + std::function OnScanStartEvent; + std::function OnScanStopEvent; + std::function OnScanFinishEvent; + std::function &)> OnScanInfoEvent; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_common.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_common.h index 6cff0f9e9..0d4bbff2a 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_common.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_common.h @@ -19,6 +19,7 @@ #include #include #include "wifi_scan_msg.h" +#include "wifi_internal_msg.h" namespace OHOS { namespace Wifi { @@ -170,31 +171,6 @@ enum ScanStatus { SCAN_STATUS_INVALID /* Invalid value */ }; -/* Scan Info */ -struct InterScanInfo { - std::string bssid; /* Access point address */ - std::string ssid; /* Network Name */ - std::string capabilities; /* - * Network performance, including authentication, - * key management, and encryption mechanisms - * supported by the access point - */ - int frequency; /* Access point frequency */ - int band; /* ap band, 1: 2.4G, 2: 5G */ - int rssi; /* signal strength */ - WifiSecurity securityType; - int64_t timestamp; /* Timestamp of scanning */ - - InterScanInfo() - { - frequency = 0; - band = 0; - rssi = 0; - securityType = WifiSecurity::INVALID; - timestamp = 0; - } -}; - struct ScanStatusReport { ScanStatus status; /* status code */ std::vector requestIndexList; /* diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.cpp index a5aa56a64..da8b40f09 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.cpp @@ -31,206 +31,117 @@ ScanInterface::~ScanInterface() } } -int ScanInterface::Init(WifiMessageQueue *mqUp) +extern "C" IScanService *Create(void) { - WIFI_LOGI("Enter ScanInterface::Init."); - - if (mqUp == nullptr) { - WIFI_LOGE("mqUp is null."); - return -1; - } - - pScanService = new (std::nothrow) ScanService(); - if (pScanService == nullptr) { - WIFI_LOGE("New ScanService failed."); - return -1; - } - - if (!(pScanService->InitScanService(mqUp))) { - WIFI_LOGE("InitScanService failed."); - delete pScanService; - pScanService = nullptr; - return -1; - } - - return 0; + return new ScanInterface(); } - -int ScanInterface::UnInit() +extern "C" void Destroy(ScanInterface *scanInterface) { - WIFI_LOGI("Enter ScanInterface::UnInit."); - if (pScanService != nullptr) { - pScanService->UnInitScanService(); - } - return 0; + delete scanInterface; } -int ScanInterface::PushMsg(WifiRequestMsgInfo *requestMsg) +ErrCode ScanInterface::Init() { - WIFI_LOGI("Enter ScanInterface::PushMsg"); + WIFI_LOGI("Enter ScanInterface::Init.\n"); - if (requestMsg == nullptr) { - WIFI_LOGE("requestMsg is null."); - return -1; + pScanService = new (std::nothrow)ScanService(); + if (pScanService == nullptr) { + WIFI_LOGE("New ScanService failed.\n"); + return WIFI_OPT_INVALID_PARAM; } - HandleRequestMsg(requestMsg); - return 0; -} - -void ScanInterface::HandleRequestMsg(const WifiRequestMsgInfo *requestMsg) -{ - WIFI_LOGI("Enter ScanInterface::HandleRequestMsg"); - if (requestMsg == nullptr) { - WIFI_LOGE("requestMsg is null."); - return; + if (!(pScanService->InitScanService(mScanSerivceCallbacks))) { + WIFI_LOGE("InitScanService failed.\n"); + delete pScanService; + pScanService = nullptr; + return WIFI_OPT_INVALID_PARAM; } - switch (requestMsg->msgCode) { - case SCAN_REQ: - DealScanMsg(); - break; - - case SCAN_PARAM_REQ: - DealScanParamMsg(requestMsg); - break; - - case SCAN_RECONNECT_REQ: - DealScanReconnectMsg(); - break; - - case SCREEN_CHANGE_NOTICE: - DealScreenChangeMsg(requestMsg); - break; - - case SCAN_NOTIFY_STA_CONN_REQ: - DealStaNotifyScanMsg(requestMsg); - break; - - case FRONT_BACK_STATUS_CHANGE_NOTICE: - DealAppModeChangeMsg(requestMsg); - break; - - case CUSTOM_STATUS_CHANGE_NOTICE: - DealCustomSceneChangeMsg(requestMsg); - break; - - case SCAN_CONTROL_REQ: - pScanService->ClearScanControlValue(); - pScanService->SystemScanProcess(true); - break; - - default: - WIFI_LOGE("requestMsg->msgCode is error."); - break; - } + return WIFI_OPT_SUCCESS; } -void ScanInterface::DealScanMsg() +ErrCode ScanInterface::UnInit() { - WIFI_LOGI("Enter ScanInterface::DealScanMsg"); + WIFI_LOGI("Enter ScanInterface::UnInit.\n"); - if (!(pScanService->Scan(true))) { - WIFI_LOGE("pScanService->Scan failed."); - } - return; + pScanService->UnInitScanService(); + + return WIFI_OPT_SUCCESS; } -void ScanInterface::DealScanParamMsg(const WifiRequestMsgInfo *requestMsg) +ErrCode ScanInterface::Scan(bool externFlag) { - WIFI_LOGI("Enter ScanInterface::DealScanParamMsg"); - if (requestMsg == nullptr) { - WIFI_LOGE("requestMsg is null."); - return; - } + WIFI_LOGI("Enter ScanInterface::Scan\n"); - if (!(pScanService->Scan(requestMsg->params.wifiScanParams))) { - WIFI_LOGE("pScanService->Scan failed."); - } - return; + return pScanService->Scan(externFlag); } -void ScanInterface::DealScanReconnectMsg() +ErrCode ScanInterface::ScanWithParam(const WifiScanParams &wifiScanParams) { - WIFI_LOGI("Enter ScanInterface::DealScanReconnectMsg"); + WIFI_LOGI("Enter ScanInterface::ScanWithParam\n"); - if (!(pScanService->Scan(false))) { - WIFI_LOGE("pScanService->Scan failed."); - } - return; + return pScanService->ScanWithParam(wifiScanParams); } -void ScanInterface::DealScreenChangeMsg(const WifiRequestMsgInfo *requestMsg) +ErrCode ScanInterface::OnScreenStateChanged(int screenState) { - WIFI_LOGI("Enter ScanInterface::DealScreenChangeMsg"); - if (requestMsg == nullptr) { - WIFI_LOGE("requestMsg is invalid."); - return; - } + WIFI_LOGI("Enter ScanInterface::OnScreenStateChanged\n"); - if (requestMsg->params.wifiMockState.type != MODE_STATE_SCREEN) { - WIFI_LOGE("requestMsg->params->wifiMockState is invalid."); - return; + if (screenState != STATE_OPEN && screenState != STATE_CLOSE) { + WIFI_LOGE("screenState param is error"); + return WIFI_OPT_INVALID_PARAM; } bool screenOn = true; - if (requestMsg->params.wifiMockState.state == STATE_CLOSE) { + if (screenState == STATE_CLOSE) { screenOn = false; } pScanService->HandleScreenStatusChanged(screenOn); - return; + return WIFI_OPT_SUCCESS; } -void ScanInterface::DealStaNotifyScanMsg(const WifiRequestMsgInfo *requestMsg) +ErrCode ScanInterface::OnClientModeStatusChanged(int staStatus) { - WIFI_LOGI("Enter ScanInterface::DealStaNotifyScanMsg"); - if (requestMsg == nullptr) { - WIFI_LOGE("requestMsg is null."); - return; - } + WIFI_LOGI("Enter ScanInterface::OnClientModeStatusChanged\n"); - pScanService->HandleStaStatusChanged(requestMsg->params.argInt); + pScanService->HandleStaStatusChanged(staStatus); pScanService->SetStaCurrentTime(); - return; + return WIFI_OPT_SUCCESS; } -void ScanInterface::DealAppModeChangeMsg(const WifiRequestMsgInfo *requestMsg) +ErrCode ScanInterface::OnAppRunningModeChanged(int appMode) { - WIFI_LOGI("Enter ScanInterface::DealAppModeChangeMsg"); - if (requestMsg == nullptr) { - WIFI_LOGE("requestMsg is null."); - return; - } + WIFI_LOGI("Enter ScanInterface::OnAppRunningModeChanged\n"); - if (requestMsg->params.wifiMockState.type != MODE_STATE_APP_RUN) { - WIFI_LOGE("requestMsg->params->wifiMockState is invalid."); - return; - } - pScanService->SetOperateAppMode(requestMsg->params.wifiMockState.state); - return; + pScanService->SetOperateAppMode(appMode); + return WIFI_OPT_SUCCESS; } -void ScanInterface::DealCustomSceneChangeMsg(const WifiRequestMsgInfo *requestMsg) +ErrCode ScanInterface::OnCustomControlStateChanged(int customScene, int customSceneStatus) { - WIFI_LOGI("Enter ScanInterface::DealCustomSceneChangeMsg"); - if (requestMsg == nullptr) { - WIFI_LOGE("requestMsg is null."); - return; - } + WIFI_LOGI("Enter ScanInterface::OnCustomControlStateChanged\n"); - if (requestMsg->params.wifiMockState.type < MODE_STATE_POWER_SAVING) { - WIFI_LOGE("requestMsg->params->wifiMockState is invalid."); - return; + if (customSceneStatus != STATE_OPEN && customSceneStatus != STATE_CLOSE) { + WIFI_LOGE("screenState param is error"); + return WIFI_OPT_INVALID_PARAM; } - time_t now = time(0); - if (requestMsg->params.wifiMockState.state == STATE_OPEN) { - pScanService->SetCustomScene(requestMsg->params.wifiMockState.type, now); - } - if (requestMsg->params.wifiMockState.state == STATE_CLOSE) { - pScanService->SystemScanProcess(true); - } - return; + pScanService->HandleCustomStatusChanged(customScene, customSceneStatus); + return WIFI_OPT_SUCCESS; } -DECLARE_INIT_SERVICE(ScanInterface); +ErrCode ScanInterface::OnControlStrategyChanged() +{ + WIFI_LOGI("Enter ScanInterface::OnControlStrategyChanged\n"); + + pScanService->ClearScanControlValue(); + pScanService->GetScanControlInfo(); + pScanService->SystemScanProcess(true); + return WIFI_OPT_SUCCESS; +} + +ErrCode ScanInterface::RegisterScanCallbacks(const IScanSerivceCallbacks &scanSerivceCallbacks) +{ + mScanSerivceCallbacks = scanSerivceCallbacks; + return WIFI_OPT_SUCCESS; +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.h index 9ebc2e4c5..0f5331dbb 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.h @@ -16,12 +16,12 @@ #ifndef OHOS_WIFI_SCAN_INTERFACE_H #define OHOS_WIFI_SCAN_INTERFACE_H -#include "base_service.h" +#include "iscan_service.h" #include "scan_service.h" namespace OHOS { namespace Wifi { -class ScanInterface : BaseService { +class ScanInterface : public IScanService { public: ScanInterface(); ~ScanInterface(); @@ -29,76 +29,75 @@ public: /** * @Description Scan service initialization function. * - * @param mqUp - message queue,which is used to return results.[in] - * @return success: 0, failed: -1 + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ - int Init(WifiMessageQueue *mqUp); + ErrCode Init(); /** - * @Description Receives the function information of the Scan service and - * distributes and processes the information. - * - * @param requestMsg - request message[in] - * @return success: 0, failed: -1 - */ - int PushMsg(WifiRequestMsgInfo *msg); - /** - * * @Description Stopping the Scan Service - * @return success: 0, failed: -1 + * + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ - int UnInit(); - -private: + ErrCode UnInit(); /** - * @Description Receives the function information of the Scan service and - * distributes and processes the information. + * @Description Processes interface service scan request. * - * @param requestMsg - request message[in] + * @param externFlag it is from an external scan[in] + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ - void HandleRequestMsg(const WifiRequestMsgInfo *requestMsg); + ErrCode Scan(bool externFlag); /** - * @Description Processes interface service SCAN_REQ messages. + * @Description Processes interface service scan with param request. * + * @param wifiScanParams Parameters in the scan request[in] + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ - void DealScanMsg(); + ErrCode ScanWithParam(const WifiScanParams &wifiScanParams); /** - * @Description Processes interface service SCAN_PARAM_REQ messages. + * @Description Processes interface service screen change request. * - * @param requestMsg request message[in] + * @param screenState screen state[in] + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ - void DealScanParamMsg(const WifiRequestMsgInfo *requestMsg); + ErrCode OnScreenStateChanged(int screenState); /** - * @Description Processes interface service SCAN_RECONNECT_REQ messages. + * @Description Processes interface service sta status change request. * + * @param staStatus sta status[in] + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ - void DealScanReconnectMsg(); + ErrCode OnClientModeStatusChanged(int staStatus); /** - * @Description Processes interface service SCREEN_CHANGE_NOTICE messages. + * @Description Processes interface service appMode change request. * - * @param requestMsg request message[in] + * @param appMode operate app mode[in] + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ - void DealScreenChangeMsg(const WifiRequestMsgInfo *requestMsg); + ErrCode OnAppRunningModeChanged(int appMode); /** - * @Description Processes interface service SCAN_NOTIFY_STA_CONN_REQ messages. + * @Description Processes interface service custom scene change request. * - * @param requestMsg request message[in] + * @param customScene custom scene[in] + * @param customSceneStatus Enter or exit the customized scenario[in] + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ - void DealStaNotifyScanMsg(const WifiRequestMsgInfo *requestMsg); + ErrCode OnCustomControlStateChanged(int customScene, int customSceneStatus); /** - * @Description Processes interface service FRONT_BACK_STATUS_CHANGE_NOTICE messages. + * @Description Processes interface service scan control info change request. * - * @param requestMsg request message[in] + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ - void DealAppModeChangeMsg(const WifiRequestMsgInfo *requestMsg); + ErrCode OnControlStrategyChanged(); /** - * @Description Processes interface service CUSTOM_STATUS_CHANGE_NOTICE messages. + * @Description Registers the callback function of the scanning module to the interface service. * - * @param requestMsg request message[in] + * @param scanSerivceCallbacks callback function + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ - void DealCustomSceneChangeMsg(const WifiRequestMsgInfo *requestMsg); + ErrCode RegisterScanCallbacks(const IScanSerivceCallbacks &scanSerivceCallbacks); private: ScanService *pScanService; + IScanSerivceCallbacks mScanSerivceCallbacks; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.cpp index d545524c2..5e1e69638 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.cpp @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include #include "scan_service.h" #include "wifi_logger.h" @@ -24,7 +23,6 @@ namespace Wifi { ScanService::ScanService() : pScanStateMachine(nullptr), pScanMonitor(nullptr), - pMessageQueueUp(nullptr), scanStartedFlag(false), scanConfigStoreIndex(0), pnoScanStartTime(0), @@ -53,15 +51,11 @@ ScanService::~ScanService() } } -bool ScanService::InitScanService(WifiMessageQueue *messageQueueUp) +bool ScanService::InitScanService(const IScanSerivceCallbacks &scanSerivceCallbacks) { WIFI_LOGI("Enter ScanService::InitScanService.\n"); - if (messageQueueUp == nullptr) { - WIFI_LOGE("messageQueueUp is null.\n"); - return false; - } - pMessageQueueUp = messageQueueUp; + mScanSerivceCallbacks = scanSerivceCallbacks; pScanStateMachine = new (std::nothrow) ScanStateMachine(); if (pScanStateMachine == nullptr) { @@ -124,12 +118,12 @@ void ScanService::HandleScanStatusReport(ScanStatusReport &scanStatusReport) scanStartedFlag = true; /* Pno scan maybe has started, stop it first */ pScanStateMachine->SendMessage(CMD_STOP_PNO_SCAN); - NotifyScanServiceStatus(SCAN_START_RES); + mScanSerivceCallbacks.OnScanStartEvent(); SystemScanProcess(true); break; } case SCAN_FINISHED_STATUS: { - NotifyScanServiceStatus(SCAN_STOP_RES); + mScanSerivceCallbacks.OnScanStopEvent(); break; } case COMMON_SCAN_SUCCESS: { @@ -186,41 +180,20 @@ void ScanService::HandleInnerEventReport(ScanInnerEventType innerEvent) } } -void ScanService::NotifyScanServiceStatus(int msgCode) -{ - WIFI_LOGI("Enter ScanService::NotifyScanServiceStatus.\n"); - - WifiResponseMsgInfo notifyScanMsg; - notifyScanMsg.msgCode = msgCode; - pMessageQueueUp->Push(notifyScanMsg); - return; -} - -void ScanService::NotifyScanInfo(int msgCode, int result) -{ - WIFI_LOGI("Enter ScanService::NotifyScanInfo.\n"); - - WifiResponseMsgInfo notifyScanMsg; - notifyScanMsg.msgCode = msgCode; - notifyScanMsg.params.result = result; - pMessageQueueUp->Push(notifyScanMsg); - return; -} - -bool ScanService::Scan(bool externFlag) +ErrCode ScanService::Scan(bool externFlag) { WIFI_LOGI("Enter ScanService::Scan.\n"); if (!scanStartedFlag) { WIFI_LOGE("Scan service has not started.\n"); - return false; + return WIFI_OPT_FAILED; } if (externFlag) { int appId = 0; if (!AllowExternScan(appId)) { WIFI_LOGE("AllowExternScan return false.\n"); - return false; + return WIFI_OPT_FAILED; } } @@ -239,37 +212,37 @@ bool ScanService::Scan(bool externFlag) scanConfig.scanStyle = SCAN_TYPE_HIGH_ACCURACY; if (!SingleScan(scanConfig)) { WIFI_LOGE("SingleScan failed.\n"); - return false; + return WIFI_OPT_FAILED; } - return true; + return WIFI_OPT_SUCCESS; } -bool ScanService::Scan(const WifiScanParams ¶ms) +ErrCode ScanService::ScanWithParam(const WifiScanParams ¶ms) { WIFI_LOGI("Enter ScanService::Scan.\n"); if (!scanStartedFlag) { WIFI_LOGE("Scan service has not started.\n"); - return false; + return WIFI_OPT_FAILED; } int appId = 0; if (!AllowExternScan(appId)) { WIFI_LOGE("AllowExternScan return false.\n"); - return false; + return WIFI_OPT_FAILED; } if ((params.band < static_cast(SCAN_BAND_UNSPECIFIED)) || (params.band > static_cast(SCAN_BAND_BOTH_WITH_DFS))) { WIFI_LOGE("params.band is error.\n"); - return false; + return WIFI_OPT_FAILED; } /* When the frequency is specified, the band must be SCAN_BAND_UNSPECIFIED */ if (params.freqs.empty() && (params.band == static_cast(SCAN_BAND_UNSPECIFIED))) { WIFI_LOGE("params is error.\n"); - return false; + return WIFI_OPT_FAILED; } ScanConfig scanConfig; @@ -298,10 +271,10 @@ bool ScanService::Scan(const WifiScanParams ¶ms) if (!SingleScan(scanConfig)) { WIFI_LOGE("SingleScan failed.\n"); - return false; + return WIFI_OPT_FAILED; } - return true; + return WIFI_OPT_SUCCESS; } bool ScanService::SingleScan(ScanConfig &scanConfig) @@ -487,12 +460,7 @@ void ScanService::HandleCommonScanFailed(std::vector &requestIndexList) } /* Notification of the end of scanning */ - if (configIter->second.fullScanFlag) { - NotifyScanInfo(SCAN_RES, static_cast(ScanHandleNotify::SCAN_FAIL)); - } else { - NotifyScanInfo(SCAN_PARAM_RES, static_cast(ScanHandleNotify::SCAN_FAIL)); - } - + mScanSerivceCallbacks.OnScanFinishEvent(static_cast(ScanHandleNotify::SCAN_FAIL)); scanConfigMap.erase(*reqIter); } @@ -523,7 +491,7 @@ void ScanService::HandleCommonScanInfo( if (StoreFullScanInfo(configIter->second, scanInfoList)) { fullScanStored = true; - NotifyScanInfo(SCAN_RES, static_cast(ScanHandleNotify::SCAN_OK)); + mScanSerivceCallbacks.OnScanFinishEvent(static_cast(ScanHandleNotify::SCAN_OK)); } else { WIFI_LOGE("StoreFullScanInfo failed.\n"); } @@ -532,7 +500,7 @@ void ScanService::HandleCommonScanInfo( if (!StoreUserScanInfo(configIter->second, scanInfoList)) { WIFI_LOGE("StoreUserScanInfo failed.\n"); } - NotifyScanInfo(SCAN_PARAM_RES, static_cast(ScanHandleNotify::SCAN_OK)); + mScanSerivceCallbacks.OnScanFinishEvent(static_cast(ScanHandleNotify::SCAN_OK)); } scanConfigMap.erase(*reqIter); @@ -558,7 +526,7 @@ bool ScanService::StoreFullScanInfo( WIFI_LOGI("Enter ScanService::StoreFullScanInfo.\n"); /* Filtering result */ - WIFI_LOGI("scanConfig.scanTime is %" PRIu64 "\n", scanConfig.scanTime); + WIFI_LOGI("scanConfig.scanTime is %" PRIu64 ".\n", scanConfig.scanTime); WIFI_LOGI("Receive %{public}d scan results.\n", (int)(scanInfoList.size())); std::vector filterScanInfo; std::vector::const_iterator iter = scanInfoList.begin(); @@ -638,19 +606,10 @@ bool ScanService::StoreUserScanInfo( return true; } -void ScanService::ReportScanInfos(const std::vector &interScanList) +void ScanService::ReportScanInfos(std::vector &interScanList) { WIFI_LOGI("Enter ScanService::ReportScanInfos.\n"); - - /* Filtering result */ - std::vector scanInfoList; - ConvertScanInfos(interScanList, scanInfoList); - - /* Notification interface service */ - WifiResponseMsgInfo notifyScanMsg; - notifyScanMsg.msgCode = SCAN_RESULT_RES; - notifyScanMsg.params.scanInfos = scanInfoList; - pMessageQueueUp->Push(notifyScanMsg); + mScanSerivceCallbacks.OnScanInfoEvent(interScanList); return; } @@ -673,7 +632,6 @@ void ScanService::ConvertScanInfos( scanInfo.securityType = iter->securityType; scanInfoList.push_back(scanInfo); } - return; } @@ -818,7 +776,7 @@ void ScanService::HandlePnoScanInfo(std::vector &scanInfoList) WIFI_LOGI("InterScanInfo.capabilities is %{public}s.\n", iter->capabilities.c_str()); WIFI_LOGI("InterScanInfo.frequency is %{public}d.\n", iter->frequency); WIFI_LOGI("InterScanInfo.rssi is %{public}d.\n", iter->rssi); - WIFI_LOGI("InterScanInfo.timestamp is %" PRIu64 "\n", iter->timestamp); + WIFI_LOGI("InterScanInfo.timestamp is %" PRIu64 ".\n", iter->timestamp); } } @@ -881,6 +839,23 @@ void ScanService::HandleStaStatusChanged(int status) return; } +void ScanService::HandleCustomStatusChanged(int customScene, int customSceneStatus) +{ + LOGI("Enter ScanService::HandleCustomStatusChanged."); + + time_t now = time(nullptr); + LOGD("customScene:%d, status:%d", customScene, customSceneStatus); + if (customSceneStatus == STATE_OPEN) { + customSceneTimeMap.insert(std::pair(customScene, now)); + } + if (customSceneStatus == STATE_CLOSE) { + customSceneTimeMap.erase(customScene); + } + SystemScanProcess(false); + + return; +} + void ScanService::SystemScanProcess(bool scanAtOnce) { WIFI_LOGI("Enter ScanService::SystemScanProcess."); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.h index c7ebb2728..608aa2e29 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.h @@ -18,6 +18,7 @@ #include #include #include +#include "iscan_service_callbacks.h" #include "wifi_log.h" #include "wifi_settings.h" #include "wifi_error_no.h" @@ -56,41 +57,29 @@ public: /** * @Description Initializing the Scan Service. * - * @param messageQueueUp - message queue which is used to return results.[in] + * @param scanSerivceCallbacks Callback function registered with the wifiManager[in]. * @return success: true, failed: false */ - bool InitScanService(WifiMessageQueue *messageQueueUp); + bool InitScanService(const IScanSerivceCallbacks &scanSerivceCallbacks); /** * @Description Stopping the Scan Service. * */ void UnInitScanService(); - /** - * @Description Notification interface service scanning status. - * - * @param msgCode - Operation Result Code[in] - */ - void NotifyScanServiceStatus(int msgCode); - /** - * @Description Notification interface service operation result. - * - * @param msgCode - Operation Result Code[in] - * @param result - Indicates whether the operation is successful or failed[in] - */ - void NotifyScanInfo(int msgCode, int result); /** * @Description Start a complete Wi-Fi scan. * * @param externFlag - Externally initiated scanning[in] + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ - bool Scan(bool externFlag); + ErrCode Scan(bool externFlag); /** * @Description Start Wi-Fi scanning based on specified parameters. * * @param params - Scan specified parameters[in] - * @return success: true, failed: false + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ - bool Scan(const WifiScanParams ¶ms); + ErrCode ScanWithParam(const WifiScanParams ¶ms); /** * @Description Starting a Single Scan. * @@ -143,6 +132,14 @@ public: * @param state - STA state[in] */ void HandleStaStatusChanged(int status); + /** + * @Description custom scene status change processing + * + * @param customScene custom scene[in] + * @param customSceneStatus custom scene status[in] + */ + void HandleCustomStatusChanged(int customScene, int customSceneStatus); + /** * @Description Sets the type of the app to be operated. * @@ -176,9 +173,9 @@ private: using ScanInfoHandlerMap = std::map; using PnoScanInfoHandlerMap = std::map; + IScanSerivceCallbacks mScanSerivceCallbacks; ScanStateMachine *pScanStateMachine; /* Scanning state machine pointer */ ScanMonitor *pScanMonitor; /* Scanning Monitor Pointer */ - WifiMessageQueue *pMessageQueueUp; /* Queue for returning messages */ bool scanStartedFlag; /* The scanning is started */ ScanInfoHandlerMap scanInfoHandlerMap; /* Map of obtaining the scanning result */ PnoScanInfoHandlerMap pnoScanInfoHandlerMap; /* Map of obtaining PNO scanning results */ @@ -258,7 +255,7 @@ private: * * @param scanInfoList - scan result list[in] */ - void ReportScanInfos(const std::vector &interScanList); + void ReportScanInfos(std::vector &interScanList); /** * @Description Convert the scanning result to the format of the interface service. * diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_callback_proxy.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_callback_proxy.cpp index 970380a28..78877dece 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_callback_proxy.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_callback_proxy.cpp @@ -4,7 +4,7 @@ * 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 + * 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, diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_death_recipient.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_death_recipient.h index 6efd1fadd..807e87fc3 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_death_recipient.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_death_recipient.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_WIFI_SCAN_CALLBACK_DEATH_H -#define OHOS_WIFI_SCAN_CALLBACK_DEATH_H +#ifndef OHOS_WIFI_SCAN_DEATH_RECIPIENT_H +#define OHOS_WIFI_SCAN_DEATH_RECIPIENT_H #include "iremote_object.h" namespace OHOS { diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_service_impl.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_service_impl.cpp index 0afc57db3..a18cebaaa 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_service_impl.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_service_impl.cpp @@ -38,7 +38,7 @@ sptr WifiScanServiceImpl::GetInstance() if (g_instance == nullptr) { std::lock_guard autoLock(g_instanceLock); if (g_instance == nullptr) { - auto service = new WifiScanServiceImpl; + auto service = new (std::nothrow) WifiScanServiceImpl; g_instance = service; } } @@ -92,16 +92,17 @@ ErrCode WifiScanServiceImpl::SetScanControlInfo(const ScanControlInfo &info) { WIFI_LOGI("WifiScanServiceImpl::SetScanControlInfo"); if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { - WIFI_LOGE("SetScanControlInfo:VerifySetWifiInfoPermission PERMISSION_DENIED!"); + WIFI_LOGE("SetScanControlInfo:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; } WifiConfigCenter::GetInstance().SetScanControlInfo(info); - WifiRequestMsgInfo msg; - msg.msgCode = WifiInternalMsgCode::SCAN_CONTROL_REQ; - if (WifiManager::GetInstance().PushMsg(WIFI_SERVICE_SCAN, msg) < 0) { - WIFI_LOGE("send scan msg failed!"); - return WIFI_OPT_FAILED; + if (IsScanServiceRunning()) { + IScanService *pService = WifiServiceManager::GetInstance().GetScanServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_SCAN_NOT_OPENED; + } + return pService->OnControlStrategyChanged(); } return WIFI_OPT_SUCCESS; @@ -110,51 +111,39 @@ ErrCode WifiScanServiceImpl::SetScanControlInfo(const ScanControlInfo &info) ErrCode WifiScanServiceImpl::Scan() { WIFI_LOGI("Scan"); - if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { - WIFI_LOGE("Scan:VerifySetWifiInfoPermission PERMISSION_DENIED!"); + WIFI_LOGE("Scan:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; } - WifiOprMidState curState = WifiConfigCenter::GetInstance().GetScanMidState(); - if (curState != WifiOprMidState::RUNNING) { - WIFI_LOGD("scan service does not started!"); + if (!IsScanServiceRunning()) { return WIFI_OPT_SCAN_NOT_OPENED; } - WifiRequestMsgInfo msg; - msg.msgCode = WifiInternalMsgCode::SCAN_REQ; - if (WifiManager::GetInstance().PushMsg(WIFI_SERVICE_SCAN, msg) < 0) { - WIFI_LOGE("send scan msg failed!"); - return WIFI_OPT_FAILED; + IScanService *pService = WifiServiceManager::GetInstance().GetScanServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_SCAN_NOT_OPENED; } - - return WIFI_OPT_SUCCESS; + return pService->Scan(true); } ErrCode WifiScanServiceImpl::AdvanceScan(const WifiScanParams ¶ms) { WIFI_LOGI("Scan with WifiScanParams, band %{public}u", params.band); if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { - WIFI_LOGE("Scan with WifiScanParams:VerifySetWifiInfoPermission PERMISSION_DENIED!"); + WIFI_LOGE("Scan with WifiScanParams:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; } - WifiOprMidState curState = WifiConfigCenter::GetInstance().GetScanMidState(); - if (curState != WifiOprMidState::RUNNING) { - WIFI_LOGD("scan service does not started!"); + if (!IsScanServiceRunning()) { return WIFI_OPT_SCAN_NOT_OPENED; } - WifiRequestMsgInfo msg; - msg.msgCode = WifiInternalMsgCode::SCAN_PARAM_REQ; - msg.params.wifiScanParams = params; - if (WifiManager::GetInstance().PushMsg(WIFI_SERVICE_SCAN, msg) < 0) { - WIFI_LOGE("send scan msg failed!"); - return WIFI_OPT_FAILED; + IScanService *pService = WifiServiceManager::GetInstance().GetScanServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_SCAN_NOT_OPENED; } - - return WIFI_OPT_SUCCESS; + return pService->ScanWithParam(params); } ErrCode WifiScanServiceImpl::IsWifiClosedScan(bool &bOpen) @@ -179,7 +168,7 @@ ErrCode WifiScanServiceImpl::GetScanInfoList(std::vector &result) } if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { - WIFI_LOGE("GetScanInfoList:VerifyGetScanInfosPermission PERMISSION_DENIED!"); + WIFI_LOGE("GetScanInfoList:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; } WifiConfigCenter::GetInstance().GetScanInfoList(result); @@ -206,5 +195,15 @@ ErrCode WifiScanServiceImpl::GetSupportedFeatures(long &features) } return WIFI_OPT_SUCCESS; } + +bool WifiScanServiceImpl::IsScanServiceRunning() +{ + WifiOprMidState curState = WifiConfigCenter::GetInstance().GetScanMidState(); + if (curState != WifiOprMidState::RUNNING) { + WIFI_LOGD("scan service does not started!"); + return false; + } + return true; +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_service_impl.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_service_impl.h index 9b6c96e7b..590c667f6 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_service_impl.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_service_impl.h @@ -48,6 +48,7 @@ public: private: bool Init(); + bool IsScanServiceRunning(); private: static sptr g_instance; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_stub.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_stub.cpp index 86ab33fbf..4c4de8efe 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_stub.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_stub.cpp @@ -126,7 +126,7 @@ int WifiScanStub::OnSetScanControlInfo(uint32_t code, MessageParcel &data, Messa info.scanIntervalList.push_back(scanIntervalMode); } - int ret = SetScanControlInfo(info); + ErrCode ret = SetScanControlInfo(info); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -136,7 +136,7 @@ int WifiScanStub::OnSetScanControlInfo(uint32_t code, MessageParcel &data, Messa int WifiScanStub::OnScan(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { WIFI_LOGD("run OnScan code %{public}u, datasize %zu", code, data.GetRawDataSize()); - int ret = Scan(); + ErrCode ret = Scan(); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -156,7 +156,7 @@ int WifiScanStub::OnScanByParams(uint32_t code, MessageParcel &data, MessageParc } params.band = data.ReadInt32(); - int ret = AdvanceScan(params); + ErrCode ret = AdvanceScan(params); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -167,7 +167,7 @@ int WifiScanStub::OnIsWifiClosedScan(uint32_t code, MessageParcel &data, Message { WIFI_LOGD("run OnIsWifiClosedScan code %{public}u, datasize %zu", code, data.GetRawDataSize()); bool bOpen = false; - int ret = IsWifiClosedScan(bOpen); + ErrCode ret = IsWifiClosedScan(bOpen); reply.WriteInt32(0); reply.WriteInt32(ret); if (ret == WIFI_OPT_SUCCESS) { @@ -180,33 +180,34 @@ int WifiScanStub::OnGetScanInfoList(uint32_t code, MessageParcel &data, MessageP { WIFI_LOGD("run OnGetScanInfoList code %{public}u, datasize %zu", code, data.GetRawDataSize()); std::vector result; - int ret = GetScanInfoList(result); + ErrCode ret = GetScanInfoList(result); reply.WriteInt32(0); reply.WriteInt32(ret); + if (ret != WIFI_OPT_SUCCESS) { + return ret; + } - if (ret == WIFI_OPT_SUCCESS) { - unsigned int size = result.size(); - reply.WriteInt32(size); - for (unsigned int i = 0; i < size; ++i) { - reply.WriteCString(result[i].bssid.c_str()); - reply.WriteCString(result[i].ssid.c_str()); - reply.WriteCString(result[i].capabilities.c_str()); - reply.WriteInt32(result[i].frequency); - reply.WriteInt32(result[i].rssi); - reply.WriteInt64(result[i].timestamp); - reply.WriteInt32(result[i].band); - reply.WriteInt32(static_cast(result[i].securityType)); - reply.WriteInt32(static_cast(result[i].channelWidth)); - reply.WriteInt32(result[i].centerFrequency0); - reply.WriteInt32(result[i].centerFrequency1); - reply.WriteInt64(result[i].features); - reply.WriteInt32(result[i].infoElems.size()); - for (unsigned int m = 0; m < result[i].infoElems.size(); ++m) { - reply.WriteInt32(result[i].infoElems[m].id); - reply.WriteInt32(result[i].infoElems[m].content.size()); - for (unsigned int n = 0; n < result[i].infoElems[m].content.size(); ++n) { - reply.WriteInt8(result[i].infoElems[m].content[n]); - } + unsigned int size = result.size(); + reply.WriteInt32(size); + for (unsigned int i = 0; i < size; ++i) { + reply.WriteCString(result[i].bssid.c_str()); + reply.WriteCString(result[i].ssid.c_str()); + reply.WriteCString(result[i].capabilities.c_str()); + reply.WriteInt32(result[i].frequency); + reply.WriteInt32(result[i].rssi); + reply.WriteInt64(result[i].timestamp); + reply.WriteInt32(result[i].band); + reply.WriteInt32(static_cast(result[i].securityType)); + reply.WriteInt32(static_cast(result[i].channelWidth)); + reply.WriteInt32(result[i].centerFrequency0); + reply.WriteInt32(result[i].centerFrequency1); + reply.WriteInt64(result[i].features); + reply.WriteInt32(result[i].infoElems.size()); + for (unsigned int m = 0; m < result[i].infoElems.size(); ++m) { + reply.WriteInt32(result[i].infoElems[m].id); + reply.WriteInt32(result[i].infoElems[m].content.size()); + for (unsigned int n = 0; n < result[i].infoElems[m].content.size(); ++n) { + reply.WriteInt8(result[i].infoElems[m].content[n]); } } } @@ -216,7 +217,7 @@ int WifiScanStub::OnGetScanInfoList(uint32_t code, MessageParcel &data, MessageP int WifiScanStub::OnRegisterCallBack(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); - int ret = WIFI_OPT_FAILED; + ErrCode ret = WIFI_OPT_FAILED; do { sptr remote = data.ReadRemoteObject(); if (remote == nullptr) { @@ -226,7 +227,7 @@ int WifiScanStub::OnRegisterCallBack(uint32_t code, MessageParcel &data, Message callback_ = iface_cast(remote); if (callback_ == nullptr) { - callback_ = new WifiScanCallbackProxy(remote); + callback_ = new (std::nothrow) WifiScanCallbackProxy(remote); WIFI_LOGD("create new `WifiScanCallbackProxy`!"); } @@ -234,7 +235,7 @@ int WifiScanStub::OnRegisterCallBack(uint32_t code, MessageParcel &data, Message ret = RegisterCallBack(callback_); } else { if (deathRecipient_ == nullptr) { - deathRecipient_ = new WifiScanDeathRecipient(); + deathRecipient_ = new (std::nothrow) WifiScanDeathRecipient(); } if ((remote->IsProxyObject()) && (!remote->AddDeathRecipient(deathRecipient_))) { WIFI_LOGD("AddDeathRecipient!"); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.cpp index dad91b204..7daa074ea 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.cpp @@ -14,7 +14,7 @@ */ #include "wifi_service_manager.h" #include -#include "wifi_log.h" +#include "wifi_logger.h" #include "define.h" #include "wifi_settings.h" @@ -68,6 +68,78 @@ int WifiServiceManager::CheckPreLoadService(void) return 0; } +int WifiServiceManager::LoadStaService(const std::string &dlname, bool bCreate) +{ + if (mStaServiceHandle.handle != nullptr) { + return 0; + } + mStaServiceHandle.handle = dlopen(dlname.c_str(), RTLD_LAZY); + if (mStaServiceHandle.handle == nullptr) { + WIFI_LOGE("dlopen %{public}s failed: %{public}s!", dlname.c_str(), dlerror()); + return -1; + } + mStaServiceHandle.create = (IStaService *(*)()) dlsym(mStaServiceHandle.handle, "Create"); + mStaServiceHandle.destroy = (void *(*)(IStaService *))dlsym(mStaServiceHandle.handle, "Destroy"); + if (mStaServiceHandle.create == nullptr || mStaServiceHandle.destroy == nullptr) { + WIFI_LOGE("%{public}s dlsym Create or Destory failed!", dlname.c_str()); + dlclose(mStaServiceHandle.handle); + mStaServiceHandle.Clear(); + return -1; + } + if (bCreate) { + mStaServiceHandle.pService = mStaServiceHandle.create(); + } + return 0; +} + +int WifiServiceManager::LoadScanService(const std::string &dlname, bool bCreate) +{ + if (mScanServiceHandle.handle != nullptr) { + return 0; + } + mScanServiceHandle.handle = dlopen(dlname.c_str(), RTLD_LAZY); + if (mScanServiceHandle.handle == nullptr) { + WIFI_LOGE("dlopen %{public}s failed: %{public}s!", dlname.c_str(), dlerror()); + return -1; + } + mScanServiceHandle.create = (IScanService *(*)()) dlsym(mScanServiceHandle.handle, "Create"); + mScanServiceHandle.destroy = (void *(*)(IScanService *))dlsym(mScanServiceHandle.handle, "Destroy"); + if (mScanServiceHandle.create == nullptr || mScanServiceHandle.destroy == nullptr) { + WIFI_LOGE("%{public}s dlsym Create or Destory failed!", dlname.c_str()); + dlclose(mScanServiceHandle.handle); + mScanServiceHandle.Clear(); + return -1; + } + if (bCreate) { + mScanServiceHandle.pService = mScanServiceHandle.create(); + } + return 0; +} + +int WifiServiceManager::LoadApService(const std::string &dlname, bool bCreate) +{ + if (mApServiceHandle.handle != nullptr) { + return 0; + } + mApServiceHandle.handle = dlopen(dlname.c_str(), RTLD_LAZY); + if (mApServiceHandle.handle == nullptr) { + WIFI_LOGE("dlopen %{public}s failed: %{public}s!", dlname.c_str(), dlerror()); + return -1; + } + mApServiceHandle.create = (IApService *(*)()) dlsym(mApServiceHandle.handle, "Create"); + mApServiceHandle.destroy = (void *(*)(IApService *))dlsym(mApServiceHandle.handle, "Destroy"); + if (mApServiceHandle.create == nullptr || mApServiceHandle.destroy == nullptr) { + WIFI_LOGE("%{public}s dlsym Create or Destory failed!", dlname.c_str()); + dlclose(mApServiceHandle.handle); + mApServiceHandle.Clear(); + return -1; + } + if (bCreate) { + mApServiceHandle.pService = mApServiceHandle.create(); + } + return 0; +} + int WifiServiceManager::CheckAndEnforceService(const std::string &name, bool bCreate) { WIFI_LOGD("WifiServiceManager::CheckAndEnforceService name: %{public}s", name.c_str()); @@ -78,47 +150,106 @@ int WifiServiceManager::CheckAndEnforceService(const std::string &name, bool bCr } WIFI_LOGD("WifiServiceManager::CheckAndEnforceService get dllname: %{public}s", dlname.c_str()); std::unique_lock lock(mMutex); - if (mServiceHandleMap.find(name) == mServiceHandleMap.end()) { - ServiceHandle tmp; - tmp.handle = dlopen(dlname.c_str(), RTLD_LAZY); - if (tmp.handle == nullptr) { - WIFI_LOGE("dlopen %{public}s failed: %{public}s!", dlname.c_str(), dlerror()); - return -1; + if (name == WIFI_SERVICE_STA) { + return LoadStaService(dlname, bCreate); + } + if (name == WIFI_SERVICE_SCAN) { + return LoadScanService(dlname, bCreate); + } + if (name == WIFI_SERVICE_AP) { + return LoadApService(dlname, bCreate); + } + return -1; +} + +IStaService *WifiServiceManager::GetStaServiceInst() +{ + if (mStaServiceHandle.handle == nullptr) { + return nullptr; + } + if (mStaServiceHandle.pService == nullptr) { + std::unique_lock lock(mMutex); + if (mStaServiceHandle.pService == nullptr) { + mStaServiceHandle.pService = mStaServiceHandle.create(); } - tmp.create = (BaseService* (*)()) dlsym(tmp.handle, "Create"); - tmp.destroy = (void *(*)(BaseService*))dlsym(tmp.handle, "Destroy"); - if (tmp.create == nullptr || tmp.destroy == nullptr) { - WIFI_LOGE("%{public}s dlsym Create or Destroy failed!", dlname.c_str()); - dlclose(tmp.handle); - return -1; + } + return mStaServiceHandle.pService; +} + +IScanService *WifiServiceManager::GetScanServiceInst() +{ + if (mScanServiceHandle.handle == nullptr) { + return nullptr; + } + if (mScanServiceHandle.pService == nullptr) { + std::unique_lock lock(mMutex); + if (mScanServiceHandle.pService == nullptr) { + mScanServiceHandle.pService = mScanServiceHandle.create(); } - if (bCreate) { - tmp.bs = tmp.create(); - if (tmp.bs == nullptr) { - WIFI_LOGE("create feature service is nullptr"); - } + } + return mScanServiceHandle.pService; +} + +IApService *WifiServiceManager::GetApServiceInst() +{ + if (mApServiceHandle.handle == nullptr) { + return nullptr; + } + if (mApServiceHandle.pService == nullptr) { + std::unique_lock lock(mMutex); + if (mApServiceHandle.pService == nullptr) { + mApServiceHandle.pService = mApServiceHandle.create(); } - mServiceHandleMap.emplace(std::make_pair(name, tmp)); + } + return mApServiceHandle.pService; +} + +int WifiServiceManager::UnloadStaService(bool bPreLoad) +{ + if (mStaServiceHandle.handle == nullptr) { + return 0; + } + if (mStaServiceHandle.pService != nullptr) { + mStaServiceHandle.destroy(mStaServiceHandle.pService); + mStaServiceHandle.pService = nullptr; + } + if (!bPreLoad) { + dlclose(mStaServiceHandle.handle); + mStaServiceHandle.Clear(); } return 0; } -BaseService *WifiServiceManager::GetServiceInst(const std::string &name) +int WifiServiceManager::UnloadScanService(bool bPreLoad) { - WIFI_LOGD("WifiServiceManager::GetServiceInst name: %{public}s", name.c_str()); - std::unique_lock lock(mMutex); - auto iter = mServiceHandleMap.find(name); - if (iter != mServiceHandleMap.end()) { - if (iter->second.bs == nullptr) { - WIFI_LOGD("WifiServiceManager::GetServiceInst start create feature service"); - iter->second.bs = iter->second.create(); - } - if (iter->second.bs == nullptr) { - WIFI_LOGE("WifiServiceManager::GetServiceInst feature service is nullptr"); - } - return iter->second.bs; + if (mScanServiceHandle.handle == nullptr) { + return 0; + } + if (mScanServiceHandle.pService != nullptr) { + mScanServiceHandle.destroy(mScanServiceHandle.pService); + mScanServiceHandle.pService = nullptr; + } + if (!bPreLoad) { + dlclose(mScanServiceHandle.handle); + mScanServiceHandle.Clear(); + } + return 0; +} + +int WifiServiceManager::UnloadApService(bool bPreLoad) +{ + if (mApServiceHandle.handle == nullptr) { + return 0; } - return nullptr; + if (mApServiceHandle.pService != nullptr) { + mApServiceHandle.destroy(mApServiceHandle.pService); + mApServiceHandle.pService = nullptr; + } + if (!bPreLoad) { + dlclose(mApServiceHandle.handle); + mApServiceHandle.Clear(); + } + return 0; } int WifiServiceManager::UnloadService(const std::string &name) @@ -126,30 +257,24 @@ int WifiServiceManager::UnloadService(const std::string &name) bool bPreLoad = WifiSettings::GetInstance().IsModulePreLoad(name); WIFI_LOGD("WifiServiceManager::UnloadService name: %{public}s", name.c_str()); std::unique_lock lock(mMutex); - auto iter = mServiceHandleMap.find(name); - if (iter != mServiceHandleMap.end()) { - ServiceHandle &tmp = iter->second; - tmp.destroy(tmp.bs); - if (!bPreLoad) { - dlclose(tmp.handle); - mServiceHandleMap.erase(iter); - } else { - tmp.bs = nullptr; - } + if (name == WIFI_SERVICE_STA) { + return UnloadStaService(bPreLoad); } - return 0; + if (name == WIFI_SERVICE_SCAN) { + return UnloadScanService(bPreLoad); + } + if (name == WIFI_SERVICE_AP) { + return UnloadApService(bPreLoad); + } + return -1; } void WifiServiceManager::UninstallAllService() { WIFI_LOGD("WifiServiceManager::UninstallAllService"); - std::unique_lock lock(mMutex); - for (auto iter = mServiceHandleMap.begin(); iter != mServiceHandleMap.end(); ++iter) { - ServiceHandle &tmp = iter->second; - tmp.destroy(tmp.bs); - dlclose(tmp.handle); - } - mServiceHandleMap.clear(); + UnloadStaService(false); + UnloadScanService(false); + UnloadApService(false); return; } } // namespace Wifi diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.h index b0400d103..01e5e3951 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.h @@ -16,23 +16,68 @@ #ifndef OHOS_WIFI_SERVICE_MANAGER_H #define OHOS_WIFI_SERVICE_MANAGER_H -#include #include #include #include -#include "base_service.h" -#include "wifi_logger.h" +#include "ista_service.h" +#include "iscan_service.h" +#include "i_ap_service.h" namespace OHOS { namespace Wifi { -struct ServiceHandle { - void *handle; /* Loads the SO handle. */ - BaseService *(*create)(); /* Address of the Create function in the SO. */ - void *(*destroy)(BaseService *); /* Address of the Destroy function in the SO */ - BaseService *bs; /* Feature Service Object */ - ServiceHandle() : handle(nullptr), create(nullptr), destroy(nullptr), bs(nullptr) +struct StaServiceHandle { + void *handle; + IStaService *(*create)(); + void *(*destroy)(IStaService *); + IStaService *pService; + StaServiceHandle() : handle(nullptr), create(nullptr), destroy(nullptr), pService(nullptr) {} + ~StaServiceHandle() + {} + void Clear() + { + handle = nullptr; + create = nullptr; + destroy = nullptr; + pService = nullptr; + } +}; + +struct ScanServiceHandle { + void *handle; + IScanService *(*create)(); + void *(*destroy)(IScanService *); + IScanService *pService; + ScanServiceHandle() : handle(nullptr), create(nullptr), destroy(nullptr), pService(nullptr) + {} + ~ScanServiceHandle() + {} + void Clear() + { + handle = nullptr; + create = nullptr; + destroy = nullptr; + pService = nullptr; + } +}; + +struct ApServiceHandle { + void *handle; + IApService *(*create)(); + void *(*destroy)(IApService *); + IApService *pService; + ApServiceHandle() : handle(nullptr), create(nullptr), destroy(nullptr), pService(nullptr) + {} + ~ApServiceHandle() + {} + void Clear() + { + handle = nullptr; + create = nullptr; + destroy = nullptr; + pService = nullptr; + } }; class WifiServiceManager { @@ -64,12 +109,25 @@ public: int CheckAndEnforceService(const std::string &name, bool bCreate = true); /** - * @Description Obtaining Loaded Feature Service Objects + * @Description Get the Sta Service Inst object * - * @param name - feature service name - * @return BaseService* - service pointer, if no feature service is loaded, nullptr is returned + * @return IStaService* - sta service pointer, if sta not supported, nullptr is returned */ - BaseService *GetServiceInst(const std::string &name); + IStaService *GetStaServiceInst(void); + + /** + * @Description Get the Scan Service Inst object + * + * @return IScanService* - scan service pointer, if scan not supported, nullptr is returned + */ + IScanService *GetScanServiceInst(void); + + /** + * @Description Get the Ap Service Inst object + * + * @return IApService* - ap service pointer, if ap not supported, nullptr is returned + */ + IApService *GetApServiceInst(void); /** * @Description unload a feature service @@ -88,10 +146,19 @@ public: private: int GetServiceDll(const std::string &name, std::string &dlname); + int LoadStaService(const std::string &dlname, bool bCreate); + int UnloadStaService(bool bPreLoad); + int LoadScanService(const std::string &dlname, bool bCreate); + int UnloadScanService(bool bPreLoad); + int LoadApService(const std::string &dlname, bool bCreate); + int UnloadApService(bool bPreLoad); + private: std::mutex mMutex; - std::unordered_map mServiceHandleMap; std::unordered_map mServiceDllMap; + StaServiceHandle mStaServiceHandle; + ScanServiceHandle mScanServiceHandle; + ApServiceHandle mApServiceHandle; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/ista_service.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/ista_service.h new file mode 100644 index 000000000..4d636e587 --- /dev/null +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/ista_service.h @@ -0,0 +1,166 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef OHOS_WIFI_STA_SERVICE_H +#define OHOS_WIFI_STA_SERVICE_H + +#include "wifi_errcode.h" +#include "wifi_msg.h" +#include "sta_service_callback.h" + +namespace OHOS { +namespace Wifi { +class IStaService { +public: + virtual ~IStaService() = default; + /** + * @Description Enable wifi + * + * @Output: Return operating results to Interface Service after enable wifi + successfully through callback function instead of returning + result immediately. + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode EnableWifi() = 0; + /** + * @Description Disable wifi + * + * @Output: Return operating results to Interface Service after enable wifi + successfully through callback function instead of returning + result immediately. + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode DisableWifi() = 0; + /** + * @Description Connect to a new network + * + * @param config - the configuration of network which is going to connect.(in) + * @Output: Return operating results to Interface Service after enable wifi + successfully through callback function instead of returning + result immediately. + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode ConnectToDevice(const WifiDeviceConfig &config) = 0; + /** + * @Description Connecting to a specified network. + * + * @param networkId - interior saved network index.(in) + * @Output: Return operating results to Interface Service after enable wifi + successfully through callback function instead of returning + result immediately. + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode ConnectToNetwork(int networkId) = 0; + /** + * @Description Disconnect to the network + * + * @Output: Return operating results to Interface Service after enable wifi + successfully through callback function instead of returning + result immediately. + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode Disconnect() = 0; + /** + * @Description ReAssociate network + * + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode ReAssociate() = 0; + /** + * @Description Add a network to config + * + * @param config -The Network info(in) + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual int AddDeviceConfig(const WifiDeviceConfig &config) = 0; + /** + * @Description Update a network to config + * + * @param config -The Network info(in) + * @Return success: networkId fail: -1 + */ + virtual int UpdateDeviceConfig(const WifiDeviceConfig &config) = 0; + /** + * @Description Remove network + * + * @param networkId -The NetworkId is going to be removed.(in) + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode RemoveDevice(int networkId) = 0; + /** + * @Description Remove all network configs + * + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode RemoveAllDevice() = 0; + /** + * @Description Enable WI-FI device configuration + * + * @param networkId - The NetworkId (in) + * @param networkId - if set true, disable other device configuration (in) + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode EnableDeviceConfig(int networkId, bool attemptEnable) = 0; + /** + * @Description Disable WI-FI device configuration + * + * @param networkId - device configuration's network id + * @return ErrCode - success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode DisableDeviceConfig(int networkId) = 0; + /** + * @Description Start WPS Connection + * + * @Output: Return operating results to Interface Service after enable wifi + successfully through callback function instead of returning + result immediately. + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode StartWps(const WpsConfig &config) = 0; + /** + * @Description Close WPS Connection + * + * @Output: Return operating results to Interface Service after enable wifi + successfully through callback function instead of returning + result immediately. + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode CancelWps() = 0; + /** + * @Description Set country code + * + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode SetCountryCode(const std::string &countryCode) = 0; + /** + * @Description ConnectivityManager process scan results. + * + * @Output: Return operating results to Interface Service after enable wifi + successfully through callback function instead of returning + result immediately. + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode ConnectivityManager(const std::vector &scanInfos) = 0; + /** + * @Description Register sta callback function + * + * @param callbacks - Callback function pointer storage structure + * @return ErrCode - success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode RegisterStaServiceCallback(const StaServiceCallback &callbacks) = 0; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.cpp index 77d96e4d8..1cae43236 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.cpp @@ -59,7 +59,7 @@ ErrCode StaAutoConnectService::InitAutoConnectService() return WIFI_OPT_SUCCESS; } -void StaAutoConnectService::OnScanInfosReadyHandler(const std::vector &scanInfos) +void StaAutoConnectService::OnScanInfosReadyHandler(const std::vector &scanInfos) { WIFI_LOGI("Enter StaAutoConnectService::OnScanInfosReadyHandler.\n"); ClearOvertimeBlockedBssid(); /* Refreshing the BSSID Blocklist */ @@ -298,7 +298,7 @@ bool StaAutoConnectService::RegisterDeviceAppraisal(StaDeviceAppraisal *appraisa } ErrCode StaAutoConnectService::AutoSelectDevice(WifiDeviceConfig &electedDevice, - const std::vector &scanInfos, std::vector &blockedBssids, WifiLinkedInfo &info) + const std::vector &scanInfos, std::vector &blockedBssids, WifiLinkedInfo &info) { WIFI_LOGI("Enter StaAutoConnectService::SelectNetwork.\n"); if (scanInfos.empty()) { @@ -315,7 +315,7 @@ ErrCode StaAutoConnectService::AutoSelectDevice(WifiDeviceConfig &electedDevice, /* Before initiating network selection, update all configured networks. */ RefreshConfigDevice(); - std::vector availableScanInfos; + std::vector availableScanInfos; /* Filter out unnecessary networks. */ GetAvailableScanInfos(availableScanInfos, scanInfos, blockedBssids, info); if (availableScanInfos.empty()) { @@ -347,7 +347,7 @@ ErrCode StaAutoConnectService::AutoSelectDevice(WifiDeviceConfig &electedDevice, } bool StaAutoConnectService::RoamingSelection( - WifiDeviceConfig &electedDevice, std::vector &availableScanInfos, WifiLinkedInfo &info) + WifiDeviceConfig &electedDevice, std::vector &availableScanInfos, WifiLinkedInfo &info) { for (auto scanInfo : availableScanInfos) { if (info.connState == ConnState::CONNECTED && scanInfo.ssid == info.ssid && scanInfo.bssid != info.bssid) { @@ -361,7 +361,7 @@ bool StaAutoConnectService::RoamingSelection( } bool StaAutoConnectService::RoamingEncryptionModeCheck( - WifiDeviceConfig &electedDevice, WifiScanInfo scanInfo, WifiLinkedInfo &info) + WifiDeviceConfig &electedDevice, InterScanInfo scanInfo, WifiLinkedInfo &info) { WifiDeviceConfig network; if (WifiSettings::GetInstance().GetDeviceConfig(scanInfo.ssid, DEVICE_CONFIG_INDEX_SSID, network) == 0) { @@ -402,7 +402,7 @@ bool StaAutoConnectService::RoamingEncryptionModeCheck( return false; } -bool StaAutoConnectService::AllowAutoSelectDevice(const std::vector &scanInfos, WifiLinkedInfo &info) +bool StaAutoConnectService::AllowAutoSelectDevice(const std::vector &scanInfos, WifiLinkedInfo &info) { WIFI_LOGI("Enter StaAutoConnectService::AllowAutoSelectDevice.\n"); if (scanInfos.empty()) { @@ -459,7 +459,7 @@ bool StaAutoConnectService::AllowAutoSelectDevice(const std::vector &scanInfos, WifiLinkedInfo &info) +bool StaAutoConnectService::CurrentDeviceGoodEnough(const std::vector &scanInfos, WifiLinkedInfo &info) { WIFI_LOGI("Enter StaAutoConnectService::CurrentDeviceGoodEnough.\n"); @@ -511,7 +511,7 @@ bool StaAutoConnectService::CurrentDeviceGoodEnough(const std::vector &scanInfos) +bool StaAutoConnectService::WhetherDevice5GAvailable(const std::vector &scanInfos) { WIFI_LOGI("Enter StaAutoConnectService::WhetherDevice5GAvailable.\n"); for (auto scaninfo : scanInfos) { @@ -557,8 +557,8 @@ void StaAutoConnectService::RefreshConfigDevice() return; } -void StaAutoConnectService::GetAvailableScanInfos(std::vector &availableScanInfos, - const std::vector &scanInfos, std::vector &blockedBssids, WifiLinkedInfo &info) +void StaAutoConnectService::GetAvailableScanInfos(std::vector &availableScanInfos, + const std::vector &scanInfos, std::vector &blockedBssids, WifiLinkedInfo &info) { WIFI_LOGI("Enter StaAutoConnectService::GetAvailableScanInfos.\n"); if (scanInfos.empty()) { diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.h index cfc80d838..f2c638193 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.h @@ -59,7 +59,7 @@ public: * * @param scanInfos - The list of scanning results(in) */ - void OnScanInfosReadyHandler(const std::vector &scanInfos); + void OnScanInfosReadyHandler(const std::vector &scanInfos); /** * @Description Whether tracking should enable or disable scanned BSSIDs * @@ -78,7 +78,7 @@ public: * @param electedDevice - Elected Device(out) * @Return success : WIFI_OPT_SUCCESS failed : WIFI_OPT_FAILED */ - ErrCode AutoSelectDevice(WifiDeviceConfig &electedDevice, const std::vector &scanInfos, + ErrCode AutoSelectDevice(WifiDeviceConfig &electedDevice, const std::vector &scanInfos, std::vector &blockedBssids, WifiLinkedInfo &info); /** * @Description Registering the Device Appraisal @@ -165,8 +165,8 @@ private: * @param info - Current Connected Device(in) * @param availableScanInfos - Available Scan Info(out) */ - void GetAvailableScanInfos(std::vector &availableScanInfos, - const std::vector &scanInfos, std::vector &blockedBssids, WifiLinkedInfo &info); + void GetAvailableScanInfos(std::vector &availableScanInfos, + const std::vector &scanInfos, std::vector &blockedBssids, WifiLinkedInfo &info); /** * @Description Whether the device needs to be switched. * @@ -174,7 +174,7 @@ private: * @param info - Current Connected Device(in) * @Return success : true failed : false */ - bool AllowAutoSelectDevice(const std::vector &scanInfos, WifiLinkedInfo &info); + bool AllowAutoSelectDevice(const std::vector &scanInfos, WifiLinkedInfo &info); /** * @Description Whether the device strength is sufficient. * @@ -182,14 +182,14 @@ private: * @param info - Current Connected Device(in) * @Return success : true failed : false */ - bool CurrentDeviceGoodEnough(const std::vector &scanInfos, WifiLinkedInfo &info); + bool CurrentDeviceGoodEnough(const std::vector &scanInfos, WifiLinkedInfo &info); /** * @Description Whether 5G devices are available. * * @param scanInfos - WifiScanInfo list of all APs in the range(in) * @Return success : true failed : false */ - bool WhetherDevice5GAvailable(const std::vector &scanInfos); + bool WhetherDevice5GAvailable(const std::vector &scanInfos); /** * @Description Select Roaming Device. * @@ -200,7 +200,7 @@ private: * @Return success : true failed : false */ bool RoamingSelection( - WifiDeviceConfig &electedDevice, std::vector &availableScanInfos, WifiLinkedInfo &info); + WifiDeviceConfig &electedDevice, std::vector &availableScanInfos, WifiLinkedInfo &info); /** * @Description Select Roaming Device. * @@ -209,7 +209,7 @@ private: * @param electedDevice - Elected Device(out) * @Return success : true failed : false */ - bool RoamingEncryptionModeCheck(WifiDeviceConfig &electedDevice, WifiScanInfo scanInfo, WifiLinkedInfo &info); + bool RoamingEncryptionModeCheck(WifiDeviceConfig &electedDevice, InterScanInfo scanInfo, WifiLinkedInfo &info); /** * @Description Updating the Configuration Center Device. * diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_define.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_define.h index 9b11e6180..f2fe7334f 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_define.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_define.h @@ -1,3 +1,17 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ /* * Copyright (C) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -35,7 +49,6 @@ namespace Wifi { #define WIFI_SVR_CMD_STA_STARTWPS 0x200C #define WIFI_SVR_CMD_STA_CANCELWPS 0x200D #define WIFI_SVR_COM_STA_START_ROAM 0x200E -#define WIFI_SVR_COM_STA_SET_COUNTRY_CODE 0x200F #define WIFI_SVR_CMD_STA_ERROR 0x3001 #define WIFI_SVR_CMD_STA_SUP_CONNECTION_EVENT 0x3002 diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_device_appraisal.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_device_appraisal.h index 08e81bf83..ec80ced8e 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_device_appraisal.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_device_appraisal.h @@ -33,7 +33,7 @@ public: {} virtual ErrCode DeviceAppraisals( - WifiDeviceConfig &electedDevice, std::vector &scanInfos, WifiLinkedInfo &info) = 0; + WifiDeviceConfig &electedDevice, std::vector &scanInfos, WifiLinkedInfo &info) = 0; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.cpp index 9d2791a55..744a46afc 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.cpp @@ -14,7 +14,6 @@ */ #include "sta_interface.h" #include "wifi_log.h" -#include "define.h" #include "wifi_logger.h" DEFINE_WIFILOG_LABEL("StaInterface"); @@ -32,174 +31,180 @@ StaInterface::~StaInterface() } } -int StaInterface::Init(WifiMessageQueue *mqUp) +extern "C" IStaService *Create(void) { - WIFI_LOGD("Enter StaInterface::Init.\n"); - if (mqUp == nullptr) { - WIFI_LOGE("mqUp is null.\n"); - return -1; - } + return new (std::nothrow)StaInterface(); +} + +extern "C" void Destroy(IStaService *pservice) +{ + delete pservice; +} +ErrCode StaInterface::EnableWifi() +{ + WIFI_LOGD("Enter StaInterface::EnableWifi.\n"); pStaService = new (std::nothrow) StaService(); if (pStaService == nullptr) { WIFI_LOGE("New StaService failed.\n"); - return -1; + return WIFI_OPT_FAILED; } - if (pStaService->InitStaService(mqUp) != WIFI_OPT_SUCCESS) { + if (pStaService->InitStaService(staCallback) != WIFI_OPT_SUCCESS) { WIFI_LOGE("InitStaService failed.\n"); delete pStaService; pStaService = nullptr; - return -1; + return WIFI_OPT_FAILED; } if (pStaService->EnableWifi() != WIFI_OPT_SUCCESS) { WIFI_LOGE("EnableWifi failed.\n"); - UnInit(); - return -1; + DisableWifi(); + return WIFI_OPT_FAILED; } - InitStaHandleMap(); - return 0; + return WIFI_OPT_SUCCESS; } -int StaInterface::InitStaHandleMap() +ErrCode StaInterface::DisableWifi() { - staHandleFuncMap[WifiInternalMsgCode::STA_CONNECT_REQ] = &StaInterface::WifiStaCmdConnectReq; - staHandleFuncMap[WIFI_SVR_CMD_RECONNECT] = &StaInterface::WifiStaCmdReconnectReq; - staHandleFuncMap[WifiInternalMsgCode::STA_REASSOCIATE_REQ] = &StaInterface::WifiStaCmdReassociateReq; - staHandleFuncMap[WifiInternalMsgCode::STA_DISCONNECT_REQ] = &StaInterface::WifiStaCmdDisconnectReq; - staHandleFuncMap[WifiInternalMsgCode::STA_REMOVE_DEVICE_REQ] = &StaInterface::WifiStaCmdRemoveDeviceReq; - staHandleFuncMap[WifiInternalMsgCode::STA_REMOVE_ALL_DEVICE_REQ] = &StaInterface::WifiStaCmdRemoveAllDeviceReq; - staHandleFuncMap[WifiInternalMsgCode::STA_START_WPS_REQ] = &StaInterface::WifiStaCmdStartWpsReq; - staHandleFuncMap[WifiInternalMsgCode::STA_CANCEL_WPS_REQ] = &StaInterface::WifiStaCmdCancelWpsReq; - staHandleFuncMap[WifiInternalMsgCode::STA_CONNECT_MANAGE_REQ] = &StaInterface::WifiStaCmdConnectManagerReq; - staHandleFuncMap[WifiInternalMsgCode::STA_SET_COUNTRY_CODE] = &StaInterface::WifiStaCmdSetCountryCodeReq; - return 0; + LOGD("Enter StaInterface::DisableWifi.\n"); + if (pStaService->DisableWifi() != WIFI_OPT_SUCCESS) { + LOGD("DisableWifi failed.\n"); + return WIFI_OPT_FAILED; + } + return WIFI_OPT_SUCCESS; } -int StaInterface::UnInit() +ErrCode StaInterface::ConnectToNetwork(int networkId) { - WIFI_LOGD("Enter StaInterface::UnInit.\n"); - int ret = 0; - if (pStaService->DisableWifi() != WIFI_OPT_SUCCESS) { - WIFI_LOGD("DisableWifi failed.\n"); - return -1; + LOGD("Enter StaInterface::Connect.\n"); + if (pStaService->ConnectToNetwork(networkId) != WIFI_OPT_SUCCESS) { + LOGD("ConnectTo failed.\n"); + return WIFI_OPT_FAILED; } - - return ret; + return WIFI_OPT_SUCCESS; } -int StaInterface::PushMsg(WifiRequestMsgInfo *requestMsg) +ErrCode StaInterface::ConnectToDevice(const WifiDeviceConfig &config) { - WIFI_LOGD("Enter StaInterface::PushMsg\n"); - if (requestMsg == nullptr) { - WIFI_LOGE("requestMsg is null.\n"); - return -1; + LOGD("Enter StaInterface::Connect.\n"); + if (pStaService->ConnectToDevice(config) != WIFI_OPT_SUCCESS) { + LOGD("ConnectTo failed.\n"); + return WIFI_OPT_FAILED; } + return WIFI_OPT_SUCCESS; +} - for (auto iter = staHandleFuncMap.begin(); iter != staHandleFuncMap.end(); ++iter) { - if (iter->first == requestMsg->msgCode) { - (this->*(iter->second))(requestMsg); - break; - } +ErrCode StaInterface::ReAssociate() +{ + LOGD("Enter StaInterface::ReAssociate.\n"); + if (pStaService->ReAssociate() != WIFI_OPT_SUCCESS) { + LOGD("ReAssociate failed.\n"); + return WIFI_OPT_FAILED; } - - return 0; + return WIFI_OPT_SUCCESS; } -void StaInterface::WifiStaCmdConnectReq(const WifiRequestMsgInfo *requestMsg) +ErrCode StaInterface::Disconnect() { - WIFI_LOGD("Enter StaInterface::WifiStaCmdConnectReq.\n"); - - if (requestMsg->params.argInt >= 0) { - pStaService->ConnectToNetwork(requestMsg->params.argInt); - } else { - pStaService->ConnectToDevice(requestMsg->params.deviceConfig); + LOGD("Enter StaInterface::Disconnect.\n"); + if (pStaService->Disconnect() != WIFI_OPT_SUCCESS) { + LOGD("Disconnect failed.\n"); + return WIFI_OPT_FAILED; } + return WIFI_OPT_SUCCESS; } -void StaInterface::WifiStaCmdReconnectReq(const WifiRequestMsgInfo *requestMsg) +int StaInterface::AddDeviceConfig(const WifiDeviceConfig &config) { - if (requestMsg == nullptr) { - WIFI_LOGE("requestMsg is null\n"); - } - WIFI_LOGD("Enter StaInterface::WifiStaCmdReconnectReq.\n"); - pStaService->ReConnect(); + LOGD("Enter StaInterface::AddDeviceConfig.\n"); + return pStaService->AddDeviceConfig(config); } -void StaInterface::WifiStaCmdReassociateReq(const WifiRequestMsgInfo *requestMsg) +int StaInterface::UpdateDeviceConfig(const WifiDeviceConfig &config) { - if (requestMsg == nullptr) { - WIFI_LOGE("requestMsg is null\n"); - } - WIFI_LOGD("Enter StaInterface::WifiStaCmdReassociateReq.\n"); - pStaService->ReAssociate(); + LOGD("Enter StaInterface::UpdateDeviceConfig.\n"); + return pStaService->UpdateDeviceConfig(config); } -void StaInterface::WifiStaCmdDisconnectReq(const WifiRequestMsgInfo *requestMsg) +ErrCode StaInterface::RemoveDevice(int networkId) { - if (requestMsg == nullptr) { - WIFI_LOGE("requestMsg is null\n"); + LOGD("Enter StaInterface::RemoveDeviceConfig.\n"); + if (pStaService->RemoveDevice(networkId) != WIFI_OPT_SUCCESS) { + LOGD("RemoveDeviceConfig failed.\n"); + return WIFI_OPT_FAILED; } - WIFI_LOGD("Enter StaInterface::WifiStaCmdDisconnectReq.\n"); - pStaService->Disconnect(); + return WIFI_OPT_SUCCESS; } -void StaInterface::WifiStaCmdRemoveDeviceReq(const WifiRequestMsgInfo *requestMsg) +ErrCode StaInterface::RemoveAllDevice() { - if (requestMsg == nullptr) { - WIFI_LOGE("requestMsg is null\n"); - return; + WIFI_LOGD("Enter StaInterface::RemoveAllDevice.\n"); + + if (pStaService->RemoveAllDevice() != WIFI_OPT_SUCCESS) { + WIFI_LOGD("RemoveAllDevice failed.\n"); + return WIFI_OPT_FAILED; } - WIFI_LOGD("Enter StaInterface::WifiStaCmdRemoveDeviceReq.\n"); - pStaService->RemoveDevice(requestMsg->params.argInt); + return WIFI_OPT_SUCCESS; +} +ErrCode StaInterface::EnableDeviceConfig(int networkId, bool attemptEnable) +{ + LOGD("Enter StaInterface::EnableDeviceConfig.\n"); + return pStaService->EnableDeviceConfig(networkId, attemptEnable); } -void StaInterface::WifiStaCmdRemoveAllDeviceReq(const WifiRequestMsgInfo *requestMsg) +ErrCode StaInterface::DisableDeviceConfig(int networkId) { - if (requestMsg == nullptr) { - WIFI_LOGE("requestMsg is null\n"); - return; - } - WIFI_LOGD("Enter StaInterface::WifiStaCmdRemoveAllDeviceReq.\n"); - pStaService->RemoveAllDevice(); + LOGD("Enter StaInterface::DisableDeviceConfig.\n"); + return pStaService->DisableDeviceConfig(networkId); } -void StaInterface::WifiStaCmdStartWpsReq(const WifiRequestMsgInfo *requestMsg) +ErrCode StaInterface::StartWps(const WpsConfig &config) { - if (requestMsg == nullptr) { - WIFI_LOGE("requestMsg is null\n"); - return; + LOGD("Enter StaInterface::StartWps.\n"); + if (pStaService->StartWps(config) != WIFI_OPT_SUCCESS) { + LOGD("StartWps failed.\n"); + return WIFI_OPT_FAILED; } - WIFI_LOGD("Enter StaInterface::WifiStaCmdStartWpsReq.\n"); - pStaService->StartWps(requestMsg->params.wpsConfig); + return WIFI_OPT_SUCCESS; } -void StaInterface::WifiStaCmdCancelWpsReq(const WifiRequestMsgInfo *requestMsg) +ErrCode StaInterface::CancelWps() { - if (requestMsg == nullptr) { - WIFI_LOGE("requestMsg is null\n"); + LOGD("Enter StaInterface::CancelWps.\n"); + if (pStaService->CancelWps() != WIFI_OPT_SUCCESS) { + LOGD("CancelWps failed.\n"); + return WIFI_OPT_FAILED; } - WIFI_LOGD("Enter StaInterface::WifiStaCmdCancelWpsReq.\n"); - pStaService->CancelWps(); + return WIFI_OPT_SUCCESS; } -void StaInterface::WifiStaCmdConnectManagerReq(const WifiRequestMsgInfo *requestMsg) +ErrCode StaInterface::ConnectivityManager(const std::vector &scanInfos) { - WIFI_LOGI("Connection management information transferred successfully.\n"); - pStaService->SyncLinkInfo(requestMsg->params.scanInfos); - pStaService->AutoConnectService(requestMsg->params.scanInfos); + LOGI("Enter Connection management.\n"); + if (pStaService->AutoConnectService(scanInfos) != WIFI_OPT_SUCCESS) { + LOGD("ConnectivityManager failed.\n"); + return WIFI_OPT_FAILED; + } + return WIFI_OPT_SUCCESS; } -void StaInterface::WifiStaCmdSetCountryCodeReq(const WifiRequestMsgInfo *requestMsg) +ErrCode StaInterface::SetCountryCode(const std::string &countryCode) { - if (requestMsg == nullptr) { - WIFI_LOGE("requestMsg is null\n"); + LOGD("Enter StaInterface::SetCountryCode.\n"); + if (pStaService->SetCountryCode(countryCode) != WIFI_OPT_SUCCESS) { + LOGD("SetCountryCode failed.\n"); + return WIFI_OPT_FAILED; } - WIFI_LOGD("Enter StaInterface::WifiStaCmdSetCountryCodeReq.\n"); - pStaService->SetCountryCode(); + return WIFI_OPT_SUCCESS; +} + +ErrCode StaInterface::RegisterStaServiceCallback(const StaServiceCallback &callbacks) +{ + LOGD("Enter StaInterface::RegisterStaServiceCallback.\n"); + staCallback = callbacks; + return WIFI_OPT_SUCCESS; } -DECLARE_INIT_SERVICE(StaInterface); } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.h index 75cd9cb42..77bfd1147 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.h @@ -16,111 +16,154 @@ #ifndef OHOS_WIFI_STA_INTERFACE_H #define OHOS_WIFI_STA_INTERFACE_H -#include "base_service.h" +#include "ista_service.h" #include "sta_service.h" namespace OHOS { namespace Wifi { -class StaInterface : BaseService { +class StaInterface : public IStaService { public: StaInterface(); - ~StaInterface() override; - using staHandleFunc = void (StaInterface::*)(const WifiRequestMsgInfo *requestMsg); - using StaHandleFuncMap = std::map; + virtual ~StaInterface() override; + /** - * @Description:The initialization function of Sta + * @Description Enable wifi * - * @param mqUp - The uplink Messagequeue used to return results - * @Return: 0 - success -1 - failed + * @Output: Return operating results to Interface Service after enable wifi + successfully through callback function instead of returning + result immediately. + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - int Init(WifiMessageQueue *mqUp) override; + virtual ErrCode EnableWifi() override; /** - * @Description:Receive Message from Sta and then process distributively. + * @Description Disable wifi * - * @param requestMsg - Request Message - * @Return: 0 - success -1 - failed + * @Output: Return operating results to Interface Service after enable wifi + successfully through callback function instead of returning + result immediately. + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - int PushMsg(WifiRequestMsgInfo *msg) override; + virtual ErrCode DisableWifi() override; /** - * @Description:Stop function of Sta. + * @Description Connect to a new network * - * @Return: 0 - success -1 - failed + * @param config - the configuration of network which is going to connect.(in) + * @Output: Return operating results to Interface Service after enable wifi + successfully through callback function instead of returning + result immediately. + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - int UnInit(void) override; - -private: + virtual ErrCode ConnectToNetwork(int networkId) override; + /** + * @Description Connecting to a specified network. + * + * @param networkId - interior saved network index.(in) + * @Output: Return operating results to Interface Service after enable wifi + successfully through callback function instead of returning + result immediately. + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode ConnectToDevice(const WifiDeviceConfig &config) override; + /** + * @Description Disconnect to the network + * + * @Output: Return operating results to Interface Service after enable wifi + successfully through callback function instead of returning + result immediately. + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode Disconnect() override; + /** + * @Description ReAssociate network + * + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode ReAssociate() override; /** - * @Description: Initialize StaHandleMap. + * @Description Add a network to config * - * @Return: 0 - success -1 - failed + * @param config -The Network info(in) + * @Return success: networkId fail: -1 */ - int InitStaHandleMap(); + virtual int AddDeviceConfig(const WifiDeviceConfig &config) override; /** - * @Description: Start connection process when receive the connecting request. + * @Description Update a network to config * - * @param requestMsg - request message + * @param config -The Network info(in) + * @Return success: networkId fail: -1 */ - void WifiStaCmdConnectReq(const WifiRequestMsgInfo *requestMsg); + virtual int UpdateDeviceConfig(const WifiDeviceConfig &config) override; /** - * @Description: Start reconnection process when receive the reconnecting request. + * @Description Remove network * - * @param requestMsg - request message + * @param networkId -The NetworkId is going to be removed.(in) + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - void WifiStaCmdReconnectReq(const WifiRequestMsgInfo *requestMsg); + virtual ErrCode RemoveDevice(int networkId) override; /** - * @Description: Start reassociation process when receive the reassociating request. + * @Description Remove all network configs * - * @param requestMsg - request message + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - void WifiStaCmdReassociateReq(const WifiRequestMsgInfo *requestMsg); + virtual ErrCode RemoveAllDevice() override; /** - * @Description: Start disconnection process when receive the disconnecting request. + * @Description Enable WI-FI device configuration * - * @param requestMsg - request message + * @param networkId - The NetworkId (in) + * @param networkId - if set true, disable other device configuration (in) + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - void WifiStaCmdDisconnectReq(const WifiRequestMsgInfo *requestMsg); + virtual ErrCode EnableDeviceConfig(int networkId, bool attemptEnable) override; /** - * @Description: Start the process of removing device configuration - when receive the request of removing device configuration. + * @Description Disable WI-FI device configuration * - * @param requestMsg - request message + * @param networkId - device configuration's network id + * @return ErrCode - success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - void WifiStaCmdRemoveDeviceReq(const WifiRequestMsgInfo *requestMsg); + virtual ErrCode DisableDeviceConfig(int networkId) override; /** - * @Description: Start the process of removing all device configuration - when receive the request of removing device configuration. + * @Description Start WPS Connection * - * @param requestMsg - request message + * @Output: Return operating results to Interface Service after enable wifi + successfully through callback function instead of returning + result immediately. + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - void WifiStaCmdRemoveAllDeviceReq(const WifiRequestMsgInfo *requestMsg); + virtual ErrCode StartWps(const WpsConfig &config) override; /** - * @Description: Start Wps connection process when receive the wps connecting request. + * @Description Close WPS Connection * - * @param requestMsg - request message + * @Output: Return operating results to Interface Service after enable wifi + successfully through callback function instead of returning + result immediately. + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - void WifiStaCmdStartWpsReq(const WifiRequestMsgInfo *requestMsg); + virtual ErrCode CancelWps() override; /** - * @Description: Start Wps connection process when receive the wps connecting request. + * @Description ConnectivityManager process scan results. * - * @param requestMsg - request message + * @Output: Return operating results to Interface Service after enable wifi + successfully through callback function instead of returning + result immediately. + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - void WifiStaCmdCancelWpsReq(const WifiRequestMsgInfo *requestMsg); + virtual ErrCode ConnectivityManager(const std::vector &scanInfos) override; /** - * @Description: Start the process of StaAutoConnectService when - receive the opening StaAutoConnectService request. + * @Description Set country code * - * @param requestMsg - request message + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - void WifiStaCmdConnectManagerReq(const WifiRequestMsgInfo *requestMsg); + virtual ErrCode SetCountryCode(const std::string &countryCode) override; /** - * @Description: Start the process of setting countrycode when receive setting countrycode request. + * @Description Register sta callback function * - * @param requestMsg - request message + * @param callbacks - Callback function pointer storage structure + * @return ErrCode - success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - void WifiStaCmdSetCountryCodeReq(const WifiRequestMsgInfo *requestMsg); + virtual ErrCode RegisterStaServiceCallback(const StaServiceCallback &callbacks) override; private: - StaHandleFuncMap staHandleFuncMap; + StaServiceCallback staCallback; StaService *pStaService; }; } // namespace Wifi diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.cpp index 47bdf1626..45d96eadd 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.cpp @@ -1,3 +1,17 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ /* * Copyright (C) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -38,12 +52,12 @@ StaSavedDeviceAppraisal::~StaSavedDeviceAppraisal() } ErrCode StaSavedDeviceAppraisal::DeviceAppraisals( - WifiDeviceConfig &electedDevice, std::vector &scanInfos, WifiLinkedInfo &info) + WifiDeviceConfig &electedDevice, std::vector &scanInfos, WifiLinkedInfo &info) { WIFI_LOGI("Enter StaSavedDeviceAppraisal::DeviceAppraisals.\n"); int highestScore = 0; int sign = 0; - WifiScanInfo scanInfoElected; + InterScanInfo scanInfoElected; scanInfoElected.rssi = VALUE_LIMIT_MIN_RSSI; for (auto scanInfo : scanInfos) { @@ -106,7 +120,7 @@ bool StaSavedDeviceAppraisal::WhetherSkipDevice(WifiDeviceConfig &device) } void StaSavedDeviceAppraisal::AppraiseDeviceQuality( - int &score, WifiScanInfo &scanInfo, WifiDeviceConfig &device, WifiLinkedInfo &info) + int &score, InterScanInfo &scanInfo, WifiDeviceConfig &device, WifiLinkedInfo &info) { WIFI_LOGI("Enter StaSavedDeviceAppraisal::AppraiseDeviceQuality.\n"); int rssi = scanInfo.rssi; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.h index 9ee8ecf14..456eae924 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.h @@ -36,7 +36,7 @@ public: * @Return: Configuration of the selected device; Null if no devices are available in this category */ ErrCode DeviceAppraisals( - WifiDeviceConfig &electedDevice, std::vector &scanInfos, WifiLinkedInfo &info) override; + WifiDeviceConfig &electedDevice, std::vector &scanInfos, WifiLinkedInfo &info) override; private: static const int MAX_SIGNAL_BAR_NUM = 5; @@ -57,7 +57,7 @@ private: * @param info - Connection information.(in) * @param score - score points.(out) */ - void AppraiseDeviceQuality(int &score, WifiScanInfo &scanInfo, WifiDeviceConfig &device, WifiLinkedInfo &info); + void AppraiseDeviceQuality(int &score, InterScanInfo &scanInfo, WifiDeviceConfig &device, WifiLinkedInfo &info); /** * @Description Signal strength converted to grids. * diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.cpp index 79214bd33..f9299f737 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.cpp @@ -15,13 +15,14 @@ #include "sta_service.h" #include "wifi_logger.h" #include "sta_define.h" +#include "sta_service_callback.h" DEFINE_WIFILOG_LABEL("StaService"); namespace OHOS { namespace Wifi { StaService::StaService() - : pStaStateMachine(nullptr), pStaMonitor(nullptr), msgQueueUp(nullptr), pStaAutoConnectService(nullptr) + : pStaStateMachine(nullptr), pStaMonitor(nullptr), pStaAutoConnectService(nullptr) {} StaService::~StaService() @@ -44,17 +45,9 @@ StaService::~StaService() } } -ErrCode StaService::InitStaService(WifiMessageQueue *pMsgQueueUp) +ErrCode StaService::InitStaService(const StaServiceCallback &callbacks) { WIFI_LOGI("Enter StaService::InitStaService.\n"); - - msgQueueUp = pMsgQueueUp; - - if (msgQueueUp == nullptr) { - WIFI_LOGE("msgQueueUp is null.\n"); - return WIFI_OPT_FAILED; - } - pStaStateMachine = new (std::nothrow) StaStateMachine(); if (pStaStateMachine == nullptr) { WIFI_LOGE("Alloc pStaStateMachine failed.\n"); @@ -66,7 +59,8 @@ ErrCode StaService::InitStaService(WifiMessageQueue *pMsgQu return WIFI_OPT_FAILED; } - pStaStateMachine->SetResponseQueue(msgQueueUp); + RegisterStaServiceCallback(callbacks); + pStaMonitor = new (std::nothrow) StaMonitor(); if (pStaMonitor == nullptr) { WIFI_LOGE("Alloc pStaMonitor failed.\n"); @@ -94,15 +88,6 @@ ErrCode StaService::InitStaService(WifiMessageQueue *pMsgQu return WIFI_OPT_SUCCESS; } -void StaService::NotifyResult(int msgCode) const -{ - WIFI_LOGI("Enter StaService::NotifyResult.\n"); - WifiResponseMsgInfo notifyMsg; - notifyMsg.msgCode = msgCode; - msgQueueUp->Push(notifyMsg); - return; -} - ErrCode StaService::EnableWifi() const { WIFI_LOGI("Enter StaService::EnableWifi.\n"); @@ -117,78 +102,66 @@ ErrCode StaService::DisableWifi() const return WIFI_OPT_SUCCESS; } -ErrCode StaService::ConnectToDevice(const WifiDeviceConfig &config) const +int StaService::AddDeviceConfig(const WifiDeviceConfig &config) const { - WIFI_LOGI("Enter StaService::ConnectToDevice.\n"); - int networkId = -1; + LOGI("Enter StaService::AddDeviceConfig.\n"); + int netWorkId = INVALID_NETWORK_ID; WifiDeviceConfig tempDeviceConfig; - if (WifiSettings::GetInstance().GetDeviceConfig(config.ssid, DEVICE_CONFIG_INDEX_SSID, tempDeviceConfig) == 0) { - WIFI_LOGD("A network with the same name already exists in the configuration center!\n"); - networkId = tempDeviceConfig.networkId; - tempDeviceConfig = config; - tempDeviceConfig.networkId = networkId; + if (WifiSettings::GetInstance().GetDeviceConfig(config.ssid, config.keyMgmt, tempDeviceConfig) == 0) { + LOGD("A network with the same name already exists in the configuration center!\n"); + netWorkId = tempDeviceConfig.networkId; pStaAutoConnectService->EnableOrDisableBssid(config.bssid, true, 0); } else { - WIFI_LOGD("Connect to a new network\n"); - if (WifiStaHalInterface::GetInstance().GetNextNetworkId(networkId) != WIFI_IDL_OPT_OK) { - WIFI_LOGE("StaService::ConnectToDevice GetNextNetworkId failed!"); - return WIFI_OPT_FAILED; + if (WifiStaHalInterface::GetInstance().GetNextNetworkId(netWorkId) != WIFI_IDL_OPT_OK) { + LOGE("StaService::AddDeviceConfig GetNextNetworkId failed!"); + return netWorkId; } - WIFI_LOGI("StaService::ConnectToDevice GetNextNetworkId succeed!"); - tempDeviceConfig = config; - tempDeviceConfig.networkId = networkId; + LOGD("StaService::AddDeviceConfig Add a new network and GetNextNetworkId() succeed!"); + } + tempDeviceConfig = config; + tempDeviceConfig.networkId = netWorkId; + + /* Setting the network to wpa */ + if(pStaStateMachine->ConvertDeviceCfg(tempDeviceConfig) != WIFI_OPT_SUCCESS) { + LOGE("StaService::AddDeviceConfig ConvertDeviceCfg failed!"); + return INVALID_NETWORK_ID; } /* Add the new network to WifiSettings. */ WifiSettings::GetInstance().AddDeviceConfig(tempDeviceConfig); WifiSettings::GetInstance().SyncDeviceConfig(); - WIFI_LOGI("keyMgmt is %s", config.keyMgmt.c_str()); - /* Setting the network to wpa */ - WifiIdlDeviceConfig idlConfig; - idlConfig.networkId = networkId; - idlConfig.ssid = config.ssid; - idlConfig.bssid = config.bssid; - idlConfig.psk = config.preSharedKey; - idlConfig.keyMgmt = config.keyMgmt; - idlConfig.priority = config.priority; - idlConfig.scanSsid = config.hiddenSSID ? 1 : 0; - idlConfig.eap = config.wifiEapConfig.eap; - idlConfig.identity = config.wifiEapConfig.identity; - idlConfig.password = config.wifiEapConfig.password; - idlConfig.wepKeyIdx = config.wepTxKeyIndex; - for (int i = 0; i < MAX_WEPKEYS_SIZE; i++) { - idlConfig.wepKeys[i] = config.wepKeys[i]; - } + return netWorkId; +} + +int StaService::UpdateDeviceConfig(const WifiDeviceConfig &config) const +{ + return AddDeviceConfig(config); +} - if (WifiStaHalInterface::GetInstance().SetDeviceConfig(networkId, idlConfig) != WIFI_IDL_OPT_OK) { - WIFI_LOGE("StaService::ConnectToDevice SetDeviceConfig failed!"); +ErrCode StaService::ConnectToDevice(const WifiDeviceConfig &config) const +{ + LOGI("Enter StaService::ConnectToDevice.\n"); + int netWorkId = AddDeviceConfig(config); + if(netWorkId == INVALID_NETWORK_ID) { + LOGD("StaService::ConnectTo AddDeviceConfig failed!"); return WIFI_OPT_FAILED; } - WIFI_LOGI("StaService::ConnectToDevice SetDeviceConfig succeed!"); - pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_CONNECT_NETWORK, networkId, NETWORK_SELECTED_BY_THE_USER); + LOGD("StaService::ConnectTo AddDeviceConfig succeed!"); + pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_CONNECT_NETWORK, netWorkId, NETWORK_SELECTED_BY_THE_USER); return WIFI_OPT_SUCCESS; } ErrCode StaService::ConnectToNetwork(int networkId) const { - WIFI_LOGI("Enter StaService::ConnectToNetwork, networkId is %{public}d.\n", networkId); - + LOGI("Enter StaService::ConnectToNetwork, networkId is %d.\n", networkId); WifiDeviceConfig config; - int ret = WifiSettings::GetInstance().GetDeviceConfig(networkId, config); - if (ret != 0) { - WIFI_LOGE("WifiDeviceConfig is null!"); + if (WifiSettings::GetInstance().GetDeviceConfig(networkId, config) != 0) { + LOGE("WifiDeviceConfig is null!"); return WIFI_OPT_FAILED; } pStaAutoConnectService->EnableOrDisableBssid(config.bssid, true, 0); pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_CONNECT_SAVED_NETWORK, networkId, NETWORK_SELECTED_BY_THE_USER); - - return WIFI_OPT_SUCCESS; -} - -ErrCode StaService::ReConnect() const -{ - WIFI_LOGI("Enter StaService::ReConnect.\n"); return WIFI_OPT_SUCCESS; } @@ -201,8 +174,24 @@ ErrCode StaService::ReAssociate() const ErrCode StaService::RemoveDevice(int networkId) const { - WIFI_LOGI("Enter StaService::RemoveDevice.\n"); - pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_REMOVE_DEVICE_CONFIG, networkId); + LOGD("Enter StaService::RemoveDeviceConfigProcess.\n"); + /* Remove network configuration. */ + if (WifiStaHalInterface::GetInstance().RemoveDevice(networkId) != WIFI_IDL_OPT_OK) { + LOGE("RemoveDeviceConfig() failed!"); + return WIFI_OPT_FAILED; + } + if (WifiStaHalInterface::GetInstance().SaveDeviceConfig() != WIFI_IDL_OPT_OK) { + LOGW("RemoveDeviceConfig-SaveDeviceConfig() failed!"); + } else { + LOGD("RemoveDeviceConfig-SaveDeviceConfig() succeed!"); + } + WifiDeviceConfig config; + if (WifiSettings::GetInstance().GetDeviceConfig(networkId, config) == 0) { + pStaAutoConnectService->EnableOrDisableBssid(config.bssid, true, 0); + } + /* Remove network configuration directly without notification to InterfaceService. */ + WifiSettings::GetInstance().RemoveDevice(networkId); + WifiSettings::GetInstance().SyncDeviceConfig(); return WIFI_OPT_SUCCESS; } @@ -213,6 +202,30 @@ ErrCode StaService::RemoveAllDevice() const return WIFI_OPT_SUCCESS; } +ErrCode StaService::EnableDeviceConfig(int networkId, bool attemptEnable) const +{ + WIFI_LOGD("Enter StaService::EnableDeviceConfig! networkid is %{public}d", networkId); + + /* Update wifi status. */ + if (WifiSettings::GetInstance().SetDeviceState(networkId, (int)WifiDeviceConfigStatus::ENABLED, attemptEnable) < + 0) { + WIFI_LOGE("Enable device config failed!"); + return WIFI_OPT_FAILED; + } + return WIFI_OPT_SUCCESS; +} + +ErrCode StaService::DisableDeviceConfig(int networkId) const +{ + WIFI_LOGD("Enter StaService::DisableDeviceConfig.networkid is %{public}d", networkId); + + if (WifiSettings::GetInstance().SetDeviceState(networkId, (int)WifiDeviceConfigStatus::DISABLED) < 0) { + WIFI_LOGE("Disable device config failed!"); + return WIFI_OPT_FAILED; + } + return WIFI_OPT_SUCCESS; +} + ErrCode StaService::Disconnect() const { WIFI_LOGI("Enter StaService::Disconnect.\n"); @@ -244,25 +257,35 @@ ErrCode StaService::CancelWps() const return WIFI_OPT_SUCCESS; } -ErrCode StaService::SetCountryCode() const +ErrCode StaService::SetCountryCode(const std::string &countryCode) const { - WIFI_LOGI("Enter StaService::SetCountryCode.\n"); - pStaStateMachine->SetCountryCode(); + LOGI("Enter StaService::SetCountryCode, countryCode=[%s]!", countryCode.c_str()); + if (WifiSupplicantHalInterface::GetInstance().WpaSetCountryCode(countryCode) != WIFI_IDL_OPT_OK) { + LOGE("WpaSetCountryCode() failed!"); + return WIFI_OPT_FAILED; + } + LOGI("WpaSetCountryCode() succeed!"); + WifiSettings::GetInstance().SetCountryCode(countryCode); return WIFI_OPT_SUCCESS; } -ErrCode StaService::AutoConnectService(const std::vector &scanInfos) +ErrCode StaService::AutoConnectService(const std::vector &scanInfos) { WIFI_LOGI("Enter StaService::AutoConnectService.\n"); pStaAutoConnectService->OnScanInfosReadyHandler(scanInfos); + pStaStateMachine->SyncLinkInfo(scanInfos); return WIFI_OPT_SUCCESS; } -ErrCode StaService::SyncLinkInfo(const std::vector &scanInfos) +void StaService::RegisterStaServiceCallback(const StaServiceCallback &callbacks) const { - WIFI_LOGI("Enter StaService::SyncLinkInfo.\n"); - pStaStateMachine->SyncLinkInfo(scanInfos); - return WIFI_OPT_SUCCESS; + LOGI("Enter StaService::RegisterStaServiceCallback."); + if (pStaStateMachine == nullptr) { + LOGE("pStaStateMachine is null.\n"); + return; + } + pStaStateMachine->RegisterStaServiceCallback(callbacks); } + } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.h index 3889e9218..2009c7382 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.h @@ -30,32 +30,25 @@ public: /** * @Description Initialize StaService module. * - * @param pMsgQueueUp - the uplink Message queue used to return results.(in) - * @Return success: WIFI_OPT_SUCCESS failed: WIFI_OPT_FAILED + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - ErrCode InitStaService(WifiMessageQueue *pMsgQueueUp); - /** - * @Description Notify the results code to Interface Service. - * - * @param msgCode - operating results code.(in) - */ - void NotifyResult(int msgCode) const; + ErrCode InitStaService(const StaServiceCallback &callbacks); /** * @Description Enable wifi * * @Output: Return operating results to Interface Service after enable wifi - successfully through NotifyResult function instead of returning + successfully through callback function instead of returning result immediately. - * @Return success: WIFI_OPT_SUCCESS failed: WIFI_OPT_FAILED + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ ErrCode EnableWifi() const; /** * @Description Disable wifi * * @Output: Return operating results to Interface Service after enable wifi - successfully through NotifyResult function instead of returning + successfully through callback function instead of returning result immediately. - * @Return success: WIFI_OPT_SUCCESS failed: WIFI_OPT_FAILED + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ ErrCode DisableWifi() const; /** @@ -63,9 +56,9 @@ public: * * @param config - the configuration of network which is going to connect.(in) * @Output: Return operating results to Interface Service after enable wifi - successfully through NotifyResult function instead of returning + successfully through callback function instead of returning result immediately. - * @Return success: WIFI_OPT_SUCCESS failed: WIFI_OPT_FAILED + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ ErrCode ConnectToDevice(const WifiDeviceConfig &config) const; /** @@ -73,84 +66,113 @@ public: * * @param networkId - interior saved network index.(in) * @Output: Return operating results to Interface Service after enable wifi - successfully through NotifyResult function instead of returning + successfully through callback function instead of returning result immediately. - * @Return success: WIFI_OPT_SUCCESS failed: WIFI_OPT_FAILED + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ ErrCode ConnectToNetwork(int networkId) const; /** - * @Description Reconnect to currently active network. + * @Description Disconnect to the network * - * @Return success: WIFI_OPT_SUCCESS failed: WIFI_OPT_FAILED + * @Output: Return operating results to Interface Service after enable wifi + successfully through callback function instead of returning + result immediately. + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - ErrCode ReConnect() const; + ErrCode Disconnect() const; /** * @Description ReAssociate network * - * @Return success: WIFI_OPT_SUCCESS failed: WIFI_OPT_FAILED + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ ErrCode ReAssociate() const; + + /** + * @Description Update a network to config + * + * @param config -The Network info(in) + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + int AddDeviceConfig(const WifiDeviceConfig &config) const; /** - * @Description Remove network + * @Description Update a network to config. + * + * @param config -The Network info(in) + * @Return success: networkId fail: -1 + */ + int UpdateDeviceConfig(const WifiDeviceConfig &config) const; + /** + * @Description Remove network config. * * @param networkId -The NetworkId is going to be removed.(in) - * @Return success: WIFI_OPT_SUCCESS failed: WIFI_OPT_FAILED + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ ErrCode RemoveDevice(int networkId) const; /** - * @Description Remove all network + * @Description Remove all network configs. * - * @Return success: WIFI_OPT_SUCCESS failed: WIFI_OPT_FAILED + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ ErrCode RemoveAllDevice() const; /** - * @Description Disconnect to the network + * @Description Enable WI-FI device Configuration. * - * @Output: Return operating results to Interface Service after enable wifi - successfully through NotifyResult function instead of returning - result immediately. - * @Return success: WIFI_OPT_SUCCESS failed: WIFI_OPT_FAILED + * @param networkId - The NetworkId (in) + * @param networkId - if set true, disable other device config (in) + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - ErrCode Disconnect() const; + ErrCode EnableDeviceConfig(int networkId, bool attemptEnable) const; + /** + * @Description Disable WI-FI device Configuration. + * + * @param networkId - device Configuration's network id + * @return ErrCode - success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + ErrCode DisableDeviceConfig(int networkId) const; /** * @Description Start WPS Connection * * @Output: Return operating results to Interface Service after enable wifi - successfully through NotifyResult function instead of returning + successfully through callback function instead of returning result immediately. - * @Return success: WIFI_OPT_SUCCESS failed: WIFI_OPT_FAILED + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ ErrCode StartWps(const WpsConfig &config) const; /** * @Description Close WPS Connection * * @Output: Return operating results to Interface Service after enable wifi - successfully through NotifyResult function instead of returning + successfully through callback function instead of returning result immediately. - * @Return success: WIFI_OPT_SUCCESS failed: WIFI_OPT_FAILED + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ ErrCode CancelWps() const; /** * @Description Set country code * - * @Return success: WIFI_OPT_SUCCESS failed: WIFI_OPT_FAILED + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - ErrCode SetCountryCode() const; + ErrCode SetCountryCode(const std::string &countryCode) const; /** - * @Description StaAutoConnectService process scan results. + * @Description ConnectivityManager process scan results. * * @Output: Return operating results to Interface Service after enable wifi - successfully through NotifyResult function instead of returning + successfully through callback function instead of returning result immediately. - * @Return success: WIFI_OPT_SUCCESS failed: WIFI_OPT_FAILED + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + ErrCode AutoConnectService(const std::vector &scanInfos); + /** + * @Description Register sta callback function + * + * @param callbacks - Callback function pointer storage structure */ - ErrCode AutoConnectService(const std::vector &scanInfos); - ErrCode SyncLinkInfo(const std::vector &scanInfos); + void RegisterStaServiceCallback(const StaServiceCallback &callbacks) const; + private: StaStateMachine *pStaStateMachine; StaMonitor *pStaMonitor; - WifiMessageQueue *msgQueueUp; StaAutoConnectService *pStaAutoConnectService; }; } // namespace Wifi diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service_callback.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service_callback.h new file mode 100644 index 000000000..73f958246 --- /dev/null +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service_callback.h @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef OHOS_STASERVICE_CALLBACK_H +#define OHOS_STASERVICE_CALLBACK_H + +#include +#include "wifi_internal_msg.h" +#include "wifi_msg.h" + +namespace OHOS { +namespace Wifi { +class StaServiceCallback { +public: + std::function OnStaOpenRes; + std::function OnStaCloseRes; + std::function OnStaConnChanged; + std::function OnWpsChanged; + std::function OnStaStreamChanged; + std::function OnStaRssiLevelChanged; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.cpp index fd361729c..9da0c442f 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.cpp @@ -1,3 +1,17 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ /* * Copyright (C) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -51,11 +65,11 @@ StaStateMachine::StaStateMachine() isWpsConnect(IsWpsConnected::WPS_INVALID), getIpSucNum(0), getIpFailNum(0), + isRoam(false), pDhcpService(nullptr), pDhcpResultNotify(nullptr), pNetSpeed(nullptr), pNetcheck(nullptr), - msgQueueUp(nullptr), pRootState(nullptr), pInitState(nullptr), pWpaStartingState(nullptr), @@ -211,12 +225,6 @@ void StaStateMachine::InitLastWifiLinkedInfo() lastLinkedInfo.detailedState = DetailedState::DISCONNECTED; } -void StaStateMachine::SetResponseQueue(WifiMessageQueue *pMsgQueueUp) -{ - msgQueueUp = pMsgQueueUp; - return; -} - void StaStateMachine::BuildStateTree() { StatePlus(pRootState, nullptr); @@ -234,6 +242,12 @@ void StaStateMachine::BuildStateTree() StatePlus(pWpaStoppingState, pRootState); } +void StaStateMachine::RegisterStaServiceCallback(const StaServiceCallback &callbacks) +{ + LOGI("RegisterStaServiceCallback"); + staCallback = callbacks; +} + /* --------------------------- state machine root state ------------------------------ */ StaStateMachine::RootState::RootState() : State("RootState") {} @@ -321,6 +335,36 @@ bool StaStateMachine::InitState::ExecuteStateMsg(InternalMessage *msg) return ret; } +ErrCode StaStateMachine::ConvertDeviceCfg(const WifiDeviceConfig &config) const +{ + LOGI("Enter StaStateMachine::ConvertDeviceCfg.\n"); + WifiIdlDeviceConfig idlConfig; + idlConfig.networkId = config.networkId; + idlConfig.ssid = config.ssid; + idlConfig.bssid = config.bssid; + idlConfig.psk = config.preSharedKey; + idlConfig.keyMgmt = config.keyMgmt; + idlConfig.priority = config.priority; + idlConfig.scanSsid = config.hiddenSSID ? 1 : 0; + idlConfig.eap = config.wifiEapConfig.eap; + idlConfig.identity = config.wifiEapConfig.identity; + idlConfig.password = config.wifiEapConfig.password; + idlConfig.wepKeyIdx = config.wepTxKeyIndex; + for (int i = 0; i < MAX_WEPKEYS_SIZE; i++) { + idlConfig.wepKeys[i] = config.wepKeys[i]; + } + + if (WifiStaHalInterface::GetInstance().SetDeviceConfig(config.networkId, idlConfig) != WIFI_IDL_OPT_OK) { + LOGE("StaStateMachine::ConvertDeviceCfg SetDeviceConfig failed!"); + return WIFI_OPT_FAILED; + } + + if (WifiStaHalInterface::GetInstance().SaveDeviceConfig() != WIFI_IDL_OPT_OK) { + LOGW("StaStateMachine::ConvertDeviceCfg SaveDeviceConfig failed!"); + } + return WIFI_OPT_SUCCESS; +} + void StaStateMachine::StartWifiProcess() { int res = WifiStaHalInterface::GetInstance().StartWifi(); @@ -347,19 +391,17 @@ void StaStateMachine::StartWifiProcess() InitLastWifiLinkedInfo(); WifiSettings::GetInstance().SaveLinkedInfo(linkedInfo); - /* Notify the InterfaceService that wifi is enabled successfully. */ - NotifyResult(WifiInternalMsgCode::STA_OPEN_RES, static_cast(OperateResState::OPEN_WIFI_SUCCEED)); + /* callback the InterfaceService that wifi is enabled successfully. */ + staCallback.OnStaOpenRes(OperateResState::OPEN_WIFI_SUCCEED); /* The current state of StaStateMachine transfers to SeparatedState after * enable supplicant. */ SwitchState(pSeparatedState); - /* Set country code */ - SetCountryCode(); } else { /* Notify the InterfaceService that wifi is failed to enable wifi. */ - WIFI_LOGE("StartWifi failed, and errcode is %{public}d", res); - NotifyResult(WifiInternalMsgCode::STA_OPEN_RES, static_cast(OperateResState::OPEN_WIFI_FAILED)); - NotifyResult(WifiInternalMsgCode::STA_OPEN_RES, static_cast(OperateResState::OPEN_WIFI_DISABLED)); + LOGE("StartWifi failed, and errcode is %d", res); + staCallback.OnStaOpenRes(OperateResState::OPEN_WIFI_FAILED); + staCallback.OnStaOpenRes(OperateResState::OPEN_WIFI_DISABLED); } } @@ -478,6 +520,7 @@ void StaStateMachine::StopWifiProcess() } else { pDhcpService->StopDhcpClient(IF_NAME, true); } + isRoam = false; if (lastNetworkId != INVALID_NETWORK_ID) { if (statusId == static_cast(WifiDeviceConfigStatus::DISABLED)) { WIFI_LOGD("The network status is DISABLED:1.\n"); @@ -502,14 +545,14 @@ void StaStateMachine::StopWifiProcess() WifiErrorNo errorNo = WifiStaHalInterface::GetInstance().StopWifi(); if (errorNo == WIFI_IDL_OPT_OK) { /* Notify result to InterfaceService. */ - NotifyResult(WifiInternalMsgCode::STA_CLOSE_RES, static_cast(OperateResState::CLOSE_WIFI_SUCCEED)); + staCallback.OnStaCloseRes(OperateResState::CLOSE_WIFI_SUCCEED); WIFI_LOGD("Stop WifiProcess successfully!"); /* The current state of StaStateMachine transfers to InitState. */ SwitchState(pInitState); } else { - WIFI_LOGE("StopWifiProcess failed, and errcode is %{public}d", errorNo); - NotifyResult(WifiInternalMsgCode::STA_OPEN_RES, static_cast(OperateResState::CLOSE_WIFI_FAILED)); + LOGE("StopWifiProcess failed,and errcode is %d", errorNo); + staCallback.OnStaCloseRes(OperateResState::CLOSE_WIFI_FAILED); } } @@ -525,9 +568,10 @@ void StaStateMachine::RemoveDeviceConfigProcess(const InternalMessage *msg) WIFI_LOGD("Remove device config successfully!"); if (WifiStaHalInterface::GetInstance().SaveDeviceConfig() != WIFI_IDL_OPT_OK) { - WIFI_LOGE("RemoveDeviceConfig:SaveDeviceConfig failed!"); + WIFI_LOGW("RemoveDeviceConfig:SaveDeviceConfig failed!"); + } else { + WIFI_LOGD("RemoveDeviceConfig-SaveDeviceConfig successfully!"); } - WIFI_LOGD("RemoveDeviceConfig-SaveDeviceConfig successfully!"); } else { WIFI_LOGE("RemoveDeviceConfig failed!"); } @@ -546,7 +590,7 @@ void StaStateMachine::RemoveAllDeviceConfigProcess() WIFI_LOGD("Remove all device config successfully!"); if (WifiStaHalInterface::GetInstance().SaveDeviceConfig() != WIFI_IDL_OPT_OK) { - WIFI_LOGE("RemoveAllDeviceConfig:SaveDeviceConfig failed!"); + WIFI_LOGW("RemoveAllDeviceConfig:SaveDeviceConfig failed!"); } } else { WIFI_LOGE("RemoveAllDeviceConfig failed!"); @@ -685,23 +729,22 @@ void StaStateMachine::DealConnectToSelectedNetCmd(InternalMessage *msg) WIFI_LOGD("Connect() succeed!"); if (WifiStaHalInterface::GetInstance().SaveDeviceConfig() != WIFI_IDL_OPT_OK) { - WIFI_LOGE("SaveDeviceConfig() failed!"); + WIFI_LOGW("SaveDeviceConfig() failed!"); + } else { + WIFI_LOGD("SaveDeviceConfig() succeed!"); } - WIFI_LOGD("SaveDeviceConfig() succeed!"); - /* Update wifi status. */ WifiSettings::GetInstance().SetWifiState(static_cast(WifiState::ENABLING)); /* Save connection information. */ SaveLinkstate(ConnState::CONNECTING, DetailedState::CONNECTING); - /* Notify result to InterfaceService. */ - NotifyResult(WifiInternalMsgCode::STA_CONNECT_RES, static_cast(OperateResState::CONNECT_CONNECTING)); + /* Callback result to InterfaceService. */ + staCallback.OnStaConnChanged(OperateResState::CONNECT_CONNECTING, linkedInfo); StartTimer(static_cast(CMD_NETWORK_CONNECT_TIMEOUT), STA_NETWORK_CONNECTTING_DELAY); } else { WIFI_LOGE("Connect failed!"); - NotifyResult( - WifiInternalMsgCode::STA_CONNECT_RES, static_cast(OperateResState::CONNECT_SELECT_NETWORK_FAILED)); + staCallback.OnStaConnChanged(OperateResState::CONNECT_SELECT_NETWORK_FAILED, linkedInfo); } } else { WIFI_LOGE("EnableNetwork() failed!"); @@ -717,7 +760,7 @@ void StaStateMachine::DealConnectTimeOutCmd(InternalMessage *msg) DisableNetwork(linkedInfo.networkId); InitWifiLinkedInfo(); WifiSettings::GetInstance().SaveLinkedInfo(linkedInfo); - NotifyResult(WifiInternalMsgCode::STA_CONNECT_RES, static_cast(OperateResState::CONNECT_CONNECTING_TIMEOUT)); + staCallback.OnStaConnChanged(OperateResState::CONNECT_CONNECTING_TIMEOUT, linkedInfo); } void StaStateMachine::DealConnectionEvent(InternalMessage *msg) @@ -736,8 +779,8 @@ void StaStateMachine::DealConnectionEvent(InternalMessage *msg) SyncAllDeviceConfigs(); wpsState = SetupMethod::INVALID; } - /* Notify result to InterfaceService. */ - NotifyResult(WifiInternalMsgCode::STA_CONNECT_RES, static_cast(OperateResState::CONNECT_OBTAINING_IP)); + /* Callback result to InterfaceService. */ + staCallback.OnStaConnChanged(OperateResState::CONNECT_AP_CONNECTED, linkedInfo); /* The current state of StaStateMachine transfers to GetIpState. */ SwitchState(pGetIpState); @@ -758,6 +801,7 @@ void StaStateMachine::DealDisconnectEvent(InternalMessage *msg) } getIpSucNum = 0; getIpFailNum = 0; + isRoam = false; if (statusId == static_cast(WifiDeviceConfigStatus::DISABLED)) { WIFI_LOGD("The network status is DISABLED:1.\n"); WifiSettings::GetInstance().SetDeviceState(lastNetworkId, static_cast(WifiDeviceConfigStatus::DISABLED)); @@ -784,8 +828,8 @@ void StaStateMachine::DealDisconnectEvent(InternalMessage *msg) } else { WifiSettings::GetInstance().SaveLinkedInfo(linkedInfo); } - /* Notify result to InterfaceService. */ - NotifyResult(WifiInternalMsgCode::STA_DISCONNECT_RES, static_cast(OperateResState::DISCONNECT_DISCONNECTED)); + /* Callback result to InterfaceService. */ + staCallback.OnStaConnChanged(OperateResState::DISCONNECT_DISCONNECTED, linkedInfo); SwitchState(pSeparatedState); } @@ -797,7 +841,7 @@ void StaStateMachine::DealWpaWrongPskEvent(InternalMessage *msg) WIFI_LOGD("enter DealStartWpsCmd\n"); InitWifiLinkedInfo(); WifiSettings::GetInstance().SaveLinkedInfo(linkedInfo); - NotifyResult(WifiInternalMsgCode::STA_CONNECT_RES, static_cast(OperateResState::CONNECT_PASSWORD_WRONG)); + staCallback.OnStaConnChanged(OperateResState::CONNECT_PASSWORD_WRONG, linkedInfo); } void StaStateMachine::DealReassociateCmd(InternalMessage *msg) @@ -813,8 +857,8 @@ void StaStateMachine::DealReassociateCmd(InternalMessage *msg) WIFI_LOGD("the last time connect to network is %{public}d", lastConnectToNetworkTimer); if (WifiStaHalInterface::GetInstance().Reassociate() == WIFI_IDL_OPT_OK) { - /* Notify result to InterfaceService */ - NotifyResult(WifiInternalMsgCode::STA_REASSOCIATE_RES, static_cast(OperateResState::CONNECT_AP_CONNECTED)); + /* Callback result to InterfaceService */ + staCallback.OnStaConnChanged(OperateResState::CONNECT_AP_CONNECTED, linkedInfo); WIFI_LOGD("StaStateMachine::LinkState::ExecuteStateMsg ReAssociate successfully!"); } else { WIFI_LOGE("ReAssociate failed!"); @@ -867,27 +911,27 @@ void StaStateMachine::StartWpsMode(InternalMessage *msg) if (WifiStaHalInterface::GetInstance().StartWpsPbcMode(wpsParam) == WIFI_IDL_OPT_OK) { wpsState = wpsConfig.setup; WIFI_LOGD("StartWpsPbcMode() succeed!"); - /* Notify result to InterfaceService. */ - NotifyResult(WifiInternalMsgCode::STA_START_WPS_RES, static_cast(WpsStartState::START_PBC_SUCCEED)); + /* Callback result to InterfaceService. */ + staCallback.OnWpsChanged(WpsStartState::START_PBC_SUCCEED, pinCode); SwitchState(pWpsState); } else { - WIFI_LOGE("StartWpsPbcMode() failed!"); - NotifyResult(WifiInternalMsgCode::STA_START_WPS_RES, static_cast(WpsStartState::START_PBC_FAILED)); + LOGE("StartWpsPbcMode() failed!"); + staCallback.OnWpsChanged(WpsStartState::START_PBC_FAILED, pinCode); } } else if (wpsConfig.setup == SetupMethod::DISPLAY) { if (WifiStaHalInterface::GetInstance().StartWpsPinMode(wpsParam, pinCode) == WIFI_IDL_OPT_OK) { wpsState = wpsConfig.setup; - /* Notify result to InterfaceService. */ - NotifyResult(WifiInternalMsgCode::STA_START_WPS_RES, static_cast(WpsStartState::START_PIN_SUCCEED)); + /* Callback result to InterfaceService. */ + staCallback.OnWpsChanged(WpsStartState::START_PIN_SUCCEED, pinCode); WIFI_LOGD("StartWpsPinMode() succeed! pincode: %d", pinCode); SwitchState(pWpsState); } else { WIFI_LOGE("StartWpsPinMode() failed!"); - NotifyResult(WifiInternalMsgCode::STA_START_WPS_RES, static_cast(WpsStartState::START_PIN_FAILED)); + staCallback.OnWpsChanged(WpsStartState::START_PIN_FAILED, pinCode); } } else { WIFI_LOGE("Start Wps failed!"); - NotifyResult(WifiInternalMsgCode::STA_START_WPS_RES, static_cast(WpsStartState::START_WPS_FAILED)); + staCallback.OnWpsChanged(WpsStartState::START_WPS_FAILED, pinCode); } } @@ -921,8 +965,8 @@ void StaStateMachine::DealWpsConnectTimeOutEvent(InternalMessage *msg) WIFI_LOGD("Wps Time out!"); DealCancelWpsCmd(msg); - /* Notify InterfaceService that WPS time out. */ - NotifyResult(WifiInternalMsgCode::STA_START_WPS_RES, static_cast(WpsStartState::WPS_TIME_OUT)); + /* Callback InterfaceService that WPS time out. */ + staCallback.OnWpsChanged(WpsStartState::WPS_TIME_OUT, pinCode); SwitchState(pSeparatedState); } @@ -936,11 +980,11 @@ void StaStateMachine::DealCancelWpsCmd(InternalMessage *msg) isWpsConnect = IsWpsConnected::WPS_INVALID; if (WifiStaHalInterface::GetInstance().StopWps() == WIFI_IDL_OPT_OK) { WIFI_LOGI("CancelWps succeed!"); - /* Notify result to InterfaceService that stop Wps connection successfully. */ + /* Callback result to InterfaceService that stop Wps connection successfully. */ if (wpsState == SetupMethod::PBC) { - NotifyResult(WifiInternalMsgCode::STA_CANCEL_WPS_RES, static_cast(WpsStartState::STOP_PBC_SUCCEED)); + staCallback.OnWpsChanged(WpsStartState::STOP_PBC_SUCCEED, pinCode); } else if (wpsState == SetupMethod::DISPLAY) { - NotifyResult(WifiInternalMsgCode::STA_CANCEL_WPS_RES, static_cast(WpsStartState::STOP_PIN_SUCCEED)); + staCallback.OnWpsChanged(WpsStartState::STOP_PIN_SUCCEED, pinCode); } if (wpsState != SetupMethod::INVALID) { wpsState = SetupMethod::INVALID; @@ -949,9 +993,10 @@ void StaStateMachine::DealCancelWpsCmd(InternalMessage *msg) if (WifiStaHalInterface::GetInstance().EnableNetwork(lastNetworkId) == WIFI_IDL_OPT_OK) { WIFI_LOGI("EnableNetwork success! networkId is %{public}d", lastNetworkId); if (WifiStaHalInterface::GetInstance().SaveDeviceConfig() != WIFI_IDL_OPT_OK) { - WIFI_LOGE("SaveDeviceConfig failed!"); + WIFI_LOGW("SaveDeviceConfig failed!"); + } else { + WIFI_LOGI("SaveDeviceConfig success!"); } - WIFI_LOGI("SaveDeviceConfig success!"); } else { WIFI_LOGE("EnableNetwork failed"); } @@ -959,9 +1004,9 @@ void StaStateMachine::DealCancelWpsCmd(InternalMessage *msg) } else { WIFI_LOGE("CancelWps failed!"); if (wpsState == SetupMethod::PBC) { - NotifyResult(WifiInternalMsgCode::STA_CANCEL_WPS_RES, static_cast(WpsStartState::STOP_PBC_FAILED)); + staCallback.OnWpsChanged(WpsStartState::STOP_PBC_FAILED, pinCode); } else if (wpsState == SetupMethod::DISPLAY) { - NotifyResult(WifiInternalMsgCode::STA_CANCEL_WPS_RES, static_cast(WpsStartState::STOP_PIN_FAILED)); + staCallback.OnWpsChanged(WpsStartState::STOP_PIN_FAILED, pinCode); } } SwitchState(pSeparatedState); @@ -1052,7 +1097,7 @@ void StaStateMachine::OnNetworkConnectionEvent(int networkId, std::string bssid) SendMessage(msg); } -void StaStateMachine::SyncLinkInfo(const std::vector &scanInfos) +void StaStateMachine::SyncLinkInfo(const std::vector &scanInfos) { WIFI_LOGI("Enter StaStateMachine::SyncLinkInfo.\n"); if (scanInfos.empty()) { @@ -1132,29 +1177,14 @@ bool StaStateMachine::SeparatedState::ExecuteStateMsg(InternalMessage *msg) bool ret = NOT_EXECUTED; switch (msg->GetMessageName()) { - case WIFI_SVR_COM_STA_SET_COUNTRY_CODE: { - ret = EXECUTED; - /* Get code from config center. */ - std::string countryCode; - WifiSettings::GetInstance().GetCountryCode(countryCode); - - WIFI_LOGI("WpaSetCountryCode() countryCode=%{public}s!", countryCode.c_str()); - if (WifiSupplicantHalInterface::GetInstance().WpaSetCountryCode(countryCode) != WIFI_IDL_OPT_OK) { - WIFI_LOGE("WpaSetCountryCode() failed!"); - } - WIFI_LOGI("WpaSetCountryCode() succeed countryCode=%{public}s!", countryCode.c_str()); - break; - } - case WIFI_SVR_CMD_STA_NETWORK_DISCONNECTION_EVENT: break; case WIFI_SVR_CMD_STA_ENABLE_WIFI: { ret = EXECUTED; WIFI_LOGE("Wifi has already started! start Wifi failed!"); - /* Notify result to InterfaceService. */ - pStaStateMachine->NotifyResult( - WifiInternalMsgCode::STA_OPEN_RES, static_cast(OperateResState::OPEN_WIFI_OVERRIDE_OPEN_FAILED)); + /* Callback result to InterfaceService. */ + pStaStateMachine->staCallback.OnStaOpenRes(OperateResState::OPEN_WIFI_OVERRIDE_OPEN_FAILED); break; } @@ -1165,11 +1195,6 @@ bool StaStateMachine::SeparatedState::ExecuteStateMsg(InternalMessage *msg) return ret; } -void StaStateMachine::SetCountryCode() -{ - SendMessage(WIFI_SVR_COM_STA_SET_COUNTRY_CODE); -} - /* --------------------------- state machine ApConnected State ------------------------------ */ StaStateMachine::ApLinkedState::ApLinkedState(StaStateMachine *staStateMachine) : State("ApLinkedState"), pStaStateMachine(staStateMachine) @@ -1280,15 +1305,13 @@ void StaStateMachine::DisConnectProcess() DisableNetwork(linkedInfo.networkId); - /* Notify result to InterfaceService. */ - NotifyResult( - WifiInternalMsgCode::STA_DISCONNECT_RES, static_cast(OperateResState::DISCONNECT_DISCONNECTING)); + /* Callback result to InterfaceService. */ + staCallback.OnStaConnChanged(OperateResState::DISCONNECT_DISCONNECTING, linkedInfo); /* The current state of StaStateMachine transfers to SeparatedState. */ SwitchState(pSeparatedState); } else { - NotifyResult( - WifiInternalMsgCode::STA_DISCONNECT_RES, static_cast(OperateResState::DISCONNECT_DISCONNECT_FAILED)); + staCallback.OnStaConnChanged(OperateResState::DISCONNECT_DISCONNECT_FAILED, linkedInfo); WIFI_LOGE("Disconnect() failed!"); } } @@ -1356,32 +1379,28 @@ bool StaStateMachine::StaWpsState::ExecuteStateMsg(InternalMessage *msg) WIFI_LOGI("WPS mode connect to a network!"); pStaStateMachine->ConnectToNetworkProcess(msg); pStaStateMachine->SyncAllDeviceConfigs(); - /* Notify result to InterfaceService. */ - pStaStateMachine->NotifyResult( - WifiInternalMsgCode::STA_CONNECT_RES, static_cast(OperateResState::CONNECT_AP_CONNECTED)); + /* Callback result to InterfaceService. */ + pStaStateMachine->staCallback.OnStaConnChanged(OperateResState::CONNECT_AP_CONNECTED, pStaStateMachine->linkedInfo); pStaStateMachine->SwitchState(pStaStateMachine->pGetIpState); break; } case WIFI_SVR_CMD_STA_STARTWPS: { ret = EXECUTED; auto setup = static_cast(msg->GetParam1()); - /* Notify InterfaceService that wps has started successfully. */ + /* Callback InterfaceService that wps has started successfully. */ WIFI_LOGE("WPS has already started, start wps failed!"); if (setup == SetupMethod::PBC) { - pStaStateMachine->NotifyResult( - WifiInternalMsgCode::STA_START_WPS_RES, static_cast(WpsStartState::PBC_STARTED_ALREADY)); + pStaStateMachine->staCallback.OnWpsChanged(WpsStartState::PBC_STARTED_ALREADY, pStaStateMachine->pinCode); } else if (setup == SetupMethod::DISPLAY) { - pStaStateMachine->NotifyResult( - WifiInternalMsgCode::STA_START_WPS_RES, static_cast(WpsStartState::PIN_STARTED_ALREADY)); + pStaStateMachine->staCallback.OnWpsChanged(WpsStartState::PIN_STARTED_ALREADY, pStaStateMachine->pinCode); } break; } case WIFI_SVR_CMD_STA_WPS_OVERLAP_EVENT: { ret = EXECUTED; WIFI_LOGI("Wps PBC Overlap!"); - /* Notify InterfaceService that PBC is conflicting. */ - pStaStateMachine->NotifyResult( - WifiInternalMsgCode::STA_START_WPS_RES, static_cast(WpsStartState::START_PBC_FAILED_OVERLAP)); + /* Callback InterfaceService that PBC is conflicting. */ + pStaStateMachine->staCallback.OnWpsChanged(WpsStartState::START_PBC_FAILED_OVERLAP, pStaStateMachine->pinCode); pStaStateMachine->SwitchState(pStaStateMachine->pSeparatedState); break; } @@ -1464,23 +1483,36 @@ void StaStateMachine::GetIpState::GoInState() if (assignMethod == AssignIpMethod::STATIC) { pStaStateMachine->currentTpType = config.wifiIpConfig.staticIpAddress.ipAddress.address.family; if (!pStaStateMachine->ConfigStaticIpAddress(config.wifiIpConfig.staticIpAddress)) { - WIFI_LOGE("ConfigStaticIpAddress failed!.\n"); + if (pStaStateMachine->staCallback.OnStaConnChanged != nullptr) { + pStaStateMachine->staCallback.OnStaConnChanged( + OperateResState::CONNECT_NETWORK_DISABLED, pStaStateMachine->linkedInfo); + } + pStaStateMachine->DisConnectProcess(); + LOGE("ConfigstaticIpAddress failed!\n"); } } else { - pStaStateMachine->currentTpType = static_cast(WifiSettings::GetInstance().GetDhcpIpType()); - if (pStaStateMachine->currentTpType == IPTYPE_IPV4) { - pStaStateMachine->pDhcpService->StartDhcpClient(IF_NAME, false); + LOGD("GetIpState get dhcp result."); + if (pStaStateMachine->isRoam && pStaStateMachine->pDhcpService->GetServerStatus()) { + pStaStateMachine->pDhcpService->RenewDhcpClient(IF_NAME); + pStaStateMachine->pDhcpService->GetDhcpResult(IF_NAME, pStaStateMachine->pDhcpResultNotify, DHCP_TIME); } else { - pStaStateMachine->pDhcpService->StartDhcpClient(IF_NAME, true); - } - if (pStaStateMachine->pDhcpService->GetDhcpResult(IF_NAME, pStaStateMachine->pDhcpResultNotify, 15) != 0) { - LOGE(" Dhcp connection failed.\n"); - pStaStateMachine->NotifyResult( - WifiInternalMsgCode::STA_CONNECT_RES, static_cast(OperateResState::CONNECT_NETWORK_DISABLED)); - pStaStateMachine->DisConnectProcess(); + pStaStateMachine->currentTpType = static_cast(WifiSettings::GetInstance().GetDhcpIpType()); + if (pStaStateMachine->currentTpType == IPTYPE_IPV4) { + pStaStateMachine->pDhcpService->StartDhcpClient(IF_NAME, false); + } else { + pStaStateMachine->pDhcpService->StartDhcpClient(IF_NAME, true); + } + if (pStaStateMachine->pDhcpService->GetDhcpResult( + IF_NAME, pStaStateMachine->pDhcpResultNotify, DHCP_TIME) != 0) { + LOGE(" Dhcp connection failed.\n"); + if (pStaStateMachine->staCallback.OnStaConnChanged != nullptr) { + pStaStateMachine->staCallback.OnStaConnChanged(OperateResState::CONNECT_OBTAINING_IP_FAILED, + pStaStateMachine->linkedInfo); + } + pStaStateMachine->DisConnectProcess(); + } } } - return; } @@ -1506,19 +1538,22 @@ bool StaStateMachine::ConfigStaticIpAddress(StaticIpAddress &staticIpAddress) DhcpResult result; switch (currentTpType) { case IPTYPE_IPV4: { + result.iptype = IPTYPE_IPV4; result.strYourCli = staticIpAddress.ipAddress.address.GetIpv4Address(); result.strRouter1 = staticIpAddress.gateway.GetIpv4Address(); result.strSubnet = staticIpAddress.GetIpv4Mask(); result.strDns1 = staticIpAddress.dnsServer1.GetIpv4Address(); + result.strDns2 = staticIpAddress.dnsServer2.GetIpv4Address(); pDhcpResultNotify->OnSuccess(1, IF_NAME, result); - break; } case IPTYPE_IPV6: { + result.iptype = IPTYPE_IPV6; result.strYourCli = staticIpAddress.ipAddress.address.GetIpv6Address(); result.strRouter1 = staticIpAddress.gateway.GetIpv6Address(); result.strSubnet = staticIpAddress.GetIpv6Mask(); result.strDns1 = staticIpAddress.dnsServer1.GetIpv6Address(); + result.strDns2 = staticIpAddress.dnsServer2.GetIpv6Address(); pDhcpResultNotify->OnSuccess(1, IF_NAME, result); break; } @@ -1528,6 +1563,7 @@ bool StaStateMachine::ConfigStaticIpAddress(StaticIpAddress &staticIpAddress) result.strRouter1 = staticIpAddress.gateway.GetIpv4Address(); result.strSubnet = staticIpAddress.GetIpv4Mask(); result.strDns1 = staticIpAddress.dnsServer1.GetIpv4Address(); + result.strDns2 = staticIpAddress.dnsServer2.GetIpv4Address(); pDhcpResultNotify->OnSuccess(1, IF_NAME, result); result.iptype = IPTYPE_IPV6; @@ -1535,6 +1571,7 @@ bool StaStateMachine::ConfigStaticIpAddress(StaticIpAddress &staticIpAddress) result.strRouter1 = staticIpAddress.gateway.GetIpv6Address(); result.strSubnet = staticIpAddress.GetIpv6Mask(); result.strDns1 = staticIpAddress.dnsServer1.GetIpv6Address(); + result.strDns2 = staticIpAddress.dnsServer2.GetIpv6Address(); pDhcpResultNotify->OnSuccess(1, IF_NAME, result); break; } @@ -1558,14 +1595,14 @@ void StaStateMachine::HandleNetCheckResult(StaNetState netState) /* Save connection information to WifiSettings. */ SaveLinkstate(ConnState::CONNECTED, DetailedState::WORKING); statusId = static_cast(WifiDeviceConfigStatus::ENABLED); - NotifyResult(WifiInternalMsgCode::STA_CONNECT_RES, static_cast(OperateResState::CONNECT_NETWORK_ENABLED)); + staCallback.OnStaConnChanged(OperateResState::CONNECT_NETWORK_ENABLED, linkedInfo); /* The current state of StaStateMachine transfers to LinkedState. */ SwitchState(pLinkedState); } else { WIFI_LOGI("HandleNetCheckResult network state is notworking\n"); SaveLinkstate(ConnState::CONNECTED, DetailedState::NOTWORKING); statusId = static_cast(WifiDeviceConfigStatus::DISABLED); - NotifyResult(WifiInternalMsgCode::STA_CONNECT_RES, static_cast(OperateResState::CONNECT_NETWORK_DISABLED)); + staCallback.OnStaConnChanged(OperateResState::CONNECT_NETWORK_DISABLED, linkedInfo); } } @@ -1585,7 +1622,7 @@ int StaStateMachine::PortalHttpDetection() } else { /* Notify result to InterfaceService. */ WIFI_LOGI("This network is portal AP,need certification!"); - NotifyResult(WifiInternalMsgCode::STA_CONNECT_RES, static_cast(OperateResState::CONNECT_CHECK_PORTAL)); + staCallback.OnStaConnChanged(OperateResState::CONNECT_CHECK_PORTAL, linkedInfo); return 0; } } @@ -1650,10 +1687,13 @@ bool StaStateMachine::ApRoamingState::ExecuteStateMsg(InternalMessage *msg) switch (msg->GetMessageName()) { case WIFI_SVR_CMD_STA_NETWORK_CONNECTION_EVENT: { ret = EXECUTED; + pStaStateMachine->isRoam = true; pStaStateMachine->ConnectToNetworkProcess(msg); /* Notify result to InterfaceService. */ - pStaStateMachine->NotifyResult( - WifiInternalMsgCode::STA_CONNECT_RES, static_cast(OperateResState::CONNECT_AP_CONNECTED)); + pStaStateMachine->staCallback.OnStaConnChanged( + OperateResState::CONNECT_ASSOCIATED, pStaStateMachine->linkedInfo); + pStaStateMachine->staCallback.OnStaConnChanged( + OperateResState::CONNECT_OBTAINING_IP, pStaStateMachine->linkedInfo); /* The current state of StaStateMachine transfers to GetIpState. */ pStaStateMachine->SwitchState(pStaStateMachine->pGetIpState); @@ -1807,8 +1847,8 @@ void StaStateMachine::DhcpResultNotify::OnSuccess(int status, const std::string IfConfig::GetInstance().SetIfAddr(result, result.iptype); if (pStaStateMachine->getIpSucNum == 0) { pStaStateMachine->SaveLinkstate(ConnState::CONNECTED, DetailedState::CONNECTED); - pStaStateMachine->NotifyResult( - WifiInternalMsgCode::STA_CONNECT_RES, static_cast(OperateResState::CONNECT_AP_CONNECTED)); + pStaStateMachine->staCallback.OnStaConnChanged( + OperateResState::CONNECT_AP_CONNECTED, pStaStateMachine->linkedInfo); /* Wait for the network adapter information to take effect. */ sleep(SLEEPTIME); @@ -1826,14 +1866,18 @@ void StaStateMachine::DhcpResultNotify::OnFailed(int status, const std::string & if (ifname.compare("wlan0") == 0) { if (pStaStateMachine->currentTpType != IPTYPE_IPV4) { if (pStaStateMachine->getIpSucNum == 0 && pStaStateMachine->getIpFailNum == 1) { - pStaStateMachine->NotifyResult( - WifiInternalMsgCode::STA_CONNECT_RES, static_cast(OperateResState::CONNECT_OBTAINING_IP_FAIL)); + pStaStateMachine->staCallback.OnStaConnChanged(OperateResState::CONNECT_OBTAINING_IP_FAILED, + pStaStateMachine->linkedInfo); pStaStateMachine->DisConnectProcess(); } } else { - pStaStateMachine->NotifyResult( - WifiInternalMsgCode::STA_CONNECT_RES, static_cast(OperateResState::CONNECT_OBTAINING_IP_FAIL)); - pStaStateMachine->DisConnectProcess(); + pStaStateMachine->staCallback.OnStaConnChanged( + OperateResState::CONNECT_OBTAINING_IP_FAILED, pStaStateMachine->linkedInfo); + if (!pStaStateMachine->isRoam) { + pStaStateMachine->DisConnectProcess(); + } else { + pStaStateMachine->SaveLinkstate(ConnState::CONNECTED, DetailedState::CONNECTED); + } } pStaStateMachine->getIpFailNum++; } @@ -1845,23 +1889,6 @@ void StaStateMachine::DhcpResultNotify::OnSerExitNotify(const std::string &ifnam } /* ------------------ state machine Comment function ----------------- */ -void StaStateMachine::NotifyResult(int msgCode, int stateCode) -{ - WIFI_LOGI("NotifyResult msgCode=%{public}d, stateCode=%{public}d.", msgCode, stateCode); - - WifiResponseMsgInfo notifyMsg; - notifyMsg.msgCode = msgCode; - if (msgCode == WifiInternalMsgCode::STA_CONNECT_RES || msgCode == WifiInternalMsgCode::STA_DISCONNECT_RES) { - notifyMsg.params.linkedInfo = linkedInfo; - } else if (msgCode == WifiInternalMsgCode::STA_START_WPS_RES) { - notifyMsg.params.argInt = pinCode; - } - notifyMsg.params.result = stateCode; - if (msgQueueUp != nullptr) { - msgQueueUp->Push(notifyMsg); - } - return; -} void StaStateMachine::SaveLinkstate(ConnState state, DetailedState detailState) { @@ -1880,7 +1907,7 @@ void StaStateMachine::DisableNetwork(int networkId) if (WifiStaHalInterface::GetInstance().SaveDeviceConfig() == WIFI_IDL_OPT_OK) { WIFI_LOGI("DisableNetwork-SaveDeviceConfig() succeed!"); } else { - WIFI_LOGE("DisableNetwork-SaveDeviceConfig() failed!"); + WIFI_LOGW("DisableNetwork-SaveDeviceConfig() failed!"); } } else { WIFI_LOGE("DisableNetwork() failed, networkId=%{public}d", networkId); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.h index dcc1e86b9..263c3ca6a 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.h @@ -30,6 +30,7 @@ #include "sta_network_check.h" #include "dhcp_service.h" #include "i_dhcp_result_notify.h" +#include "sta_service_callback.h" #include "sta_define.h" namespace OHOS { @@ -50,6 +51,8 @@ static const int CMD_NETWORK_CONNECT_TIMEOUT = 0X08; static const int STA_NETWORK_CONNECTTING_DELAY = 60 * 1000; static const int PIN_CODE_LEN = 8; /* pincode length */ +static const int DHCP_TIME = 15; + /* * During the WPS PIN connection, the WPA_SUPPLICANT blocklist is cleared every 10 seconds * until the network connection is successful. @@ -303,18 +306,6 @@ public: * @Return: WIFI_OPT_SUCCESS - success WIFI_OPT_FAILED - failed */ ErrCode InitStaStateMachine(); - /** - * @Description Sets response queue with input queue - * - * @param pMsgQueueUp - response message information queue(in) - */ - void SetResponseQueue(WifiMessageQueue *pMsgQueueUp); - /** - * @Description Notify operating result to InterfaceService. - * - * @param msgCode - operating results code.(in) - */ - void NotifyResult(int msgCode, int stateCode = 0); /** * @Description Start roaming connection. * @@ -328,17 +319,26 @@ public: * @param bssid - bssid - the mac address of wifi(in) */ void OnNetworkConnectionEvent(int networkId, std::string bssid); + + /** + * @Description Register sta callback function + * + * @param callbacks - Callback function pointer storage structure + */ + void RegisterStaServiceCallback(const StaServiceCallback &callbacks); /** * @Description Synchronize the linked information * * @param scanInfos - the results obtaining by scanning(in) */ - void SyncLinkInfo(const std::vector &scanInfos); + void SyncLinkInfo(const std::vector &scanInfos); /** - * @Description Set country code + * @Description Convert the deviceConfig structure and set it to wpa_supplicant * + * @param config -The Network info(in) + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - void SetCountryCode(); + ErrCode ConvertDeviceCfg(const WifiDeviceConfig &config) const; private: /** @@ -593,6 +593,7 @@ private: private: StaSmHandleFuncMap staSmHandleFuncMap; + StaServiceCallback staCallback; int statusId; int lastNetworkId; @@ -608,13 +609,13 @@ private: IsWpsConnected isWpsConnect; int getIpSucNum; int getIpFailNum; + bool isRoam; WifiLinkedInfo linkedInfo; WifiLinkedInfo lastLinkedInfo; IDhcpService *pDhcpService; DhcpResultNotify *pDhcpResultNotify; StaNetWorkSpeed *pNetSpeed; StaNetworkCheck *pNetcheck; - WifiMessageQueue *msgQueueUp; /* Uplink message queue. */ RootState *pRootState; InitState *pInitState; diff --git a/services/wifi_standard/wifi_hal/wifi_hal_crpc_server.c b/services/wifi_standard/wifi_hal/wifi_hal_crpc_server.c index 31d1ca7b7..b1bb0473a 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_crpc_server.c +++ b/services/wifi_standard/wifi_hal/wifi_hal_crpc_server.c @@ -272,7 +272,7 @@ int OnTransact(RpcServer *server, Context *context) } /* Callback request */ -int OnCallbackTransact(RpcServer *server, int event, Context *context) +int OnCallbackTransact(const RpcServer *server, int event, Context *context) { if (server == NULL || context == NULL) { return -1; @@ -315,7 +315,7 @@ int OnCallbackTransact(RpcServer *server, int event, Context *context) return 0; } -int EndCallbackTransact(RpcServer *server, int event) +int EndCallbackTransact(const RpcServer *server, int event) { if (server == NULL) { return -1; diff --git a/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal/wifi_hostapd_hal.c b/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal/wifi_hostapd_hal.c index ee4f7418d..85aac4682 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal/wifi_hostapd_hal.c +++ b/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal/wifi_hostapd_hal.c @@ -487,7 +487,7 @@ static int SetApInfo(HostsapdConfig *info) LOGE("SetApChannel failed. retval %{public}d", retval); return retval; } - if ((retval = SetApMaxConn(info->maxConn)) != 0) { + if (info->maxConn >= 0 && (retval = SetApMaxConn(info->maxConn)) != 0) { LOGE("SetApMaxConn failed. retval %{public}d", retval); return retval; } diff --git a/services/wifi_standard/wifi_hal/wifi_hal_module_manage.c b/services/wifi_standard/wifi_hal/wifi_hal_module_manage.c index 5ecff0616..075aa75ef 100755 --- a/services/wifi_standard/wifi_hal/wifi_hal_module_manage.c +++ b/services/wifi_standard/wifi_hal/wifi_hal_module_manage.c @@ -29,6 +29,7 @@ static ModuleInfo *g_halModuleList = NULL; +#define STOP_MODULE_TRY_TIMES 3 #define MAX_WPA_MAIN_ARGC_NUM 20 #define MAX_WPA_MAIN_ARGV_LEN 64 @@ -134,7 +135,7 @@ int StartModuleInternal(const char *moduleName, const char *startCmd, pid_t *pPr pthread_join(tid, NULL); exit(0); } else { - LOGE("Create wpa process id is [%d]", pid); + LOGE("Create wpa process id is [%{public}d]", pid); sleep(1); *pProcessId = pid; } @@ -146,20 +147,28 @@ int StopModuleInternal(const char *moduleName, pid_t processId) if (moduleName == NULL) { return 0; } - if (kill(processId, SIGTERM) == -1) { - if (ESRCH == errno) { - LOGI("kill [%d] success, pid no exist", processId); + int tryTimes = STOP_MODULE_TRY_TIMES; + while (tryTimes-- >= 0) { + if (kill(processId, SIGTERM) == -1) { + if (ESRCH == errno) { + LOGI("kill [%{public}d] success, pid no exist", processId); + return 0; + } + LOGE("kill [%{public}d] failed", processId); + return -1; + } + sleep(1); + int ret = waitpid(processId, NULL, WNOHANG); + if (ret <= 0) { + LOGI("Waitpid %{public}d return %{public}d, and retry", processId, ret); + continue; + } else { + LOGD("waitpid [%{public}d] success", processId); return 0; } - LOGE("kill [%d] failed", processId); - return -1; - } - LOGD("waitpid [%d] start, reclaiming process resources", processId); - if (waitpid(processId, NULL, 0) == -1) { - LOGE("waitpid [%d] failed", processId); - return -1; } - return 0; + LOGE("stop [%{public}d] failed, cannot send SIGTERM signal to stop process", processId); + return -1; } ModuleInfo *FindModule(const char *moduleName) -- Gitee From d81f9a74fe0bb18db51fa703e8c92a6e8ef95af4 Mon Sep 17 00:00:00 2001 From: zhangfeng Date: Wed, 8 Sep 2021 09:04:26 +0000 Subject: [PATCH 2/5] add dhcp server feature Signed-off-by: zhangfeng --- .../dhcp_manage/dhcp_server/BUILD.gn | 49 + .../dhcp_server/etc/dhcpd.conf.sample | 53 + .../dhcp_server/etc/dhcpd_mini.conf | 22 + .../dhcp_server/include/address_utils.h | 56 + .../dhcp_server/include/common_util.h | 40 + .../dhcp_server/include/dhcp_address_pool.h | 83 + .../dhcp_server/include/dhcp_binding.h | 68 + .../dhcp_server/include/dhcp_config.h | 66 + .../dhcp_server/include/dhcp_define.h | 89 + .../dhcp_server/include/dhcp_ipv4.h | 138 ++ .../dhcp_server/include/dhcp_logger.h | 85 + .../dhcp_server/include/dhcp_message.h | 76 + .../dhcp_server/include/dhcp_option.h | 71 + .../dhcp_server/include/dhcp_server.h | 44 + .../dhcp_server/include/hash_table.h | 70 + .../dhcp_server/src/address_utils.c | 307 +++ .../dhcp_manage/dhcp_server/src/common_util.c | 201 ++ .../dhcp_server/src/dhcp_address_pool.c | 616 ++++++ .../dhcp_server/src/dhcp_binding.c | 193 ++ .../dhcp_manage/dhcp_server/src/dhcp_config.c | 328 ++++ .../dhcp_manage/dhcp_server/src/dhcp_dhcpd.c | 752 ++++++++ .../dhcp_manage/dhcp_server/src/dhcp_option.c | 298 +++ .../dhcp_manage/dhcp_server/src/dhcp_server.c | 1700 +++++++++++++++++ .../dhcp_manage/dhcp_server/src/hash_table.c | 378 ++++ 24 files changed, 5783 insertions(+) create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/BUILD.gn create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/etc/dhcpd.conf.sample create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/etc/dhcpd_mini.conf create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/address_utils.h create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/common_util.h create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_address_pool.h create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_binding.h create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_config.h create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_define.h create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_ipv4.h create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_logger.h create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_message.h create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_option.h create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_server.h create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/hash_table.h create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/address_utils.c create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/common_util.c create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_address_pool.c create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_binding.c create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_config.c create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_dhcpd.c create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_option.c create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_server.c create mode 100644 services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/hash_table.c diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/BUILD.gn b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/BUILD.gn new file mode 100644 index 000000000..c6cddb576 --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# 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. + +import("//build/ohos.gni") +ohos_executable("dhcp_server") { + install_enable = true + dhcp_hilog_enable = true + sources = [ + "src/address_utils.c", + "src/common_util.c", + "src/dhcp_address_pool.c", + "src/dhcp_binding.c", + "src/dhcp_config.c", + "src/dhcp_dhcpd.c", + "src/dhcp_option.c", + "src/dhcp_server.c", + "src/hash_table.c", + ] + + include_dirs = [ + "include", + "include/common", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include", + "//utils/native/base/include", + ] + + deps = [ "//utils/native/base:utils" ] + + cflags_cc = [ "-fno-rtti" ] + + defines = [ "__OHOS__" ] + if (dhcp_hilog_enable) { + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + defines += [ "DHCP_HILOG_ENABLE" ] + } + + part_name = "wifi_standard" + subsystem_name = "communication" +} diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/etc/dhcpd.conf.sample b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/etc/dhcpd.conf.sample new file mode 100644 index 000000000..d3408fded --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/etc/dhcpd.conf.sample @@ -0,0 +1,53 @@ +#################### default #################### +# Server identifier. +#serverId=192.168.150.200 + +# Default subnet mask. +#netmask=255.255.255.0 + +# Default gateway. +#gateway=192.168.150.254 + +# Lease time value. +leaseTime=43200 +# Renewal time value. +#renewalTime=21600 +# Rebinding time value. +#rebindingTime=34560 + +# Address Range: {beginIp},{endIp} +#pool=192.168.150.100,192.168.150.200 + +# Ip distribue mode [0|1]: 0-random, 1-sequence(default). +#distribution=0 + +# Broadcast flags enable [0|1]: 0-no, 1-yes(default). + +# Domain name server IP address: [,] [,] ... +dns=8.8.8.8,8.8.4.4,114.114.114.114 + +#################### interface1 #################### +# Network interface name, if this parameter is specified, the item is mandatory.(interface config) +interface=wlan1 +# Server identifier, if this parameter is specified, the item is mandatory. +server=192.168.150.200 +# Subnet mask, if this parameter is specified, the item is mandatory. +netmask=255.255.255.0 +gateway=192.168.150.255 + +#leaseTime=6000 +pool=192.168.150.100,192.168.150.200 +#dns=8.8.8.8,8.8.4.4,114.114.114.114 + +#################### interface2 #################### +# Network interface name, if this parameter is specified, the item is mandatory. +#interface=wlan2 +# Server identifier, if this parameter is specified, the item is mandatory. +#server=192.168.255.200 +# Subnet mask, if this parameter is specified, the item is mandatory. +#netmask=255.255.255.0 + +#gateway=192.168.255.255 +#leaseTime=8000 +#pool=192.168.255.2,192.168.255.254 +#dns=8.8.8.8,8.8.4.4,114.114.114.114 diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/etc/dhcpd_mini.conf b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/etc/dhcpd_mini.conf new file mode 100644 index 000000000..b202b205a --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/etc/dhcpd_mini.conf @@ -0,0 +1,22 @@ +dns=223.5.5.5,8.8.8.8 +interface=eth0 +server=192.168.150.1 +netmask=255.255.255.0 +gateway=192.168.150.254 +dns=192.168.150.252 + +interface=wlan0 +server=192.168.150.1 +netmask=255.255.255.0 +gateway=192.168.150.1 +pool=192.168.150.150,192.168.150.200 + +interface=wlan1 +server=192.168.189.1 +netmask=255.255.255.0 +gateway=192.168.189.254 +pool=192.168.189.120,192.168.189.200 + +interface=wlan1-p2p-go0 +server=192.168.190.1 +netmask=255.255.255.128 \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/address_utils.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/address_utils.h new file mode 100644 index 000000000..44db05cc1 --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/address_utils.h @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef OHOS_ADDRESS_UTILS_H +#define OHOS_ADDRESS_UTILS_H + +#include +#include +#include + +#define MAC_ADDR_LENGTH 6 + +#ifdef __cplusplus +extern "C" { +#endif + +uint32_t NetworkAddress(uint32_t ip, uint32_t netmask); +uint32_t FirstIpAddress(uint32_t ip, uint32_t netmask); +uint32_t NextIpAddress(uint32_t currIp, uint32_t netmask, uint32_t offset); +uint32_t FirstNetIpAddress(uint32_t networkAddr); +uint32_t LastIpAddress(uint32_t ip, uint32_t netmask); +int IpInNetwork(uint32_t ip, uint32_t network, uint32_t netmask); +int IpInRange(uint32_t ip, uint32_t beginIp, uint32_t endIp, uint32_t netmask); +uint32_t BroadCastAddress(uint32_t ip, uint32_t netmask); +uint32_t ParseIpAddr(const char *strIp); +uint32_t ParseIpHtonl(const char *strIp); +int NetworkBits(uint32_t netmask); +int HostBits(uint32_t netmask); +int HostTotal(uint32_t netmask); +uint32_t ParseIp(const uint8_t *ipAddr); +const char *ParseStrIp(uint32_t ipAddr); +int IsEmptyHWAddr(uint8_t macAddr[DHCP_HWADDR_LENGTH]); +char *ParseStrMac(uint8_t macAddr[DHCP_HWADDR_LENGTH]); +int ParseMacAddress(const char *strMac, uint8_t macAddr[DHCP_HWADDR_LENGTH]); + +uint32_t HostToNetwork(uint32_t host); +uint32_t NetworkToHost(uint32_t network); + +char *ParseLogMac(uint8_t macAddr[DHCP_HWADDR_LENGTH]); +int AddrEquels(uint8_t firstAddr[DHCP_HWADDR_LENGTH], uint8_t secondAddr[DHCP_HWADDR_LENGTH], int addrLength); +#ifdef __cplusplus +} +#endif +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/common_util.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/common_util.h new file mode 100644 index 000000000..a0f6fce0c --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/common_util.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef OHOS_COMMON_UTIL_H +#define OHOS_COMMON_UTIL_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif +void LogTime(); +uint64_t Tmspsec(); +uint64_t Tmspusec(); +void LeftTrim(char *buf); +void RightTrim(char *buf); +void TrimString(char *buf); +const char *GetFilePath(const char *fileName); + +const char *GetLeaseFile(const char *fileName, const char *ifname); +int CreatePath(const char *fileName); +int RemoveSpaceCharacters(char *buf, size_t bufSize); + +#ifdef __cplusplus +} +#endif +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_address_pool.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_address_pool.h new file mode 100644 index 000000000..04f3b865f --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_address_pool.h @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef OHOS_DHCP_ADDRESS_POOL_H +#define OHOS_DHCP_ADDRESS_POOL_H + +#include +#include "dhcp_define.h" +#include "dhcp_option.h" +#include "hash_table.h" +#include "dhcp_binding.h" + +#ifdef __cplusplus +extern "C" { +#endif +typedef struct DhcpAddressPool DhcpAddressPool; +typedef AddressBinding *(*QueryBind)(uint8_t macAddr[DHCP_HWADDR_LENGTH], PDhcpOptionList cliOptins); +typedef AddressBinding *(*AddBind)(uint8_t macAddr[DHCP_HWADDR_LENGTH], PDhcpOptionList cliOptins); +typedef uint32_t (*Distribute)(DhcpAddressPool *pool, uint8_t macAddr[DHCP_HWADDR_LENGTH]); + +typedef struct { + uint32_t beginAddress; + uint32_t endAddress; +} IpAddressRange; + +struct DhcpAddressPool { + char ifname[IFACE_NAME_SIZE]; + uint32_t netmask; + IpAddressRange addressRange; + uint32_t serverId; + uint32_t gateway; + uint32_t leaseTime; + uint32_t renewalTime; + uint32_t rebindingTime; + uint32_t distribution; + Distribute distribue; + QueryBind binding; + AddBind newBinding; + HashTable leaseTable; + DhcpOptionList fixedOptions; + int initialized; +}; + +int InitAddressPool(DhcpAddressPool *pool, const char *ifname, PDhcpOptionList options); +void FreeAddressPool(DhcpAddressPool *pool); +AddressBinding *FindBindingByIp(uint32_t bingdingIp); +int IsReserved(uint8_t macAddr[DHCP_HWADDR_LENGTH]); +int IsReservedIp(DhcpAddressPool *pool, uint32_t ipAddress); +int AddBinding(AddressBinding *binding); +int AddReservedBinding(uint8_t macAddr[DHCP_HWADDR_LENGTH]); +int RemoveReservedBinding(uint8_t macAddr[DHCP_HWADDR_LENGTH]); +int RemoveBinding(uint8_t macAddr[DHCP_HWADDR_LENGTH]); +int ReleaseBinding(uint8_t macAddr[DHCP_HWADDR_LENGTH]); +int AddLease(DhcpAddressPool *pool, AddressBinding *lease); +AddressBinding *GetLease(DhcpAddressPool *pool, uint32_t ipAddress); +int UpdateLease(DhcpAddressPool *pool, AddressBinding *lease); +int RemoveLease(DhcpAddressPool *pool, AddressBinding *lease); +int ReBinding(uint8_t macAddr[DHCP_HWADDR_LENGTH]); +int LoadBindingRecoders(DhcpAddressPool *pool); +int SaveBindingRecoders(const DhcpAddressPool *pool, int force); + +AddressBinding *GetBindingByMac(HashTable *bindTable, uint8_t macAddr[DHCP_HWADDR_LENGTH]); +AddressBinding *GetBindingByIp(HashTable *bindTable, uint32_t ipAddress); +AddressBinding *QueryBinding(uint8_t macAddr[DHCP_HWADDR_LENGTH], PDhcpOptionList cliOptins); +void SetDistributeMode(int mode); +int GetDistributeMode(); + +#ifdef __cplusplus +} +#endif +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_binding.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_binding.h new file mode 100644 index 000000000..a23d706a6 --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_binding.h @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef OHOS_DHCP_BINDING_H +#define OHOS_DHCP_BINDING_H + +#include "dhcp_define.h" +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif +enum BindingMode { BIND_MODE_STATIC = 0, BIND_MODE_DYNAMIC, BIND_MODE_RESERVED }; + +enum BindingState { BIND_NONE = 0, BIND_PENDING, BIND_ASSOCIATED, BIND_EXPIRED, BIND_RELEASED }; + +typedef struct AddressBinding AddressBinding; +struct AddressBinding { + uint32_t ipAddress; + uint8_t chaddr[16]; + uint32_t clientId; + uint64_t bindingTime; + uint64_t pendingTime; + uint64_t expireIn; + uint64_t leaseTime; + uint64_t pendingInterval; + int bindingStatus; + int bindingMode; +}; +typedef struct AddressBinding *PAddressBinding; + +typedef struct AddressBindingNode AddressBindingNode; +struct AddressBindingNode { + AddressBinding bind; + AddressBindingNode *next; +}; +typedef struct AddressBindingNode *PAddressBindingNode; + +typedef struct AddressBindingList AddressBindingList; +struct AddressBindingList { + int size; + AddressBindingNode *first; +}; +typedef struct AddressBindingList *PAddressBindingList; + +uint64_t NextPendingInterval(uint64_t pendingInterval); +int IsExpire(AddressBinding *binding); +int WriteAddressBinding(AddressBinding *binding, char *out, uint32_t size); +int ParseAddressBinding(AddressBinding *binding, const char *buf); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_config.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_config.h new file mode 100644 index 000000000..c3544fb9b --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_config.h @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef OHOS_DHCP_CONFIG_H +#define OHOS_DHCP_CONFIG_H + + +#include +#include +#include +#include "dhcp_define.h" +#include "dhcp_option.h" +#include "dhcp_address_pool.h" +#include "dhcp_binding.h" + +#ifdef __cplusplus +extern "C" { +#endif +typedef struct DhcpConfig DhcpConfig; +struct DhcpConfig { + char ifname[IFACE_NAME_SIZE]; /* Network interface name. */ + uint32_t serverId; /* Server identifier. */ + uint32_t netmask; /* Default subnet mask. */ + uint32_t gateway; /* Default gateway. */ + uint32_t leaseTime; /* Lease time value, default DHCP_LEASE_TIME. */ + uint32_t renewalTime; /* Renewal time value. */ + uint32_t rebindingTime; /* Rebinding time value. */ + uint32_t distribution; /* Ip distribue mode [0|1]: 0-random, 1-sequence(default). */ + uint32_t broadcast; /* Broadcast flags enable [0|1]: 0-no, 1-yes(default). */ + IpAddressRange pool; /* Address Range. */ + DhcpOptionList options; /* Append dhcp options. */ +}; +typedef struct DhcpConfig *PDhcpConfig; + +typedef struct DhcpConfigNode DhcpConfigNode; +struct DhcpConfigNode { + DhcpConfig config; + DhcpConfigNode *next; +}; +typedef struct DhcpConfigNode *PDhcpConfigNode; + +typedef struct DhcpConfigList DhcpConfigList; +struct DhcpConfigList { + int size; + DhcpConfigNode *first; +}; +typedef struct DhcpConfigList *PDhcpConfigList; + +int LoadConfig(const char *configFile, const char *ifname, DhcpConfig *config); + +#ifdef __cplusplus +} +#endif +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_define.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_define.h new file mode 100644 index 000000000..6759187f3 --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_define.h @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef OHOS_DHCP_DEFINE_H +#define OHOS_DHCP_DEFINE_H + +#define DHCP_LEASE_TIME 21600 +#define DHCP_RENEWAL_TIME 10800 +#define DHCP_REBINDING_TIME 17280 +#define DHCP_DEFAULT_TIMEOUT 30 +#define DHCP_ADDRESS_LENGTH 4 +#define DHCP_HWADDR_LENGTH 16 +#define DHCP_HOST_NAME_LENGTH 64 +#define DHCP_BOOT_FILE_LENGTH 128 +#define DHCP_LEASE_FILE_LENGTH 256 +#define DHCP_FILE_LINE_LENGTH 1024 +#define DHCP_REFRESH_LEASE_FILE_INTERVAL 5 +#define DHCP_MESSAGE_FLAG_LENGTH 16 +#define DHCP_MAX_PATH_LENGTH 256 +#define DHCP_ONE_BYTE_BITS 8 + +#ifdef __OHOS__ +#define DHCPD_CONFIG_FILE "/data/dhcp/etc/dhcpd.conf" +#define DHCPD_EXT_CONFIG_PATH "/data/dhcp/etc/dhcpd.d" +#define DHCPD_LOG_PATH "/data/log/dhcpd" +#define DHCPD_LEASE_FILE "/data/dhcp/dhcpd_lease.lease" +#define DHCPD_PID_FILE "/data/dhcp/dhcpd.pid" +#else +#define DHCPD_CONFIG_FILE "/etc/dhcp/dhcpd.conf" +#define DHCPD_EXT_CONFIG_PATH "/etc/dhcp/dhcpd.d" +#define DHCPD_LEASE_FILE "/etc/dhcp/dhcpd_lease.lease" +#define DHCPD_LOG_PATH "/var/log/dhcpd" +#define DHCPD_PID_FILE "/etc/dhcp/dhcpd.pid" +#endif // __OHOS__ +#define DHCPD_VERSION "0.0.1" + +#define DHCP_SERVER_PORT 67 +#define DHCP_CLIENT_PORT 68 + +#define DHCP_OPTIONS_SIZE 312 +#define IFACE_NAME_SIZE 50 +#define PID_MAX_LEN 16 + +#define DHCP_RENEWAL_MULTIPLE 0.5 +#define DHCP_REBIND_MULTIPLE 0.875 + +#define DHCP_TRUE 1 +#define DHCP_FALSE 0 +enum DhcpNumber { + NUM_ZERO = 0, + NUM_ONE, + NUM_TWO, + NUM_THREE, + NUM_FOUR, + NUM_FIVE, + NUM_SIX, + NUM_SEVEN, + NUM_EIGHT, + NUM_NINE, + NUM_TEN, + NUM_ELEVEN, + NUM_TWELVE, + NUM_THIRTEEN, + NUM_FOURTEEN, +}; + +enum DhcpReturnCode { + RET_SUCCESS = 0, + RET_FAILED, + RET_ERROR, + ERR_SELECT, + RET_BREAK, + RET_WAIT_SAVE, + RET_NO_SUPPORTED +}; + +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_ipv4.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_ipv4.h new file mode 100644 index 000000000..cde0d39c9 --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_ipv4.h @@ -0,0 +1,138 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef OHOS_DHCP_IPV4_H +#define OHOS_DHCP_IPV4_H + +// See: RFC 2132 DHCP Options and BOOTP Vendor Extensions March 1997 +enum DhcpOptions { + + /* + * 3. RFC 1497 Vendor Extensions + * This section lists the vendor extensions as defined in RFC 1497. + * They are defined here for completeness. + */ + PAD_OPTION = 0, + END_OPTION = 255, + + SUBNET_MASK_OPTION = 1, + TIME_OFFSET_OPTION = 2, + ROUTER_OPTION = 3, + TIME_SERVER_OPTION = 4, + NAME_SERVER_OPTION = 5, + DOMAIN_NAME_SERVER_OPTION = 6, + LOG_SERVER_OPTION = 7, + COOKIE_SERVER_OPTION = 8, + LPR_SERVER_OPTION = 9, + IMPRESS_SERVER_OPTION = 10, + RESOURCE_LOCATION_SERVER_OPTION = 11, + HOST_NAME_OPTION = 12, + BOOT_FILE_SIZE_OPTION = 13, + MERIT_DUMP_FILE_OPTION = 14, + DOMAIN_NAME_OPTION = 15, + SWAP_SERVER_OPTION = 16, + ROOT_PATH_OPTION = 17, + EXTENSIONS_PATH_OPTION = 18, + + /* + * IP Layer Parameters per Host + * This section details the options that affect the operation of the IP layer on a per-host basis. + */ + IP_FORWARDING_OPTION = 19, + NON_LOCAL_SOURCE_ROUTING_OPTION = 20, + POLICY_FILTER_OPTION = 21, + MAXIMUM_DATAGRAM_REASSEMBLY_SIZE_OPTION = 22, + DEFAULT_IP_TIME_TO_LIVE_OPTION = 23, + PATH_MTU_AGING_TIMEOUT_OPTION = 24, + PATH_MTU_PLATEAU_TABLE_OPTION = 25, + + /* + * 5. IP Layer Parameters per Interface + * This section details the options that affect the operation of the IP layer on a per-interface basis. It is + * expected that a client can issue multiple requests, one per interface, in order to configure interfaces with + * their specific parameters. + */ + INTERFACE_MTU_OPTION = 26, + ALL_SUBNETS_ARE_LOCAL_OPTION = 27, + BROADCAST_ADDRESS_OPTION = 28, + PERFORM_MASK_DISCOVERY_OPTION = 29, + MASK_SUPPLIER_OPTION = 30, + PERFORM_ROUTER_DISCOVERY_OPTION = 31, + ROUTER_SOLICITATION_ADDRESS_OPTION = 32, + STATIC_ROUTE_OPTION = 33, + + /* + * 6. Link Layer Parameters per Interface + * This section lists the options that affect the operation of the data link layer on a per-interface basis. + */ + TRAILER_ENCAPSULATION_OPTION = 34, // 6.1. Trailer Encapsulation Option + ARP_CACHE_TIMEOUT_OPTION = 35, // 6.2. ARP Cache Timeout Option + ETHERNET_ENCAPSULATION_OPTION = 36, // 6.3. Ethernet Encapsulation Option + + /* + * 7. TCP Parameters + * This section lists the options that affect the operation of the TCP layer on a per-interface basis. + */ + TCP_DEFAULT_TTL_OPTION = 37, // 7.1. TCP Default TTL Option + TCP_KEEPALIVE_INTERVAL_OPTION = 38, // 7.2. TCP Keepalive Interval Option + TCP_KEEPALIVE_GARBAGE_OPTION = 39, // 7.3. TCP Keepalive Garbage Option + + /* + * 8. Application and Service Parameters + * This section details some miscellaneous options used to configure miscellaneous applications and services. + */ + NETWORK_INFO_SERVICE_DOMAIN_OPTION = 40, // 8.1. Network Information Service Domain Option + NETWORK_INFO_SERVERS_OPTION = 41, // 8.2. Network Information Servers Option + NETWORK_TIME_PROTOCOL_SERVERS_OPTION = 42, // 8.3. Network Time Protocol Servers Option + VENDOR_SPECIFIC_INFO_OPTION = 43, // 8.4. Vendor Specific Information + NETBIOS_OVER_IP_NAME_SERVER_OPTION = 44, // 8.5. NetBIOS over TCP/IP Name Server Option + NETBIOS_OVER_IP_DATAGRAM_DIST_SERVER_OPTION = 45, // 8.6. NetBIOS over TCP/IP Datagram Distribution Server Option + NETBIOS_OVER_IP_NODE_TYPE_OPTION = 46, // 8.7. NetBIOS over TCP/IP Node Type Option + NETBIOS_OVER_IP_SCOPE_OPTION = 47, // 8.8. NetBIOS over TCP/IP Scope Option + X_WINDOW_SYSTEM_FONT_SERVER_OPTION = 48, // 8.9. X Window System Font Server Option + X_WINDOW_SYSTEM_DISPLAY_MANAGER_OPTION = 49, // 8.10. X Window System Display Manager Option + NETWORK_INFO_SERVICE_PLUS_DOMAIN_OPTION = 64, // 8.11. Network Information Service+ Domain Option + NETWORK_INFO_SERVICE_PLUS_SERVERS_OPTION = 65, // 8.12. Network Information Service+ Servers Option + MOBILE_IP_HOME_AGENT_OPTION = 68, // 8.13. Mobile IP Home Agent option + SMTP_SERVER_OPTION = 69, // 8.14. Simple Mail Transport Protocol (SMTP) Server Option + POP3_SERVER_OPTION = 70, // 8.15. Post Office Protocol (POP3) Server Option + NNTP_SERVER_OPTION = 71, // 8.16. Network News Transport Protocol (NNTP) Server Option + DEFAULT_WEB_SERVER_OPTION = 72, // 8.17. Default World Wide Web (WWW) Server Option + DEFAULT_FINGER_SERVER_OPTION = 73, // 8.18. Default Finger Server Option + DEFAULT_IRC_SERVER_OPTION = 74, // 8.19. Default Internet Relay Chat (IRC) Server Option + STREETTALK_SERVER_OPTION = 75, // 8.20. StreetTalk Server Option + STDA_SERVER_OPTION = 76, // 8.21. StreetTalk Directory Assistance (STDA) Server Option + + /* + * 9. DHCP Extensions + * This section details the options that are specific to DHCP. + */ + REQUESTED_IP_ADDRESS_OPTION = 50, + IP_ADDRESS_LEASE_TIME_OPTION = 51, + OPTION_OVERLOAD_OPTION = 52, + TFTP_SERVER_NAME_OPTION = 66, + BOOTFILE_NAME_OPTION = 67, + DHCP_MESSAGE_TYPE_OPTION = 53, + SERVER_IDENTIFIER_OPTION = 54, + PARAMETER_REQUEST_LIST_OPTION = 55, + MESSAGE_OPTION = 56, + MAXIMUM_DHCP_MESSAGE_SIZE_OPTION = 57, + RENEWAL_TIME_VALUE_OPTION = 58, + REBINDING_TIME_VALUE_OPTION = 59, + VENDOR_CLASS_IDENTIFIER_OPTION = 60, + CLIENT_IDENTIFIER_OPTION = 61 +}; + +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_logger.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_logger.h new file mode 100644 index 000000000..f519b8dea --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_logger.h @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef OHOS_DHCP_LOGGER_H +#define OHOS_DHCP_LOGGER_H + +#ifdef DHCP_HILOG_ENABLE +#include "hilog/log_c.h" + +#undef LOG_TAG +#define LOG_TAG "DhcpServer" + +#undef LOG_DOMAIN +#define LOG_DOMAIN 0x0000000 + +#define LOGD(...) ((void)HiLogPrint(LOG_CORE, LOG_DEBUG, LOG_DOMAIN, LOG_TAG, __VA_ARGS__)) + +#define LOGI(...) ((void)HiLogPrint(LOG_CORE, LOG_INFO, LOG_DOMAIN, LOG_TAG, __VA_ARGS__)) + +#define LOGW(...) ((void)HiLogPrint(LOG_CORE, LOG_WARN, LOG_DOMAIN, LOG_TAG, __VA_ARGS__)) + +#define LOGE(...) ((void)HiLogPrint(LOG_CORE, LOG_ERROR, LOG_DOMAIN, LOG_TAG, __VA_ARGS__)) + +#define LOGF(...) ((void)HiLogPrint(LOG_CORE, LOG_FATAL, LOG_DOMAIN, LOG_TAG, __VA_ARGS__)) +#else +#include +#include +#include "common_util.h" + +#define LOG_DEBUG "Debug" +#define LOG_TRACE "Trace" +#define LOG_WARN " Warn" +#define LOG_ERROR "Error" +#define LOG_INFO " Info" + +#define DEBUG_MODE 1 + +#define LOG_TAG "DhcpServer" + +#define LOGD(log, ...) \ + do { \ + LogTime(); \ + printf(" %s] %s ", LOG_DEBUG, LOG_TAG); \ + printf((log), ##__VA_ARGS__); \ + printf("(line:%d)\n", __LINE__); \ + } while (0); + +#define LOGW(log, ...) \ + do { \ + LogTime(); \ + printf(" %s] %s ", LOG_WARN, LOG_TAG); \ + printf((log), ##__VA_ARGS__); \ + printf("\n"); \ + } while (0); + +#define LOGE(log, ...) \ + do { \ + LogTime(); \ + printf(" %s] %s ", LOG_ERROR, LOG_TAG); \ + printf((log), ##__VA_ARGS__); \ + printf("(line:%d)\n", __LINE__); \ + } while (0); + +#define LOGI(log, ...) \ + do { \ + LogTime(); \ + printf(" %s] %s ", LOG_INFO, LOG_TAG); \ + printf((log), ##__VA_ARGS__); \ + printf("\n"); \ + } while (0); + +#endif // DHCP_HILOG_ENABLE +#endif diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_message.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_message.h new file mode 100644 index 000000000..8024a3ede --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_message.h @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef OHOS_DHCP_MESSAGE_H +#define OHOS_DHCP_MESSAGE_H + +#include "dhcp_define.h" +#include "dhcp_option.h" +#include + +#define BOOTREQUEST 1 +#define BOOTREPLY 2 + +#define DHCP_MSG_HEADER_SIZE 236 + +enum DhcpMessageType { + DHCPDISCOVER = 1, + DHCPOFFER = 2, + DHCPREQUEST = 3, + DHCPDECLINE = 4, + DHCPACK = 5, + DHCPNAK = 6, + DHCPRELEASE = 7, + DHCPINFORM = 8 +}; + +enum DhcpReplyType { + REPLY_NONE = 0, + REPLY_OFFER, + REPLY_ACK, + REPLY_NAK, +}; + +typedef struct DhcpMessage DhcpMessage; +struct DhcpMessage { + uint8_t op; + uint8_t htype; + uint8_t hlen; + uint8_t hops; + uint32_t xid; + uint16_t secs; + uint16_t flags; + uint32_t ciaddr; + uint32_t yiaddr; + uint32_t siaddr; + uint32_t giaddr; + + uint8_t chaddr[DHCP_HWADDR_LENGTH]; + + uint8_t sname[DHCP_HOST_NAME_LENGTH]; + uint8_t file[DHCP_BOOT_FILE_LENGTH]; + uint8_t options[DHCP_OPTIONS_SIZE]; +}; +typedef struct DhcpMessage *PDhcpMessage; + +typedef struct DhcpMsgInfo DhcpMsgInfo; +struct DhcpMsgInfo { + DhcpMessage packet; + int length; + DhcpOptionList options; +}; +typedef struct DhcpMsgInfo *PDhcpMsgInfo; + +#endif diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_option.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_option.h new file mode 100644 index 000000000..cf0af1a5d --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_option.h @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef OHOS_DHCP_OPTION_H +#define OHOS_DHCP_OPTION_H + +#include +#include +#include + +#define DHCP_OPTION_SIZE 256 +#define DHCP_END_OPTION_CODE 255 + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct DhcpOption DhcpOption; +struct DhcpOption { + uint8_t code; + uint8_t length; + uint8_t data[DHCP_OPTION_SIZE]; +}; +typedef struct DhcpOption *PDhcpOption; + +typedef struct DhcpOptionNode DhcpOptionNode; +struct DhcpOptionNode { + struct DhcpOptionNode *previous; + struct DhcpOptionNode *next; + DhcpOption option; +}; +typedef struct DhcpOptionNode *PDhcpOptionNode; + +typedef struct DhcpOptionList DhcpOptionList; +struct DhcpOptionList { + PDhcpOptionNode first; + PDhcpOptionNode last; + size_t size; +}; +typedef struct DhcpOptionList *PDhcpOptionList; + +int InitOptionList(PDhcpOptionList pOptions); +int HasInitialized(PDhcpOptionList pOptions); +int PushBackOption(PDhcpOptionList pOptions, PDhcpOption option); +int PushFrontOption(PDhcpOptionList pOptions, PDhcpOption option); +int RemoveOption(PDhcpOptionList pOptions, uint8_t code); +PDhcpOptionNode GetOptionNode(PDhcpOptionList pOptions, uint8_t code); +PDhcpOption GetOption(PDhcpOptionList pOptions, uint8_t code); +void ClearOptions(PDhcpOptionList pOptions); +void FreeOptionList(PDhcpOptionList pOptions); +int FillOption(PDhcpOption pOption, const char *data, size_t len); +int FillU32Option(PDhcpOption pOption, uint32_t u32); +int FillOptionData(PDhcpOption pOption, const uint8_t *data, size_t len); +int AppendAddressOption(PDhcpOption pOption, uint32_t address); + +#ifdef __cplusplus +} +#endif +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_server.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_server.h new file mode 100644 index 000000000..df8182192 --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_server.h @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef OHOS_DHCP_SERVER_H +#define OHOS_DHCP_SERVER_H +#include "dhcp_config.h" +#include "dhcp_address_pool.h" + +enum DhcpServerState { ST_IDEL = 0, ST_STARTING, ST_RUNNING, ST_RELOADNG, ST_STOPING, ST_STOPED }; +typedef int (*DhcpServerCallback)(int, int, const char *ifname); + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct ServerContext ServerContext; +typedef struct { + char ifname[IFACE_NAME_SIZE]; + ServerContext *instance; +} DhcpServerContext, *PDhcpServerContext; + +PDhcpServerContext InitializeServer(DhcpConfig *config); +int StartDhcpServer(PDhcpServerContext ctx); +int StopDhcpServer(PDhcpServerContext ctx); +int GetServerStatus(PDhcpServerContext ctx); +void RegisterDhcpCallback(PDhcpServerContext ctx, DhcpServerCallback callback); +int FreeServerContex(PDhcpServerContext ctx); + +#ifdef __cplusplus +} +#endif +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/hash_table.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/hash_table.h new file mode 100644 index 000000000..f73ba9475 --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/hash_table.h @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef OHOS_HASH_TABLE_H +#define OHOS_HASH_TABLE_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define HASH_MINI_CAPACITY 8 + +enum HashTableResult { + HASH_SUCCESS = 0, + HASH_ERROR, + HASH_UPDATED, + HASH_INSERTED, + HASH_KEY_NOT_FOUND, + HASH_NOT_EMPTY, +}; + +typedef int (*HashComparison)(uintptr_t, uintptr_t, size_t); +typedef size_t (*HashType)(uintptr_t, size_t); +typedef struct HashNode { + struct HashNode *next; + uintptr_t key; + uintptr_t value; +} HashNode; + +typedef struct HashTable { + size_t size; + size_t threshold; + size_t capacity; + size_t keySize; + size_t valueSize; + HashComparison compare; + HashType hash; + HashNode **nodes; +} HashTable; + +int CreateHashTable(HashTable *table, size_t keySize, size_t valueSize, size_t capacity); +int Initialized(const HashTable *table); +int DestroyHashTable(HashTable *table); +int Insert(HashTable *table, uintptr_t key, uintptr_t value); +int ContainsKey(const HashTable *table, uintptr_t key); +uintptr_t At(HashTable *table, uintptr_t key); +int Remove(HashTable *table, uintptr_t key); +int ClearAll(HashTable *table); +int Empty(const HashTable *table); +int Resize(HashTable *table, size_t newSize); + +#ifdef __cplusplus +} +#endif +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/address_utils.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/address_utils.c new file mode 100644 index 000000000..0b27af4f7 --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/address_utils.c @@ -0,0 +1,307 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 "address_utils.h" +#include +#include +#include +#include +#include "dhcp_logger.h" + +#undef LOG_TAG +#define LOG_TAG "DhcpServerAddressUtil" + +#define IPV4_ADDRESS_BITS 32 +#define BIT_MAX_VALUE 2 +#define IP_ADDRESS_LENGTH 4 +#define MAD_ADDR_BUF_SIZE 50 +#define MAC_STRING_SIZE 17 + +enum MacAddressIndex { + MAI_ZERO = 0, + MAI_ONE = 1, + MAI_TWO = 2, + MAI_THREE = 3, + MAI_FOUR = 4, + MAI_FIVE = 5 +}; + +uint32_t NetworkAddress(uint32_t ip, uint32_t netmask) +{ + return (ip & netmask); +} + +uint32_t FirstIpAddress(uint32_t ip, uint32_t netmask) +{ + uint32_t network = NetworkAddress(ip, netmask); + uint32_t firstIp = htonl(network) + 1; + return htonl(firstIp); +} + +uint32_t NextIpAddress(uint32_t currIp, uint32_t netmask, uint32_t offset) +{ + uint32_t network = NetworkAddress(currIp, netmask); + uint32_t broadcast = BroadCastAddress(currIp, netmask); + uint32_t lastIp = LastIpAddress(currIp, netmask); + uint32_t hostTotal = HostTotal(netmask); + uint32_t next = offset; + if (currIp == lastIp || currIp == broadcast) { + return FirstIpAddress(currIp, netmask); + } + if (next > hostTotal) { + next = next % hostTotal; + } + uint32_t nextIp = htonl(currIp) + next + 1; + if (next && nextIp > htonl(lastIp)) { + nextIp = htonl(network) + (nextIp - htonl(lastIp)); + } + return htonl(nextIp); +} + +uint32_t FirstNetIpAddress(uint32_t network) +{ + uint32_t firstIp = htonl(network) + 1; + return htonl(firstIp); +} + +uint32_t LastIpAddress(uint32_t ip, uint32_t netmask) +{ + uint32_t network = NetworkAddress(ip, netmask); + uint32_t lastIp = htonl(network) + HostTotal(netmask); + if (lastIp) { + lastIp -= 1; + } + return htonl(lastIp); +} + +int IpInNetwork(uint32_t ip, uint32_t network, uint32_t netmask) +{ + uint32_t firstNet = NetworkAddress(ip, netmask); + uint32_t secondNet = NetworkAddress(network, netmask); + + uint32_t beginIp = FirstIpAddress(network, netmask); + uint32_t broadCast = BroadCastAddress(network, netmask); + + if (firstNet == secondNet) { + if (ip >= beginIp && ip <= broadCast) { + return DHCP_TRUE; + } + } + return DHCP_FALSE; +} + +int IpInRange(uint32_t ip, uint32_t beginIp, uint32_t endIp, uint32_t netmask) +{ + uint32_t network = NetworkAddress(ip, netmask); + uint32_t firstNet = NetworkAddress(beginIp, netmask); + uint32_t secondNet = NetworkAddress(endIp, netmask); + if (network != firstNet || firstNet != secondNet) { + return 0; + } + if (ip >= beginIp && ip <= endIp) { + return DHCP_TRUE; + } + return DHCP_FALSE; +} + +uint32_t BroadCastAddress(uint32_t ip, uint32_t netmask) +{ + uint32_t network = NetworkAddress(ip, netmask); + uint32_t broadcast = htonl(network) + HostTotal(netmask); + return htonl(broadcast); +} + +int NetworkBits(uint32_t netmask) +{ + int bits = 0; + uint32_t net = htonl(netmask); + for (size_t i = 0; i < IPV4_ADDRESS_BITS; i++) { + if (net == 0) { + break; + } + bits++; + net <<= 1; + } + return bits; +} + +int HostBits(uint32_t netmask) +{ + int bits = 0; + uint32_t net = htonl(netmask); + for (int i = IPV4_ADDRESS_BITS; i > 0; --i) { + bits++; + net >>= 1; + if ((net & 1) != 0) { + break; + } + } + return bits; +} + +int HostTotal(uint32_t netmask) +{ + int hostBits = HostBits(netmask); + int total = 1; + for (size_t i = 0; i < (size_t)hostBits; i++) { + total *= BIT_MAX_VALUE; + } + total--; + return total; +} +uint32_t ParseIpAddr(const char *strIp) +{ + struct in_addr inAddr; + uint32_t ip = 0; + int ret = inet_aton(strIp, &inAddr); + if (ret != 0) { + if (memcpy_s(&ip, sizeof(struct in_addr), &inAddr, sizeof(uint32_t)) != EOK) { + return 0; + }; + return ip; + } + return 0; +} + +uint32_t ParseIpHtonl(const char *strIp) +{ + uint32_t ip = ParseIpAddr(strIp); + return htonl(ip); +} + +uint32_t ParseIp(const uint8_t *ipAddr) +{ + uint32_t ip = 0; + if (memcpy_s(&ip, IP_ADDRESS_LENGTH, ipAddr, IP_ADDRESS_LENGTH) != EOK) { + return 0; + } + return ip; +} + +const char *ParseStrIp(uint32_t ipAddr) +{ + struct in_addr inAddr; + if (memcpy_s(&inAddr, sizeof(inAddr), &ipAddr, sizeof(ipAddr)) != EOK) { + return "0.0.0.0"; + } + return inet_ntoa(inAddr); +} + +char *ParseStrMac(uint8_t macAddr[DHCP_HWADDR_LENGTH]) +{ + static char strMacAddr[MAD_ADDR_BUF_SIZE] = {0}; + if (!macAddr) { + return 0; + } + if (memset_s(strMacAddr, MAD_ADDR_BUF_SIZE, '\0', sizeof(strMacAddr)) != EOK || + sprintf_s(strMacAddr, MAD_ADDR_BUF_SIZE, "%02x:%02x:%02x:%02x:%02x:%02x", macAddr[MAI_ZERO], + macAddr[MAI_ONE], macAddr[MAI_TWO], macAddr[MAI_THREE], macAddr[MAI_FOUR], macAddr[MAI_FIVE]) < 0) { + return 0; + } + return strMacAddr; +} + +static int8_t IsValidHexCharAndConvert(char c) +{ + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'a' && c <= 'f') { + return c - 'a' + ('9' - '0' + 1); + } + if (c >= 'A' && c <= 'F') { + return c - 'A' + ('9' - '0' + 1); + } + return -1; +} + +int ParseMacAddress(const char *strMac, uint8_t macAddr[DHCP_HWADDR_LENGTH]) +{ + if (strMac == NULL || strlen(strMac) != MAC_STRING_SIZE) { + return DHCP_FALSE; + } + size_t len = strlen(strMac); + const int shiftNum = 4; + const int macSpaceNum = 3; + unsigned char tmp = 0; + for (size_t i = 0, j = 0; i < len; ++i) { + if (j == 0 || j == 1) { + int8_t v = IsValidHexCharAndConvert(strMac[i]); + if (v < 0) { + return 0; + } + tmp <<= shiftNum; + tmp |= v; + ++j; + } else { + if (strMac[i] != ':') { + return 0; + } + macAddr[i / macSpaceNum] = tmp; + j = 0; + tmp = 0; + } + } + macAddr[MAC_STRING_SIZE / macSpaceNum] = tmp; + return DHCP_TRUE; +} + +uint32_t HostToNetwork(uint32_t host) +{ + return htonl(host); +} + +uint32_t NetworkToHost(uint32_t network) +{ + return ntohl(network); +} + +char *ParseLogMac(uint8_t macAddr[DHCP_HWADDR_LENGTH]) +{ + static char strLogMacAddr[MAD_ADDR_BUF_SIZE] = {0}; + if (!macAddr) { + return 0; + } + if (memset_s(strLogMacAddr, MAD_ADDR_BUF_SIZE, '\0', MAD_ADDR_BUF_SIZE) != EOK || + sprintf_s(strLogMacAddr, MAD_ADDR_BUF_SIZE, "??:%02x:??:??:%02x:%02x", macAddr[NUM_ONE], macAddr[MAI_FOUR], + macAddr[MAI_FIVE]) < 0) { + return 0; + } + return strLogMacAddr; +} + +int IsEmptyHWAddr(uint8_t macAddr[DHCP_HWADDR_LENGTH]) +{ + for (int i = 0; i < MAC_ADDR_LENGTH; i++) { + if (macAddr[i] != 0) { + return DHCP_FALSE; + } + } + return DHCP_TRUE; +} + +int AddrEquels(uint8_t firstAddr[DHCP_HWADDR_LENGTH], uint8_t secondAddr[DHCP_HWADDR_LENGTH], int addrLength) +{ + int len = addrLength; + if (len > DHCP_HWADDR_LENGTH) { + len = DHCP_HWADDR_LENGTH; + } + for (int i = 0; i < len; i++) { + if ((firstAddr[i] != secondAddr[i])) { + return DHCP_FALSE; + } + } + return DHCP_TRUE; +} \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/common_util.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/common_util.c new file mode 100644 index 000000000..e413b050d --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/common_util.c @@ -0,0 +1,201 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 "common_util.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "dhcp_logger.h" +#include "dhcp_define.h" + +#define NEW_FILEPATH_MODE 0755 +#define TIME_BASE_YEAR 1900 +#define TIME_SEC_TO_USEC (1000 * 1000) + +#undef LOG_TAG +#define LOG_TAG "DhcpServerCommon" + +typedef struct tm *ptm; +void LogTime() +{ + time_t curr; + time(&curr); + ptm tt = localtime(&curr); + tt->tm_year += TIME_BASE_YEAR; + printf("[%04d-%02d-%02d %02d:%02d:%02d", + tt->tm_year, + tt->tm_mon + 1, + tt->tm_mday, + tt->tm_hour, + tt->tm_min, + tt->tm_sec); +} + +uint64_t Tmspusec() +{ + struct timeval t; + gettimeofday(&t, 0); + return (uint64_t)((long long)t.tv_sec * TIME_SEC_TO_USEC + t.tv_usec); +} + +uint64_t Tmspsec() +{ + struct timeval t; + gettimeofday(&t, 0); + return (uint64_t)((long long)t.tv_sec); +} + +void LeftTrim(char *buf) +{ + if (buf == NULL || (buf[0] != ' ' && buf[0] != '\t')) { + return; + } + int i = 0; + while (buf[i] == ' ' || buf[i] == '\t') { + ++i; + } + int j = 0; + while (buf[i] != '\0') { + buf[j++] = buf[i++]; + } + buf[j] = '\0'; + return; +} + +void RightTrim(char *buf) +{ + if (buf == NULL || buf[0] == '\0') { + return; + } + int i = strlen(buf) - 1; + while (i >= 0 && (buf[i] == ' ' || buf[i] == '\t')) { + buf[i] = '\0'; + --i; + } + return; +} + +void TrimString(char *buf) +{ + RightTrim(buf); + LeftTrim(buf); + return; +} + +const char *GetFilePath(const char *fileName) +{ + static char currFilePath[DHCP_MAX_PATH_LENGTH]; + if (!fileName) { + return 0; + } + int flen = strlen(fileName); + if (!flen) { + return 0; + } + char currName[DHCP_MAX_PATH_LENGTH] = {'\0'}; + if (memcpy_s(currName, sizeof(currName), fileName, strlen(fileName)) != EOK) { + return 0; + } + char *last = strrchr(currName, '/'); + if (last) { + *last = '\0'; + } + if (memset_s(currFilePath, sizeof(currFilePath), '\0', sizeof(currFilePath)) != EOK) { + return 0; + } + if (memcpy_s(currFilePath, sizeof(currFilePath), currName, strlen(currName)) != EOK) { + return 0; + } + return currFilePath; +} + +const char *GetLeaseFile(const char *fileName, const char *ifname) +{ + static char leaseFileName[DHCP_MAX_PATH_LENGTH]; + if (!fileName || ifname) { + return 0; + } + if (snprintf_s(leaseFileName, sizeof(leaseFileName), sizeof(leaseFileName) - 1, "%s.%s", fileName, ifname) < 0) { + LOGE("Failed to get dhcp lease file path!"); + return 0; + } + return leaseFileName; +} + +int CreatePath(const char *fileName) +{ + if (!fileName) { + return RET_FAILED; + } + int len = strlen(fileName); + if (!len) { + return RET_FAILED; + } + char filePath[DHCP_MAX_PATH_LENGTH] = {'\0'}; + if (strncpy_s(filePath, sizeof(filePath), fileName, len) != EOK) { + return RET_FAILED; + } + for (int i = 0; i < len; i++) { + if (filePath[i] == '/') { + filePath[i] = '\0'; + if (access(filePath, 0) != 0) { + mkdir(filePath, NEW_FILEPATH_MODE); + } + filePath[i] = '/'; + } + } + if (len > 0 && access(filePath, 0) != 0) { + mkdir(filePath, NEW_FILEPATH_MODE); + } + return RET_SUCCESS; +} + +int RemoveSpaceCharacters(char *buf, size_t bufSize) +{ + if ((buf == NULL) || (strlen(buf) == 0) || (bufSize == 0)) { + LOGE("RemoveSpaceCharacters() buf == NULL or len == 0!"); + return DHCP_FALSE; + } + + /* Handle rightmost spaces. */ + int nEnd = strlen(buf) - 1; + while ((nEnd >= 0) && isspace(buf[nEnd])) { + buf[nEnd--] = '\0'; + } + + /* Handle leftmost spaces. */ + int i = 0; + while (isspace(buf[i])) { + buf[i++] = '\0'; + } + + int j = 0; + while (buf[i] != '\0') { + buf[j++] = buf[i++]; + } + buf[j] = '\0'; + + return DHCP_TRUE; +} \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_address_pool.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_address_pool.c new file mode 100644 index 000000000..efe43bd78 --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_address_pool.c @@ -0,0 +1,616 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 "dhcp_address_pool.h" +#include +#include +#include +#include +#include +#include "securec.h" +#include "address_utils.h" +#include "common_util.h" +#include "dhcp_logger.h" + +#undef LOG_TAG +#define LOG_TAG "DhcpServerAddressPool" + +#define DHCP_POOL_INIT_SIZE 10 +#define DHCP_RELEASE_REMOVE_MODE 0 + +static int g_releaseRemoveMode = DHCP_RELEASE_REMOVE_MODE; +static HashTable g_bindingRecoders; +static int g_distributeMode = 0; + +AddressBinding *QueryBinding(uint8_t macAddr[DHCP_HWADDR_LENGTH], PDhcpOptionList cliOptins) +{ + return GetBindingByMac(&g_bindingRecoders, macAddr); +} + +AddressBinding *GetBindingByMac(HashTable *bindTable, uint8_t macAddr[DHCP_HWADDR_LENGTH]) +{ + if (!bindTable) { + LOGE("binding table pointer is null."); + return NULL; + } + if (!Initialized(bindTable)) { + LOGE("binding recoders table dosn't initialized"); + return NULL; + } + if (ContainsKey(&g_bindingRecoders, (uintptr_t)macAddr)) { + return (AddressBinding *)At(bindTable, (uintptr_t)macAddr); + } + return NULL; +} + +AddressBinding *GetBindingByIp(HashTable *bindTable, uint32_t ipAddress) +{ + if (!bindTable) { + LOGE("binding table pointer is null."); + return NULL; + } + if (!Initialized(bindTable)) { + LOGE("binding recoders table dosn't initialized"); + return NULL; + } + if (ContainsKey(bindTable, (uintptr_t)&ipAddress)) { + return (AddressBinding *)At(bindTable, (uintptr_t)&ipAddress); + } + return NULL; +} + +AddressBinding *AddNewBinding(uint8_t macAddr[DHCP_HWADDR_LENGTH], PDhcpOptionList cliOptins) +{ + AddressBinding newBind = {0}; + newBind.bindingMode = BIND_MODE_DYNAMIC; + newBind.bindingStatus = BIND_PENDING; + memcpy_s(newBind.chaddr, DHCP_HWADDR_LENGTH, macAddr, DHCP_HWADDR_LENGTH); + newBind.bindingTime = Tmspsec(); + newBind.pendingTime = Tmspsec(); + newBind.expireIn = newBind.bindingTime + DHCP_LEASE_TIME; + newBind.leaseTime = DHCP_LEASE_TIME; + Insert(&g_bindingRecoders, (uintptr_t)macAddr, (uintptr_t)&newBind); + return GetBindingByMac(&g_bindingRecoders, macAddr); +} + +int CheckIpAvailability(DhcpAddressPool *pool, uint8_t macAddr[DHCP_HWADDR_LENGTH], uint32_t distIp) +{ + if (!pool) { + LOGE("pool pointer is null."); + return DHCP_FALSE; + } + if (IsReserved(macAddr)) { + LOGW("client address(%s) is reserved address.", ParseLogMac(macAddr)); + return DHCP_FALSE; + } + AddressBinding *lease = GetLease(pool, distIp); + if (lease) { + int same = AddrEquels(lease->chaddr, macAddr, MAC_ADDR_LENGTH); + if (distIp == pool->serverId || distIp == pool->gateway) { + return DHCP_FALSE; + } + if (lease->bindingMode == BIND_MODE_STATIC && !same) { + return DHCP_FALSE; + } + if (IsReservedIp(pool, distIp) && !same) { + return DHCP_FALSE; + } + if (same) { + lease->pendingTime = Tmspsec(); + lease->bindingTime = lease->pendingTime; + return DHCP_TRUE; + } + if (IsExpire(lease) && !same) { + LOGD("the binding recoder has expired."); + lease->pendingTime = Tmspsec(); + lease->bindingTime = lease->pendingTime; + RemoveBinding(lease->chaddr); + if (memcpy_s(lease->chaddr, DHCP_HWADDR_LENGTH, macAddr, MAC_ADDR_LENGTH) != EOK) { + LOGD("failed to rewrite client address."); + } + return DHCP_TRUE; + } + return DHCP_FALSE; + } + return DHCP_TRUE; +} + +int CheckRangeAvailability( + DhcpAddressPool *pool, uint8_t macAddr[DHCP_HWADDR_LENGTH], uint32_t distIp, int *outOfRange) +{ + if (!pool || !pool->addressRange.beginAddress || !pool->addressRange.endAddress) { + return RET_ERROR; + } + if (!pool->netmask || IsEmptyHWAddr(macAddr)) { + return RET_ERROR; + } + uint32_t beginIp = pool->addressRange.beginAddress; + uint32_t endIp = pool->addressRange.endAddress; + if (IpInRange(distIp, beginIp, endIp, pool->netmask)) { + LOGD("distribution IP address is: %s", ParseStrIp(distIp)); + AddressBinding lease = {0}; + lease.pendingTime = Tmspsec(); + lease.leaseTime = pool->leaseTime; + lease.bindingMode = BIND_PENDING; + lease.ipAddress = distIp; + lease.bindingTime = lease.pendingTime; + lease.leaseTime = pool->leaseTime; + if (memcpy_s(lease.chaddr, sizeof(lease.chaddr), macAddr, MAC_ADDR_LENGTH) != EOK) { + LOGE("failed to set lease chaddr fields"); + return RET_ERROR; + } + if (AddLease(pool, &lease) != RET_SUCCESS) { + LOGE("failed to add lease."); + return RET_ERROR; + } + return RET_SUCCESS; + } + if (*outOfRange) { + LOGD("out of address range, ip: %s", ParseStrIp(distIp)); + return RET_FAILED; + } else { + distIp = beginIp; + *outOfRange = 1; + } + return RET_FAILED; +} + +uint32_t NextIpOffset(uint32_t netmask) +{ + uint32_t offset = 0; + if (g_distributeMode && netmask) { + uint32_t total = HostTotal(netmask); + if (total) { + offset = Tmspusec() % total; + } + LOGD("next ip offset is: %u", offset); + } + return offset; +} + +uint32_t AddressDistribute(DhcpAddressPool *pool, uint8_t macAddr[DHCP_HWADDR_LENGTH]) +{ + if (!pool || !pool->addressRange.beginAddress || !pool->addressRange.endAddress) { + return 0; + } + if (!pool->netmask || IsEmptyHWAddr(macAddr)) { + return 0; + } + if (pool->distribution == 0) { + pool->distribution = pool->addressRange.beginAddress; + } + int total = HostTotal(pool->netmask); + uint32_t distIp = pool->distribution; + if (distIp < pool->addressRange.beginAddress) { + distIp = pool->addressRange.beginAddress; + pool->distribution = distIp; + } + int distSucess = 0; + int outOfRange = 0; + for (int i = 0; i < total; i++) { + int offset = 0; + if (i == 0) { + offset = NextIpOffset(pool->netmask); + } + distIp = NextIpAddress(distIp, pool->netmask, offset); + if (!CheckIpAvailability(pool, macAddr, pool->distribution)) { + continue; + } + int ret = CheckRangeAvailability(pool, macAddr, distIp, &outOfRange); + if (ret == RET_ERROR) { + break; + } + if (ret == RET_SUCCESS) { + distSucess = 1; + break; + } + } + if (!distSucess || !distIp) { + return 0; + } + pool->distribution = distIp; + return pool->distribution; +} +int InitAddressPool(DhcpAddressPool *pool, const char *ifname, PDhcpOptionList options) +{ + if (!pool) { + LOGD("address pool pointer is null."); + return RET_ERROR; + } + + if (memset_s(pool, sizeof(DhcpAddressPool), 0, sizeof(DhcpAddressPool)) != EOK) { + LOGD("failed to init dhcp pool."); + return RET_ERROR; + } + + if (InitOptionList(&pool->fixedOptions) != RET_SUCCESS) { + LOGD("failed to init options field for dhcp pool."); + return RET_FAILED; + } + + if (CreateHashTable(&pool->leaseTable, sizeof(uint32_t), sizeof(AddressBinding), DHCP_POOL_INIT_SIZE) != + HASH_SUCCESS) { + LOGD("failed to create lease table."); + FreeOptionList(&pool->fixedOptions); + return RET_FAILED; + } + if (!Initialized(&g_bindingRecoders)) { + if (CreateHashTable(&g_bindingRecoders, MAC_ADDR_LENGTH, sizeof(AddressBinding), DHCP_POOL_INIT_SIZE) != + HASH_SUCCESS) { + LOGD("failed to create binding recoding table."); + FreeAddressPool(pool); + return RET_FAILED; + } + } + + pool->distribue = AddressDistribute; + pool->binding = QueryBinding; + pool->newBinding = AddNewBinding; + return RET_SUCCESS; +} + +void FreeAddressPool(DhcpAddressPool *pool) +{ + if (!pool) { + return; + } + + if (pool->fixedOptions.size > 0) { + FreeOptionList(&pool->fixedOptions); + } + + if (pool && Initialized(&pool->leaseTable)) { + DestroyHashTable(&pool->leaseTable); + } + + if (Initialized(&g_bindingRecoders)) { + DestroyHashTable(&g_bindingRecoders); + } +} + +AddressBinding *FindBindingByIp(uint32_t ipAddress) +{ + if (!Initialized(&g_bindingRecoders)) { + if (CreateHashTable(&g_bindingRecoders, MAC_ADDR_LENGTH, sizeof(AddressBinding), DHCP_POOL_INIT_SIZE) != + HASH_SUCCESS) { + LOGD("failed to create binding recoding table."); + return NULL; + } + } + if (!g_bindingRecoders.nodes) { + return NULL; + } + for (size_t current = 0; current < g_bindingRecoders.capacity; ++current) { + HashNode *node = g_bindingRecoders.nodes[current]; + while (node) { + HashNode *next = node->next; + AddressBinding *binding = (AddressBinding *)node->value; + if (binding && ipAddress == binding->ipAddress) { + return binding; + } + node = next; + } + } + return NULL; +} + +int IsReserved(uint8_t macAddr[DHCP_HWADDR_LENGTH]) +{ + if (!Initialized(&g_bindingRecoders)) { + LOGD("binding recoders table dosn't initialized"); + return DHCP_FALSE; + } + if (ContainsKey(&g_bindingRecoders, (uintptr_t)macAddr)) { + AddressBinding *binding = GetBindingByMac(&g_bindingRecoders, macAddr); + if (binding && binding->bindingMode == BIND_MODE_RESERVED) { + return DHCP_TRUE; + } + } + return DHCP_FALSE; +} + +int IsReservedIp(DhcpAddressPool *pool, uint32_t ipAddress) +{ + if (!pool) { + return DHCP_FALSE; + } + if (!ipAddress) { + return DHCP_FALSE; + } + if (ContainsKey(&pool->leaseTable, (uintptr_t)&ipAddress)) { + AddressBinding *lease = GetBindingByIp(&pool->leaseTable, ipAddress); + if (lease && lease->bindingMode == BIND_MODE_RESERVED) { + return DHCP_TRUE; + } + } + return DHCP_FALSE; +} + +int AddBinding(AddressBinding *binding) +{ + if (!Initialized(&g_bindingRecoders)) { + if (CreateHashTable(&g_bindingRecoders, MAC_ADDR_LENGTH, sizeof(AddressBinding), DHCP_POOL_INIT_SIZE) != + HASH_SUCCESS) { + LOGD("failed to create binding recoding table."); + return RET_FAILED; + } + } + if (!binding) { + LOGE("binding pointer is null."); + return RET_ERROR; + } + if (IsEmptyHWAddr(binding->chaddr)) { + LOGE("binding address is empty."); + return RET_ERROR; + } + if (!binding->ipAddress) { + LOGE("binding ip is empty."); + return RET_ERROR; + } + if (!ContainsKey(&g_bindingRecoders, (uintptr_t)binding->chaddr)) { + if (Insert(&g_bindingRecoders, (uintptr_t)binding->chaddr, (uintptr_t)binding) == HASH_INSERTED) { + return RET_SUCCESS; + } + } else { + LOGW("binding recoder exist."); + return RET_FAILED; + } + return RET_FAILED; +} +int AddReservedBinding(uint8_t macAddr[DHCP_HWADDR_LENGTH]) +{ + if (!Initialized(&g_bindingRecoders)) { + if (CreateHashTable(&g_bindingRecoders, MAC_ADDR_LENGTH, sizeof(AddressBinding), DHCP_POOL_INIT_SIZE) != + HASH_SUCCESS) { + LOGD("failed to create binding recoding table."); + return RET_FAILED; + } + } + AddressBinding *binding = GetBindingByMac(&g_bindingRecoders, macAddr); + if (binding) { + binding->bindingMode = BIND_MODE_RESERVED; + } else { + AddressBinding bind = {0}; + bind.bindingMode = BIND_MODE_RESERVED; + bind.bindingTime = Tmspsec(); + bind.pendingTime = bind.bindingTime; + if (Insert(&g_bindingRecoders, (uintptr_t)macAddr, (uintptr_t)&bind) == HASH_INSERTED) { + return RET_SUCCESS; + } + return RET_FAILED; + } + return RET_SUCCESS; +} + +int RemoveBinding(uint8_t macAddr[DHCP_HWADDR_LENGTH]) +{ + if (ContainsKey(&g_bindingRecoders, (uintptr_t)macAddr)) { + if (Remove(&g_bindingRecoders, (uintptr_t)macAddr) == HASH_SUCCESS) { + return RET_SUCCESS; + } + return RET_ERROR; + } + return RET_FAILED; +} + +int RemoveReservedBinding(uint8_t macAddr[DHCP_HWADDR_LENGTH]) +{ + if (ContainsKey(&g_bindingRecoders, (uintptr_t)macAddr)) { + AddressBinding *binding = GetBindingByMac(&g_bindingRecoders, macAddr); + if (!binding) { + LOGE("failed to get binding recoder."); + return RET_FAILED; + } + if (binding->bindingMode == BIND_MODE_RESERVED) { + if (Remove(&g_bindingRecoders, (uintptr_t)macAddr) == HASH_SUCCESS) { + return RET_SUCCESS; + } + LOGE("failed to remove reserved binding recoder."); + } else { + LOGW("binding mode is not 'BIND_MODE_RESERVED'."); + } + return RET_FAILED; + } + return RET_FAILED; +} + +int ReleaseBinding(uint8_t macAddr[DHCP_HWADDR_LENGTH]) +{ + if (ContainsKey(&g_bindingRecoders, (uintptr_t)macAddr)) { + if (g_releaseRemoveMode) { + return Remove(&g_bindingRecoders, (uintptr_t)macAddr); + } + + AddressBinding *binding = GetBindingByMac(&g_bindingRecoders, macAddr); + if (!binding) { + LOGE("failed to query binding."); + return RET_ERROR; + } + binding->bindingStatus = BIND_RELEASED; + return RET_SUCCESS; + } + return RET_FAILED; +} + +int ReBinding(uint8_t macAddr[DHCP_HWADDR_LENGTH]) +{ + if (ContainsKey(&g_bindingRecoders, (uintptr_t)macAddr)) { + AddressBinding *binding = GetBindingByMac(&g_bindingRecoders, macAddr); + if (!binding) { + LOGE("failed to query binding."); + return RET_ERROR; + } + + if (binding->bindingStatus == BIND_ASSOCIATED) { + } + LOGE("client not binding."); + } + return RET_FAILED; +} + +int AddLease(DhcpAddressPool *pool, AddressBinding *lease) +{ + if (!pool) { + return RET_ERROR; + } + + if (!lease || !lease->ipAddress || IsEmptyHWAddr(lease->chaddr)) { + return RET_ERROR; + } + if (!ContainsKey(&pool->leaseTable, (uintptr_t)&lease->ipAddress)) { + if (Insert(&pool->leaseTable, (uintptr_t)&lease->ipAddress, (uintptr_t)lease) == HASH_INSERTED) { + return RET_SUCCESS; + } + } else { + if (Insert(&pool->leaseTable, (uintptr_t)&lease->ipAddress, (uintptr_t)lease) == HASH_UPDATED) { + LOGD("update lease info."); + return RET_SUCCESS; + } + } + return RET_FAILED; +} + +AddressBinding *GetLease(DhcpAddressPool *pool, uint32_t ipAddress) +{ + if (!ipAddress) { + return NULL; + } + + if (!pool) { + return NULL; + } + + if (ContainsKey(&pool->leaseTable, (uintptr_t)&ipAddress)) { + AddressBinding *lease = GetBindingByIp(&pool->leaseTable, ipAddress); + if (!lease) { + LOGE("failed to update lease recoder."); + return NULL; + } + return lease; + } + return NULL; +} + +int UpdateLease(DhcpAddressPool *pool, AddressBinding *lease) +{ + if (!pool) { + return RET_ERROR; + } + + if (!lease || !lease->ipAddress || IsEmptyHWAddr(lease->chaddr)) { + return RET_ERROR; + } + + if (ContainsKey(&pool->leaseTable, (uintptr_t)&lease->ipAddress)) { + if (Insert(&pool->leaseTable, (uintptr_t)&lease->ipAddress, (uintptr_t)lease) == HASH_UPDATED) { + return RET_SUCCESS; + } + } + return RET_FAILED; +} + +int RemoveLease(DhcpAddressPool *pool, AddressBinding *lease) +{ + if (!pool) { + return RET_ERROR; + } + + if (!lease || !lease->ipAddress || IsEmptyHWAddr(lease->chaddr)) { + return RET_ERROR; + } + + if (ContainsKey(&pool->leaseTable, (uintptr_t)&lease->ipAddress)) { + if (Remove(&pool->leaseTable, (uintptr_t)&lease->ipAddress) == HASH_SUCCESS) { + return RET_SUCCESS; + } + } + return RET_FAILED; +} + +int LoadBindingRecoders(DhcpAddressPool *pool) +{ + if (pool == NULL) { + return RET_FAILED; + } + char filePath[DHCP_LEASE_FILE_LENGTH] = {0}; + if (snprintf_s(filePath, sizeof(filePath), sizeof(filePath) - 1, "%s.%s", DHCPD_LEASE_FILE, pool->ifname) < 0) { + LOGE("Failed to get dhcp lease file path!"); + return RET_FAILED; + } + FILE *fp = fopen(filePath, "r"); + LOGD("lease file: %s", filePath); + if (fp == NULL) { + return RET_FAILED; + } + char line[DHCP_FILE_LINE_LENGTH] = {0}; + while (fgets(line, DHCP_FILE_LINE_LENGTH, fp) != NULL) { + TrimString(line); + if (line[0] == '\0') { /* skip empty line */ + continue; + } + AddressBinding bind = {0}; + if (ParseAddressBinding(&bind, line) != 0) { + continue; + } + Insert(&(pool->leaseTable), (uintptr_t)&bind.ipAddress, (uintptr_t)&bind); + } + fclose(fp); + return RET_SUCCESS; +} + +int SaveBindingRecoders(const DhcpAddressPool *pool, int force) +{ + if (pool == NULL) { + return RET_FAILED; + } + static uint64_t lastTime = 0; + uint64_t currTime = Tmspsec(); + if (force == 0 && currTime < lastTime + DHCP_REFRESH_LEASE_FILE_INTERVAL) { + return RET_WAIT_SAVE; + } + char filePath[DHCP_LEASE_FILE_LENGTH] = {0}; + if (snprintf_s(filePath, sizeof(filePath), sizeof(filePath) - 1, "%s.%s", DHCPD_LEASE_FILE, pool->ifname) < 0) { + LOGE("Failed to set dhcp lease file path!"); + return RET_FAILED; + } + char line[DHCP_FILE_LINE_LENGTH] = {0}; + FILE *fp = fopen(filePath, "w"); + if (fp == NULL) { + return RET_FAILED; + } + for (size_t index = 0; index < pool->leaseTable.capacity; ++index) { + HashNode *node = pool->leaseTable.nodes[index]; + while (node != NULL) { + if (WriteAddressBinding((AddressBinding *)node->value, line, sizeof(line)) != RET_SUCCESS) { + LOGW("Failed to convert binding info to string"); + } else { + fprintf(fp, "%s\n", line); + } + node = node->next; + } + } + fclose(fp); + lastTime = currTime; + return RET_SUCCESS; +} + +void SetDistributeMode(int mode) +{ + g_distributeMode = mode; +} +int GetDistributeMode() +{ + return g_distributeMode; +} \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_binding.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_binding.c new file mode 100644 index 000000000..333cc8f39 --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_binding.c @@ -0,0 +1,193 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 "dhcp_binding.h" +#include +#include +#include "dhcp_logger.h" +#include "address_utils.h" +#include "common_util.h" + +#undef LOG_TAG +#define LOG_TAG "DhcpServerBinding" +#define PENDING_INTERVAL_MAX_TIME 1200 +#define PENDING_INTERVAL_LEVEL0 3 +#define PENDING_INTERVAL_LEVEL1 10 +#define PENDING_INTERVAL_LEVEL2 30 +#define PENDING_MIN_WAITING_TIMES 1 +#define PENDING_INTERVAL_LEVEL1_TIMES 2 +#define PENDING_INTERVAL_LEVEL2_TIMES 5 + + +uint64_t NextPendingInterval(uint64_t pendingInterval) +{ + uint64_t next = pendingInterval; + if (next < PENDING_INTERVAL_LEVEL0) { + next += PENDING_MIN_WAITING_TIMES; + } else if (next < PENDING_INTERVAL_LEVEL1) { + next += PENDING_INTERVAL_LEVEL1_TIMES; + } else if (next < PENDING_INTERVAL_LEVEL2) { + next += PENDING_INTERVAL_LEVEL2_TIMES; + } else { + next = PENDING_INTERVAL_MAX_TIME; + } + return next; +} + +int IsExpire(AddressBinding *binding) +{ + if (!binding) { + LOGE("binding is null."); + return DHCP_FALSE; + } + uint64_t expireIn = binding->expireIn; + if (binding->bindingStatus == BIND_PENDING) { + expireIn = binding->pendingTime + binding->leaseTime; + } else if (binding->bindingStatus == BIND_ASSOCIATED) { + expireIn = binding->bindingTime + binding->leaseTime; + } + uint64_t curr = Tmspsec(); + if (curr > expireIn) { + binding->bindingStatus = BIND_EXPIRED; + return DHCP_TRUE; + } + return DHCP_FALSE; +} + +#define BINDING_MAC_ADDR_POS 0 +#define BINDING_IP_ADDR_POS 1 +#define BINDING_LEASE_TIME_POS 2 +#define BINDING_BINDING_TIME_POS 3 +#define BINDING_PENDING_TIME_POS 4 +#define BINDING_PENDING_INTERVAL_POS 5 +#define BINDING_BINDING_MODE_POS 6 +#define BINDING_BINDING_STATUS_POS 7 +#define BINDING_STRING_SIZE 8 + +int WriteAddressBinding(AddressBinding *binding, char *out, uint32_t size) +{ + const char *mac = ParseStrMac(binding->chaddr); + const char *ip = ParseStrIp(binding->ipAddress); + if (mac == NULL || ip == NULL) { + return RET_FAILED; + } + if (snprintf_s(out, size, size - 1, "%s %s %llu %llu %llu %llu %d %d", mac, ip, binding->leaseTime, + binding->bindingTime, binding->pendingTime, binding->pendingInterval, binding->bindingMode, + binding->bindingStatus) < 0) { + return RET_FAILED; + } + return RET_SUCCESS; +} + +static void ReleaseStrings(char **strs) +{ + if (strs == NULL) { + return; + } + int i = 0; + while (strs[i] != NULL) { + free(strs[i]); + ++i; + } + free(strs); + return; +} + +static char **SplitString(const char *buf, const char *split) +{ + const char *pos = buf; + const char *p = NULL; + size_t len = strlen(split); + int num = 0; + while ((p = strstr(pos, split)) != NULL) { + if (p != pos) { + ++num; + } + pos = p + len; + } + if (*pos != '\0') { + ++num; + } + if (num == 0) { + return NULL; + } + char **strs = (char **)calloc(num + 1, sizeof(char *)); + if (strs == NULL) { + return NULL; + } + pos = buf; + num = 0; + while ((p = strstr(pos, split)) != NULL) { + if (p != pos) { + size_t strLen = p - pos + 1; + strs[num] = (char *)calloc(strLen, sizeof(char)); + if (strs[num] == NULL || strncpy_s(strs[num], strLen, pos, p - pos) != EOK) { + ReleaseStrings(strs); + return NULL; + } + ++num; + } + pos = p + len; + } + if (*pos != '\0') { + size_t strLen = strlen(pos) + 1; + strs[num] = (char *)calloc(strLen, sizeof(char)); + if (strs[num] == NULL || strncpy_s(strs[num], strLen, pos, strlen(pos)) != EOK) { + ReleaseStrings(strs); + return NULL; + } + } + return strs; +} + +int ParseAddressBinding(AddressBinding *binding, const char *buf) +{ + uint64_t curr = Tmspsec(); + char **strs = SplitString(buf, " "); + if (strs == NULL) { + return -1; + } + int num = 0; + while (strs[num] != NULL) { + ++num; + } + int ret = -1; + do { + if (num < BINDING_STRING_SIZE) { + break; + } + ParseMacAddress(strs[BINDING_MAC_ADDR_POS], binding->chaddr); + binding->ipAddress = ParseIpAddr(strs[BINDING_IP_ADDR_POS]); + binding->leaseTime = atol(strs[BINDING_LEASE_TIME_POS]); + binding->bindingTime = atol(strs[BINDING_BINDING_TIME_POS]); + binding->pendingTime = atol(strs[BINDING_PENDING_TIME_POS]); + if (binding->bindingTime && binding->bindingTime < binding->pendingTime) { + break; + } + if (binding->pendingTime > curr) { /* if pending time over than current system time */ + binding->bindingTime = binding->bindingTime - binding->pendingTime + curr; + binding->pendingTime = curr; + } + binding->pendingInterval = atol(strs[BINDING_PENDING_INTERVAL_POS]); + binding->bindingMode = atoi(strs[BINDING_BINDING_MODE_POS]); + binding->bindingStatus = atoi(strs[BINDING_BINDING_STATUS_POS]); + if (binding->bindingStatus == BIND_ASSOCIATED) { + binding->expireIn = binding->bindingTime + binding->leaseTime; + } + ret += 1; /* set ret = 0 */ + } while (0); + ReleaseStrings(strs); + return ret; +} diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_config.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_config.c new file mode 100644 index 000000000..d4621a8b7 --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_config.c @@ -0,0 +1,328 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 "dhcp_config.h" +#include +#include +#include +#include +#include +#include "dhcp_logger.h" +#include "common_util.h" +#include "address_utils.h" +#include "dhcp_ipv4.h" +#include "securec.h" + +#undef LOG_TAG +#define LOG_TAG "DhcpServerConfig" + + +#define FILE_LINE_LEN_MAX 1024 +#define FILE_LINE_DELIMITER "=" + +static int SetEnableConfigInfo(DhcpConfig *dhcpConfig, const char *pKey, const char *pValue) +{ + if ((dhcpConfig == NULL) || (pKey == NULL) || (pValue == NULL)) { + LOGE("SetEnableConfigInfo param dhcpConfig or pKey or pValue is NULL!"); + return 0; + } + + uint32_t uValue = (uint32_t)atoi(pValue); + if ((uValue != 0) && (uValue != 1)) { + LOGE("enable:%s error", pValue); + return 0; + } + + if (strcmp(pKey, "distribution") == 0) { + dhcpConfig->distribution = uValue; + } else if (strcmp(pKey, "broadcast") == 0) { + dhcpConfig->broadcast = uValue; + } else { + LOGE("invalid key:%s", pKey); + return 0; + } + return 1; +} + +static int SetTimeConfigInfo(DhcpConfig *dhcpConfig, const char *pKey, const char *pValue) +{ + if ((dhcpConfig == NULL) || (pKey == NULL) || (pValue == NULL)) { + LOGE("SetTimeConfigInfo param dhcpConfig or pKey or pValue is NULL!"); + return 0; + } + + uint32_t uValue = 0; + if ((uValue = (uint32_t)atoi(pValue)) == 0) { + LOGE("atoi failed, time:%s", pValue); + return 0; + } + + if (strcmp(pKey, "leaseTime") == 0) { + dhcpConfig->leaseTime = uValue; + } else if (strcmp(pKey, "renewalTime") == 0) { + dhcpConfig->renewalTime = uValue; + } else if (strcmp(pKey, "rebindingTime") == 0) { + dhcpConfig->rebindingTime = uValue; + } else { + LOGE("invalid key:%s", pKey); + return 0; + } + return 1; +} + +static int SetNetConfigInfo(DhcpConfig *dhcpConfig, const char *pKey, const char *pValue, int common) +{ + if ((dhcpConfig == NULL) || (pKey == NULL) || (pValue == NULL)) { + LOGE("SetNetConfigInfo param dhcpConfig or pKey or pValue is NULL!"); + return 0; + } + + uint32_t uValue = 0; + if ((uValue = ParseIpAddr(pValue)) == 0) { + LOGE("ParseIpAddr failed, ip:%s", pValue); + return 0; + } + + if (((strcmp(pKey, "serverId") == 0) && common) || ((strcmp(pKey, "server") == 0) && !common)) { + dhcpConfig->serverId = uValue; + } else if (strcmp(pKey, "gateway") == 0) { + dhcpConfig->gateway = uValue; + } else if (strcmp(pKey, "netmask") == 0) { + dhcpConfig->netmask = uValue; + } else { + LOGE("invalid key:%s", pKey); + return 0; + } + return 1; +} + +static int SetIpAddressPool(DhcpConfig *dhcpConfig, const char *pValue) +{ + if ((dhcpConfig == NULL) || (pValue == NULL)) { + LOGE("SetIpAddressPool param dhcpConfig or pValue is NULL!"); + return 0; + } + + char *pSrc = (char *)pValue; + char *pSave = NULL; + char *pTok = strtok_r(pSrc, ",", &pSave); + if (((pTok == NULL) || (strlen(pTok) == 0)) || ((pSave == NULL) || (strlen(pSave) == 0))) { + LOGE("strtok_r pTok or pSave NULL or len is 0!"); + return 0; + } + + uint32_t begin; + if (((begin = ParseIpAddr(pTok)) == 0)) { + LOGE("ParseIpAddr begin:%s failed!", pTok); + return 0; + } + dhcpConfig->pool.beginAddress = begin; + uint32_t end; + if (((end = ParseIpAddr(pSave)) == 0)) { + LOGE("ParseIpAddr end:%s failed!", pSave); + return 0; + } + dhcpConfig->pool.endAddress = end; + return 1; +} + +static int SetDnsInfo(DhcpConfig *dhcpConfig, const char *pValue) +{ + if ((dhcpConfig == NULL) || (pValue == NULL)) { + LOGE("SetDnsInfo param dhcpConfig or pValue is NULL!"); + return 0; + } + if (dhcpConfig->options.first == NULL) { + LOGE("set dns options.first pointer is null."); + return 0; + } + + char *pSrc = (char *)pValue; + char *pSave = NULL; + char *pTok = strtok_r(pSrc, ",", &pSave); + if ((pTok == NULL) || (strlen(pTok) == 0)) { + LOGE("strtok_r pTok NULL or len is 0!"); + return 0; + } + + DhcpOption optDns = {DOMAIN_NAME_SERVER_OPTION, 0, {0}}; + if (GetOption(&dhcpConfig->options, optDns.code) != NULL) { + RemoveOption(&dhcpConfig->options, optDns.code); + } + + uint32_t dnsAddress; + while (pTok != NULL) { + if ((dnsAddress = ParseIpAddr(pTok)) == 0) { + LOGE("ParseIpAddr %s failed, code:%d", pTok, optDns.code); + return 0; + } + if (AppendAddressOption(&optDns, dnsAddress) != RET_SUCCESS) { + LOGW("failed append dns option."); + }; + pTok = strtok_r(NULL, ",", &pSave); + } + PushBackOption(&dhcpConfig->options, &optDns); + return 1; +} + +static int SetIfnameInfo(DhcpConfig *dhcpConfig, const char *pValue) +{ + if ((dhcpConfig == NULL) || (pValue == NULL)) { + LOGE("SetIfnameInfo dhcpConfig or pValue is NULL!"); + return 0; + } + if (strlen(pValue) >= IFACE_NAME_SIZE) { + LOGE("ifname:%s too long!", pValue); + return 0; + } + if (memset_s(dhcpConfig->ifname, IFACE_NAME_SIZE, '\0', IFACE_NAME_SIZE) != EOK) { + return 0; + } + if (memcpy_s(dhcpConfig->ifname, IFACE_NAME_SIZE, pValue, strlen(pValue)) != EOK) { + return 0; + } + return 1; +} + +static int SetDhcpConfig(DhcpConfig *dhcpConfig, const char *strLine, int common) +{ + if ((strLine == NULL) || (strlen(strLine) == 0)) { + LOGE("SetDhcpConfig param strLine is NULL or len = 0!"); + return 0; + } + + char *pSrc = (char *)strLine; + char *pSave = NULL; + char *pTok = strtok_r(pSrc, FILE_LINE_DELIMITER, &pSave); + if (pTok == NULL) { + LOGE("strtok_r pTok NULL!"); + return 0; + } + if (strcmp(pTok, "interface") == 0) { + return SetIfnameInfo(dhcpConfig, pSave); + } else if (strcmp(pTok, "dns") == 0) { + return SetDnsInfo(dhcpConfig, pSave); + } else if (strcmp(pTok, "pool") == 0) { + return SetIpAddressPool(dhcpConfig, pSave); + } else if ((((strcmp(pTok, "serverId") == 0) && common) || ((strcmp(pTok, "server") == 0) && !common)) || + (strcmp(pTok, "gateway") == 0) || (strcmp(pTok, "netmask") == 0)) { + return SetNetConfigInfo(dhcpConfig, pTok, pSave, common); + } else if ((strcmp(pTok, "leaseTime") == 0) || (strcmp(pTok, "renewalTime") == 0) || + (strcmp(pTok, "rebindingTime") == 0)) { + return SetTimeConfigInfo(dhcpConfig, pTok, pSave); + } else if ((strcmp(pTok, "distribution") == 0) || (strcmp(pTok, "broadcast") == 0)) { + return SetEnableConfigInfo(dhcpConfig, pTok, pSave); + } else { + LOGE("invalid key:%s", pTok); + return 0; + } +} + +static int ParseConfigFile(const char *configFile, const char *ifname, DhcpConfig *dhcpConfig) +{ + if ((configFile == NULL) || (strlen(configFile) == 0) || (dhcpConfig == NULL)) { + LOGE("ParseConfigFile param configFile or dhcpConfig is NULL or len = 0!"); + return RET_FAILED; + } + + FILE *fp = fopen(configFile, "r"); + if (fp == NULL) { + LOGE("fopen %s failed, err:%s", configFile, strerror(errno)); + return 0; + } + + int bComm = 1; + int bValid = 1; + char strLine[FILE_LINE_LEN_MAX] = {0}; + while (fgets(strLine, FILE_LINE_LEN_MAX, fp) != NULL) { + if ((strchr(strLine, '#') != NULL) || (strchr(strLine, '=') == NULL) || + !RemoveSpaceCharacters(strLine, FILE_LINE_LEN_MAX)) { + if (memset_s(strLine, FILE_LINE_LEN_MAX, 0, FILE_LINE_LEN_MAX) != EOK) { + break; + } + continue; + } + if (memcmp(strLine, "interface", strlen("interface")) == 0) { + bComm = 0; + bValid = 0; + if ((ifname == NULL) || (strlen(ifname) == 0) || (strstr(strLine, ifname) != NULL)) { + LOGI("%s %s find ifname:%s", configFile, strLine, ((ifname == NULL) ? "" : ifname)); + bValid = 1; + } else { + LOGI("%s %s no find ifname:%s", configFile, strLine, ifname); + } + } + if (bValid && !SetDhcpConfig(dhcpConfig, strLine, bComm)) { + LOGE("set dhcp config %s %s failed", configFile, strLine); + return 0; + } + if (memset_s(strLine, FILE_LINE_LEN_MAX, 0, FILE_LINE_LEN_MAX) != EOK) { + break; + } + } + fclose(fp); + return 1; +} + +static int CheckDhcpConfig(DhcpConfig *config) +{ + if (config == NULL) { + LOGE("CheckDhcpConfig param config is null"); + return 0; + } + if ((strlen(config->ifname) > 0) && ((config->serverId == 0))) { + LOGE("failed to config serverId or netmask"); + return 0; + } + + if (config->renewalTime == 0) { + config->renewalTime = config->leaseTime * DHCP_RENEWAL_MULTIPLE; + } + if (config->rebindingTime == 0) { + config->rebindingTime = config->leaseTime * DHCP_REBIND_MULTIPLE; + } + return 1; +} + +int LoadConfig(const char *configFile, const char *ifname, DhcpConfig *config) +{ + if ((configFile == NULL) || (strlen(configFile) == 0) || (ifname == NULL) || (strlen(ifname) == 0) || + (config == NULL)) { + LOGE("LoadConfig param configFile or ifname or config is NULL or len = 0!"); + return RET_FAILED; + } + + /* Default config. */ + config->leaseTime = DHCP_LEASE_TIME; + config->distribution = 1; + config->broadcast = 1; + + /* Set file config. */ + if (!ParseConfigFile(configFile, ifname, config)) { + LOGE("parse config file %s error!", configFile); + return RET_FAILED; + } + LOGI("parse config file %s success", configFile); + + if (!CheckDhcpConfig(config)) { + LOGE("check dhcp config failed"); + return RET_FAILED; + } + + if ((strlen(config->ifname) == 0) && !SetIfnameInfo(config, ifname)) { + LOGE("set ifname %s error!", ifname); + return RET_FAILED; + } + return RET_SUCCESS; +} diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_dhcpd.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_dhcpd.c new file mode 100644 index 000000000..f859a6783 --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_dhcpd.c @@ -0,0 +1,752 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 +#include +#include +#include +#include +#include +#include +#include +#include "dhcp_server.h" +#include "dhcp_define.h" +#include "dhcp_logger.h" +#include "dhcp_ipv4.h" +#include "hash_table.h" +#include "address_utils.h" +#include "securec.h" +#include "common_util.h" +#include "dhcp_config.h" + +#undef LOG_TAG +#define LOG_TAG "DhcpServerMain" + +#define NO_ARG 0 +#define REQUIRED_ARG 1 +#define OPTIONAL_ARG 2 + +#define ARGUMENT_NAME_SIZE 32 +#define ARGUMENT_VALUE_SIZE 256 +#define INIT_ARGS_SIZE 4 +#define USAGE_DESC_MAX_LENGTH 32 +#define DEFAUTL_NET_MASK "255.255.255.0" + +static HashTable g_argumentsTable; +static DhcpConfig g_dhcpConfig; + +static PDhcpServerContext g_dhcpServer = 0; + +typedef struct DhcpUsage DhcpUsage; +struct DhcpUsage { + struct option *opt; + const char *params; + const char *desc; + const char *example; + int required; + int (*dealOption)(const char *, const char *); +}; + +typedef struct ArgumentInfo ArgumentInfo; +struct ArgumentInfo { + char name[ARGUMENT_NAME_SIZE]; + char value[ARGUMENT_VALUE_SIZE]; +}; + +enum SignalEvent { + EXIT = 0, + RELOAD, + RESTART, +}; + +static struct option longOptions[] = { + {"ifname", REQUIRED_ARG, 0, 'i'}, + {"conf", REQUIRED_ARG, 0, 'c'}, + {"dns", REQUIRED_ARG, 0, 'd'}, + {"gateway", REQUIRED_ARG, 0, 'g'}, + {"server", REQUIRED_ARG, 0, 's'}, + {"netmask", REQUIRED_ARG, 0, 'n'}, + {"pool", REQUIRED_ARG, 0, 'P'}, + {"lease", REQUIRED_ARG, 0, 0}, + {"renewal", REQUIRED_ARG, 0, 0}, + {"rebinding", REQUIRED_ARG, 0, 0}, + {"version", NO_ARG, 0, 'v'}, + {"help", NO_ARG, 0, 'h'}, + {0, 0, 0, 0}, +}; + +typedef struct DhcpOptionField { + const char *field; + int code; + const char *explain; + const char *format; + int supported; + int (*parseOption)(DhcpOption *, int, char *); + +} DhcpOptionField; + +static int InitArguments() +{ + if (CreateHashTable(&g_argumentsTable, ARGUMENT_NAME_SIZE, sizeof(ArgumentInfo), INIT_ARGS_SIZE) != HASH_SUCCESS) { + return RET_FAILED; + } + return RET_SUCCESS; +} + +static void FreeArguments() +{ + if (!Initialized(&g_argumentsTable)) { + return; + } + DestroyHashTable(&g_argumentsTable); +} + +static int HasArgument(const char *argument) +{ + char name[ARGUMENT_NAME_SIZE] = {'\0', 0}; + if (!argument) { + return 0; + } + size_t ssize = strlen(argument); + if (ssize > ARGUMENT_NAME_SIZE) { + ssize = ARGUMENT_NAME_SIZE; + } + if (memcpy_s(name, ARGUMENT_NAME_SIZE, argument, ssize) != EOK) { + LOGE("failed to set argument name."); + return 0; + } + if (ContainsKey(&g_argumentsTable, (uintptr_t)name)) { + return 1; + } + return 0; +} + +static ArgumentInfo *GetArgument(const char *name) +{ + char argName[ARGUMENT_NAME_SIZE] = {'\0'}; + size_t ssize = strlen(name); + if (ssize > ARGUMENT_NAME_SIZE) { + ssize = ARGUMENT_NAME_SIZE; + } + if (memcpy_s(argName, ARGUMENT_NAME_SIZE, name, ssize) != EOK) { + LOGE("failed to set argument name."); + return NULL; + } + if (ContainsKey(&g_argumentsTable, (uintptr_t)argName)) { + ArgumentInfo *arg = (ArgumentInfo *)At(&g_argumentsTable, (uintptr_t)argName); + return arg; + } + return NULL; +} + +static int DefaultArgument(const char *argument, const char *val) +{ + LOGD("Input argument is: [%s], value is [%s]", (argument == NULL) ? "" : argument, + (val == NULL) ? "" : val); + return RET_SUCCESS; +} + +static int PutArgument(const char *argument, const char *val) +{ + if (!argument) { + return 0; + } + if (!val) { + return RET_FAILED; + } + + if (HasArgument(argument)) { + return RET_FAILED; + } + + ArgumentInfo arg; + size_t ssize = strlen(argument); + if (ssize >= ARGUMENT_NAME_SIZE) { + ssize = ARGUMENT_NAME_SIZE -1; + } + size_t vlen = strlen(val); + if (memset_s(arg.name, ARGUMENT_NAME_SIZE, '\0', ARGUMENT_NAME_SIZE) != EOK) { + LOGE("failed to reset argument name."); + return RET_ERROR; + } + if (memcpy_s(arg.name, ARGUMENT_NAME_SIZE, argument, ssize) != EOK) { + LOGE("failed to set argument name."); + return RET_ERROR; + } + if (vlen < 0) { + return RET_ERROR; + } + if (vlen >= ARGUMENT_VALUE_SIZE) { + LOGE("value string too long."); + return RET_ERROR; + } + if (memset_s(arg.value, ARGUMENT_VALUE_SIZE, '\0', ARGUMENT_NAME_SIZE) != EOK) { + LOGE("failed to reset argument value."); + return RET_ERROR; + } + if (memcpy_s(arg.value, ARGUMENT_VALUE_SIZE, val, vlen) != EOK) { + LOGE("failed to set argument value."); + return RET_ERROR; + } + int ret = Insert(&g_argumentsTable, (uintptr_t)arg.name, (uintptr_t)&arg); + if (ret == HASH_INSERTED) { + return RET_SUCCESS; + } + return RET_FAILED; +} + +static int PutIpArgument(const char *argument, const char *val) +{ + if (!ParseIpAddr(val)) { + LOGE("%s format error.", argument); + return RET_FAILED; + } + return PutArgument(argument, val); +} + +static int PutPoolArgument(const char *argument, const char *val) +{ + if (!val) { + return 0; + } + if (strchr(val, ',') == NULL) { + LOGE("too few pool option arguments."); + return RET_FAILED; + } + return PutArgument(argument, val); +} + +static int ShowVersion(const char *argument, const char *val) +{ + printf("version:%s\n", DHCPD_VERSION); + return RET_BREAK; +} + +const char *optionString = "i:c:d:g:s:n:P:S:Bp:o:lb:rvhD"; +static DhcpUsage usages[] = { + {&longOptions[NUM_ZERO], "", "network interface name.", "--ifname eth0", 1, PutArgument}, + {&longOptions[NUM_ONE], "", "configure file name.", "--conf /etc/conf/dhcp_server.conf", 0, PutArgument}, + {&longOptions[NUM_TWO], "[,dns2][,dns3][...]", "domain name server IP address list.", "", 0, PutArgument}, + {&longOptions[NUM_THREE], "", "gateway option.", "", 0, PutIpArgument}, + {&longOptions[NUM_FOUR], "", "server identifier.", "", 1, PutIpArgument}, + {&longOptions[NUM_FIVE], "", "default subnet mask.", "", 1, PutIpArgument}, + {&longOptions[NUM_SIX], ",", "pool address range.", "", 0, + PutPoolArgument}, + {&longOptions[NUM_SEVEN], "", "set lease time value, the value is in units of seconds.", "", 0, + PutArgument}, + {&longOptions[NUM_EIGHT], "", "set renewal time value, the value is in units of seconds.", "", 0, + PutArgument}, + {&longOptions[NUM_NINE], "", "set rebinding time value, the value is in units of seconds.", "", 0, + PutArgument}, + {&longOptions[NUM_TEN], "", "show version information.", "", 0, ShowVersion}, + {&longOptions[NUM_ELEVEN], "", "show help information.", "", 0, DefaultArgument}, + {0, "", "", ""}, +}; + +int findIndex(int c) +{ + int size = sizeof(longOptions) / sizeof(longOptions[0]); + for (int i = 0; i < size; ++i) { + if (longOptions[i].val == c) { + return i; + } + } + return -1; +} + +void ShowUsage(const DhcpUsage *usage) +{ + if (!usage) { + return; + } + if (usage->opt->val) { + printf("-%c,--%s ", usage->opt->val, usage->opt->name); + } else { + printf(" --%s ", usage->opt->name); + } + if (usage->params[0] == '\0') { + printf("\t%s\n", usage->desc); + } else { + int plen = strlen(usage->params) + strlen(usage->params); + if (plen < USAGE_DESC_MAX_LENGTH) { + printf("\t\t%s\t\t%s\n", usage->params, usage->desc); + } else { + printf("\t\t%s\n", usage->params); + printf("\t\t\t%s\n\n", usage->desc); + } + } +} + +void PrintRequiredArguments() +{ + size_t argc = sizeof(usages) / sizeof(DhcpUsage); + printf("required parameters:"); + int idx = 0; + for (size_t i = 0; i < argc; i++) { + DhcpUsage usage = usages[i]; + if (!usage.opt) { + break; + } + if (usage.required) { + if (idx == 0) { + printf("\"%s\"", usage.opt->name); + } else { + printf(", \"%s\"", usage.opt->name); + } + idx++; + } + } + printf(".\n\n"); + printf("Usage: dhcp_server [options] \n"); + printf("e.g: dhcp_server -i eth0 -c /data/dhcp/dhcp_server.conf \n"); + printf(" dhcp_server --help \n\n"); +} + +void PrintUsage() +{ + printf("Usage: dhcp_server [options] \n\n"); + + size_t argc = sizeof(usages) / sizeof(DhcpUsage); + for (size_t i = 0; i < argc; i++) { + DhcpUsage usage = usages[i]; + if (!usage.opt) { + break; + } + ShowUsage(&usage); + } + printf("\n"); +} + +void ShowHelp(int argc, char *argv[]) +{ + if (argc == NUM_TWO) { + PrintUsage(); + return; + } +} + +int ParseArguments(int argc, char *argv[]) +{ + int ret; + opterr = 0; + size_t optsc = sizeof(usages) / sizeof(DhcpUsage); + int index = -1; + int rst = RET_SUCCESS; + + while ((ret = getopt_long(argc, argv, optionString, longOptions, &index)) != -1) { + if (ret == '?') { + LOGW("unknown input arguments! ret = ?"); + index = -1; + continue; + } + if (index < 0) { + index = findIndex(ret); + } + if (index < 0 || index >= (int)optsc) { + LOGD("unknown input arguments! ret = %c, index = %d", ret, index); + index = -1; + continue; + } + DhcpUsage *usage = &usages[index]; + rst = usage->dealOption(usage->opt->name, optarg); + if (rst != RET_SUCCESS) { + break; + } + index = -1; + } + + + return rst; +} + +void LoadLocalConfig(DhcpAddressPool *pool) +{ + LOGD("loading local configure ..."); +} + +void ReloadLocalConfig(DhcpAddressPool *pool) +{ + LOGD("reloading local configure ..."); +} + +static int InitNetworkAbout(DhcpConfig *config) +{ + ArgumentInfo *arg = GetArgument("netmask"); + if (arg) { + LOGI("subnet mask:%s", arg->value); + uint32_t argNetmask = ParseIpAddr(arg->value); + if (argNetmask) { + config->netmask = argNetmask; + } else { + LOGW("error netmask argument."); + return RET_FAILED; + } + } else { + if (!config->netmask) { + config->netmask = ParseIpAddr(DEFAUTL_NET_MASK); + } + } + arg = GetArgument("gateway"); + if (arg) { + LOGI("gateway:%s", arg->value); + uint32_t argGateway = ParseIpAddr(arg->value); + if (argGateway) { + config->gateway = argGateway; + } else { + LOGE("error gateway argument."); + return RET_FAILED; + } + } + return RET_SUCCESS; +} + +static int PareseAddreesRange(DhcpConfig *config) +{ + ArgumentInfo *arg = GetArgument("pool"); + if (arg) { + LOGD("pool info:%s", arg->value); + int index = 0; + char *src = arg->value; + char *delim = ","; + char *poolPartArg; + poolPartArg = strtok(src, delim); + while (poolPartArg) { + if (index == 0) { + config->pool.beginAddress = ParseIpAddr(poolPartArg); + LOGD("address range begin of: %s", poolPartArg); + } else if (index == 1) { + config->pool.endAddress = ParseIpAddr(poolPartArg); + LOGD("address range end of: %s", poolPartArg); + } + index++; + poolPartArg = strtok(NULL, delim); + } + if (!config->pool.beginAddress || !config->pool.endAddress) { + LOGE("'pool' argument format error."); + return RET_FAILED; + } + return RET_SUCCESS; + } + LOGW("failed to get 'pool' argument."); + return RET_FAILED; +} + +static int InitAddressRange(DhcpConfig *config) +{ + if (HasArgument("pool")) { + if (PareseAddreesRange(config) != RET_SUCCESS) { + LOGW("dhcp range config error."); + return RET_FAILED; + } + } else { + if (!config->pool.beginAddress || !config->pool.endAddress) { + config->pool.beginAddress = FirstIpAddress(config->serverId, config->netmask); + config->pool.endAddress = LastIpAddress(config->serverId, config->netmask); + } + } + return RET_SUCCESS; +} + +static int InitDomainNameServer(DhcpConfig *config) +{ + ArgumentInfo *arg = GetArgument("dns"); + if (arg) { + DhcpOption argOpt = {DOMAIN_NAME_SERVER_OPTION, 0, {0}}; + + char *pSave = NULL; + char *pTok = strtok_r(arg->value, ",", &pSave); + if ((pTok == NULL) || (strlen(pTok) == 0)) { + LOGE("strtok_r pTok NULL or len is 0!"); + return RET_FAILED; + } + uint32_t dnsAddress; + while (pTok != NULL) { + if ((dnsAddress = ParseIpAddr(pTok)) == 0) { + LOGE("ParseIpAddr %s failed, code:%d", pTok, argOpt.code); + return RET_FAILED; + } + if (AppendAddressOption(&argOpt, dnsAddress) != RET_SUCCESS) { + LOGW("failed to append dns option."); + }; + pTok = strtok_r(NULL, ",", &pSave); + } + + if (GetOption(&config->options, argOpt.code) != NULL) { + RemoveOption(&config->options, DOMAIN_NAME_SERVER_OPTION); + } + PushBackOption(&config->options, &argOpt); + } + return RET_SUCCESS; +} + +static int InitServerId(DhcpConfig *config) +{ + ArgumentInfo *arg = GetArgument("server"); + if (arg) { + LOGI("server id:%s", arg->value); + uint32_t argServerId = ParseIpAddr(arg->value); + if (argServerId) { + config->serverId = argServerId; + } else { + LOGE("error server argument."); + return RET_FAILED; + } + } else { + if (!config->serverId) { + LOGE("failed to get 'server' argument or config item."); + return RET_FAILED; + } + } + return RET_SUCCESS; +} + +static int InitLeaseTime(DhcpConfig *config) +{ + ArgumentInfo *arg = GetArgument("lease"); + if (arg) { + config->leaseTime = atoi(arg->value); + } else { + if (!config->leaseTime) { + config->leaseTime = DHCP_LEASE_TIME; + } + } + return RET_SUCCESS; +} + +static int InitRenewalTime(DhcpConfig *config) +{ + ArgumentInfo *arg = GetArgument("renewal"); + if (arg) { + config->renewalTime = atoi(arg->value); + } else { + if (!config->rebindingTime) { + config->rebindingTime = DHCP_RENEWAL_TIME; + } + config->renewalTime = DHCP_RENEWAL_TIME; + } + return RET_SUCCESS; +} + +static int InitRebindingTime(DhcpConfig *config) +{ + ArgumentInfo *arg = GetArgument("rebinding"); + if (arg) { + config->rebindingTime = atoi(arg->value); + } else { + if (!config->rebindingTime) { + config->rebindingTime = DHCP_REBINDING_TIME; + } + } + return RET_SUCCESS; +} +static int InitConfigByArguments(DhcpConfig *config) +{ + if (!config) { + LOGE("dhcp configure pointer is null."); + return RET_FAILED; + } + if (InitServerId(config) != RET_SUCCESS) { + return RET_FAILED; + } + if (InitNetworkAbout(config) != RET_SUCCESS) { + return RET_FAILED; + } + if (InitAddressRange(config) != RET_SUCCESS) { + return RET_FAILED; + } + if (InitLeaseTime(config) != RET_SUCCESS) { + return RET_FAILED; + } + if (InitRenewalTime(config) != RET_SUCCESS) { + return RET_FAILED; + } + if (InitRebindingTime(config) != RET_SUCCESS) { + return RET_FAILED; + } + if (InitDomainNameServer(config) != RET_SUCCESS) { + return RET_FAILED; + } + return RET_SUCCESS; +} + +int ServerActionCallback(int state, int code, const char *ifname) +{ + int ret = 0; + switch (state) { + case ST_STARTING: { + if (code == 0) { + LOGD(" callback[%s] ==> server starting ...", ifname); + } else if (code == 1) { + LOGD(" callback[%s] ==> server started.", ifname); + } else if (code == NUM_TWO) { + LOGD(" callback[%s] ==> server start failed.", ifname); + } + break; + } + case ST_RELOADNG: { + LOGD(" callback[%s] ==> reloading ...", ifname); + break; + } + case ST_STOPED: { + LOGD(" callback[%s] ==> server stoped.", ifname); + exit(0); + break; + } + default: + break; + } + return ret; +} + +static void SignalHandler(int signal) +{ + switch (signal) { + case SIGTERM: { + StopDhcpServer(g_dhcpServer); + break; + } + case SIGUSR1: + break; + default: + break; + } +} + +static int RegisterSignalHandle(void) +{ + if (signal(SIGTERM, SignalHandler) == SIG_ERR) { + LOGE("RegisterSignalHandle() failed, signal SIGTERM err:%s!", strerror(errno)); + return RET_FAILED; + } + + if (signal(SIGUSR1, SignalHandler) == SIG_ERR) { + LOGE("RegisterSignalHandle() failed, signal SIGUSR1 err:%s!", strerror(errno)); + return RET_FAILED; + } + + return RET_SUCCESS; +} + +int ValidateArguments() +{ + size_t argc = sizeof(usages) / sizeof(DhcpUsage); + for (size_t i = 0; i < argc; i++) { + DhcpUsage usage = usages[i]; + if (!usage.opt) { + break; + } + if (usage.required && !HasArgument(usage.opt->name)) { + printf("missing required parameter '%s' \n", usage.opt->name); + return 0; + } + } + return 1; +} + +static int InitializeDhcpConfig(const char *ifname, DhcpConfig *config) +{ + if (!config) { + LOGE("dhcp configure pointer is null."); + return RET_FAILED; + } + if (InitOptionList(&config->options) != RET_SUCCESS) { + LOGE("failed to initialize options."); + return RET_FAILED; + } + char *configFile = DHCPD_CONFIG_FILE; + if (HasArgument("conf")) { + ArgumentInfo *configArg = GetArgument("conf"); + if (configArg) { + configFile = configArg->value; + } else { + LOGE("failed to get config file name."); + return RET_FAILED; + } + } + LOGD("load local config file:%s", configFile); + if (LoadConfig(configFile, ifname, config) != RET_SUCCESS) { + LOGE("faile to load configure file."); + return RET_FAILED; + } + if (InitConfigByArguments(config) != RET_SUCCESS) { + LOGE("faile to parse arguments."); + return RET_FAILED; + } + + return RET_SUCCESS; +} + +static void FreeLocalConfig() +{ + FreeOptionList(&g_dhcpConfig.options); +} + +void FreeSeverResources() +{ + FreeArguments(); + FreeLocalConfig(); + FreeServerContex(g_dhcpServer); +} +int main(int argc, char *argv[]) +{ + if (argc == 1) { + PrintRequiredArguments(); + return 1; + } + if (strcmp("-h", argv[argc - 1]) == 0 || strcmp("--help", argv[argc - 1]) == 0) { + ShowHelp(argc, argv); + return 0; + } + if (InitArguments() != RET_SUCCESS) { + LOGE("failed to init arguments table."); + return 1; + } + int ret = ParseArguments(argc, argv); + if (ret != RET_SUCCESS) { + FreeArguments(); + return 1; + } + ArgumentInfo *ifaceName = GetArgument("ifname"); + if (!ifaceName || strlen(ifaceName->value) == 0) { + printf("missing required parameters:\"ifname\"\n"); + FreeArguments(); + return 1; + } + if (InitializeDhcpConfig(ifaceName->value, &g_dhcpConfig) != RET_SUCCESS) { + LOGW("failed to initialize config."); + } + g_dhcpServer = InitializeServer(&g_dhcpConfig); + if (g_dhcpServer == NULL) { + LOGE("failed to initialize dhcp server."); + FreeArguments(); + return 1; + } + if (RegisterSignalHandle() != RET_SUCCESS) { + FreeSeverResources(); + return 1; + } + RegisterDhcpCallback(g_dhcpServer, ServerActionCallback); + if (StartDhcpServer(g_dhcpServer)) { + FreeSeverResources(); + return 1; + } + FreeSeverResources(); + return 0; +} \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_option.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_option.c new file mode 100644 index 000000000..882536710 --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_option.c @@ -0,0 +1,298 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 "dhcp_option.h" +#include +#include +#include +#include "dhcp_define.h" +#include "dhcp_logger.h" +#include "securec.h" + +#undef LOG_TAG +#define LOG_TAG "DhcpServerOption" + +PDhcpOptionNode CreateOptionNode(PDhcpOption opt) +{ + if (!opt) { + LOGE("input parameter is null."); + return NULL; + } + if ((int)opt->length > DHCP_OPTION_SIZE) { + LOGE("input parameter length error. length:%hhu", opt->length); + return NULL; + } + DhcpOptionNode *pNode = (DhcpOptionNode *)calloc(1, sizeof(DhcpOptionNode)); + if (pNode == NULL) { + LOGE("failed to create dhcp option node!"); + return NULL; + } + pNode->option.code = opt->code; + pNode->option.length = opt->length; + memcpy_s(pNode->option.data, opt->length, opt->data, opt->length); + pNode->previous = pNode->next = 0; + + return pNode; +} + +int HasInitialized(PDhcpOptionList pOptions) +{ + if (!pOptions) { + LOGE("option list pointer is null."); + return 0; + } + if (pOptions->first != NULL) { + return 1; + } + return 0; +} + +int InitOptionList(PDhcpOptionList pOptions) +{ + if (!pOptions) { + return RET_ERROR; + } + if (pOptions->first != NULL && pOptions->first == pOptions->last) { + return RET_SUCCESS; + } + + DhcpOptionNode *pNode = (DhcpOptionNode *)calloc(1, sizeof(DhcpOptionNode)); + if (!pNode) { + LOGE("failed to create dhcp option node!"); + return 1; + } + + pOptions->size = 0; + pOptions->first = pOptions->last = pNode; + pOptions->first->previous = NULL; + pOptions->last->next = NULL; + return RET_SUCCESS; +} + +int PushBackOption(PDhcpOptionList pOptions, PDhcpOption pOption) +{ + if (!pOptions) { + LOGE("option list pointer is null."); + return RET_ERROR; + } + if (!pOption) { + LOGE("option pointer is null."); + return RET_ERROR; + } + if (pOptions->first == NULL) { + LOGE("option list not initialized"); + return RET_SUCCESS; + } + DhcpOptionNode *pNode = CreateOptionNode(pOption); + if (!pNode) { + LOGE("failed to crate option node."); + return 1; + } + pNode->previous = pOptions->last; + pOptions->last->next = pNode; + pOptions->last = pNode; + pOptions->size++; + + return RET_SUCCESS; +} + +int PushFrontOption(PDhcpOptionList pOptions, PDhcpOption pOption) +{ + if (!pOptions) { + LOGE("option list pointer is null."); + return RET_ERROR; + } + if (!pOption) { + LOGE("option pointer is null."); + return RET_ERROR; + } + PDhcpOptionNode pNode = CreateOptionNode(pOption); + if (!pNode) { + return RET_FAILED; + } + + if (pOptions->first == pOptions->last) { + pNode->previous = pOptions->first; + pOptions->first->next = pNode; + pOptions->last = pNode; + } else { + pNode->next = pOptions->first->next; + pNode->next->previous = pNode; + pNode->previous = pOptions->first; + pOptions->first->next = pNode; + } + pOptions->size++; + + return RET_SUCCESS; +} + +int RemoveOption(PDhcpOptionList pOptions, uint8_t code) +{ + if (pOptions->size == 0) { + return RET_ERROR; + } + DhcpOptionNode *pNode = GetOptionNode(pOptions, code); + if (pNode == NULL) { + return RET_FAILED; + } + if (pNode == pOptions->last) { + pOptions->last = pNode->previous; + pOptions->last->next = NULL; + } else { + pNode->next->previous = pNode->previous; + pNode->previous->next = pNode->next; + } + pOptions->size--; + free(pNode); + return RET_SUCCESS; +} + +PDhcpOptionNode GetOptionNode(PDhcpOptionList pOptions, uint8_t code) +{ + PDhcpOptionNode pNode = pOptions->first->next; + while (pNode != NULL && pNode->option.code != code) { + pNode = pNode->next; + } + return pNode; +} + +PDhcpOption GetOption(PDhcpOptionList pOptions, uint8_t code) +{ + PDhcpOptionNode pNode = GetOptionNode(pOptions, code); + if (pNode) { + return &pNode->option; + } + return NULL; +} + +void ClearOptions(PDhcpOptionList pOptions) +{ + if (pOptions->size == 0) { + return; + } + DhcpOptionNode *pNode = pOptions->first->next; + while (pNode != NULL) { + if (pNode == pOptions->last) { + pOptions->last = pOptions->first; + pOptions->last->next = NULL; + } else { + pNode->next->previous = pNode->previous; + pNode->previous->next = pNode->next; + } + free(pNode); + pNode = pOptions->first->next; + } + pNode = pOptions->first; + pOptions->size = 0; + pOptions->first = pOptions->last = pNode; + pOptions->first->previous = NULL; + pOptions->last->next = NULL; +} + +void FreeOptionList(PDhcpOptionList pOptions) +{ + if (pOptions->size == 0) { + return; + } + DhcpOptionNode *pNode = pOptions->first->next; + while (pNode != NULL) { + if (pNode == pOptions->last) { + pOptions->last = pOptions->first; + pOptions->last->next = NULL; + } else { + pNode->next->previous = pNode->previous; + pNode->previous->next = pNode->next; + } + free(pNode); + pNode = pOptions->first->next; + } + pOptions->size = 0; + free(pOptions->first); + pOptions->first = pOptions->last = NULL; + return; +} + +int FillOption(PDhcpOption pOption, const char *data, size_t len) +{ + if (!pOption) { + return RET_ERROR; + } + if (!data) { + return RET_FAILED; + } + size_t flen = len; + if (flen > (DHCP_OPTION_SIZE - 1)) { + flen = DHCP_OPTION_SIZE - 1; + } + if (memcpy_s(pOption->data, sizeof(pOption->data) - 1, data, flen) != EOK) { + return RET_ERROR; + } + pOption->length = flen; + return RET_SUCCESS; +} + +int FillU32Option(PDhcpOption pOption, uint32_t u32) +{ + if (!pOption) { + return RET_ERROR; + } + if (memcpy_s(pOption->data, sizeof(pOption->data), &u32, sizeof(uint32_t)) != EOK) { + return RET_ERROR; + } + pOption->length = sizeof(uint32_t); + return RET_SUCCESS; +} + +int FillOptionData(PDhcpOption pOption, const uint8_t *data, size_t len) +{ + int flen = len; + if (!pOption) { + return RET_ERROR; + } + if (!data) { + return RET_FAILED; + } + if (flen > (DHCP_OPTION_SIZE)) { + flen = DHCP_OPTION_SIZE; + } + if (memcpy_s(pOption->data, sizeof(pOption->data), data, flen) != EOK) { + return RET_ERROR; + } + pOption->length = flen; + return RET_SUCCESS; +} + +int AppendAddressOption(PDhcpOption pOption, uint32_t address) +{ + if (!pOption) { + return RET_ERROR; + } + uint8_t addrLen = pOption->length; + uint8_t *pData = pOption->data; + int spaceSize = sizeof(pOption->data) - addrLen; + if (spaceSize < DHCP_ADDRESS_LENGTH) { + LOGE("failed to append address, not enough space for option data."); + return RET_ERROR; + } + if ((int)addrLen > 0) { + pData += addrLen; + } + addrLen = DHCP_ADDRESS_LENGTH; + if (memcpy_s(pData, spaceSize, &address, DHCP_ADDRESS_LENGTH) != EOK) { + return RET_ERROR; + } + pOption->length = addrLen; + return RET_SUCCESS; +} diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_server.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_server.c new file mode 100644 index 000000000..e19301ac9 --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_server.c @@ -0,0 +1,1700 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 "dhcp_server.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "dhcp_ipv4.h" +#include "dhcp_message.h" +#include "dhcp_option.h" +#include "dhcp_ipv4.h" +#include "securec.h" +#include "dhcp_logger.h" +#include "address_utils.h" +#include "common_util.h" +#include "dhcp_address_pool.h" +#include "dhcp_config.h" + +#undef LOG_TAG +#define LOG_TAG "DhcpServer" + +#define DHCP_SEL_WAIT_TIMEOUTS 1500 +#define OPT_MESSAGE_TYPE_LEGTH 1 +#define OPT_HEADER_LENGTH 2 +#define OPT_TIME_LENGTH 4 +#define OPT_TYPE_FIELD_LENGTH 1 +#define OPT_MAC_ADDR_LENGTH 6 +#define MAGIC_COOKIE_LENGTH 4 +#define OPT_BROADCAST_FLAG_ENABLE 0 + +#define OFFER_MIN_INTERVAL_TIME 5 + +#define PENDING_DEFAULT_TIMEOUT 1200 +#define PENDING_DEFAULT_INTERVAL 1 +#define PENDING_INTERVAL_CHECKING_ENABLE 1 +#define DHCP_MAGIC_COOKIE 0x63825363 +#define RECV_BUFFER_SIZE 2048 +#define ALLOW_NOBINDING_REQUEST 1 +#define REUSE_ADDRESS_ENABLE 1 +#define WAIT_STOPED_TIME 5 + +const uint8_t MAGIC_COOKIE_DATA[MAGIC_COOKIE_LENGTH] = {0x63, 0x82, 0x53, 0x63}; // Vendor Information "Magic Cookie" + +enum AssignedNumbers { + ETHERNET = 1, // Ethernet (10Mb) + EXPERIMENTAL_ETHERNET, // Experimental Ethernet (3Mb) + AMATEUR_RADIO_AX_25, // Amateur Radio AX.25 + PROTEON_PRONET_TOKEN_RING, // Proteon ProNET Token Ring + CHAOS, + IEEE802_NETWORKS, + ARCNET, + HYPERCHANNEL, + LANSTAR +}; + +struct ServerContext { + int broadCastFlagEnable; + DhcpAddressPool addressPool; + DhcpServerCallback callback; + DhcpConfig config; + int serverFd; + int looperState; + int initialized; +}; + +enum LooperState { + LS_IDLE = 0, + LS_STARING, + LS_RUNNING, + LS_RELOADNG, + LS_STOPING, + LS_STOPED +}; +typedef struct sockaddr_in sockaddr_in; +static int FillReply(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply); +static int OnReceivedDiscover(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply); +static int OnReceivedRequest(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply); +static int OnReceivedDecline(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply); +static int OnReceivedRelease(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply); +static int OnReceivedInform(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply); +static int SendDhcpOffer(PDhcpServerContext ctx, PDhcpMsgInfo reply); +static int SendDhcpAck(PDhcpServerContext ctx, PDhcpMsgInfo reply); +static int SendDhcpNak(PDhcpServerContext ctx, PDhcpMsgInfo reply); +static int ParseMessageOptions(PDhcpMsgInfo msg); + +static int ParseReplyOptions(PDhcpMsgInfo reply); +struct sockaddr_in *BroadcastAddrIn(); + +static struct ServerContext *GetServerInstance(const DhcpServerContext *ctx) +{ + if (!ctx || !ctx->instance) { + return NULL; + } + return (struct ServerContext *)ctx->instance; +} +void OnUpdateServerConfig(); +int HasFixSocket(int fd) +{ + int flags; + if ((flags = fcntl(fd, F_GETFL)) == -1 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) { + return DHCP_FALSE; + } + return DHCP_TRUE; +} + +typedef struct ifreq ifreq; +typedef struct sockaddr sockaddr; + +int BindNetInterface(int fd, const char *ifname) +{ + if (!fd || !ifname) { + return RET_FAILED; + } + ifreq iface; + if (memset_s(&iface, sizeof(iface), 0, sizeof(iface)) != EOK) { + return RET_FAILED; + } + if (ifname) { + ssize_t ifnameSize = strlen(ifname); + if (ifnameSize < IFNAMSIZ) { + strncpy_s(iface.ifr_ifrn.ifrn_name, IFNAMSIZ, ifname, ifnameSize); + } else { + LOGE("network interface name too long."); + return RET_FAILED; + } + if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, (char *)&iface, sizeof(iface)) == -1) { + LOGE("failed to bind network device interface[%s].", ifname); + return RET_FAILED; + } + } else { + LOGW("no interface specified."); + } + return RET_SUCCESS; +} + +int InitServer(const char *ifname) +{ + sockaddr_in srvAddrIn = {0}; + int optval = 1; + int optrval = 0; + srvAddrIn.sin_family = AF_INET; + srvAddrIn.sin_port = htons(DHCP_SERVER_PORT); + srvAddrIn.sin_addr.s_addr = INADDR_ANY; + int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (fd == -1) { + LOGE("failed to create server socket!"); + return -1; + } + if (!HasFixSocket(fd)) { + LOGD("failed to fcntl O_NONBLOCK flag!"); + } + if (BindNetInterface(fd, ifname) != RET_SUCCESS) { + return -1; + } + socklen_t optlen = sizeof(optrval); + if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *)&optrval, &optlen) == -1) { + LOGD("failed to receive buffer size."); + } else { + LOGD("receive buffer size is %d", optrval); + }; + if (REUSE_ADDRESS_ENABLE && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, sizeof(optval)) == -1) { + LOGW("failed to setsockopt 'SO_REUSEADDR' for server socket!"); + } + if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &optval, sizeof(optval)) == -1) { + LOGE("failed to setsockopt 'SO_BROADCAST' for server socket!"); + return -1; + } + if (bind(fd, (sockaddr *)&srvAddrIn, sizeof(sockaddr)) == -1) { + LOGE("failed to bind server!"); + return -1; + } + return fd; +} +struct sockaddr_in *BroadcastAddrIn() +{ + static struct sockaddr_in broadcastAddrIn = {0}; + if (broadcastAddrIn.sin_port == 0) { + broadcastAddrIn.sin_port = htons(DHCP_CLIENT_PORT); + broadcastAddrIn.sin_family = AF_INET; + broadcastAddrIn.sin_addr.s_addr = INADDR_BROADCAST; + } + return &broadcastAddrIn; +} + +struct sockaddr_in *SourceAddrIn() +{ + static struct sockaddr_in sourceAddrIn = {0}; + sourceAddrIn.sin_port = htons(DHCP_CLIENT_PORT); + sourceAddrIn.sin_family = AF_INET; + sourceAddrIn.sin_addr.s_addr = INADDR_ANY; + return &sourceAddrIn; +} + +struct sockaddr_in *ResetSourceAddr() +{ + struct sockaddr_in *srcAddr = SourceAddrIn(); + srcAddr->sin_port = htons(DHCP_CLIENT_PORT); + srcAddr->sin_family = AF_INET; + srcAddr->sin_addr.s_addr = INADDR_ANY; + return srcAddr; +} + +uint32_t SourceIpAddress() +{ + uint32_t srcIp = SourceAddrIn()->sin_addr.s_addr; + return srcIp; +} +struct sockaddr_in *DestinationAddrIn() +{ + static struct sockaddr_in destAddrIn = {0}; + if (destAddrIn.sin_port == 0) { + destAddrIn.sin_port = htons(DHCP_CLIENT_PORT); + destAddrIn.sin_family = AF_INET; + } + return &destAddrIn; +} + +struct sockaddr_in *DestinationAddr(uint32_t ipAddress) +{ + struct sockaddr_in *destAddr = DestinationAddrIn(); + destAddr->sin_addr.s_addr = htonl(ipAddress); + return destAddr; +} + +int ReceiveDhcpMessage(int sock, PDhcpMsgInfo msgInfo) +{ + static uint8_t recvBuffer[RECV_BUFFER_SIZE] = {0}; + struct timeval tmt; + fd_set recvFd; + FD_ZERO(&recvFd); + FD_SET(sock, &recvFd); + time_t tms = DHCP_SEL_WAIT_TIMEOUTS; + tmt.tv_sec = tms; + tmt.tv_usec = 0; + if (select(sock + 1, &recvFd, NULL, NULL, &tmt) < 0) { + LOGE("select error, %s", strerror(errno)); + return ERR_SELECT; + } + if (!FD_ISSET(sock, &recvFd)) { + LOGE("failed to select isset."); + return RET_ERROR; + } + socklen_t ssize = sizeof(sockaddr_in); + struct sockaddr_in *srcAddrIn = ResetSourceAddr(); + srcAddrIn->sin_addr.s_addr = INADDR_ANY; + int rsize = recvfrom(sock, recvBuffer, RECV_BUFFER_SIZE, 0, (struct sockaddr *)srcAddrIn, (socklen_t *)&ssize); + if (!rsize) { + LOGE("receive error, %s", strerror(errno)); + return RET_FAILED; + } + if (rsize > (int)sizeof(DhcpMsgInfo) || rsize < DHCP_MSG_HEADER_SIZE) { + LOGW("message length error, received %d bytes.", rsize); + return RET_FAILED; + } + msgInfo->length = rsize; + memcpy_s(&msgInfo->packet, sizeof(DhcpMessage), recvBuffer, rsize); + if (msgInfo->packet.op != BOOTREQUEST) { + LOGW("dhcp message type error!"); + return RET_FAILED; + } + if (msgInfo->packet.hlen > DHCP_HWADDR_LENGTH) { + LOGW("hlen error!"); + return RET_FAILED; + } + if (IsEmptyHWAddr(msgInfo->packet.chaddr)) { + LOGW("client hardware address error!"); + return RET_FAILED; + } + if (IsReserved(msgInfo->packet.chaddr)) { + LOGD("ignore client, %s", ParseLogMac(msgInfo->packet.chaddr)); + return RET_FAILED; + } + return RET_SUCCESS; +} + +void InitReply(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply) +{ + if (!reply) { + LOGE("reply messsage pointer is null!"); + return; + } + reply->packet.op = BOOTREPLY; + reply->packet.htype = ETHERNET; + reply->packet.hlen = OPT_MAC_ADDR_LENGTH; + reply->packet.secs = 0; + reply->packet.secs = 0; + reply->packet.ciaddr = 0; + if (memset_s(reply->packet.sname, sizeof(reply->packet.sname), '\0', sizeof(reply->packet.sname)) != EOK) { + LOGE("failed to reset message packet[sname]!"); + return; + }; + if (memset_s(reply->packet.file, sizeof(reply->packet.file), '\0', sizeof(reply->packet.file)) != EOK) { + LOGE("failed to reset message packet[file]!"); + return; + } + + if (FillReply(ctx, received, reply) != RET_SUCCESS) { + LOGW("failed to fill reply message."); + } +} + +void OnUpdateServerConfig(PDhcpServerContext ctx) +{ + LOGD("OnUpdateServerConfig ..."); + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return; + } + if (srvIns->callback) { + srvIns->callback(ST_RELOADNG, 0, ctx->ifname); + } +} + +static void OnServerStoping(PDhcpServerContext ctx) +{ + LOGD("server stoping ..."); + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return; + } + if (srvIns->callback) { + srvIns->callback(ST_STOPING, 0, ctx->ifname); + } +} + +void OnServerStoped(PDhcpServerContext ctx, int code) +{ + LOGD("OnServerStoped."); + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return; + } + LOGD("saving lease recoders ...."); + if (SaveBindingRecoders(&srvIns->addressPool, 1) == RET_SUCCESS) { + LOGI("lease seaved. total: %zu", srvIns->addressPool.leaseTable.size); + } else { + LOGW("failed to save lease."); + } + if (srvIns->callback) { + srvIns->callback(ST_STOPED, code, ctx->ifname); + } +} + +int SendDhcpReply(PDhcpServerContext ctx, int replyType, PDhcpMsgInfo reply) +{ + if (!reply) { + LOGE("reply message pointer is null."); + return RET_FAILED; + } + int sendRet = -1; + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return RET_FAILED; + } + switch (replyType) { + case REPLY_OFFER: + LOGD("<== send reply dhcp offer."); + sendRet = SendDhcpOffer(ctx, reply); + break; + case REPLY_ACK: + LOGD("<== send reply dhcp ack."); + sendRet = SendDhcpAck(ctx, reply); + break; + case REPLY_NAK: + LOGD("<== send reply dhcp nak."); + sendRet = SendDhcpNak(ctx, reply); + break; + default: + break; + } + if (replyType && sendRet != RET_SUCCESS) { + return RET_FAILED; + } + return RET_SUCCESS; +} + +static int MessageProcess(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply) +{ + int replyType = REPLY_NONE; + if (!received) { + return replyType; + } + PDhcpOption opt = GetOption(&received->options, DHCP_MESSAGE_TYPE_OPTION); + if (!opt) { + LOGE("error dhcp message, missing required message type option."); + return replyType; + } + uint8_t messageType = opt->data[0]; + switch (messageType) { + case DHCPDISCOVER: { + LOGD("==> Received DHCPDISCOVER message."); + replyType = OnReceivedDiscover(ctx, received, reply); + break; + } + case DHCPREQUEST: { + LOGD("==> Received DHCPREQUEST message."); + replyType = OnReceivedRequest(ctx, received, reply); + break; + } + case DHCPDECLINE: { + LOGD("==> Received DHCPDECLINE message."); + replyType = OnReceivedDecline(ctx, received, reply); + break; + } + case DHCPRELEASE: { + LOGD("==> Received DHCPRELEASE message."); + replyType = OnReceivedRelease(ctx, received, reply); + break; + } + case DHCPINFORM: { + LOGD("==> Received DHCPINFORM message."); + replyType = OnReceivedInform(ctx, received, reply); + break; + } + default: + break; + } + return replyType; +} + + +int SaveLease(PDhcpServerContext ctx) +{ + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return RET_FAILED; + } + int saveRet = SaveBindingRecoders(&srvIns->addressPool, 0); + if (saveRet == RET_FAILED) { + LOGD("failed to save lease recoders. total: %zu", srvIns->addressPool.leaseTable.size); + } else if (saveRet == RET_SUCCESS) { + LOGD("lease recoders saved."); + } + return saveRet; +} + +static int OnLooperStateChanged(PDhcpServerContext ctx) +{ + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return RET_FAILED; + } + + if (srvIns->looperState == LS_RELOADNG) { + OnUpdateServerConfig(ctx); + srvIns->looperState = LS_RUNNING; + } else if (srvIns->looperState == LS_STOPING) { + OnServerStoping(ctx); + return RET_BREAK; + } + return RET_SUCCESS; +} + +static int ContinueReceive(PDhcpMsgInfo from, int recvRet) +{ + if (!from) { + return DHCP_TRUE; + } + if (recvRet != RET_SUCCESS) { + return DHCP_TRUE; + } + size_t recLength = from->length; + LOGD("received, length:%zu", recLength); + if (ParseMessageOptions(from) != 0) { + LOGE("invalid dhcp message."); + return DHCP_TRUE; + } + if (!GetOption(&from->options, DHCP_MESSAGE_TYPE_OPTION)) { + LOGW("can't found 'message type' option."); + return DHCP_TRUE; + } + return DHCP_FALSE; +} + +static int BeginLooper(PDhcpServerContext ctx) +{ + DhcpMsgInfo from; + DhcpMsgInfo reply; + int saveLease = 0; + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return RET_FAILED; + } + ctx->instance->serverFd = InitServer(ctx->ifname); + if (!ctx->instance->serverFd) { + LOGE("failed to initialize server socket."); + return RET_FAILED; + } + InitOptionList(&from.options); + InitOptionList(&reply.options); + srvIns->looperState = LS_RUNNING; + while (srvIns->looperState) { + if (OnLooperStateChanged(ctx) != RET_SUCCESS) { + break; + } + ClearOptions(&from.options); + ClearOptions(&reply.options); + if (saveLease && SaveLease(ctx) == RET_SUCCESS) { + saveLease = 0; + } + int recvRet = ReceiveDhcpMessage(ctx->instance->serverFd, &from); + if (ContinueReceive(&from, recvRet)) { + if (recvRet == RET_ERROR || recvRet == ERR_SELECT) { + break; + } + continue; + } + InitReply(ctx, &from, &reply); + int replyType = MessageProcess(ctx, &from, &reply); + int snedRet = -1; + if (replyType && (snedRet = SendDhcpReply(ctx, replyType, &reply)) != RET_SUCCESS) { + LOGE("failed to send reply message."); + } + if (replyType == REPLY_ACK && snedRet) { + saveLease = 1; + } + } // while (srvIns->looperState) + FreeOptionList(&from.options); + FreeOptionList(&reply.options); + LOGD("dhcp server message looper stoped."); + close(ctx->instance->serverFd); + srvIns->looperState = LS_STOPED; + return 0; +} + +static int CheckAddressRange(DhcpAddressPool *pool) +{ + uint32_t serverNetwork = NetworkAddress(pool->serverId, pool->netmask); + uint32_t firstNetwork = NetworkAddress(pool->addressRange.beginAddress, pool->netmask); + uint32_t sencodNetwork = NetworkAddress(pool->addressRange.endAddress, pool->netmask); + if (!serverNetwork || !firstNetwork || !sencodNetwork) { + LOGE("network config error."); + return DHCP_FALSE; + } + if (serverNetwork != firstNetwork || firstNetwork != serverNetwork) { + LOGE("server network and address pool network belong to different networks."); + return DHCP_FALSE; + } + return DHCP_TRUE; +} + +void InitBindingRecoders(DhcpAddressPool *pool) +{ + if (!pool) { + LOGE("address pool pointer is null."); + return; + } + HashTable *table = &pool->leaseTable; + if (!Initialized(table)) { + LOGE("pool does not init."); + return; + } + uint32_t realLeaseTotal = 0; + for (size_t current = 0; current < table->capacity; ++current) { + HashNode *node = table->nodes[current]; + int invalidBindig; + while (node) { + HashNode *next = node->next; + AddressBinding *binding = (AddressBinding*)node->value; + if (binding && !IsEmptyHWAddr(binding->chaddr) && binding->ipAddress) { + AddBinding(binding); + realLeaseTotal++; + invalidBindig = 0; + } else { + LOGE("bad binding recoder."); + invalidBindig = 1; + } + if (!invalidBindig && pool->distribution < binding->ipAddress) { + pool->distribution = binding->ipAddress; + } + node = next; + } + } + LOGD("lease recoder total: %zu", realLeaseTotal); +} + +void InitLeaseFile(DhcpAddressPool *pool) +{ + const char *leasePath = GetFilePath(DHCPD_LEASE_FILE); + if (access(leasePath, 0) != 0) { + LOGD("lease file path does not exist."); + if (!CreatePath(leasePath)) { + LOGE("failed to create lease file directory."); + return; + } else { + LOGD("lease file directory created."); + } + } + if (LoadBindingRecoders(pool) != RET_SUCCESS) { + LOGW("failed to load lease recoders."); + } + InitBindingRecoders(pool); +} + +int StartDhcpServer(PDhcpServerContext ctx) +{ + LOGD("dhcp server starting ..."); + if (!ctx) { + LOGE("server context pointer is null."); + return RET_FAILED; + } + ServerContext *srvIns = GetServerInstance(ctx); + if (!ctx) { + LOGE("dhcp server context instance pointer is null."); + return RET_FAILED; + } + if (strlen(ctx->ifname) == 0 || ctx->ifname[0] == '\0') { + LOGE("context interface is null or empty."); + return RET_FAILED; + } + if (!srvIns->initialized) { + LOGE("dhcp server no initialized."); + return RET_FAILED; + } + LOGD("bind interface: %s", ctx->ifname); + LOGI("begin dhcp message looper"); + if (srvIns->callback) { + srvIns->callback(ST_STARTING, 1, ctx->ifname); + } + int ret = BeginLooper(ctx); + if (ret != RET_SUCCESS) { + LOGD("faild to start dhcp server."); + FreeAddressPool(&srvIns->addressPool); + OnServerStoped(ctx, ret); + return RET_FAILED; + } + FreeAddressPool(&srvIns->addressPool); + OnServerStoped(ctx, ret); + return RET_SUCCESS; +} + +int StopDhcpServer(PDhcpServerContext ctx) +{ + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + return RET_FAILED; + } + srvIns->looperState = LS_STOPING; + return RET_SUCCESS; +} + +int GetServerStatus(PDhcpServerContext ctx) +{ + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return -1; + } + return srvIns->looperState; +} + +static int FillReply(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply) +{ + if (!received || !reply) { + return RET_ERROR; + } + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return RET_FAILED; + } + if (received->packet.ciaddr && received->packet.ciaddr != INADDR_BROADCAST) { + reply->packet.ciaddr = received->packet.ciaddr; + } + if (received->packet.flags) { + reply->packet.flags = received->packet.flags; + } + if (received->packet.xid) { + reply->packet.xid = received->packet.xid; + } + if (received->packet.siaddr && received->packet.siaddr != INADDR_BROADCAST) { + reply->packet.siaddr = received->packet.siaddr; + } else { + reply->packet.siaddr = srvIns->addressPool.serverId; + } + if (received->packet.giaddr && received->packet.giaddr != INADDR_BROADCAST) { + reply->packet.giaddr = received->packet.giaddr; + } else { + if (srvIns->addressPool.gateway) { + reply->packet.giaddr = srvIns->addressPool.gateway; + } + } + if (received->packet.hlen) { + reply->packet.hlen = received->packet.hlen; + LOGD("fill reply - chaddr:%s", ParseLogMac(received->packet.chaddr)); + if (memset_s(reply->packet.chaddr, sizeof(reply->packet.chaddr), 0, sizeof(reply->packet.chaddr)) != EOK) { + LOGE("failed to reset message packet[chaddr]!"); + return RET_ERROR; + } + if (memcpy_s(reply->packet.chaddr, received->packet.hlen, + received->packet.chaddr, received->packet.hlen) != EOK) { + LOGE("failed to copy message packet[chaddr]!"); + return RET_ERROR; + } + } + if (received->packet.giaddr) { + reply->packet.giaddr = received->packet.giaddr; + } + return 0; +} + +int AppendReplyTimeOptions(PDhcpServerContext ctx, PDhcpOptionList options) +{ + if (!ctx || !options) { + LOGE("server context or options poninter is null."); + return RET_FAILED; + } + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return RET_FAILED; + } + uint32_t leaseTime = HostToNetwork(DHCP_LEASE_TIME); + if (srvIns->addressPool.leaseTime) { + leaseTime = HostToNetwork(srvIns->addressPool.leaseTime); + } + DhcpOption optLeaseTime = {IP_ADDRESS_LEASE_TIME_OPTION, OPT_TIME_LENGTH, {0}}; + FillU32Option(&optLeaseTime, leaseTime); + PushBackOption(options, &optLeaseTime); + + uint32_t t1Time = HostToNetwork(DHCP_RENEWAL_TIME); + if (srvIns->addressPool.renewalTime) { + t1Time = HostToNetwork(srvIns->addressPool.renewalTime); + } + DhcpOption optRenewTime = {RENEWAL_TIME_VALUE_OPTION, OPT_TIME_LENGTH, {0}}; + FillU32Option(&optLeaseTime, t1Time); + PushBackOption(options, &optRenewTime); + + uint32_t t2Time = HostToNetwork(DHCP_REBINDING_TIME); + if (srvIns->addressPool.rebindingTime) { + t2Time = HostToNetwork(srvIns->addressPool.rebindingTime); + } + DhcpOption optRebindTime = {REBINDING_TIME_VALUE_OPTION, OPT_TIME_LENGTH, {0}}; + FillU32Option(&optRebindTime, t2Time); + PushBackOption(options, &optRebindTime); + + return RET_SUCCESS; +} + +static int Repending(DhcpAddressPool *pool, AddressBinding *binding) +{ + if (!pool) { + LOGE("address pool pointer is null."); + return REPLY_NONE; + } + uint32_t bindingIp = binding->ipAddress; + LOGD(" binding found, bindIp:%s", ParseStrIp(bindingIp)); + binding->pendingInterval = NextPendingInterval(binding->pendingInterval); + uint64_t tms = Tmspsec() - binding->pendingTime; + if (tms < binding->pendingInterval) { + binding->pendingTime = Tmspsec(); + LOGW("message interval is too short, ignore the message."); + return REPLY_NONE; + } + binding->pendingTime = Tmspsec(); + binding->pendingInterval = 0; + binding->bindingStatus = BIND_PENDING; + uint32_t srcIp = SourceIpAddress(); + if (srcIp && srcIp != INADDR_BROADCAST && bindingIp != INADDR_BROADCAST && srcIp != bindingIp) { + LOGW("source(0x%x) ip address and bound(0x%x) ip address inconsistency.", srcIp, bindingIp); + return REPLY_NAK; + } + if (srcIp && srcIp == bindingIp) { + if (!ContainsKey(&pool->leaseTable, (uintptr_t)&srcIp)) { + LOGD("can't find lease information."); + if (Insert(&pool->leaseTable, (uintptr_t)&srcIp, (uintptr_t)binding) != HASH_INSERTED) { + LOGE("failed to insert lease information."); + } + } else { + if (Insert(&pool->leaseTable, (uintptr_t)&srcIp, (uintptr_t)binding) != HASH_UPDATED) { + LOGE("failed to update lease information."); + } + } + } + return REPLY_OFFER; +} + +static int Rebinding(DhcpAddressPool *pool, AddressBinding *binding) +{ + uint64_t pendingTime = binding->pendingTime; + int replyType = Repending(pool, binding); + binding->bindingStatus = BIND_ASSOCIATED; + if (!binding->leaseTime) { + binding->leaseTime = pool->leaseTime; + } + binding->bindingTime = Tmspsec(); + binding->expireIn = binding->bindingTime + binding->leaseTime; + binding->pendingTime = pendingTime; + if (replyType == REPLY_OFFER) { + replyType = REPLY_ACK; + } + return replyType; +} + +static void AddAddressOption(PDhcpMsgInfo reply, uint8_t code, int32_t address) +{ + if (!reply) { + LOGE("reply message pointer is null."); + return; + } + DhcpOption optAddress = {code, 0, {0}}; + if (AppendAddressOption(&optAddress, address) != RET_SUCCESS) { + LOGE("failed to append address option."); + return; + }; + PushBackOption(&reply->options, &optAddress); +} + +static int AddReplyServerIdOption(PDhcpOptionList options, uint32_t serverId) +{ + if (!options) { + LOGE("option list pointer is null."); + return RET_FAILED; + } + if (!serverId || serverId==INADDR_BROADCAST) { + LOGE("servier id error."); + return RET_FAILED; + } + DhcpOption optSrvId = {SERVER_IDENTIFIER_OPTION, 0, {0}}; + if (AppendAddressOption(&optSrvId, serverId) != RET_SUCCESS) { + LOGE("failed to append server id option."); + return RET_FAILED; + } + if (GetOption(options, SERVER_IDENTIFIER_OPTION)) { + LOGD("server identifier option exists."); + return RET_SUCCESS; + } + PushBackOption(options, &optSrvId); + return RET_SUCCESS; +} + +static void AddReplyMessageTypeOption(PDhcpMsgInfo reply, uint8_t replyMessageType) +{ + if (!reply) { + LOGE("reply message pointer is null."); + return; + } + DhcpOption optMsgType = {DHCP_MESSAGE_TYPE_OPTION, OPT_MESSAGE_TYPE_LEGTH, {replyMessageType, 0}}; + PushBackOption(&reply->options, &optMsgType); +} + + +static AddressBinding *GetBinding(DhcpAddressPool *pool, PDhcpMsgInfo received) +{ + if (!pool) { + LOGE("address pool pointer is null."); + return NULL; + } + if (!received) { + LOGE("received message pointer is null."); + return NULL; + } + AddressBinding *binding = pool->binding(received->packet.chaddr, &received->options); + if (!binding) { + binding = pool->newBinding(received->packet.chaddr, &received->options); + if (pool->leaseTime) { + binding->leaseTime = pool->leaseTime; + } + binding->ipAddress = pool->distribue(pool, received->packet.chaddr); + LOGD("new binding ip:%s", ParseStrIp(binding->ipAddress)); + } else { + LOGD("rebinding ip:%s", ParseStrIp(binding->ipAddress)); + } + return binding; +} + +static int OnReceivedDiscover(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply) +{ + if (!received || !reply) { + LOGE("receive or reply message pointer is null."); + return REPLY_NONE; + } + LOGI("received 'Discover' message from: %s", ParseLogMac(received->packet.chaddr)); + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return REPLY_NONE; + } + PDhcpOption optReqIp = GetOption(&received->options, REQUESTED_IP_ADDRESS_OPTION); + if (optReqIp) { + uint32_t reqIp = ParseIp(optReqIp->data); + if (reqIp) { + LOGD(" request ip: %s", ParseStrIp(reqIp)); + } + } + uint32_t srcIp = SourceIpAddress(); + if (!srvIns->broadCastFlagEnable) { + if (srcIp) { + LOGD(" client repending:%s", ParseStrIp(srcIp)); + } else { + srcIp = INADDR_BROADCAST; + } + DestinationAddr(srcIp); + } + AddressBinding *binding = GetBinding(&srvIns->addressPool, received); + if (!binding) { + return REPLY_NONE; + } + if (!binding->ipAddress) { + LOGE("no ip address available."); + return REPLY_NONE; + } + AddressBinding *lease = GetLease(&srvIns->addressPool, binding->ipAddress); + if (!lease) { + LOGD("add lease recoder."); + AddLease(&srvIns->addressPool, binding); + lease = GetLease(&srvIns->addressPool, binding->ipAddress); + } + AddReplyMessageTypeOption(reply, DHCPOFFER); + reply->packet.yiaddr = lease->ipAddress; + return REPLY_OFFER; +} + + +static uint32_t GetRequestIpAddress(PDhcpMsgInfo received) +{ + uint32_t reqIp = 0; + if (!received) { + return reqIp; + } + PDhcpOption optReqIp = GetOption(&received->options, REQUESTED_IP_ADDRESS_OPTION); + if (optReqIp) { + reqIp = ParseIp(optReqIp->data); + } + return reqIp; +} + +static int GetYourIpAddress(PDhcpMsgInfo received, uint32_t *yourIpAddr) +{ + uint32_t cliIp = received->packet.ciaddr; + uint32_t srcIp = SourceIpAddress(); + uint32_t reqIp = GetRequestIpAddress(received); + if (cliIp && srcIp && cliIp != srcIp) { + LOGE("error dhcp request message, missing required request option."); + return RET_FAILED; + } + if (reqIp && srcIp && reqIp != srcIp) { + LOGE("error dhcp request message, request ip error."); + return RET_FAILED; + } + if (cliIp && reqIp && cliIp != reqIp) { + LOGE("error dhcp request message, client ip error."); + return RET_FAILED; + } + + if (srcIp && srcIp != INADDR_BROADCAST) { + *yourIpAddr = srcIp; + } else if (cliIp && cliIp != INADDR_BROADCAST) { + *yourIpAddr = cliIp; + } else if (reqIp && reqIp != INADDR_BROADCAST) { + *yourIpAddr = reqIp; + } + + if (srcIp && srcIp != INADDR_BROADCAST) { + DestinationAddr(srcIp); + } else if (srcIp == INADDR_ANY) { + DestinationAddr(INADDR_BROADCAST); + } + return RET_SUCCESS; +} + +static int NotBindingRequest(DhcpAddressPool *pool, PDhcpMsgInfo received, PDhcpMsgInfo reply) +{ + uint32_t yourIpAddr = 0; + if (GetYourIpAddress(received, &yourIpAddr) != RET_SUCCESS) { + return REPLY_NONE; + } + AddressBinding *lease = GetLease(pool, yourIpAddr); + if (!lease) { + if (SourceIpAddress()) { + return REPLY_NAK; + } + return REPLY_NONE; + } + int sameAddr = AddrEquels(lease->chaddr, received->packet.chaddr, MAC_ADDR_LENGTH); + if (lease->bindingStatus == BIND_ASSOCIATED && !sameAddr) { + if (!IsExpire(lease)) { + return REPLY_NAK; + } + RemoveLease(pool, lease); + } + AddressBinding *binding = pool->newBinding(received->packet.chaddr, &received->options); + binding->ipAddress = yourIpAddr; + if (pool->leaseTime) { + binding->leaseTime = pool->leaseTime; + } + int replyType = Repending(pool, binding); + if (replyType != REPLY_ACK) { + return replyType; + } + if (!lease) { + LOGD("add new lease recoder."); + AddLease(pool, binding); + lease = GetLease(pool, binding->ipAddress); + } + if (!lease) { + LOGD("failed to get lease."); + return REPLY_NONE; + } + lease->bindingStatus = BIND_ASSOCIATED; + lease->bindingTime = Tmspsec(); + lease->expireIn = lease->bindingTime + binding->leaseTime; + reply->packet.yiaddr = lease->ipAddress; + return REPLY_ACK; +} + +static int ValidateRequestMessage(const PDhcpServerContext ctx, const PDhcpMsgInfo received, PDhcpMsgInfo reply, uint32_t *yourIp) +{ + if (!received || !reply) { + LOGE("receive or reply message pointer is null."); + return REPLY_NONE; + } + LOGI("received 'Request' message from: %s.", ParseLogMac(received->packet.chaddr)); + uint32_t yourIpAddr = INADDR_BROADCAST; + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return RET_FAILED; + } + if (GetYourIpAddress(received, &yourIpAddr) != RET_SUCCESS) { + if (yourIpAddr && yourIpAddr != INADDR_BROADCAST) { + return REPLY_NAK; + } + return REPLY_NONE; + } + PDhcpOption optReqSrvId = GetOption(&received->options, SERVER_IDENTIFIER_OPTION); + if (optReqSrvId) { + uint32_t reqSrvId = ParseIp(optReqSrvId->data); + LOGD(" reuquest server id is:%s", ParseStrIp(reqSrvId)); + if (reqSrvId != srvIns->addressPool.serverId) { + LOGW("other dhcp server process."); + return REPLY_NONE; + } + } else { + LOGW("request message not specified server identifier option."); + } + return REPLY_ACK; +} + +static int HasNobindgRequest(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply) +{ + if (!received || !reply) { + LOGE("receive or reply message pointer is null."); + return REPLY_NONE; + } + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return REPLY_NONE; + } + AddressBinding *binding = srvIns->addressPool.binding(received->packet.chaddr, &received->options); + if (!binding && ALLOW_NOBINDING_REQUEST) { + LOGE("client not binding."); + uint32_t srcIp = SourceIpAddress(); + uint32_t reqIp = GetRequestIpAddress(received); + LOGD("allow no binding request mode."); + if (!reqIp && !srcIp) { + LOGE("error dhcp message."); + return REPLY_NONE; + } + if (!IpInNetwork(reqIp, srvIns->addressPool.serverId, srvIns->addressPool.netmask)) { + LOGE("error request ip."); + return REPLY_NAK; + } + return NotBindingRequest(&srvIns->addressPool, received, reply); + } + return REPLY_ACK; +} + +static int OnReceivedRequest(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply) +{ + int ret; + uint32_t yourIpAddr; + if ((ret = ValidateRequestMessage(ctx, received, reply, &yourIpAddr)) != REPLY_ACK) { + return ret; + } + ServerContext *srvIns = GetServerInstance(ctx); + AddressBinding *binding = srvIns->addressPool.binding(received->packet.chaddr, &received->options); + if ((ret = HasNobindgRequest(ctx, received, reply)) != REPLY_ACK) { + return ret; + } + Rebinding(&srvIns->addressPool, binding); + AddressBinding *lease = GetLease(&srvIns->addressPool, yourIpAddr); + if (lease) { + int sameAddr = AddrEquels(lease->chaddr, received->packet.chaddr, MAC_ADDR_LENGTH); + if (!sameAddr && !IsExpire(lease)) { + LOGW("invalid request ip address."); + return REPLY_NAK; + } + if (!sameAddr && IsExpire(lease)) { + if (memcpy_s(lease->chaddr, DHCP_HWADDR_LENGTH, binding->chaddr, MAC_ADDR_LENGTH) != EOK) { + LOGW("failed to update lease client address."); + } + } + lease->bindingStatus = BIND_ASSOCIATED; + lease->bindingTime = binding->bindingTime; + lease->expireIn = binding->expireIn; + } else { + LOGW("can not found lease recoder."); + } + uint32_t bindingIp = binding->ipAddress; + if (bindingIp && yourIpAddr != INADDR_BROADCAST && yourIpAddr != bindingIp) { + LOGE("error request ip binding."); + return REPLY_NAK; + } + AddAddressOption(reply, SUBNET_MASK_OPTION, srvIns->addressPool.netmask); + if (srvIns->addressPool.gateway) { + AddAddressOption(reply, ROUTER_OPTION, srvIns->addressPool.gateway); + } + reply->packet.yiaddr = bindingIp; + return REPLY_ACK; +} + +static int OnReceivedDecline(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply) +{ + if (!received || !reply) { + LOGE("receive or reply message pointer is null."); + return REPLY_NONE; + } + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return REPLY_NONE; + } + LOGI("received 'Decline' message from: %s.", ParseLogMac(received->packet.chaddr)); + uint32_t reqIp = 0; + PDhcpOption optReqIp = GetOption(&received->options, REQUESTED_IP_ADDRESS_OPTION); + if (optReqIp) { + reqIp = ParseIp(optReqIp->data); + } + if (!reqIp) { + LOGD("invalid request ip address."); + return REPLY_NONE; + } + AddressBinding* binding = srvIns->addressPool.binding(received->packet.chaddr, &received->options); + if (!binding) { + LOGD("client not binding."); + return REPLY_NONE; + } + if (binding->ipAddress != reqIp) { + LOGD("invalid request ip address."); + return REPLY_NONE; + } + if (ContainsKey(&srvIns->addressPool.leaseTable, (uintptr_t)&binding->ipAddress)) { + AddressBinding *lease = GetBindingByIp(&srvIns->addressPool.leaseTable, binding->ipAddress); + if (lease) { + lease->bindingStatus = BIND_MODE_RESERVED; + lease->expireIn = Tmspsec() + lease->leaseTime; + } else { + LOGE("failed to get lease info."); + } + } + RemoveBinding(received->packet.chaddr); + return REPLY_NONE; +} + +static int OnReceivedRelease(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply) +{ + if (!received || !reply) { + LOGE("receive or reply message pointer is null."); + return REPLY_NONE; + } + LOGI("received 'Release' message from: %s", ParseLogMac(received->packet.chaddr)); + if (!ctx || !ctx->instance) { + LOGE("dhcp server context pointer is null."); + return RET_FAILED; + } + PDhcpOption optReqIp = GetOption(&received->options, REQUESTED_IP_ADDRESS_OPTION); + if (!optReqIp) { + LOGW("missing required request option."); + } + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return RET_FAILED; + } + AddressBinding *binding = srvIns->addressPool.binding(received->packet.chaddr, &received->options); + if (!binding) { + LOGD("client not binding."); + return REPLY_NONE; + } + uint32_t bindIp = binding->ipAddress; + uint32_t reqIp = 0; + if (optReqIp) { + reqIp = ParseIp(optReqIp->data); + } + uint32_t srcIp = SourceIpAddress(); + LOGD("request ip: %s", ParseStrIp(reqIp)); + if (reqIp && reqIp != srcIp) { + LOGE("error release message, invalid request ip address."); + return REPLY_NONE; + } + if (reqIp && reqIp != bindIp) { + LOGE("error release message, invalid request ip address."); + return REPLY_NONE; + } + AddressBinding *lease = GetLease(&srvIns->addressPool, bindIp); + if (lease) { + RemoveLease(&srvIns->addressPool, lease); + LOGD("lease recoder has been removed."); + } else { + LOGW("can't found lease recoder."); + } + + if (ReleaseBinding(received->packet.chaddr) != RET_SUCCESS) { + LOGW("failed to release client[%s] bind.", ParseLogMac(received->packet.chaddr)); + } + LOGD("client released."); + return REPLY_NONE; +} + +static int OnReceivedInform(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply) +{ + if (!received || !reply) { + LOGE("receive or reply message pointer is null."); + return REPLY_NONE; + } + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return RET_FAILED; + } + LOGI("received 'Inform' message from: %s", ParseLogMac(received->packet.chaddr)); + if (IsEmptyHWAddr(received->packet.chaddr)) { + LOGD("error dhcp 'Inform' message."); + } + return REPLY_ACK; +} + +static int AppendFixedOptions(PDhcpServerContext ctx, PDhcpMsgInfo reply) +{ + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return RET_FAILED; + } + if (!reply) { + return RET_FAILED; + } + if (srvIns->addressPool.fixedOptions.size > 0) { + DhcpOptionNode *pNode = srvIns->addressPool.fixedOptions.first->next; + for (size_t i = 0; pNode != NULL && i < srvIns->addressPool.fixedOptions.size; i++) { + PDhcpOption opt = NULL; + if (pNode->option.code) { + opt = GetOption(&reply->options, pNode->option.code); + } + if (opt == NULL) { + PushBackOption(&reply->options, &pNode->option); + } + pNode = pNode->next; + } + } + return RET_SUCCESS; +} +int AppendReplyTypeOption(PDhcpMsgInfo reply, int replyType) +{ + if (!reply) { + return RET_FAILED; + } + if (!replyType) { + return RET_FAILED; + } + uint8_t msgType = 0; + switch (replyType) { + case REPLY_OFFER: + msgType = DHCPOFFER; + break; + case REPLY_ACK: + msgType = DHCPACK; + break; + case REPLY_NAK: + msgType = DHCPNAK; + break; + default: + break; + } + PDhcpOption pOptMsgType = GetOption(&reply->options, DHCP_MESSAGE_TYPE_OPTION); + if (!pOptMsgType) { + LOGD("append message type option for reply message, type:%hhu", msgType); + DhcpOption optMsgType = {DHCP_MESSAGE_TYPE_OPTION, OPT_MESSAGE_TYPE_LEGTH, {msgType, 0}}; + PushFrontOption(&reply->options, &optMsgType); + } else { + if (pOptMsgType->data[0] != msgType) { + LOGD("error dhcp nak message type."); + return RET_FAILED; + } + } + return RET_SUCCESS; +} + +static int SendDhcpOffer(PDhcpServerContext ctx, PDhcpMsgInfo reply) +{ + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return RET_FAILED; + } + if (AppendReplyTypeOption(reply, REPLY_OFFER) != RET_SUCCESS) { + return RET_FAILED; + } + if (AppendReplyTimeOptions(ctx, &reply->options) != RET_SUCCESS || + AddReplyServerIdOption(&reply->options, srvIns->addressPool.serverId) != RET_SUCCESS) { + return RET_FAILED; + } + if (AppendFixedOptions(ctx, reply) != RET_SUCCESS) { + LOGW("failed to append fixed reply options."); + } + if (ParseReplyOptions(reply) != RET_SUCCESS) { + LOGE("failed to parse reply options."); + return RET_FAILED; + } + int ret; + struct sockaddr_in *bcastAddrIn = BroadcastAddrIn(); + struct sockaddr_in *destAddrIn = DestinationAddrIn(); + if (srvIns->broadCastFlagEnable == 1 && destAddrIn) { + int broadCastFlag = 1; + if (reply->packet.flags && (reply->packet.flags >> (DHCP_MESSAGE_FLAG_LENGTH - 1)) == 0) { + broadCastFlag = 0; + } + if (!broadCastFlag && destAddrIn->sin_addr.s_addr) { + ret = sendto(srvIns->serverFd, &reply->packet, reply->length, 0, (struct sockaddr *)destAddrIn, + sizeof(*destAddrIn)); + } else { + ret = sendto(srvIns->serverFd, &reply->packet, reply->length, 0, (struct sockaddr *)bcastAddrIn, + sizeof(*bcastAddrIn)); + } + } else { + ret = sendto( + srvIns->serverFd, &reply->packet, reply->length, 0, (struct sockaddr *)bcastAddrIn, sizeof(*bcastAddrIn)); + } + if (!ret) { + LOGD("failed to send dhcp offer message."); + return RET_FAILED; + } + LOGI(" send reply offer, length:%d", reply->length); + return RET_SUCCESS; +} + +static int SendDhcpAck(PDhcpServerContext ctx, PDhcpMsgInfo reply) +{ + if (AppendReplyTypeOption(reply, REPLY_ACK) != RET_SUCCESS) { + return RET_FAILED; + } + if (AppendFixedOptions(ctx, reply) != RET_SUCCESS) { + LOGW("failed to append fixed reply options."); + } + if (!ctx || !ctx->instance) { + LOGE("dhcp server context pointer is null."); + return RET_FAILED; + } + ServerContext *srvIns = GetServerInstance(ctx); + + if (AppendReplyTimeOptions(ctx, &reply->options) != RET_SUCCESS) { + return RET_FAILED; + } + if (AddReplyServerIdOption(&reply->options, srvIns->addressPool.serverId) != RET_SUCCESS) { + return RET_FAILED; + } + if (ParseReplyOptions(reply) != RET_SUCCESS) { + return RET_FAILED; + } + sockaddr_in *destAddrIn = DestinationAddrIn(); + int ret = sendto(srvIns->serverFd, &reply->packet, reply->length, 0, (struct sockaddr *)destAddrIn, + sizeof(*destAddrIn)); + if (!ret) { + LOGD("failed to send dhcp ack message."); + return RET_FAILED; + } + LOGI(" send reply ack, size:%d", reply->length); + return RET_SUCCESS; +} + +static int SendDhcpNak(PDhcpServerContext ctx, PDhcpMsgInfo reply) +{ + if (AppendReplyTypeOption(reply, REPLY_NAK) != RET_SUCCESS) { + return RET_FAILED; + } + if (!ctx || !ctx->instance) { + LOGE("dhcp server context pointer is null."); + return RET_FAILED; + } + ServerContext *srvIns = GetServerInstance(ctx); + if (ParseReplyOptions(reply) != RET_SUCCESS) { + return RET_FAILED; + } + + struct sockaddr_in *destAddrIn = DestinationAddrIn(); + int ret = sendto(srvIns->serverFd, &reply->packet, reply->length, 0, (struct sockaddr *)destAddrIn, + sizeof(*destAddrIn)); + if (!ret) { + LOGD("failed to send dhcp ack message."); + return RET_FAILED; + } + LOGI(" send reply nak, size:%d", reply->length); + return RET_SUCCESS; +} + +static int ParseMessageOptions(PDhcpMsgInfo msg) +{ + if (msg->packet.hlen < 0) { + return RET_FAILED; + } + if (msg->packet.hlen > DHCP_MESSAGE_FLAG_LENGTH) { + return RET_FAILED; + } + + if (msg->length < (DHCP_MSG_HEADER_SIZE + MAGIC_COOKIE_LENGTH)) { + return RET_FAILED; + } + DhcpOption *current, *end; + current = (DhcpOption *)msg->packet.options; + end = (DhcpOption *)(((uint8_t *)msg->packet.options) + (msg->length - DHCP_MSG_HEADER_SIZE)); + + if (memcmp(current, MAGIC_COOKIE_DATA, sizeof(MAGIC_COOKIE_DATA)) != 0) { + LOGD("bad magic cookie."); + return RET_FAILED; + } + current = (DhcpOption *)(((uint8_t *)current) + MAGIC_COOKIE_LENGTH); + int pos = (int)(((uint8_t *)current) + MAGIC_COOKIE_LENGTH); + + int optTotal = 0; + int optionLength = msg->length - DHCP_MSG_HEADER_SIZE; + while (current < end && current->code != END_OPTION) { + pos += OPT_HEADER_LENGTH + current->length; + if (pos >= optionLength) { + LOGD("out of option max size."); + return RET_FAILED; + } + if (PushBackOption(&msg->options, current) != RET_SUCCESS) { + LOGD("faild to PushOption."); + } + current = (DhcpOption *)(((uint8_t *)current) + OPT_HEADER_LENGTH + current->length); + optTotal++; + } + + if (current < end && current->code == END_OPTION) { + LOGD("option list size:%d xid:%u", msg->options.size, msg->packet.xid); + return RET_SUCCESS; + } + + LOGD("option list parse failed."); + return RET_FAILED; +} + +static int ResetMessageOptions(PDhcpMsgInfo reply) +{ + if (!reply || reply->options.size == 0) { + LOGE("message pointer is null."); + return RET_ERROR; + } + if (memset_s(reply->packet.options, DHCP_OPTIONS_SIZE, 0, DHCP_OPTIONS_SIZE) != EOK) { + LOGE("failed to reset message options!"); + return RET_ERROR; + } + return RET_SUCCESS; +} + +static int ValidateReplyOptions(PDhcpMsgInfo reply) +{ + if (!reply) { + LOGE("reply message pointer is null."); + return RET_FAILED; + } + int ret = RET_FAILED; + if ((ret = ResetMessageOptions(reply)) != RET_SUCCESS) { + return ret; + } + reply->length = DHCP_MSG_HEADER_SIZE; + PDhcpOptionNode pNode = reply->options.first; + if (!pNode) { + return RET_ERROR; + } + pNode = pNode->next; + PDhcpOption pOptMsgType = GetOption(&reply->options, DHCP_MESSAGE_TYPE_OPTION); + if (!pOptMsgType) { + LOGE("unkown reply message type."); + return ret; + } + return RET_SUCCESS; +} + +static int ParseReplyOptions(PDhcpMsgInfo reply) +{ + int ret = RET_FAILED; + if ((ret = ValidateReplyOptions(reply)) != RET_SUCCESS) { + return ret; + } + PDhcpOptionNode pNode = reply->options.first->next; + DhcpOption endOpt = {END_OPTION, 0}; + PushBackOption(&reply->options, &endOpt); + int replyOptsLength = 0; + uint8_t *current = reply->packet.options, olen = MAGIC_COOKIE_LENGTH; + uint32_t cookie = htonl(DHCP_MAGIC_COOKIE); + if (memcpy_s(current, olen, &cookie, olen) != EOK) { + LOGE("memcpy cookie out of options buffer!"); + return RET_FAILED; + } + replyOptsLength += olen; + current += olen; + ret = RET_SUCCESS; + while (pNode && (uint32_t)pNode->option.length < DHCP_OPTION_SIZE) { + if ((uint32_t)pNode->option.code == END_OPTION) { + olen = OPT_HEADER_LENGTH + 1; + } else { + olen = OPT_HEADER_LENGTH + pNode->option.length; + } + if (memcpy_s(current, olen, &pNode->option, olen) != EOK) { + LOGE("memcpy current option out of options buffer!"); + ret = RET_FAILED; + break; + } + current += olen; + replyOptsLength += olen; + if ((uint32_t)pNode->option.code == END_OPTION) { + break; + } + pNode = pNode->next; + if (replyOptsLength >= DHCP_OPTIONS_SIZE) { + LOGE("current option out of options buffer!"); + ret = RET_FAILED; + break; + } + } + reply->length += replyOptsLength; + return ret; +} + +void RegisterDhcpCallback(PDhcpServerContext ctx, DhcpServerCallback callback) +{ + LOGI("register server callback."); + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return; + } + srvIns->callback = callback; +} + +static int InitServerContext(DhcpConfig *config, DhcpServerContext *ctx) +{ + if (!config) { + LOGE("server configure pointer is null."); + return RET_FAILED; + } + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return RET_FAILED; + } + if (InitAddressPool(&srvIns->addressPool, config->ifname, NULL) != RET_SUCCESS) { + LOGD("failed to init address pool."); + return RET_FAILED; + } + if (memcpy_s(ctx->ifname, sizeof(ctx->ifname), config->ifname, strlen(config->ifname)) != EOK) { + LOGD("failed to set interface name."); + return RET_FAILED; + } + srvIns->serverFd = 0; + srvIns->callback = 0; + srvIns->looperState = LS_IDLE; + srvIns->broadCastFlagEnable = config->broadcast; + srvIns->addressPool.serverId = config->serverId; + srvIns->addressPool.netmask = config->netmask; + srvIns->addressPool.gateway = config->gateway; + if (config->pool.beginAddress && config->pool.endAddress) { + srvIns->addressPool.addressRange.beginAddress = config->pool.beginAddress; + srvIns->addressPool.addressRange.endAddress = config->pool.endAddress; + } else { + srvIns->addressPool.addressRange.beginAddress = FirstIpAddress(config->serverId, config->netmask); + srvIns->addressPool.addressRange.endAddress = LastIpAddress(config->serverId, config->netmask); + } + if (memcpy_s(srvIns->addressPool.ifname, sizeof(srvIns->addressPool.ifname), + config->ifname, strlen(config->ifname)) != EOK) { + LOGD("failed to set interface name."); + return RET_FAILED; + } + if (!CheckAddressRange(&srvIns->addressPool)) { + return RET_FAILED; + } + + InitLeaseFile(&srvIns->addressPool); + return RET_SUCCESS; +} + +static int InitServerFixedOptions(DhcpConfig *config, DhcpServerContext *ctx) +{ + if (!config) { + LOGE("server configure pointer is null."); + return RET_FAILED; + } + ServerContext *srvIns = GetServerInstance(ctx); + if (!srvIns) { + LOGE("dhcp server context pointer is null."); + return RET_FAILED; + } + + if (!HasInitialized(&config->options)) { + LOGE("dhcp configure has not been initialized."); + return RET_FAILED; + } + + if (config->options.first != NULL && config->options.size > 0) { + DhcpOptionNode *pNode = config->options.first->next; + for (size_t i = 0; pNode != NULL && i < config->options.size; i++) { + PushBackOption(&srvIns->addressPool.fixedOptions, &pNode->option); + LOGD("append fixed option ==> %hhu,%d", pNode->option.code, + pNode->option.length); + pNode = pNode->next; + } + } + return RET_SUCCESS; +} + +PDhcpServerContext InitializeServer(DhcpConfig *config) +{ + DhcpServerContext *context = NULL; + if (!config) { + LOGE("dhcp server config pointer is null."); + return NULL; + } + if (strlen(config->ifname) == 0) { + LOGE("can't found interface name config."); + return NULL; + } + if (!config->serverId || !config->netmask) { + LOGE("missing required parameter or config item: \"serverId\", \"netmask\""); + return NULL; + } + if ((context = (DhcpServerContext *)calloc(1, sizeof(DhcpServerContext))) == NULL) { + LOGE("failed to calloc server context."); + return NULL; + } + if ((context->instance = calloc(1, sizeof(ServerContext))) == NULL) { + LOGE("failed to calloc server instance."); + FreeServerContex(context); + return NULL; + } + if (InitServerContext(config, context) != RET_SUCCESS) { + LOGE("failed initialize dhcp server context."); + FreeServerContex(context); + return NULL; + } + if (InitServerFixedOptions(config, context) != RET_SUCCESS) { + LOGE("failed initialize dhcp server fixed options."); + FreeServerContex(context); + return NULL; + } + LOGD("server id: %s", ParseStrIp(config->serverId)); + LOGD("netmask: %s", ParseStrIp(config->netmask)); + if (config->gateway) { + LOGD("gateway: %s", ParseStrIp(config->gateway)); + } + LOGD("address range begin of: %s", ParseStrIp(config->pool.beginAddress)); + LOGD("address range end of: %s", ParseStrIp(config->pool.endAddress)); + context->instance->initialized = 1; + return context; +} + +int FreeServerContex(PDhcpServerContext ctx) +{ + if (!ctx) { + LOGE("dhcp server context pointer is null."); + return RET_FAILED; + } + if (ctx->instance) { + ServerContext *srvIns = GetServerInstance(ctx); + FreeAddressPool(&srvIns->addressPool); + free(ctx->instance); + ctx->instance = NULL; + } + free(ctx); + return RET_SUCCESS; +} \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/hash_table.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/hash_table.c new file mode 100644 index 000000000..c0404e911 --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/hash_table.c @@ -0,0 +1,378 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 "hash_table.h" +#include +#include +#include +#include "securec.h" + +#define HASH_TRUE 1 +#define HASH_FALSE 0 + +#define HASH_CAP_LOAD_FACTOR 5 +#define HASH_CAP_GROWTH_FACTOR 10 +#define HASH_CALC_CODE_CALC 5 + +const int HASH_DEFAULT_VALUE = 5381; +const int HASH_CALC_MODE_HASH = 1; + +size_t HashCode(uintptr_t key, size_t keySize); +int HashCompare(uintptr_t firstKey, uintptr_t secondKey, size_t keySize); +size_t Hash(const HashTable *table, uintptr_t key); +int HashEquals(const HashTable *table, uintptr_t firstKey, uintptr_t secondKey); +int HashShouldGrow(HashTable *table); +int HashShouldShrink(HashTable *table); +int CapExtend(HashTable *table, size_t miniCapacity); +HashNode *HashCreateNode(HashTable *table, uintptr_t key, uintptr_t value, HashNode *next); +int HashPushFront(HashTable *table, size_t index, uintptr_t key, uintptr_t value); +void DestroyHashNode(HashNode *node); +int HashAdjustCapacity(HashTable *table); +int HashAllocate(HashTable *table, size_t capacity); +void HashRehash(HashTable *table, HashNode **old, size_t oldCapacity); + +int CreateHashTable(HashTable *table, size_t keySize, size_t valueSize, size_t capacity) +{ + if (table == 0) { + return HASH_ERROR; + } + + if (capacity < HASH_MINI_CAPACITY) { + capacity = HASH_MINI_CAPACITY; + } + + if (HashAllocate(table, capacity) == HASH_ERROR) { + return HASH_ERROR; + } + + table->keySize = keySize; + table->valueSize = valueSize; + table->hash = HashCode; + table->compare = HashCompare; + table->size = 0; + return HASH_SUCCESS; +} + +int DestroyHashTable(HashTable *table) +{ + if (!Initialized(table)) { + return HASH_ERROR; + } + for (size_t current = 0; current < table->capacity; ++current) { + HashNode *node = table->nodes[current]; + while (node) { + HashNode *next = node->next; + DestroyHashNode(node); + node = next; + } + } + free(table->nodes); + return HASH_SUCCESS; +} + +int Insert(HashTable *table, uintptr_t key, uintptr_t value) +{ + if (!Initialized(table)) { + return HASH_ERROR; + } + if (key == 0) { + return HASH_ERROR; + } + if (HashShouldGrow(table)) { + HashAdjustCapacity(table); + } + + size_t index = Hash(table, key); + for (HashNode *node = table->nodes[index]; node; node = node->next) { + if (HashEquals(table, key, node->key)) { + memcpy_s((void *)node->value, table->valueSize, (void *)value, table->valueSize); + return HASH_UPDATED; + } + } + if (HashPushFront(table, index, key, value) == HASH_ERROR) { + return HASH_ERROR; + } + ++table->size; + return HASH_INSERTED; +} + +int ContainsKey(const HashTable *table, uintptr_t key) +{ + if (!Initialized(table)) { + return HASH_FALSE; + } + if (key == 0) { + return HASH_FALSE; + } + + size_t index = Hash(table, key); + for (HashNode *node = table->nodes[index]; node; node = node->next) { + if (HashEquals(table, key, node->key)) { + return HASH_TRUE; + } + } + return HASH_FALSE; +} + +uintptr_t At(HashTable *table, uintptr_t key) +{ + if (table == 0) { + return 0; + } + if (key == 0) { + return 0; + } + + size_t index = Hash(table, key); + for (HashNode *node = table->nodes[index]; node; node = node->next) { + if (HashEquals(table, key, node->key)) { + return node->value; + } + } + return 0; +} + +int Remove(HashTable *table, uintptr_t key) +{ + if (table == 0) { + return HASH_ERROR; + } + if (key == 0) { + return HASH_ERROR; + } + + size_t index = Hash(table, key); + HashNode *node = table->nodes[index]; + + for (HashNode *previous = NULL; node; previous = node, node = node->next) { + if (HashEquals(table, key, node->key)) { + if (previous) { + previous->next = node->next; + } else { + table->nodes[index] = node->next; + } + + DestroyHashNode(node); + --table->size; + int shouldShrink = 0; + if (HashShouldShrink(table)) { + shouldShrink = 1; + } + if (shouldShrink && HashAdjustCapacity(table) == HASH_ERROR) { + return HASH_ERROR; + } + return HASH_SUCCESS; + } + } + return HASH_KEY_NOT_FOUND; +} + +int ClearAll(HashTable *table) +{ + if (table == 0 || table->nodes == 0) { + return HASH_ERROR; + } + if (table->size == 0) { + return HASH_SUCCESS; + } + if (DestroyHashTable(table) == HASH_ERROR || HashAllocate(table, HASH_MINI_CAPACITY) == HASH_ERROR) { + return HASH_ERROR; + } + table->size = 0; + return HASH_SUCCESS; +} + +int Empty(const HashTable *table) +{ + if (table == 0) { + return HASH_ERROR; + } + if (table->size == 0) { + return HASH_SUCCESS; + } + return HASH_NOT_EMPTY; +} + +int Initialized(const HashTable *table) +{ + if (table && table->capacity && table->keySize && table->valueSize && table->hash && table->compare) { + return HASH_TRUE; + } + return HASH_FALSE; +} + +int CapExtend(HashTable *table, size_t miniCapacity) +{ + if (!Initialized(table)) { + return HASH_ERROR; + } + + if (miniCapacity > table->threshold) { + return Resize(table, miniCapacity / HASH_CAP_LOAD_FACTOR); + } + return HASH_SUCCESS; +} + +int HashCompare(uintptr_t firstKey, uintptr_t secondKey, size_t keySize) +{ + if (memcmp((void *)firstKey, (void *)secondKey, keySize) == 0) { + return 0; + } + return 1; +} + +size_t HashCode(uintptr_t rawKey, size_t keySize) +{ + size_t hash = HASH_DEFAULT_VALUE; + const char *key = (char *)rawKey; + + for (size_t byte = 0; byte < keySize; ++byte) { + hash = ((hash << HASH_CALC_CODE_CALC) + hash) ^ key[byte]; + } + return hash; +} + +size_t Hash(const HashTable *table, uintptr_t key) +{ + if (HASH_CALC_MODE_HASH) { + return table->hash(key, table->keySize) % table->capacity; + } + return table->hash(key, table->keySize) & table->capacity; +} + +int HashEquals(const HashTable *table, uintptr_t firstKey, uintptr_t secondKey) +{ + if (table->compare(firstKey, secondKey, table->keySize) == 0) { + return HASH_TRUE; + } + return HASH_FALSE; +} + +int HashShouldGrow(HashTable *table) +{ + if (table->size == table->capacity) { + return HASH_TRUE; + } + return HASH_FALSE; +} + +int HashShouldShrink(HashTable *table) +{ + static size_t capSszie = sizeof(size_t); + if (table->size == table->capacity / capSszie) { + return HASH_TRUE; + } + return HASH_FALSE; +} + +HashNode *HashCreateNode(HashTable *table, uintptr_t key, uintptr_t value, HashNode *next) +{ + HashNode *node = (HashNode *)calloc(1, sizeof(HashNode)); + if (node == 0) { + return 0; + } + int flag = 0; + do { + node->key = (uintptr_t)calloc(table->keySize, sizeof(char)); + node->value = (uintptr_t)calloc(table->valueSize, sizeof(char)); + if (node->key == 0 || node->value == 0) { + break; + } + if (memcpy_s((void *)node->key, table->keySize, (void *)key, table->keySize) != EOK || + memcpy_s((void *)node->value, table->valueSize, (void *)value, table->valueSize) != EOK) { + break; + } + flag += 1; + } while (0); + if (flag == 0) { + free((void *)node->key); + free((void *)node->value); + free(node); + return 0; + } + node->next = next; + return node; +} + +int HashPushFront(HashTable *table, size_t index, uintptr_t key, uintptr_t value) +{ + table->nodes[index] = HashCreateNode(table, key, value, table->nodes[index]); + if (table->nodes[index] != NULL) { + return HASH_SUCCESS; + } + return HASH_ERROR; +} + +void DestroyHashNode(HashNode *node) +{ + free((void *)node->key); + free((void *)node->value); + free(node); +} + +int HashAdjustCapacity(HashTable *table) +{ + return Resize(table, table->size * HASH_CAP_GROWTH_FACTOR); +} + +int HashAllocate(HashTable *table, size_t capacity) +{ + if (capacity <= 0) { + return HASH_ERROR; + } + if ((table->nodes = calloc(capacity, sizeof(HashNode *))) == 0) { + return HASH_ERROR; + } + table->capacity = capacity; + table->threshold = capacity * HASH_CAP_LOAD_FACTOR; + return HASH_SUCCESS; +} + +int Resize(HashTable *table, size_t newSize) +{ + HashNode **old; + size_t oldSize; + size_t readySize = newSize; + if (readySize < HASH_MINI_CAPACITY) { + if (table->capacity > HASH_MINI_CAPACITY) { + readySize = HASH_MINI_CAPACITY; + } else { + return HASH_SUCCESS; + } + } + + old = table->nodes; + oldSize = table->capacity; + if (HashAllocate(table, readySize) == HASH_ERROR) { + return HASH_ERROR; + } + HashRehash(table, old, oldSize); + free(old); + return HASH_SUCCESS; +} + +void HashRehash(HashTable *table, HashNode **old, size_t oldCapacity) +{ + for (size_t current = 0; current < oldCapacity; ++current) { + HashNode *node = old[current]; + while (node != 0) { + HashNode *next = node->next; + size_t newPos = Hash(table, node->key); + node->next = table->nodes[newPos]; + table->nodes[newPos] = node; + node = next; + } + } +} \ No newline at end of file -- Gitee From 85cdf9ccfe4009805672f4b6c423e5ade2c40618 Mon Sep 17 00:00:00 2001 From: zhangfeng Date: Fri, 10 Sep 2021 03:55:55 +0000 Subject: [PATCH 3/5] dhcp server code optimize and bug fix Signed-off-by: zhangfeng --- .../dhcp_server/etc/dhcpd.conf.sample | 24 ++++++++----- .../dhcp_server/etc/dhcpd_mini.conf | 15 +++++++- .../dhcp_server/include/address_utils.h | 2 +- .../dhcp_server/include/common_util.h | 6 ++-- .../dhcp_server/include/dhcp_address_pool.h | 2 +- .../dhcp_server/include/dhcp_binding.h | 2 +- .../dhcp_server/src/address_utils.c | 4 +-- .../dhcp_manage/dhcp_server/src/common_util.c | 6 ++-- .../dhcp_server/src/dhcp_address_pool.c | 28 +++++++++------ .../dhcp_server/src/dhcp_binding.c | 18 +++++++--- .../dhcp_manage/dhcp_server/src/dhcp_config.c | 2 +- .../dhcp_manage/dhcp_server/src/dhcp_dhcpd.c | 36 ++++++------------- .../dhcp_manage/dhcp_server/src/dhcp_server.c | 29 ++++++++------- 13 files changed, 99 insertions(+), 75 deletions(-) diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/etc/dhcpd.conf.sample b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/etc/dhcpd.conf.sample index d3408fded..4fd416af4 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/etc/dhcpd.conf.sample +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/etc/dhcpd.conf.sample @@ -1,3 +1,16 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# 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. + #################### default #################### # Server identifier. #serverId=192.168.150.200 @@ -18,13 +31,8 @@ leaseTime=43200 # Address Range: {beginIp},{endIp} #pool=192.168.150.100,192.168.150.200 -# Ip distribue mode [0|1]: 0-random, 1-sequence(default). -#distribution=0 - -# Broadcast flags enable [0|1]: 0-no, 1-yes(default). - # Domain name server IP address: [,] [,] ... -dns=8.8.8.8,8.8.4.4,114.114.114.114 +#dns=223.5.5.5,8.8.8.8 #################### interface1 #################### # Network interface name, if this parameter is specified, the item is mandatory.(interface config) @@ -37,7 +45,7 @@ gateway=192.168.150.255 #leaseTime=6000 pool=192.168.150.100,192.168.150.200 -#dns=8.8.8.8,8.8.4.4,114.114.114.114 +#dns=223.5.5.5,8.8.8.8 #################### interface2 #################### # Network interface name, if this parameter is specified, the item is mandatory. @@ -50,4 +58,4 @@ pool=192.168.150.100,192.168.150.200 #gateway=192.168.255.255 #leaseTime=8000 #pool=192.168.255.2,192.168.255.254 -#dns=8.8.8.8,8.8.4.4,114.114.114.114 +#dns=223.5.5.5,8.8.8.8 diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/etc/dhcpd_mini.conf b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/etc/dhcpd_mini.conf index b202b205a..9704872f1 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/etc/dhcpd_mini.conf +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/etc/dhcpd_mini.conf @@ -1,4 +1,17 @@ -dns=223.5.5.5,8.8.8.8 +# Copyright (C) 2021 Huawei Device Co., Ltd. +# 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. + +#dns=223.5.5.5,8.8.8.8 interface=eth0 server=192.168.150.1 netmask=255.255.255.0 diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/address_utils.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/address_utils.h index 44db05cc1..b93981d79 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/address_utils.h +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/address_utils.h @@ -42,7 +42,7 @@ int HostTotal(uint32_t netmask); uint32_t ParseIp(const uint8_t *ipAddr); const char *ParseStrIp(uint32_t ipAddr); int IsEmptyHWAddr(uint8_t macAddr[DHCP_HWADDR_LENGTH]); -char *ParseStrMac(uint8_t macAddr[DHCP_HWADDR_LENGTH]); +char *ParseStrMac(const uint8_t *macAddr, size_t addrSize); int ParseMacAddress(const char *strMac, uint8_t macAddr[DHCP_HWADDR_LENGTH]); uint32_t HostToNetwork(uint32_t host); diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/common_util.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/common_util.h index a0f6fce0c..58afcd7be 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/common_util.h +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/common_util.h @@ -22,9 +22,9 @@ #ifdef __cplusplus extern "C" { #endif -void LogTime(); -uint64_t Tmspsec(); -uint64_t Tmspusec(); +void LogTime(void); +uint64_t Tmspsec(void); +uint64_t Tmspusec(void); void LeftTrim(char *buf); void RightTrim(char *buf); void TrimString(char *buf); diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_address_pool.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_address_pool.h index 04f3b865f..a54b13e45 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_address_pool.h +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_address_pool.h @@ -75,7 +75,7 @@ AddressBinding *GetBindingByMac(HashTable *bindTable, uint8_t macAddr[DHCP_HWADD AddressBinding *GetBindingByIp(HashTable *bindTable, uint32_t ipAddress); AddressBinding *QueryBinding(uint8_t macAddr[DHCP_HWADDR_LENGTH], PDhcpOptionList cliOptins); void SetDistributeMode(int mode); -int GetDistributeMode(); +int GetDistributeMode(void); #ifdef __cplusplus } diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_binding.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_binding.h index a23d706a6..5ef3bcba2 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_binding.h +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_binding.h @@ -59,7 +59,7 @@ typedef struct AddressBindingList *PAddressBindingList; uint64_t NextPendingInterval(uint64_t pendingInterval); int IsExpire(AddressBinding *binding); -int WriteAddressBinding(AddressBinding *binding, char *out, uint32_t size); +int WriteAddressBinding(const AddressBinding *binding, char *out, uint32_t size); int ParseAddressBinding(AddressBinding *binding, const char *buf); #ifdef __cplusplus diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/address_utils.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/address_utils.c index 0b27af4f7..35744572e 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/address_utils.c +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/address_utils.c @@ -199,10 +199,10 @@ const char *ParseStrIp(uint32_t ipAddr) return inet_ntoa(inAddr); } -char *ParseStrMac(uint8_t macAddr[DHCP_HWADDR_LENGTH]) +char *ParseStrMac(const uint8_t *macAddr, size_t addrSize) { static char strMacAddr[MAD_ADDR_BUF_SIZE] = {0}; - if (!macAddr) { + if (!macAddr || addrSize < MAC_ADDR_LENGTH) { return 0; } if (memset_s(strMacAddr, MAD_ADDR_BUF_SIZE, '\0', sizeof(strMacAddr)) != EOK || diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/common_util.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/common_util.c index e413b050d..296fc4d10 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/common_util.c +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/common_util.c @@ -38,7 +38,7 @@ #define LOG_TAG "DhcpServerCommon" typedef struct tm *ptm; -void LogTime() +void LogTime(void) { time_t curr; time(&curr); @@ -53,14 +53,14 @@ void LogTime() tt->tm_sec); } -uint64_t Tmspusec() +uint64_t Tmspusec(void) { struct timeval t; gettimeofday(&t, 0); return (uint64_t)((long long)t.tv_sec * TIME_SEC_TO_USEC + t.tv_usec); } -uint64_t Tmspsec() +uint64_t Tmspsec(void) { struct timeval t; gettimeofday(&t, 0); diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_address_pool.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_address_pool.c index efe43bd78..b98408699 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_address_pool.c +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_address_pool.c @@ -193,9 +193,9 @@ uint32_t AddressDistribute(DhcpAddressPool *pool, uint8_t macAddr[DHCP_HWADDR_LE } int total = HostTotal(pool->netmask); uint32_t distIp = pool->distribution; - if (distIp < pool->addressRange.beginAddress) { + if (!distIp || distIp < pool->addressRange.beginAddress) { distIp = pool->addressRange.beginAddress; - pool->distribution = distIp; + //pool->distribution = distIp; } int distSucess = 0; int outOfRange = 0; @@ -205,7 +205,8 @@ uint32_t AddressDistribute(DhcpAddressPool *pool, uint8_t macAddr[DHCP_HWADDR_LE offset = NextIpOffset(pool->netmask); } distIp = NextIpAddress(distIp, pool->netmask, offset); - if (!CheckIpAvailability(pool, macAddr, pool->distribution)) { + LOGD("===>distIp:%s", ParseStrIp(distIp)); + if (!CheckIpAvailability(pool, macAddr, distIp)) { continue; } int ret = CheckRangeAvailability(pool, macAddr, distIp, &outOfRange); @@ -229,17 +230,22 @@ int InitAddressPool(DhcpAddressPool *pool, const char *ifname, PDhcpOptionList o LOGD("address pool pointer is null."); return RET_ERROR; } - if (memset_s(pool, sizeof(DhcpAddressPool), 0, sizeof(DhcpAddressPool)) != EOK) { LOGD("failed to init dhcp pool."); return RET_ERROR; } - + if (memset_s(pool->ifname, IFACE_NAME_SIZE, '\0', IFACE_NAME_SIZE) != EOK) { + LOGD("failed to reset interface name."); + return RET_ERROR; + } + if (strncpy_s(pool->ifname, IFACE_NAME_SIZE, ifname, strlen(ifname)) != EOK) { + LOGD("failed to set interface name."); + return RET_ERROR; + } if (InitOptionList(&pool->fixedOptions) != RET_SUCCESS) { LOGD("failed to init options field for dhcp pool."); return RET_FAILED; } - if (CreateHashTable(&pool->leaseTable, sizeof(uint32_t), sizeof(AddressBinding), DHCP_POOL_INIT_SIZE) != HASH_SUCCESS) { LOGD("failed to create lease table."); @@ -487,12 +493,11 @@ AddressBinding *GetLease(DhcpAddressPool *pool, uint32_t ipAddress) if (!ipAddress) { return NULL; } - if (!pool) { return NULL; } - - if (ContainsKey(&pool->leaseTable, (uintptr_t)&ipAddress)) { + int ipAddr = ipAddress; + if (ContainsKey(&pool->leaseTable, (uintptr_t)&ipAddr)) { AddressBinding *lease = GetBindingByIp(&pool->leaseTable, ipAddress); if (!lease) { LOGE("failed to update lease recoder."); @@ -593,7 +598,8 @@ int SaveBindingRecoders(const DhcpAddressPool *pool, int force) for (size_t index = 0; index < pool->leaseTable.capacity; ++index) { HashNode *node = pool->leaseTable.nodes[index]; while (node != NULL) { - if (WriteAddressBinding((AddressBinding *)node->value, line, sizeof(line)) != RET_SUCCESS) { + AddressBinding *binding = (AddressBinding *)node->value; + if (WriteAddressBinding(binding, line, sizeof(line)) != RET_SUCCESS) { LOGW("Failed to convert binding info to string"); } else { fprintf(fp, "%s\n", line); @@ -610,7 +616,7 @@ void SetDistributeMode(int mode) { g_distributeMode = mode; } -int GetDistributeMode() +int GetDistributeMode(void) { return g_distributeMode; } \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_binding.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_binding.c index 333cc8f39..d8c9bc6e7 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_binding.c +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_binding.c @@ -14,11 +14,12 @@ */ #include "dhcp_binding.h" -#include +#include #include #include "dhcp_logger.h" #include "address_utils.h" #include "common_util.h" +#include "securec.h" #undef LOG_TAG #define LOG_TAG "DhcpServerBinding" @@ -52,11 +53,15 @@ int IsExpire(AddressBinding *binding) LOGE("binding is null."); return DHCP_FALSE; } + uint64_t leaseTime = binding->leaseTime; + if (!leaseTime) { + leaseTime = DHCP_LEASE_TIME; + } uint64_t expireIn = binding->expireIn; if (binding->bindingStatus == BIND_PENDING) { - expireIn = binding->pendingTime + binding->leaseTime; + expireIn = binding->pendingTime + leaseTime; } else if (binding->bindingStatus == BIND_ASSOCIATED) { - expireIn = binding->bindingTime + binding->leaseTime; + expireIn = binding->bindingTime + leaseTime; } uint64_t curr = Tmspsec(); if (curr > expireIn) { @@ -76,9 +81,12 @@ int IsExpire(AddressBinding *binding) #define BINDING_BINDING_STATUS_POS 7 #define BINDING_STRING_SIZE 8 -int WriteAddressBinding(AddressBinding *binding, char *out, uint32_t size) +int WriteAddressBinding(const AddressBinding *binding, char *out, uint32_t size) { - const char *mac = ParseStrMac(binding->chaddr); + if (!binding || !out) { + return RET_FAILED; + } + const char *mac = ParseStrMac(binding->chaddr, sizeof(binding->chaddr)); const char *ip = ParseStrIp(binding->ipAddress); if (mac == NULL || ip == NULL) { return RET_FAILED; diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_config.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_config.c index d4621a8b7..9ca24ca91 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_config.c +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_config.c @@ -189,7 +189,7 @@ static int SetIfnameInfo(DhcpConfig *dhcpConfig, const char *pValue) if (memset_s(dhcpConfig->ifname, IFACE_NAME_SIZE, '\0', IFACE_NAME_SIZE) != EOK) { return 0; } - if (memcpy_s(dhcpConfig->ifname, IFACE_NAME_SIZE, pValue, strlen(pValue)) != EOK) { + if (strncpy_s(dhcpConfig->ifname, IFACE_NAME_SIZE, pValue, strlen(pValue)) != EOK) { return 0; } return 1; diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_dhcpd.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_dhcpd.c index f859a6783..cc5d2e6d0 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_dhcpd.c +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_dhcpd.c @@ -33,7 +33,6 @@ #include "hash_table.h" #include "address_utils.h" #include "securec.h" -#include "common_util.h" #include "dhcp_config.h" #undef LOG_TAG @@ -102,7 +101,7 @@ typedef struct DhcpOptionField { } DhcpOptionField; -static int InitArguments() +static int InitArguments(void) { if (CreateHashTable(&g_argumentsTable, ARGUMENT_NAME_SIZE, sizeof(ArgumentInfo), INIT_ARGS_SIZE) != HASH_SUCCESS) { return RET_FAILED; @@ -110,7 +109,7 @@ static int InitArguments() return RET_SUCCESS; } -static void FreeArguments() +static void FreeArguments(void) { if (!Initialized(&g_argumentsTable)) { return; @@ -235,6 +234,9 @@ static int PutPoolArgument(const char *argument, const char *val) static int ShowVersion(const char *argument, const char *val) { + if (argument && PutArgument(argument, val) != RET_SUCCESS) { + LOGD("failed to put argument 'version'."); + } printf("version:%s\n", DHCPD_VERSION); return RET_BREAK; } @@ -294,7 +296,7 @@ void ShowUsage(const DhcpUsage *usage) } } -void PrintRequiredArguments() +void PrintRequiredArguments(void) { size_t argc = sizeof(usages) / sizeof(DhcpUsage); printf("required parameters:"); @@ -319,7 +321,7 @@ void PrintRequiredArguments() printf(" dhcp_server --help \n\n"); } -void PrintUsage() +void PrintUsage(void) { printf("Usage: dhcp_server [options] \n\n"); @@ -334,7 +336,7 @@ void PrintUsage() printf("\n"); } -void ShowHelp(int argc, char *argv[]) +void ShowHelp(int argc) { if (argc == NUM_TWO) { PrintUsage(); @@ -644,22 +646,6 @@ static int RegisterSignalHandle(void) return RET_SUCCESS; } -int ValidateArguments() -{ - size_t argc = sizeof(usages) / sizeof(DhcpUsage); - for (size_t i = 0; i < argc; i++) { - DhcpUsage usage = usages[i]; - if (!usage.opt) { - break; - } - if (usage.required && !HasArgument(usage.opt->name)) { - printf("missing required parameter '%s' \n", usage.opt->name); - return 0; - } - } - return 1; -} - static int InitializeDhcpConfig(const char *ifname, DhcpConfig *config) { if (!config) { @@ -693,12 +679,12 @@ static int InitializeDhcpConfig(const char *ifname, DhcpConfig *config) return RET_SUCCESS; } -static void FreeLocalConfig() +static void FreeLocalConfig(void) { FreeOptionList(&g_dhcpConfig.options); } -void FreeSeverResources() +void FreeSeverResources(void) { FreeArguments(); FreeLocalConfig(); @@ -711,7 +697,7 @@ int main(int argc, char *argv[]) return 1; } if (strcmp("-h", argv[argc - 1]) == 0 || strcmp("--help", argv[argc - 1]) == 0) { - ShowHelp(argc, argv); + ShowHelp(argc); return 0; } if (InitArguments() != RET_SUCCESS) { diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_server.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_server.c index e19301ac9..4cccda17e 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_server.c +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_server.c @@ -32,7 +32,6 @@ #include "securec.h" #include "dhcp_logger.h" #include "address_utils.h" -#include "common_util.h" #include "dhcp_address_pool.h" #include "dhcp_config.h" @@ -104,7 +103,7 @@ static int SendDhcpNak(PDhcpServerContext ctx, PDhcpMsgInfo reply); static int ParseMessageOptions(PDhcpMsgInfo msg); static int ParseReplyOptions(PDhcpMsgInfo reply); -struct sockaddr_in *BroadcastAddrIn(); +struct sockaddr_in *BroadcastAddrIn(void); static struct ServerContext *GetServerInstance(const DhcpServerContext *ctx) { @@ -113,7 +112,7 @@ static struct ServerContext *GetServerInstance(const DhcpServerContext *ctx) } return (struct ServerContext *)ctx->instance; } -void OnUpdateServerConfig(); + int HasFixSocket(int fd) { int flags; @@ -137,12 +136,13 @@ int BindNetInterface(int fd, const char *ifname) } if (ifname) { ssize_t ifnameSize = strlen(ifname); - if (ifnameSize < IFNAMSIZ) { - strncpy_s(iface.ifr_ifrn.ifrn_name, IFNAMSIZ, ifname, ifnameSize); - } else { + if (ifnameSize > IFNAMSIZ) { LOGE("network interface name too long."); return RET_FAILED; } + if (strncpy_s(iface.ifr_ifrn.ifrn_name, IFNAMSIZ, ifname, ifnameSize) != EOK) { + return RET_FAILED; + }; if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, (char *)&iface, sizeof(iface)) == -1) { LOGE("failed to bind network device interface[%s].", ifname); return RET_FAILED; @@ -191,7 +191,7 @@ int InitServer(const char *ifname) } return fd; } -struct sockaddr_in *BroadcastAddrIn() +struct sockaddr_in *BroadcastAddrIn(void) { static struct sockaddr_in broadcastAddrIn = {0}; if (broadcastAddrIn.sin_port == 0) { @@ -202,7 +202,7 @@ struct sockaddr_in *BroadcastAddrIn() return &broadcastAddrIn; } -struct sockaddr_in *SourceAddrIn() +struct sockaddr_in *SourceAddrIn(void) { static struct sockaddr_in sourceAddrIn = {0}; sourceAddrIn.sin_port = htons(DHCP_CLIENT_PORT); @@ -211,7 +211,7 @@ struct sockaddr_in *SourceAddrIn() return &sourceAddrIn; } -struct sockaddr_in *ResetSourceAddr() +struct sockaddr_in *ResetSourceAddr(void) { struct sockaddr_in *srcAddr = SourceAddrIn(); srcAddr->sin_port = htons(DHCP_CLIENT_PORT); @@ -220,12 +220,12 @@ struct sockaddr_in *ResetSourceAddr() return srcAddr; } -uint32_t SourceIpAddress() +uint32_t SourceIpAddress(void) { uint32_t srcIp = SourceAddrIn()->sin_addr.s_addr; return srcIp; } -struct sockaddr_in *DestinationAddrIn() +struct sockaddr_in *DestinationAddrIn(void) { static struct sockaddr_in destAddrIn = {0}; if (destAddrIn.sin_port == 0) { @@ -825,7 +825,8 @@ static void AddAddressOption(PDhcpMsgInfo reply, uint8_t code, int32_t address) LOGE("reply message pointer is null."); return; } - DhcpOption optAddress = {code, 0, {0}}; + DhcpOption optAddress = {0, 0, {0}}; + optAddress.code = code; if (AppendAddressOption(&optAddress, address) != RET_SUCCESS) { LOGE("failed to append address option."); return; @@ -1031,7 +1032,8 @@ static int NotBindingRequest(DhcpAddressPool *pool, PDhcpMsgInfo received, PDhcp return REPLY_ACK; } -static int ValidateRequestMessage(const PDhcpServerContext ctx, const PDhcpMsgInfo received, PDhcpMsgInfo reply, uint32_t *yourIp) +static int ValidateRequestMessage(const PDhcpServerContext ctx, const PDhcpMsgInfo received, + PDhcpMsgInfo reply, uint32_t *yourIp) { if (!received || !reply) { LOGE("receive or reply message pointer is null."); @@ -1061,6 +1063,7 @@ static int ValidateRequestMessage(const PDhcpServerContext ctx, const PDhcpMsgIn } else { LOGW("request message not specified server identifier option."); } + *yourIp = yourIpAddr; return REPLY_ACK; } -- Gitee From cd00c7fdc18dd1de5001f0f1fe52a311417867dc Mon Sep 17 00:00:00 2001 From: zhangfeng Date: Fri, 10 Sep 2021 10:06:36 +0000 Subject: [PATCH 4/5] delete unused code and fix error for cpp header Signed-off-by: zhangfeng --- .../dhcp_manage/dhcp_server/include/address_utils.h | 2 +- .../dhcp_manage/dhcp_server/src/dhcp_address_pool.c | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/address_utils.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/address_utils.h index b93981d79..e7a603785 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/address_utils.h +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/address_utils.h @@ -17,7 +17,7 @@ #define OHOS_ADDRESS_UTILS_H #include -#include +#include #include #define MAC_ADDR_LENGTH 6 diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_address_pool.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_address_pool.c index b98408699..31da1d80c 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_address_pool.c +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_address_pool.c @@ -205,7 +205,6 @@ uint32_t AddressDistribute(DhcpAddressPool *pool, uint8_t macAddr[DHCP_HWADDR_LE offset = NextIpOffset(pool->netmask); } distIp = NextIpAddress(distIp, pool->netmask, offset); - LOGD("===>distIp:%s", ParseStrIp(distIp)); if (!CheckIpAvailability(pool, macAddr, distIp)) { continue; } -- Gitee From 1cafcf8339e2eedf59e7cb47c100870fd2d45eb3 Mon Sep 17 00:00:00 2001 From: zhangfeng Date: Mon, 13 Sep 2021 07:24:13 +0000 Subject: [PATCH 5/5] add hilink c interface Signed-off-by: zhangfeng --- interfaces/innerkits/native_c/station_info.h | 61 ++++ interfaces/innerkits/native_c/wifi_device.h | 243 +++++++++++++ .../innerkits/native_c/wifi_device_config.h | 233 ++++++++++++ .../innerkits/native_c/wifi_error_code.h | 70 ++++ interfaces/innerkits/native_c/wifi_event.h | 131 +++++++ interfaces/innerkits/native_c/wifi_hotspot.h | 144 ++++++++ .../innerkits/native_c/wifi_hotspot_config.h | 121 +++++++ .../innerkits/native_c/wifi_linked_info.h | 79 +++++ .../innerkits/native_c/wifi_scan_info.h | 67 ++++ interfaces/innerkits/native_cpp/napi/BUILD.gn | 2 +- .../wifi_standard/{src => }/BUILD.gn | 45 +-- .../wifi_standard/c_adapter/wifi_c_device.cpp | 332 ++++++++++++++++++ .../wifi_standard/c_adapter/wifi_c_event.cpp | 288 +++++++++++++++ .../c_adapter/wifi_c_hotspot.cpp | 179 ++++++++++ .../wifi_standard/c_adapter/wifi_c_utils.cpp | 118 +++++++ .../wifi_standard/c_adapter/wifi_c_utils.h | 42 +++ ohos.build | 2 +- 17 files changed, 2135 insertions(+), 22 deletions(-) create mode 100755 interfaces/innerkits/native_c/station_info.h create mode 100755 interfaces/innerkits/native_c/wifi_device.h create mode 100755 interfaces/innerkits/native_c/wifi_device_config.h create mode 100755 interfaces/innerkits/native_c/wifi_error_code.h create mode 100755 interfaces/innerkits/native_c/wifi_event.h create mode 100755 interfaces/innerkits/native_c/wifi_hotspot.h create mode 100755 interfaces/innerkits/native_c/wifi_hotspot_config.h create mode 100755 interfaces/innerkits/native_c/wifi_linked_info.h create mode 100755 interfaces/innerkits/native_c/wifi_scan_info.h rename interfaces/innerkits/native_cpp/wifi_standard/{src => }/BUILD.gn (76%) create mode 100755 interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_device.cpp create mode 100755 interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_event.cpp create mode 100755 interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_hotspot.cpp create mode 100755 interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_utils.cpp create mode 100755 interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_utils.h diff --git a/interfaces/innerkits/native_c/station_info.h b/interfaces/innerkits/native_c/station_info.h new file mode 100755 index 000000000..8f26d7b29 --- /dev/null +++ b/interfaces/innerkits/native_c/station_info.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup wifiservice + * @{ + * + * @brief Provides functions for the Wi-Fi station and hotspot modes. + * + * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a + * station or hotspot, query the station or hotspot status, and listen for events. \n + * + * @since 7 + */ + +/** + * @file station_info.h + * + * @brief Defines the structure and macro of the station information contained in the event information. + * + * The station information is passed to {@link OnHotspotStaJoin} or {@link OnHotspotStaLeave} invoked when a specified + * event occurs. + * + * @since 7 + */ + +#ifndef HARMONY_OS_LITE_WIFI_STATION_INFO_H +#define HARMONY_OS_LITE_WIFI_STATION_INFO_H +#include "wifi_device_config.h" + +/** + * @brief Represents the station information. + * + * The station information is returned when {@link OnHotspotStaJoin} or {@link OnHotspotStaLeave} is called. \n + * + * @since 7 + */ +typedef struct { + /** Network name of the station */ + char name[DEVICE_NAME_LEN]; + /** MAC address. For its length, see {@link WIFI_MAC_LEN}. */ + unsigned char macAddress[WIFI_MAC_LEN]; + /** IP address of the station */ + unsigned int ipAddress; + unsigned short disconnectedReason; +} StationInfo; + +#endif // HARMONY_OS_LITE_WIFI_STATION_INFO_H +/** @} */ diff --git a/interfaces/innerkits/native_c/wifi_device.h b/interfaces/innerkits/native_c/wifi_device.h new file mode 100755 index 000000000..82488b5b0 --- /dev/null +++ b/interfaces/innerkits/native_c/wifi_device.h @@ -0,0 +1,243 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup wifiservice + * @{ + * + * @brief Provides functions for the Wi-Fi station and hotspot modes. + * + * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a + * station or hotspot, query the station or hotspot status, and listen for events. \n + * + * @since 7 + */ + +/** + * @file wifi_device.h + * + * @brief Provides capabilities to enable and disable the station mode, connect to and disconnect from a station, + * query the station status, and listen for events. + * + * @since 7 + */ + +#ifndef WIFI_DEVICE_C_H +#define WIFI_DEVICE_C_H +#include "wifi_event.h" +#include "station_info.h" +#include "wifi_scan_info.h" +#include "wifi_error_code.h" +#include "wifi_linked_info.h" +#include "wifi_device_config.h" + +/** + * @brief Enables the station mode. + * + * @return Returns {@link WIFI_SUCCESS} if the station mode is enabled; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode EnableWifi(void); + +/** + * @brief Disables the station mode. + * + * @return Returns {@link WIFI_SUCCESS} if the station mode is disabled; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode DisableWifi(void); + +/** + * @brief Checks whether the station mode is enabled. + * + * @return Returns {@link WIFI_STA_ACTIVE} if the station mode is enabled; returns {@link WIFI_STA_NOT_ACTIVE} + * otherwise. + * @since 7 + */ +int IsWifiActive(void); + +/** + * @brief Starts a Wi-Fi scan. + * + * @return Returns {@link WIFI_SUCCESS} if the Wi-Fi scan is started; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode Scan(void); + +/** + * @brief Obtains an array of hotspots detected in a Wi-Fi scan. + * + * The array of hotspots can be obtained only after the Wi-Fi scan is complete. \n + * + * @param result Indicates the array of hotspots detected in a Wi-Fi scan. The array is requested and released by the + * caller. The value must be greater than or equal to {@link WIFI_SCAN_HOTSPOT_LIMIT}. + * @param size Indicates the size of the array. + * @return Returns {@link WIFI_SUCCESS} if the array of hotspots detected in the Wi-Fi scan is obtained; returns an + * error code defined in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode GetScanInfoList(WifiScanInfo *result, unsigned int *size); + +/** + * @brief Adds a specified hotspot configuration for connecting to a hotspot. + * + * This function generates a networkId. \n + * + * @param config Indicates the hotspot configuration to add. + * @param result Indicates the generated networkId. Each networkId matches a hotspot configuration. + * @return Returns {@link WIFI_SUCCESS} if the specified hotspot configuration is added; returns an error code defined + * in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode AddDeviceConfig(const WifiDeviceConfig *config, int *result); + +/** + * @brief Obtains all hotspot configurations. + * + * Hotspot configurations were added using {@link AddDeviceConfig}. \n + * + * @param result Indicates the array of all hotspot configurations. The array is requested and released by the caller. + * The value must be greater than or equal to {@link WIFI_MAX_CONFIG_SIZE}. + * @param size Indicates the size of the array. + * @return Returns {@link WIFI_SUCCESS} if all hotspot configurations are obtained; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode GetDeviceConfigs(WifiDeviceConfig *result, unsigned int *size); + +/** + * @brief Removes a hotspot configuration matching a specified networkId. + * + * @param networkId Indicates the networkId matching the hotspot configuration to remove. + * @return Returns {@link WIFI_SUCCESS} if the hotspot configuration is removed; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode RemoveDevice(int networkId); + +/** + * @brief Disable a hotspot configuration matching a specified networkId. If the config is diabled, it will + * not be auto connected. + * + * @param networkId Indicates the networkId matching the hotspot configuration to disable. + * @return Returns {@link WIFI_SUCCESS} if the hotspot configuration is disabled; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode DisableDeviceConfig(int networkId); + +/** + * @brief Enable a hotspot configuration matching a specified networkId. If the config is enabled, it will + * be connected automatically when wifi is enabled. When the config is added, it is enabled in default. + * + * @param networkId Indicates the networkId matching the hotspot configuration to enable. + * @return Returns {@link WIFI_SUCCESS} if the hotspot configuration is enabled; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode EnableDeviceConfig(int networkId); + +/** + * @brief Connects to a hotspot matching a specified networkId. + * + * Before calling this function, call {@link AddDeviceConfig} to add a hotspot configuration. \n + * + * @param networkId Indicates the networkId matching the target hotspot. + * @return Returns {@link WIFI_SUCCESS} if the hotspot is connected; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode ConnectTo(int networkId); + +/** + * @brief Connect to a hotspot by config. + * + * @param config is device configuration to connect the Wi-Fi network. + * @return Returns {@link WIFI_SUCCESS} if the hotspot is connected; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode ConnectToDevice(const WifiDeviceConfig *config); + +/** + * @brief Disconnects this Wi-Fi connection. + * + * @return Returns {@link WIFI_SUCCESS} if this Wi-Fi connection is disconnected; returns an error code defined + * in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode Disconnect(void); + +/** + * @brief Obtains information about the connected hotspot. + * + * @param result Indicates the information about the connected hotspot. + * @return Returns {@link WIFI_SUCCESS} if the information about the connected hotspot is obtained; returns an error + * code defined in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode GetLinkedInfo(WifiLinkedInfo *result); + +/** + * @brief Obtains the MAC address of this device. + * + * @param result Indicates the MAC address of this device. It is a char array whose length is 6. + * @return Returns {@link WIFI_SUCCESS} if the MAC address of this device is obtained; returns an error code defined + * in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode GetDeviceMacAddress(unsigned char *result); + +/** + * @brief Starts a Wi-Fi scan based on a specified parameter. + * + * Only results matching the specified parameter will be returned for the Wi-Fi scan.\n + * + * @param params Indicates the pointer to the parameter for starting the Wi-Fi scan. + * For details, see {@link WifiScanParams}. + * @return Returns {@link WIFI_SUCCESS} if the Wi-Fi scan is started successfully; + * returns an error code defined in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode AdvanceScan(WifiScanParams *params); + +/* + * @brief get the ip address. + * + * @return Returns {@link WIFI_SUCCESS} if the IP is got; returns an error code defined + * in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode GetIpInfo(IpInfo *info); + +/** + * @brief Obtains the signal level indicated by a specified received signal strength indicator (RSSI) and frequency + * band. + * + * + * Based on the signal level, you can display the signal strength represented by the number of signal bars. \n + * + * @param rssi Indicates the RSSI. + * @param band Indicates the frequency band, either {@link HOTSPOT_BAND_TYPE_5G} or {@link HOTSPOT_BAND_TYPE_2G}. + * @return Returns the signal level if it is obtained; returns -1 otherwise. + * @since 7 + */ +int GetSignalLevel(int rssi, int band); + +#endif // WIFI_DEVICE_C_H +/** @} */ diff --git a/interfaces/innerkits/native_c/wifi_device_config.h b/interfaces/innerkits/native_c/wifi_device_config.h new file mode 100755 index 000000000..03550efcf --- /dev/null +++ b/interfaces/innerkits/native_c/wifi_device_config.h @@ -0,0 +1,233 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup wifiservice + * @{ + * + * @brief Provides functions for the Wi-Fi station and hotspot modes. + * + * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a + * station or hotspot, query the station or hotspot status, and listen for events. \n + * + * @since 7 + */ + +/** + * @file wifi_device_config.h + * + * @brief Defines the Wi-Fi station configuration. + * + * The Wi-Fi station configuration includes the security type and data length. \n + * + * @since 7 + */ + +#ifndef HARMONY_OS_LITE_WIFI_DEVICE_CONFIG_H +#define HARMONY_OS_LITE_WIFI_DEVICE_CONFIG_H + +/** + * @brief Indicates the maximum number of Wi-Fi station configurations that can be added using {@link AddDeviceConfig}. + * + * If the maximum number is reached, an error will be returned. In this case, you must delete at least one + * configuration before you can add new ones. \n + */ +#define WIFI_MAX_CONFIG_SIZE 10 +/** + * @brief Indicates the value of networkId when the configuration file is unavailable. + * + * Generally, the configuration file is unavailable because the configuration matching the networkId is + * uninitialized. \n + */ +#define WIFI_CONFIG_INVALID (-1) +/** + * @brief Indicates the maximum length of a Wi-Fi SSID. + * + * The maximum length is 32, and the last bit is reserved and set to \0. \n + */ +#define WIFI_MAX_SSID_LEN 33 // 32 + \0 +/** + * @brief Indicates the maximum length of a Wi-Fi key. + * + * The maximum length is 64, and the last bit is reserved and set to \0. \n + */ +#define WIFI_MAX_KEY_LEN 65 // 64 + \0 +/** + * @brief Indicates the maximum length of a Wi-Fi MAC address or a Wi-Fi BSSID. + * + */ +#define WIFI_MAC_LEN 6 + +/** + * @brief Indicates the maximum length of a Wi-Fi PSK. + * + */ +#define WIFI_PSK_LEN 32 + +/** + * @brief Indicates the maximum number of DNS servers. + * + * A maximum of two DNS servers are allowed. \n + */ +#define WIFI_MAX_DNS_NUM 2 + +/** + * @brief Indicates the maximum length of a device name. + * + */ +#define DEVICE_NAME_LEN 128 + +/** + * @brief Enumerates Wi-Fi security types. + * + * @since 7 + */ +typedef enum { + /** Invalid security type */ + WIFI_SEC_TYPE_INVALID = -1, + /** Open */ + WIFI_SEC_TYPE_OPEN, + /** Wired Equivalent Privacy (WEP) */ + WIFI_SEC_TYPE_WEP, + /** Pre-shared key (PSK) */ + WIFI_SEC_TYPE_PSK, + /** Simultaneous Authentication of Equals (SAE) */ + WIFI_SEC_TYPE_SAE, +} WifiSecurityType; + +/** + * @brief Enumerates psk encryption types. + * + * @since 7 + */ +typedef enum { + /** Indicates that the ascii type of psk encryption type */ + WIFI_PSK_TYPE_ASCII = 0, + /** Indicates that the hex type of psk encryption type */ + WIFI_PSK_TYPE_HEX, +} WifiPskType; + +/** + * @brief Defines the IP configuration of the Wi-Fi device. + * + * The IP configuration is mainly used for connecting to the device. \n + * + * @since 3 + */ +typedef struct { + /** IP address of the Wi-Fi device */ + unsigned int ipAddress; + /** Gateway of the Wi-Fi device */ + unsigned int gateway; + /** DNS server addresses for the Wi-Fi device */ + unsigned int dnsServers[WIFI_MAX_DNS_NUM]; + /** Subnet mask of the Wi-Fi device */ + unsigned int netmask; +} IpConfig; + +/** + * @brief Enumerates IP address types for the Wi-Fi device. + * + * @since 3 + */ +typedef enum { + /** IP address dynamically assigned by DHCP */ + DHCP, + /** Static IP address */ + STATIC_IP, + /** Unknown IP address type */ + UNKNOWN +} IpType; + +/** + * @brief Represents the Wi-Fi station configuration used to connect to a specified Wi-Fi device. + * + * @since 7 + */ +typedef struct WifiDeviceConfig { + /** Service set ID (SSID). For its length, see {@link WIFI_MAX_SSID_LEN}. */ + char ssid[WIFI_MAX_SSID_LEN]; + /** Basic service set ID (BSSID). For its length, see {@link WIFI_MAC_LEN}. */ + unsigned char bssid[WIFI_MAC_LEN]; + /** Key. For its length, see {@link WIFI_MAX_KEY_LEN}. */ + char preSharedKey[WIFI_MAX_KEY_LEN]; + /** Security type. It is defined in {@link WifiSecurityType}. */ + int securityType; + /** Allocated networkId */ + int netId; + /** Frequency */ + unsigned int freq; + /** PSK type, see {@link WifiPskType}. */ + int wapiPskType; + /** IP address type */ + IpType ipType; + /** Static IP address */ + IpConfig staticIp; + /* 1 for hidden config */ + int isHiddenSsid; +} WifiDeviceConfig; + +/** + * @brief Enumerates Wi-Fi scan types. + * + * @since 7 + */ +typedef enum { + /** A scan based on a specified frequency. */ + WIFI_FREQ_SCAN, + /** A scan based on a specified SSID. */ + WIFI_SSID_SCAN, + /** A scan based on a specified BSSID. */ + WIFI_BSSID_SCAN, + /** A scan based on a specified frequency band. */ + WIFI_BAND_SCAN +} WifiScanType; + +/** + * @brief Represents the Wi-Fi station configuration used to connect to a specified Wi-Fi device. + * + * @since 7 + */ +typedef struct { + /** Service set ID (SSID). Its maximum length is defined by {@link WIFI_MAX_SSID_LEN}. */ + char ssid[WIFI_MAX_SSID_LEN]; + /** Length of the SSID. */ + char ssidLen; + /** Basic service set ID (BSSID). Its length is defined by {@link WIFI_MAC_LEN}. */ + char bssid[WIFI_MAC_LEN]; + /** Frequency. */ + int freqs; + /** Frequency band. */ + int band; + /** Wi-Fi scan type, which is defined by {@link WifiScanType}. */ + WifiScanType scanType; +} WifiScanParams; + +/** + * @brief IP info + * + * @since 7 + */ +typedef struct { + unsigned int ipAddress; + unsigned int netMask; + unsigned int netGate; + unsigned int dns1; + unsigned int dns2; + unsigned int serverAddress; + int leaseDuration; +} IpInfo; +#endif // HARMONY_OS_LITE_WIFI_DEVICE_CONFIG_H +/** @} */ diff --git a/interfaces/innerkits/native_c/wifi_error_code.h b/interfaces/innerkits/native_c/wifi_error_code.h new file mode 100755 index 000000000..de6e24006 --- /dev/null +++ b/interfaces/innerkits/native_c/wifi_error_code.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup wifiservice + * @{ + * + * @brief Provides functions for the Wi-Fi station and hotspot modes. + * + * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a + * station or hotspot, query the station or hotspot status, and listen for events. \n + * + * @since 7 + */ + +/** + * @file wifi_error_code.h + * + * @brief Defines error codes of the Wi-Fi service. + * + * @since 7 + */ + +#ifndef WIFI_ERROR_CODE_C_H +#define WIFI_ERROR_CODE_C_H + +/** + * @brief Enumerates Wi-Fi error codes. + * + * @since 7 + */ +typedef enum { + /** No errors. */ + WIFI_SUCCESS = 0, + /** Invalid parameters */ + ERROR_WIFI_INVALID_ARGS = -1, + /** Invalid chip */ + ERROR_WIFI_CHIP_INVALID = -2, + /** Invalid Wi-Fi interface */ + ERROR_WIFI_IFACE_INVALID = -3, + /** Invalid RTT controller */ + ERROR_WIFI_RTT_CONTROLLER_INVALID = -4, + /** Wi-Fi not supported by the current version or device */ + ERROR_WIFI_NOT_SUPPORTED = -5, + /** Wi-Fi unavailable */ + ERROR_WIFI_NOT_AVAILABLE = -6, + /** Wi-Fi not initialized or started */ + ERROR_WIFI_NOT_STARTED = -7, + /** System busy */ + ERROR_WIFI_BUSY = -8, + /** Wi-Fi invalid password */ + ERROR_WIFI_INVALID_PASSWORD = -9, + /** Unknown error */ + ERROR_WIFI_UNKNOWN = -128 +} WifiErrorCode; + +#endif // WIFI_ERROR_CODE_C_H +/** @} */ \ No newline at end of file diff --git a/interfaces/innerkits/native_c/wifi_event.h b/interfaces/innerkits/native_c/wifi_event.h new file mode 100755 index 000000000..3e7b723a2 --- /dev/null +++ b/interfaces/innerkits/native_c/wifi_event.h @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup wifiservice + * @{ + * + * @brief Provides functions for the Wi-Fi station and hotspot modes. + * + * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a + * station or hotspot, query the station or hotspot status, and listen for events. \n + * + * @since 7 + */ + +/** + * @file wifi_event.h + * + * @brief Defines callbacks and structure of Wi-Fi events. + * + * {@link RegisterWifiEvent} can be used to listen for Wi-Fi connection, disconnection, and scan events. \n + * + * @since 7 + */ +#ifndef WIFI_EVENT_C_H +#define WIFI_EVENT_C_H + +#include "wifi_linked_info.h" +#include "station_info.h" +#include "wifi_error_code.h" + +/** + * @brief Indicates that the Wi-Fi station mode is enabled. + * + */ +#define WIFI_STA_ACTIVE 1 +/** + * @brief Indicates that the Wi-Fi station mode is disabled. + * + */ +#define WIFI_STA_NOT_ACTIVE 0 + +/** + * @brief Indicates that the Wi-Fi hotspot mode is enabled. + * + */ +#define WIFI_HOTSPOT_ACTIVE 1 +/** + * @brief Indicates that the Wi-Fi hotspot mode is disabled. + * + */ +#define WIFI_HOTSPOT_NOT_ACTIVE 0 + +/** + * @brief Indicates the maximum number of event listeners that can be registered using {@link RegisterWifiEvent}. + * + * When the maximum number is reached, you need to unregister at least one listener before registering new ones. \n + */ +#define WIFI_MAX_EVENT_SIZE 10 + +/** + * @brief Represents the pointer to a Wi-Fi event callback for station and hotspot connection, disconnection, or scan. + * + * + * If you do not need a callback, set the value of its pointer to NULL. \n + * + * @since 7 + */ +typedef struct { + /** Connection state change */ + void (*OnWifiConnectionChanged)(int state, WifiLinkedInfo *info); + /** Scan state change */ + void (*OnWifiScanStateChanged)(int state, int size); + /** Hotspot state change */ + void (*OnHotspotStateChanged)(int state); + /** Station connected */ + void (*OnHotspotStaJoin)(StationInfo *info); + /** Station disconnected */ + void (*OnHotspotStaLeave)(StationInfo *info); +} WifiEvent; + +/** + * @brief Enumerates states in Wi-Fi events. + * + * + * + * @since 7 + */ +typedef enum { + /** Unavailable state */ + WIFI_STATE_NOT_AVALIABLE = 0, + /** Available state */ + WIFI_STATE_AVALIABLE +} WifiEventState; + +/** + * @brief Registers a callback for a specified Wi-Fi event. + * + * The registered callback will be invoked when the Wi-Fi event defined in {@link WifiEvent} occurs. \n + * + * @param event Indicates the event for which the callback is to be registered. + * @return Returns {@link WIFI_SUCCESS} if the callback is registered successfully; returns an error code defined + * in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode RegisterWifiEvent(const WifiEvent *event); + +/** + * @brief Unregisters a callback previously registered for a specified Wi-Fi event. + * + * @param event Indicates the event for which the callback is to be unregistered. + * @return Returns {@link WIFI_SUCCESS} if the callback is unregistered successfully; returns an error code defined + * in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode UnRegisterWifiEvent(const WifiEvent *event); + +#endif // WIFI_EVENT_C_H +/** @} */ diff --git a/interfaces/innerkits/native_c/wifi_hotspot.h b/interfaces/innerkits/native_c/wifi_hotspot.h new file mode 100755 index 000000000..79b6a4cfa --- /dev/null +++ b/interfaces/innerkits/native_c/wifi_hotspot.h @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup wifiservice + * @{ + * + * @brief Provides functions for the Wi-Fi station and hotspot modes. + * + * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a + * station or hotspot, query the station or hotspot status, and listen for events. \n + * + * @since 7 + */ + +/** + * @file wifi_hotspot.h + * + * @brief Provides capabilities to enable and disable the hotspot mode, connect to and disconnect from a hotspot, query + * the hotspot status, and listen for events. + * + * @since 7 + */ + +#ifndef HARMONY_OS_LITE_WIFI_HOTSPOT_H +#define HARMONY_OS_LITE_WIFI_HOTSPOT_H +#include "wifi_device.h" +#include "wifi_error_code.h" +#include "wifi_hotspot_config.h" +#include "wifi_event.h" + +/** + * @brief Defines the default channel of the hotspot mode. + */ +#define HOTSPOT_DEFAULT_CHANNEL 6 + +/** + * @brief Enables the hotspot mode. + * + * Before using this function, you need to invoke {@link SetHotspotConfig} and set at least the SSID, security type, + * and key. \n + * + * @return Returns {@link WIFI_SUCCESS} if the hotspot mode is enabled; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode EnableHotspot(void); + +/** + * @brief Disables the hotspot mode. + * + * @return Returns {@link WIFI_SUCCESS} if the hotspot mode is disabled; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode DisableHotspot(void); + +/** + * @brief Sets a specified hotspot configuration. + * + * The hotspot configuration includes the SSID, security type, and key. The configuration set overwrites the existing + * configuration and takes effect after the hotspot mode is re-enabled. \n + * Before enabling the hotspot mode for the first time, you must call this function. \n + * + * @param config Indicates the hotspot configuration to set. + * @return Returns {@link WIFI_SUCCESS} if the hotspot configuration is set; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode SetHotspotConfig(const HotspotConfig *config); + +/** + * @brief Obtains a specified hotspot configuration. + * + * The hotspot configuration includes the SSID, security type, and key. \n + * + * @param result Indicates the obtained hotspot configuration. + * @return Returns {@link WIFI_SUCCESS} if the hotspot configuration is obtained; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode GetHotspotConfig(HotspotConfig *result); + +/** + * @brief Checks whether the hotspot mode is enabled. + * + * @return Returns {@link WIFI_HOTSPOT_ACTIVE} if the hotspot mode is enabled; returns {@link WIFI_HOTSPOT_NOT_ACTIVE} + * otherwise. + * @since 7 + */ +int IsHotspotActive(void); + +/** + * @brief Obtains an array of stations connected to this hotspot. + * + * The station information is defined in {@link StationInfo}. \n + * + * @param result Indicates the array of stations connected to this hotspot. The array is requested and released by the + * caller. The value must be greater than or equal to {@link WIFI_MAX_STA_NUM}. + * @param size Indicates the size of the array. + * @return Returns {@link WIFI_SUCCESS} if the array of stations connected to this hotspot is obtained; returns an error + * code defined in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode GetStationList(StationInfo *result, unsigned int *size); + +/** + * @brief Disconnects from the station with a specified MAC address. + * + * @param mac Indicates the pointer to the MAC address of the station. + * @param macLen Indicates the length of the MAC address of the station. + * @return Returns {@link WIFI_SUCCESS} if the function is successfully called; + * returns an error code defined in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode DisassociateSta(unsigned char *mac, int macLen); + +/** + * @brief Adds the hotspot transmit power to the beacon. + * + * After the transmit power is added, the beacon must contain specified IEs. If the minimum transmit power + * 0xFFFFFFFF is added, the beacon does not contain the IEs. \n + * The transmit power is added to the ie field only, exerting no impacts on the transmit power. \n + * @param power Indicates the transmit power to add. + * @return Returns {@link WIFI_SUCCESS} if the function is successfully called; returns an error code defined + * in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode AddTxPowerInfo(int power); + +#endif // HARMONY_OS_LITE_WIFI_HOTSPOT_H_ +/** @} */ diff --git a/interfaces/innerkits/native_c/wifi_hotspot_config.h b/interfaces/innerkits/native_c/wifi_hotspot_config.h new file mode 100755 index 000000000..fef32e742 --- /dev/null +++ b/interfaces/innerkits/native_c/wifi_hotspot_config.h @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup wifiservice + * @{ + * + * @brief Provides functions for the Wi-Fi station and hotspot modes. + * + * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a + * station or hotspot, query the station or hotspot status, and listen for events. \n + * + * @since 7 + */ + +/** + * @file wifi_hotspot_config.h + * + * @brief Defines the Wi-Fi hotspot configuration. + * + * @since 7 + */ + +#ifndef WIFI_HOTSPOT_CONFIG_C_H +#define WIFI_HOTSPOT_CONFIG_C_H + +#include "wifi_device_config.h" +#include "wifi_error_code.h" + +/** + * @brief Defines the maximum number of stations connected to a hotspot. + */ +#define WIFI_MAX_STA_NUM 6 + +/** + * @brief Enumerates received signal strength indicator (RSSI) levels. + * + * Four RSSI levels are available: 1 to 4. The higher the RSSI level, the stronger the Wi-Fi signal. + * + * @since 7 + */ +typedef enum { + /** Level 1. The RSSI value for a 2.4 GHz hotspot ranges from -88 (included) to -82 (excluded), + * and that for a 5 GHz hotspot ranges from -85 (included) to -79 (excluded). */ + RSSI_LEVEL_1 = 1, + /** Level 2. The RSSI value for a 2.4 GHz hotspot ranges from -82 (included) to -75 (excluded), + * and that for a 5 GHz hotspot ranges from -79 (included) to -72 (excluded). */ + RSSI_LEVEL_2 = 2, + /** Level 3. The RSSI value for a 2.4 GHz hotspot ranges from -75 (included) to -65 (excluded), + * and that for a 5 GHz hotspot ranges from -72 (included) to -65 (excluded). */ + RSSI_LEVEL_3 = 3, + /** Level 4. The RSSI value for a 2.4 GHz or 5 GHz hotspot is greater than or equal to -65. */ + RSSI_LEVEL_4 = 4, +} RssiLevel; + +/** + * @brief Enumerates frequency bands supported by the Wi-Fi hotspot mode. + * + * @since 7 + */ +typedef enum { + /** 2.4 GHz */ + HOTSPOT_BAND_TYPE_2G = 1, + /** 5 GHz */ + HOTSPOT_BAND_TYPE_5G = 2, +} HotspotBandType; + +/** + * @brief Represents the hotspot configuration. + * + * A hotspot configuration must contain the SSID (or BSSID), security type, and key (if the security type is open). \n + * + * @since 7 + */ +typedef struct { + /** Service set ID (SSID). For its length, see {@link WIFI_MAX_SSID_LEN}. */ + char ssid[WIFI_MAX_SSID_LEN]; + /** Security type */ + int securityType; + /** Frequency band */ + int band; + /** Channel number */ + int channelNum; + /** Key. For its length, see {@link WIFI_MAX_SSID_LEN}. */ + char preSharedKey[WIFI_MAX_KEY_LEN]; +} HotspotConfig; + +/** + * @brief Sets the frequency band for this hotspot. + * + * @param band Indicates the frequency band to set. + * @return Returns {@link WIFI_SUCCESS} if the frequency band is set; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode SetBand(int band); + +/** + * @brief Obtains the frequency band of this hotspot. + * + * @param result Indicates the obtained frequency band. + * @return Returns {@link WIFI_SUCCESS} if the frequency band is obtained; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode GetBand(int *result); + +#endif // WIFI_HOTSPOT_CONFIG_C_H +/** @} */ diff --git a/interfaces/innerkits/native_c/wifi_linked_info.h b/interfaces/innerkits/native_c/wifi_linked_info.h new file mode 100755 index 000000000..0e6ea3c4d --- /dev/null +++ b/interfaces/innerkits/native_c/wifi_linked_info.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup wifiservice + * @{ + * + * @brief Provides functions for the Wi-Fi station and hotspot modes. + * + * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a + * station or hotspot, query the station or hotspot status, and listen for events. \n + * + * @since 7 + */ + +/** + * @file wifi_linked_info.h + * + * @brief Defines the data structure and macro of the Wi-Fi connection information. + * + * @since 7 + */ + +#ifndef HARMONY_OS_LITE_WIFI_LINKED_INFO_H +#define HARMONY_OS_LITE_WIFI_LINKED_INFO_H +#include "wifi_device_config.h" + +/** + * @brief Enumerates Wi-Fi connection states. + * + * @since 7 + */ +typedef enum { + /** Disconnected */ + WIFI_DISCONNECTED, + /** Connected */ + WIFI_CONNECTED +} WifiConnState; + +/** + * @brief Represents the Wi-Fi connection information. + * + * This refers to the information about the hotspot connected to this station. The information is obtained using + * {@link GetLinkedInfo}. + * + * @since 7 + */ +typedef struct { + /** Service set ID (SSID). For its length, see {@link WIFI_MAX_SSID_LEN}. */ + char ssid[WIFI_MAX_SSID_LEN]; + /** Basic service set ID (BSSID). For its length, see {@link WIFI_MAC_LEN}. */ + unsigned char bssid[WIFI_MAC_LEN]; + /** Received signal strength indicator (RSSI) */ + int rssi; + /** Wi-Fi band information of hotspot */ + int band; + /** Wi-Fi frequency information of hotspot */ + int frequency; + /** Wi-Fi connection state, which is defined in {@link WifiConnState} */ + WifiConnState connState; + /** Reason for Wi-Fi disconnection */ + unsigned short disconnectedReason; + /** IP address of the connected hotspot */ + unsigned int ipAddress; +} WifiLinkedInfo; +#endif // HARMONY_OS_LITE_WIFI_LINKED_INFO_H +/** @} */ diff --git a/interfaces/innerkits/native_c/wifi_scan_info.h b/interfaces/innerkits/native_c/wifi_scan_info.h new file mode 100755 index 000000000..c7fededc9 --- /dev/null +++ b/interfaces/innerkits/native_c/wifi_scan_info.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup wifiservice + * @{ + * + * @brief Provides functions for the Wi-Fi station and hotspot modes. + * + * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a + * station or hotspot, query the station or hotspot status, and listen for events. \n + * + * @since 7 + */ + +/** + * @file wifi_scan_info.h + * + * @brief Defines the data structure and macro of the Wi-Fi scan result information. + * + * @since 7 + */ + +#ifndef WIFI_SCAN_INFO_C_H +#define WIFI_SCAN_INFO_C_H + +#include "wifi_device_config.h" + +/** + * @brief Indicates the maximum number of hotspots that can be detected in a Wi-Fi scan. + */ +#define WIFI_SCAN_HOTSPOT_LIMIT 64 + +/** + * @brief Represents the Wi-Fi scan result information. + * + * @since 7 + */ +typedef struct { + /** Service set ID (SSID). For its length, see {@link WIFI_MAX_SSID_LEN}. */ + char ssid[WIFI_MAX_SSID_LEN]; + /** Basic service set ID (BSSID). For its length, see {@link WIFI_MAC_LEN}. */ + unsigned char bssid[WIFI_MAC_LEN]; + /** Security type. For details, see {@link WifiSecurityType}. */ + int securityType; + /** Received signal strength indicator (RSSI) */ + int rssi; + /** Frequency band */ + int band; + /** Frequency in MHz */ + int frequency; +} WifiScanInfo; + +#endif // WIFI_SCAN_INFO_C_H +/** @} */ diff --git a/interfaces/innerkits/native_cpp/napi/BUILD.gn b/interfaces/innerkits/native_cpp/napi/BUILD.gn index 0ae5ef889..ea63e51dd 100755 --- a/interfaces/innerkits/native_cpp/napi/BUILD.gn +++ b/interfaces/innerkits/native_cpp/napi/BUILD.gn @@ -42,7 +42,7 @@ ohos_shared_library("wifi_native_js") { "//base/notification/ces_standard/frameworks/native:cesfwk_innerkits", "//foundation/aafwk/standard/interfaces/innerkits/want:want", "//foundation/ace/napi:ace_napi", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/src:wifi_sdk", + "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard:wifi_sdk", "//utils/native/base:utils", ] diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/BUILD.gn b/interfaces/innerkits/native_cpp/wifi_standard/BUILD.gn similarity index 76% rename from interfaces/innerkits/native_cpp/wifi_standard/src/BUILD.gn rename to interfaces/innerkits/native_cpp/wifi_standard/BUILD.gn index aef341930..5f5946ce4 100755 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/BUILD.gn +++ b/interfaces/innerkits/native_cpp/wifi_standard/BUILD.gn @@ -28,17 +28,10 @@ config("wifi_sdk_header") { "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log/", "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", - - # "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", - # "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils", - # "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config", - # "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage", - # "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common", ] } + config("wifi_sdk_config") { visibility = [ "//:*" ] include_dirs = [ ":wifi_fw_common_header" ] @@ -55,8 +48,8 @@ config("wifi_sdk_config") { ohos_source_set("wifi_device_proxy_impl") { sources = [ - "wifi_device_impl.cpp", - "wifi_device_proxy.cpp", + "src/wifi_device_impl.cpp", + "src/wifi_device_proxy.cpp", ] configs = [ @@ -69,8 +62,8 @@ ohos_source_set("wifi_device_proxy_impl") { ohos_source_set("wifi_hotspot_proxy_impl") { sources = [ - "wifi_hotspot_impl.cpp", - "wifi_hotspot_proxy.cpp", + "src/wifi_hotspot_impl.cpp", + "src/wifi_hotspot_proxy.cpp", ] configs = [ @@ -83,8 +76,8 @@ ohos_source_set("wifi_hotspot_proxy_impl") { ohos_source_set("wifi_scan_proxy_impl") { sources = [ - "wifi_scan_impl.cpp", - "wifi_scan_proxy.cpp", + "src/wifi_scan_impl.cpp", + "src/wifi_scan_proxy.cpp", ] configs = [ @@ -97,13 +90,20 @@ ohos_source_set("wifi_scan_proxy_impl") { ohos_shared_library("wifi_sdk") { install_enable = true + + include_dirs = [ "//foundation/communication/wifi/interfaces/innerkits" ] + sources = [ - "wifi_device.cpp", - "wifi_device_callback_stub.cpp", - "wifi_hotspot.cpp", - "wifi_hotspot_callback_stub.cpp", - "wifi_scan.cpp", - "wifi_scan_callback_stub.cpp", + "c_adapter/wifi_c_device.cpp", + "c_adapter/wifi_c_event.cpp", + "c_adapter/wifi_c_hotspot.cpp", + "c_adapter/wifi_c_utils.cpp", + "src/wifi_device.cpp", + "src/wifi_device_callback_stub.cpp", + "src/wifi_hotspot.cpp", + "src/wifi_hotspot_callback_stub.cpp", + "src/wifi_scan.cpp", + "src/wifi_scan_callback_stub.cpp", ] deps = [ @@ -111,7 +111,12 @@ ohos_shared_library("wifi_sdk") { ":wifi_hotspot_proxy_impl", ":wifi_scan_proxy_impl", "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//base/notification/ces_standard/frameworks/core:cesfwk_core", + "//base/notification/ces_standard/frameworks/native:cesfwk_innerkits", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage:wifi_manager_service", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/bounds_checking_function:libsec_static", "//utils/native/base:utils", ] diff --git a/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_device.cpp b/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_device.cpp new file mode 100755 index 000000000..5fa4d702e --- /dev/null +++ b/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_device.cpp @@ -0,0 +1,332 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 "native_c/wifi_device.h" +#include "native_cpp/wifi_standard/include/wifi_device.h" +#include "native_cpp/wifi_standard/include/wifi_scan.h" +#include "native_c/wifi_scan_info.h" +#include "native_c/wifi_device_config.h" +#include "wifi_logger.h" +#include "wifi_c_utils.h" +#include "securec.h" + +DEFINE_WIFILOG_LABEL("WifiCDevice"); + +static std::map g_secTypeKeyMgmtMap = { + {WIFI_SEC_TYPE_OPEN, "NONE"}, + {WIFI_SEC_TYPE_WEP, "WEP"}, + {WIFI_SEC_TYPE_PSK, "WPA-PSK"}, + {WIFI_SEC_TYPE_SAE, "SAE"}, +}; + +std::unique_ptr wifiDevicePtr = OHOS::Wifi::WifiDevice::GetInstance(WIFI_DEVICE_ABILITY_ID); +std::unique_ptr wifiScanPtr = OHOS::Wifi::WifiScan::GetInstance(WIFI_SCAN_ABILITY_ID); + +WifiErrorCode EnableWifi() +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiDevicePtr->EnableWifi()); +} + +WifiErrorCode DisableWifi() +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiDevicePtr->DisableWifi()); +} + +int IsWifiActive() +{ + if (wifiDevicePtr == nullptr) { + return false; + } + + bool isActive = false; + OHOS::Wifi::ErrCode ret = wifiDevicePtr->IsWifiActive(isActive); + return (ret == OHOS::Wifi::WIFI_OPT_SUCCESS) && isActive; +} + +WifiErrorCode Scan() +{ + CHECK_PTR_RETURN(wifiScanPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiScanPtr->Scan()); +} + +WifiErrorCode GetScanInfoList(WifiScanInfo *result, unsigned int *size) +{ + CHECK_PTR_RETURN(wifiScanPtr, ERROR_WIFI_NOT_AVAILABLE); + if (result == nullptr) { + WIFI_LOGE("Scan info receive addr is null!"); + return ERROR_WIFI_UNKNOWN; + } + + std::vector vecScnIanfos; + OHOS::Wifi::ErrCode ret = wifiScanPtr->GetScanInfoList(vecScnIanfos); + *size = (int)vecScnIanfos.size(); + for (auto& each : vecScnIanfos) { + if (memcpy_s(result->ssid, WIFI_MAX_SSID_LEN, each.ssid.c_str(), each.ssid.size() + 1) != EOK) { + return ERROR_WIFI_UNKNOWN; + } + if (OHOS::Wifi::MacStrToArray(each.bssid, result->bssid) != EOK) { + WIFI_LOGE("Scan info convert bssid error!"); + return ERROR_WIFI_UNKNOWN; + } + result->securityType = static_cast(each.securityType); + result->rssi = each.rssi; + result->band = each.band; + result->frequency = each.frequency; + ++result; + } + return GetCErrorCode(ret); +} + +static std::string GetKeyMgmtBySecType(const int securityType) +{ + WifiSecurityType key = WifiSecurityType(securityType); + std::map::const_iterator iter = g_secTypeKeyMgmtMap.find(key); + return iter == g_secTypeKeyMgmtMap.end() ? "NONE" : iter->second; +} + +static int GetSecTypeByKeyMgmt(const std::string& keyMgmt) +{ + for (auto& each : g_secTypeKeyMgmtMap) { + if (each.second == keyMgmt) { + return static_cast(each.first); + } + } + return static_cast(WIFI_SEC_TYPE_OPEN); +} + +static void GetStaticIpFromC(const IpConfig& ipConfig, OHOS::Wifi::StaticIpAddress& staticIp) +{ + /* Just IPV4 now */ + staticIp.ipAddress.address.addressIpv4 = ipConfig.ipAddress; + staticIp.gateway.addressIpv4 = ipConfig.gateway; + if (WIFI_MAX_DNS_NUM > 0) { + staticIp.dnsServer1.addressIpv4 = ipConfig.dnsServers[0]; + } + /* Has backup DNS server */ + if (WIFI_MAX_DNS_NUM > 1) { + staticIp.dnsServer2.addressIpv4 = ipConfig.dnsServers[1]; + } + /* netmask: automatic calculate netmask, don't support customized set this value currently */ +} + +static void GetStaticIpFromCpp(const OHOS::Wifi::StaticIpAddress& staticIp, IpConfig& ipConfig) +{ + /* Just IPV4 now */ + ipConfig.ipAddress = staticIp.ipAddress.address.addressIpv4; + ipConfig.gateway = staticIp.gateway.addressIpv4; + if (WIFI_MAX_DNS_NUM > 0) { + ipConfig.dnsServers[0] = staticIp.dnsServer1.addressIpv4; + } + /* Has backup DNS server */ + if (WIFI_MAX_DNS_NUM > 1) { + ipConfig.dnsServers[1] = staticIp.dnsServer2.addressIpv4; + } + /* netmask: not support now */ +} + +static void ConvertDeviceConfigFromC(const WifiDeviceConfig *config, OHOS::Wifi::WifiDeviceConfig& deviceConfig) +{ + deviceConfig.ssid = config->ssid; + if (OHOS::Wifi::IsMacArrayEmpty(config->bssid)) { + deviceConfig.bssid = ""; + } else { + deviceConfig.bssid = OHOS::Wifi::MacArrayToStr(config->bssid); + } + deviceConfig.preSharedKey = config->preSharedKey; + deviceConfig.keyMgmt = GetKeyMgmtBySecType(config->securityType); + deviceConfig.networkId = config->netId; + deviceConfig.frequency = config->freq; + /* wapiPskType is not support, don't verify now */ + if (config->ipType == DHCP) { + deviceConfig.wifiIpConfig.assignMethod = OHOS::Wifi::AssignIpMethod::DHCP; + } else if (config->ipType == STATIC_IP) { + deviceConfig.wifiIpConfig.assignMethod = OHOS::Wifi::AssignIpMethod::STATIC; + GetStaticIpFromC(config->staticIp, deviceConfig.wifiIpConfig.staticIpAddress); + } else { + deviceConfig.wifiIpConfig.assignMethod = OHOS::Wifi::AssignIpMethod::UNASSIGNED; + } + deviceConfig.hiddenSSID = config->isHiddenSsid; +} + +static OHOS::Wifi::ErrCode ConvertDeviceConfigFromCpp(const OHOS::Wifi::WifiDeviceConfig& deviceConfig, + WifiDeviceConfig *result) +{ + if (memcpy_s(result->ssid, WIFI_MAX_SSID_LEN, deviceConfig.ssid.c_str(), deviceConfig.ssid.size() + 1) != EOK) { + return OHOS::Wifi::WIFI_OPT_FAILED; + } + if (OHOS::Wifi::MacStrToArray(deviceConfig.bssid, result->bssid) != EOK) { + WIFI_LOGE("device config convert bssid error!"); + return OHOS::Wifi::WIFI_OPT_FAILED; + } + if (memcpy_s(result->preSharedKey, WIFI_MAX_KEY_LEN, deviceConfig.preSharedKey.c_str(), WIFI_MAX_KEY_LEN) != EOK) { + return OHOS::Wifi::WIFI_OPT_FAILED; + } + result->securityType = GetSecTypeByKeyMgmt(deviceConfig.keyMgmt); + result->netId = deviceConfig.networkId; + result->freq = deviceConfig.frequency; + /* wapiPskType is not support now */ + if (deviceConfig.wifiIpConfig.assignMethod == OHOS::Wifi::AssignIpMethod::DHCP) { + result->ipType = DHCP; + } else if (deviceConfig.wifiIpConfig.assignMethod == OHOS::Wifi::AssignIpMethod::STATIC) { + result->ipType = STATIC_IP; + GetStaticIpFromCpp(deviceConfig.wifiIpConfig.staticIpAddress, result->staticIp); + } else { + result->ipType = UNKNOWN; + } + result->isHiddenSsid = deviceConfig.hiddenSSID; + return OHOS::Wifi::WIFI_OPT_SUCCESS; +} + +WifiErrorCode AddDeviceConfig(const WifiDeviceConfig *config, int *result) +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + OHOS::Wifi::WifiDeviceConfig deviceConfig; + ConvertDeviceConfigFromC(config, deviceConfig); + int addResult = -1; + OHOS::Wifi::ErrCode ret = wifiDevicePtr->AddDeviceConfig(deviceConfig, addResult); + *result = addResult; + return GetCErrorCode(ret); +} + +WifiErrorCode GetDeviceConfigs(WifiDeviceConfig *result, unsigned int *size) +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + if (result == nullptr) { + WIFI_LOGE("Get device configs result array is null!"); + return ERROR_WIFI_UNKNOWN; + } + + std::vector vecDeviceConfigs; + OHOS::Wifi::ErrCode ret = wifiDevicePtr->GetDeviceConfigs(vecDeviceConfigs); + if (ret != OHOS::Wifi::WIFI_OPT_SUCCESS) { + WIFI_LOGE("Get device configs error!"); + return GetCErrorCode(ret); + } + *size = (int)vecDeviceConfigs.size(); + for (auto& each : vecDeviceConfigs) { + OHOS::Wifi::ErrCode retValue = ConvertDeviceConfigFromCpp(each, result++); + if (retValue != OHOS::Wifi::WIFI_OPT_SUCCESS) { + ret = retValue; + WIFI_LOGE("Convert device configs error!"); + } + } + return GetCErrorCode(ret); +} + +WifiErrorCode RemoveDevice(int networkId) +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiDevicePtr->RemoveDevice(networkId)); +} + +WifiErrorCode DisableDeviceConfig(int networkId) +{ + return GetCErrorCode(OHOS::Wifi::WIFI_OPT_NOT_SUPPORTED); +} + +WifiErrorCode EnableDeviceConfig(int networkId) +{ + return GetCErrorCode(OHOS::Wifi::WIFI_OPT_NOT_SUPPORTED); +} + +WifiErrorCode ConnectTo(int networkId) +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiDevicePtr->ConnectToNetwork(networkId)); +} + +WifiErrorCode ConnectToDevice(const WifiDeviceConfig *config) +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + OHOS::Wifi::WifiDeviceConfig deviceConfig; + ConvertDeviceConfigFromC(config, deviceConfig); + return GetCErrorCode(wifiDevicePtr->ConnectToDevice(deviceConfig)); +} + +WifiErrorCode Disconnect() +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiDevicePtr->Disconnect()); +} + +static OHOS::Wifi::ErrCode GetLinkedInfoFromCpp(const OHOS::Wifi::WifiLinkedInfo& linkedInfo, WifiLinkedInfo *result) +{ + if (memcpy_s(result->ssid, WIFI_MAX_SSID_LEN, linkedInfo.ssid.c_str(), linkedInfo.ssid.size() + 1) != EOK) { + return OHOS::Wifi::WIFI_OPT_FAILED; + } + if (OHOS::Wifi::MacStrToArray(linkedInfo.bssid, result->bssid) != EOK) { + WIFI_LOGE("linked info convert bssid error!"); + return OHOS::Wifi::WIFI_OPT_FAILED; + } + result->rssi = linkedInfo.rssi; + result->band = linkedInfo.band; + result->frequency = linkedInfo.frequency; + result->connState = linkedInfo.connState == OHOS::Wifi::ConnState::CONNECTED ? WIFI_CONNECTED : WIFI_DISCONNECTED; + /* disconnectedReason not support */ + result->ipAddress = linkedInfo.ipAddress; + return OHOS::Wifi::WIFI_OPT_SUCCESS; +} + +WifiErrorCode GetLinkedInfo(WifiLinkedInfo *result) +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + OHOS::Wifi::WifiLinkedInfo linkedInfo; + OHOS::Wifi::ErrCode ret = wifiDevicePtr->GetLinkedInfo(linkedInfo); + if (ret == OHOS::Wifi::WIFI_OPT_SUCCESS) { + OHOS::Wifi::ErrCode retValue = GetLinkedInfoFromCpp(linkedInfo, result); + if (retValue != OHOS::Wifi::WIFI_OPT_SUCCESS) { + WIFI_LOGE("Get linked info from cpp error!"); + ret = retValue; + } + } + return GetCErrorCode(ret); +} + +WifiErrorCode GetDeviceMacAddress(unsigned char *result) +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + std::string mac; + OHOS::Wifi::ErrCode ret = wifiDevicePtr->GetDeviceMacAddress(mac); + if (ret == OHOS::Wifi::WIFI_OPT_SUCCESS) { + if (OHOS::Wifi::MacStrToArray(mac, result) != EOK) { + WIFI_LOGE("get mac convert to array error!"); + return ERROR_WIFI_UNKNOWN; + } + } + return GetCErrorCode(ret); +} + +WifiErrorCode AdvanceScan(WifiScanParams *params) +{ + return GetCErrorCode(OHOS::Wifi::WIFI_OPT_NOT_SUPPORTED); +} + +WifiErrorCode GetIpInfo(IpInfo *info) +{ + return GetCErrorCode(OHOS::Wifi::WIFI_OPT_NOT_SUPPORTED); +} + +int GetSignalLevel(int rssi, int band) +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + int level = -1; + OHOS::Wifi::ErrCode ret = wifiDevicePtr->GetSignalLevel(rssi, band, level); + if (ret != OHOS::Wifi::WIFI_OPT_SUCCESS) { + WIFI_LOGW("Get wifi signal level fail: %{public}d", ret); + } + return level; +} diff --git a/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_event.cpp b/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_event.cpp new file mode 100755 index 000000000..931f417b9 --- /dev/null +++ b/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_event.cpp @@ -0,0 +1,288 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 "native_c/wifi_event.h" +#include "native_c/wifi_device.h" +#include "native_c/wifi_scan_info.h" +#include "wifi_logger.h" +#include "common_event_manager.h" +#include "common_event.h" +#include + +DEFINE_WIFILOG_LABEL("WifiCEvent"); + +const std::string WIFI_USUAL_EVENT_CONN_STATE = "usual.event.wifi.CONN_STATE"; +const std::string WIFI_USUAL_EVENT_SCAN_STATE = "usual.event.wifi.SCAN_FINISHED"; +const std::string WIFI_USUAL_EVENT_HOTSPOT_STATE = "usual.event.wifi.HOTSPOT_STATE"; +const std::string WIFI_USUAL_EVENT_STA_JOIN = "usual.event.wifi.WIFI_HS_STA_JOIN"; +const std::string WIFI_USUAL_EVENT_STA_LEAVE = "usual.event.wifi.WIFI_HS_STA_LEAVE"; + +using ConnectionChangeCb = void (*)(int, WifiLinkedInfo*); +using ScanStateChangeCb = void (*)(int, int); +using HotspotStateChangeCb = void (*)(int); +using HotspotJoinCb = void (*)(StationInfo*); +using HotspotLeaveCb = void (*)(StationInfo*); + +using namespace OHOS::EventFwk; +class EventManager { +public: + EventManager() { + } + + virtual ~EventManager() { + } + + bool AddConnectionChangeCb(const ConnectionChangeCb cb) { + if (m_setConnectionChangeCb.empty()) { + if (!SubscribeServiceEvent(WIFI_USUAL_EVENT_CONN_STATE)) { + return false; + } + } + return m_setConnectionChangeCb.insert(cb).second; + } + + void RemoveConnectionChangeCb(const ConnectionChangeCb cb) { + m_setConnectionChangeCb.erase(cb); + if (m_setConnectionChangeCb.empty()) { + UnsubscribeServiceEvent(WIFI_USUAL_EVENT_CONN_STATE); + } + } + + static std::set GetConnectionChangeCb() { + return m_setConnectionChangeCb; + } + + bool AddScanStateChangeCb(const ScanStateChangeCb cb) { + if (m_setScanStateChangeCb.empty()) { + if (!SubscribeServiceEvent(WIFI_USUAL_EVENT_SCAN_STATE)) { + return false; + } + } + return m_setScanStateChangeCb.insert(cb).second; + } + + void RemoveScanStateChangeCb(const ScanStateChangeCb cb) { + m_setScanStateChangeCb.erase(cb); + if (m_setScanStateChangeCb.empty()) { + UnsubscribeServiceEvent(WIFI_USUAL_EVENT_SCAN_STATE); + } + } + + static std::set GetScanStateChangeCb() { + return m_setScanStateChangeCb; + } + + bool AddHotspotChangeCb(const HotspotStateChangeCb cb) { + if (m_setHotspotChangeCb.empty()) { + if (!SubscribeServiceEvent(WIFI_USUAL_EVENT_HOTSPOT_STATE)) { + return false; + } + } + return m_setHotspotChangeCb.insert(cb).second; + } + + void RemoveHotspotChangeCb(const HotspotStateChangeCb cb) { + m_setHotspotChangeCb.erase(cb); + if (m_setHotspotChangeCb.empty()) { + UnsubscribeServiceEvent(WIFI_USUAL_EVENT_HOTSPOT_STATE); + } + } + + static std::set GetHotspotChangeCb() { + return m_setHotspotChangeCb; + } + + bool AddHotspotJoinCb(const HotspotJoinCb cb) { + if (m_setHotspotJoinCb.empty()) { + if (!SubscribeServiceEvent(WIFI_USUAL_EVENT_STA_JOIN)) { + return false; + } + } + return m_setHotspotJoinCb.insert(cb).second; + } + + void RemoveHotspotJoinCb(const HotspotJoinCb cb) { + m_setHotspotJoinCb.erase(cb); + if (m_setHotspotJoinCb.empty()) { + UnsubscribeServiceEvent(WIFI_USUAL_EVENT_STA_JOIN); + } + } + + static std::set GetHotspotJoinCb() { + return m_setHotspotJoinCb; + } + + bool AddHotspotLeaveCb(const HotspotLeaveCb cb) { + if (m_setHotspotLeaveCb.empty()) { + if (!SubscribeServiceEvent(WIFI_USUAL_EVENT_STA_LEAVE)) { + return false; + } + } + return m_setHotspotLeaveCb.insert(cb).second; + } + + void RemoveHotspotLeaveCb(const HotspotLeaveCb cb) { + m_setHotspotLeaveCb.erase(cb); + if (m_setHotspotLeaveCb.empty()) { + UnsubscribeServiceEvent(WIFI_USUAL_EVENT_STA_LEAVE); + } + } + + static std::set GetHotspotLeaveCb() { + return m_setHotspotLeaveCb; + } + + class WifiEventSubscriber : public OHOS::EventFwk::CommonEventSubscriber { + public: + explicit WifiEventSubscriber(const OHOS::EventFwk::CommonEventSubscribeInfo &subscribeInfo) + : CommonEventSubscriber(subscribeInfo) { + } + + virtual ~WifiEventSubscriber() { + } + + virtual void OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data) override { + std::string event = data.GetWant().GetAction(); + int code = data.GetCode(); + WIFI_LOGI("Received event: %{public}s, value: %{public}d", event.c_str(), code); + if (event == WIFI_USUAL_EVENT_CONN_STATE && !GetConnectionChangeCb().empty()) { + WifiLinkedInfo linkInfo; + WifiErrorCode ret = GetLinkedInfo(&linkInfo); + if (ret != WIFI_SUCCESS) { + WIFI_LOGE("Received event get linked info failed"); + return; + } + for (auto& cb : GetConnectionChangeCb()) { + cb(code, &linkInfo); + } + } + + if (event == WIFI_USUAL_EVENT_SCAN_STATE && !EventManager::m_setScanStateChangeCb.empty()) { + for (auto& cb : EventManager::m_setScanStateChangeCb) { + cb(code, WIFI_SCAN_HOTSPOT_LIMIT); + } + } + + if (event == WIFI_USUAL_EVENT_HOTSPOT_STATE && !EventManager::m_setHotspotChangeCb.empty()) { + for (auto& cb : EventManager::m_setHotspotChangeCb) { + cb(code); + } + } + + if (event == WIFI_USUAL_EVENT_STA_JOIN && !EventManager::m_setHotspotJoinCb.empty()) { + } + + if (event == WIFI_USUAL_EVENT_STA_LEAVE && !EventManager::m_setHotspotLeaveCb.empty()) { + } + } + }; + + bool SubscribeServiceEvent(const std::string& event) { + MatchingSkills matchingSkills; + matchingSkills.AddEvent(event); + CommonEventSubscribeInfo subscriberInfo(matchingSkills); + std::shared_ptr subscriber = std::make_shared(subscriberInfo); + WIFI_LOGI("Subscribe event: %{public}s", event.c_str()); + bool subscribeResult = CommonEventManager::SubscribeCommonEvent(subscriber); + if (subscribeResult) { + m_mapEventSubscriber[event] = subscriber; + } else { + WIFI_LOGE("Subscribe service event fail: %{public}s", event.c_str()); + } + return subscribeResult; + } + + bool UnsubscribeServiceEvent(const std::string& event) { + std::map>::iterator iter; + iter = m_mapEventSubscriber.find(event); + if (iter == m_mapEventSubscriber.end()) { + return false; + } + + bool unsubscribeResult = CommonEventManager::SubscribeCommonEvent(iter->second); + if (!unsubscribeResult) { + WIFI_LOGE("Unsubscribe event fail: %{public}s", event.c_str()); + } + return unsubscribeResult; + } + +private: + static std::set m_setConnectionChangeCb; + static std::set m_setScanStateChangeCb; + static std::set m_setHotspotChangeCb; + static std::set m_setHotspotJoinCb; + static std::set m_setHotspotLeaveCb; + std::map > m_mapEventSubscriber; +}; +std::set EventManager::m_setConnectionChangeCb; +std::set EventManager::m_setScanStateChangeCb; +std::set EventManager::m_setHotspotChangeCb; +std::set EventManager::m_setHotspotJoinCb; +std::set EventManager::m_setHotspotLeaveCb; + +static EventManager g_eventManager; + +WifiErrorCode RegisterWifiEvent(const WifiEvent *event) { + WIFI_LOGI("Register wifi event"); + if (event == nullptr) { + return ERROR_WIFI_INVALID_ARGS; + } + + if (event->OnWifiConnectionChanged != nullptr) { + return g_eventManager.AddConnectionChangeCb(event->OnWifiConnectionChanged) + ? WIFI_SUCCESS : ERROR_WIFI_INVALID_ARGS; + } + if (event->OnWifiScanStateChanged != nullptr) { + return g_eventManager.AddScanStateChangeCb(event->OnWifiScanStateChanged) + ? WIFI_SUCCESS : ERROR_WIFI_INVALID_ARGS; + } + if (event->OnHotspotStateChanged != nullptr) { + return g_eventManager.AddHotspotChangeCb(event->OnHotspotStateChanged) + ? WIFI_SUCCESS : ERROR_WIFI_INVALID_ARGS; + } + if (event->OnHotspotStaJoin != nullptr) { + return g_eventManager.AddHotspotJoinCb(event->OnHotspotStaJoin) + ? WIFI_SUCCESS : ERROR_WIFI_INVALID_ARGS; + } + if (event->OnHotspotStaLeave != nullptr) { + return g_eventManager.AddHotspotLeaveCb(event->OnHotspotStaLeave) + ? WIFI_SUCCESS : ERROR_WIFI_INVALID_ARGS; + } + return ERROR_WIFI_INVALID_ARGS; +} + +WifiErrorCode UnRegisterWifiEvent(const WifiEvent *event) { + WIFI_LOGI("Unregister wifi event"); + if (event == nullptr) { + return ERROR_WIFI_INVALID_ARGS; + } + + if (event->OnWifiConnectionChanged != nullptr) { + g_eventManager.RemoveConnectionChangeCb(event->OnWifiConnectionChanged); + } + if (event->OnWifiScanStateChanged != nullptr) { + g_eventManager.RemoveScanStateChangeCb(event->OnWifiScanStateChanged); + } + if (event->OnHotspotStateChanged != nullptr) { + g_eventManager.RemoveHotspotChangeCb(event->OnHotspotStateChanged); + } + if (event->OnHotspotStaJoin != nullptr) { + g_eventManager.RemoveHotspotJoinCb(event->OnHotspotStaJoin); + } + if (event->OnHotspotStaLeave != nullptr) { + g_eventManager.RemoveHotspotLeaveCb(event->OnHotspotStaLeave); + } + return WIFI_SUCCESS; +} diff --git a/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_hotspot.cpp b/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_hotspot.cpp new file mode 100755 index 000000000..863ed3a55 --- /dev/null +++ b/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_hotspot.cpp @@ -0,0 +1,179 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 "native_c/wifi_hotspot.h" +#include "native_c/wifi_hotspot_config.h" +#include "native_c/wifi_device_config.h" +#include "native_cpp/wifi_standard/include/wifi_hotspot.h" +#include "wifi_logger.h" +#include "wifi_c_utils.h" +#include "securec.h" +#include "ip_tools.h" + +DEFINE_WIFILOG_LABEL("WifiCHotspot"); + +std::unique_ptr hotspotPtr = OHOS::Wifi::WifiHotspot::GetInstance(WIFI_HOTSPOT_ABILITY_ID); + +WifiErrorCode EnableHotspot() +{ + CHECK_PTR_RETURN(hotspotPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(hotspotPtr->EnableHotspot()); +} + +WifiErrorCode DisableHotspot() +{ + CHECK_PTR_RETURN(hotspotPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(hotspotPtr->DisableHotspot()); +} + +int IsHotspotActive(void) +{ + if (hotspotPtr == nullptr) { + return false; + } + return hotspotPtr->IsHotspotActive(); +} + +/* Others type is not support for AP */ +static std::map g_mapSecTypeToKeyMgmt = { + {WifiSecurityType::WIFI_SEC_TYPE_OPEN, OHOS::Wifi::KeyMgmt::NONE}, + {WifiSecurityType::WIFI_SEC_TYPE_PSK, OHOS::Wifi::KeyMgmt::WPA_PSK}, +}; + +static OHOS::Wifi::KeyMgmt GetKeyMgmtFromSecurityType(int secType) +{ + WifiSecurityType key = WifiSecurityType(secType); + std::map::iterator iter = g_mapSecTypeToKeyMgmt.find(key); + return iter == g_mapSecTypeToKeyMgmt.end() ? OHOS::Wifi::KeyMgmt::NONE : iter->second; +} + +static int GetSecurityTypeFromKeyMgmt(OHOS::Wifi::KeyMgmt keyMgmt) +{ + for (auto& each : g_mapSecTypeToKeyMgmt) { + if (each.second == keyMgmt) { + return static_cast(each.first); + } + } + return static_cast(WifiSecurityType::WIFI_SEC_TYPE_OPEN); +} + +static bool IsSecurityTypeSupported(int secType) +{ + WifiSecurityType key = WifiSecurityType(secType); + std::map::iterator iter = g_mapSecTypeToKeyMgmt.find(key); + return iter != g_mapSecTypeToKeyMgmt.end(); +} + +static WifiErrorCode GetHotspotConfigFromC(const HotspotConfig *config, OHOS::Wifi::HotspotConfig& hotspotConfig) +{ + hotspotConfig.SetSsid(config->ssid); + if (!IsSecurityTypeSupported(config->securityType)) { + WIFI_LOGE("Ap security is not supported!"); + return ERROR_WIFI_NOT_SUPPORTED; + } + hotspotConfig.SetSecurityType(GetKeyMgmtFromSecurityType(config->securityType)); + hotspotConfig.SetBand(OHOS::Wifi::BandType(config->band)); + hotspotConfig.SetChannel(config->channelNum); + hotspotConfig.SetPreSharedKey(config->preSharedKey); + return WIFI_SUCCESS; +} + +static WifiErrorCode GetHotspotConfigFromCpp(const OHOS::Wifi::HotspotConfig& hotspotConfig, HotspotConfig *result) +{ + if (memcpy_s(result->ssid, WIFI_MAX_SSID_LEN, + hotspotConfig.GetSsid().c_str(), hotspotConfig.GetSsid().size() + 1) != EOK) { + return ERROR_WIFI_UNKNOWN; + } + result->securityType = GetSecurityTypeFromKeyMgmt(hotspotConfig.GetSecurityType()); + result->band = static_cast(hotspotConfig.GetBand()); + result->channelNum = hotspotConfig.GetChannel(); + if (memcpy_s(result->preSharedKey, WIFI_MAX_KEY_LEN, + hotspotConfig.GetPreSharedKey().c_str(), hotspotConfig.GetPreSharedKey().size() + 1) != EOK) { + return ERROR_WIFI_UNKNOWN; + } + return WIFI_SUCCESS; +} + +WifiErrorCode SetHotspotConfig(const HotspotConfig *config) +{ + CHECK_PTR_RETURN(hotspotPtr, ERROR_WIFI_NOT_AVAILABLE); + OHOS::Wifi::HotspotConfig hotspotConfig; + WifiErrorCode ret = GetHotspotConfigFromC(config, hotspotConfig); + if (ret != WIFI_SUCCESS) { + return ret; + } + return GetCErrorCode(hotspotPtr->SetHotspotConfig(hotspotConfig)); +} + +WifiErrorCode GetHotspotConfig(HotspotConfig *result) +{ + CHECK_PTR_RETURN(hotspotPtr, ERROR_WIFI_NOT_AVAILABLE); + OHOS::Wifi::HotspotConfig hotspotConfig; + OHOS::Wifi::ErrCode ret = hotspotPtr->GetHotspotConfig(hotspotConfig); + if (ret == OHOS::Wifi::WIFI_OPT_SUCCESS) { + WifiErrorCode retValue = GetHotspotConfigFromCpp(hotspotConfig, result); + if (retValue != WIFI_SUCCESS) { + WIFI_LOGE("Get hotspot config from cpp error!"); + return retValue; + } + } + return GetCErrorCode(ret); +} + +static WifiErrorCode GetStaListFromCpp(const std::vector& vecStaList, StationInfo *result) +{ + for (auto& each : vecStaList) { + if (memcpy_s(result->name, DEVICE_NAME_LEN, each.deviceName.c_str(), each.deviceName.size() + 1) != EOK) { + return ERROR_WIFI_UNKNOWN; + } + if (OHOS::Wifi::MacStrToArray(each.bssid, result->macAddress) != EOK) { + WIFI_LOGE("Get sta list convert bssid error!"); + return ERROR_WIFI_UNKNOWN; + } + result->ipAddress = OHOS::Wifi::IpTools::ConvertIpv4Address(each.ipAddr); + } + return WIFI_SUCCESS; +} + +WifiErrorCode GetStationList(StationInfo *result, unsigned int *size) +{ + if (result == nullptr) { + WIFI_LOGE("Station info list receive addr is null!"); + return ERROR_WIFI_UNKNOWN; + } + CHECK_PTR_RETURN(hotspotPtr, ERROR_WIFI_NOT_AVAILABLE); + + std::vector vecStaList; + OHOS::Wifi::ErrCode ret = hotspotPtr->GetStationList(vecStaList); + *size = (int)vecStaList.size(); + if (ret == OHOS::Wifi::WIFI_OPT_SUCCESS) { + WifiErrorCode retValue = GetStaListFromCpp(vecStaList, result); + if (retValue != WIFI_SUCCESS) { + WIFI_LOGE("Get station list from cpp error!"); + return retValue; + } + } + return GetCErrorCode(ret); +} + +WifiErrorCode DisassociateSta(unsigned char *mac, int macLen) +{ + return GetCErrorCode(OHOS::Wifi::WIFI_OPT_NOT_SUPPORTED); +} + +WifiErrorCode AddTxPowerInfo(int power) +{ + return GetCErrorCode(OHOS::Wifi::WIFI_OPT_NOT_SUPPORTED); +} diff --git a/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_utils.cpp b/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_utils.cpp new file mode 100755 index 000000000..822a4f153 --- /dev/null +++ b/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_utils.cpp @@ -0,0 +1,118 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 "wifi_c_utils.h" +#include +#include + +namespace OHOS { +namespace Wifi { +static std::map g_ErrCodeMap = { + {WIFI_OPT_SUCCESS, WIFI_SUCCESS}, + {WIFI_OPT_FAILED, ERROR_WIFI_UNKNOWN}, + {WIFI_OPT_NOT_SUPPORTED, ERROR_WIFI_NOT_SUPPORTED}, + {WIFI_OPT_INVALID_PARAM, ERROR_WIFI_INVALID_ARGS}, + {WIFI_OPT_FORBID_AIRPLANE, ERROR_WIFI_NOT_AVAILABLE}, + {WIFI_OPT_FORBID_POWSAVING, ERROR_WIFI_NOT_AVAILABLE}, + {WIFI_OPT_PERMISSION_DENIED, ERROR_WIFI_UNKNOWN}, + {WIFI_OPT_OPEN_FAIL_WHEN_CLOSING, ERROR_WIFI_BUSY}, + {WIFI_OPT_OPEN_SUCC_WHEN_OPENED, ERROR_WIFI_BUSY}, + {WIFI_OPT_CLOSE_FAIL_WHEN_OPENING, ERROR_WIFI_BUSY}, + {WIFI_OPT_CLOSE_SUCC_WHEN_CLOSED, ERROR_WIFI_BUSY}, + {WIFI_OPT_STA_NOT_OPENED, ERROR_WIFI_NOT_STARTED}, + {WIFI_OPT_SCAN_NOT_OPENED, ERROR_WIFI_NOT_STARTED}, + {WIFI_OPT_AP_NOT_OPENED, ERROR_WIFI_NOT_STARTED}, + {WIFI_OPT_INVALID_CONFIG, ERROR_WIFI_UNKNOWN} +}; + +WifiErrorCode GetCErrorCode(ErrCode errCode) +{ + std::map::const_iterator iter = g_ErrCodeMap.find(errCode); + return iter == g_ErrCodeMap.end() ? ERROR_WIFI_UNKNOWN : iter->second; +} + +static unsigned char ConvertStrChar(char ch) +{ + constexpr int numDiffForHexAlphabet = 10; + if (ch >= '0' && ch <= '9') { + return (ch - '0'); + } + if (ch >= 'A' && ch <= 'F') { + return (ch - 'A' + numDiffForHexAlphabet); + } + if (ch >= 'a' && ch <= 'f') { + return (ch - 'a' + numDiffForHexAlphabet); + } + return 0; +} + +errno_t MacStrToArray(const std::string& strMac, unsigned char mac[WIFI_MAC_LEN]) +{ + constexpr int strMacLen = 18; + char tempArray[strMacLen] = { 0 }; + errno_t ret = memcpy_s(tempArray, strMacLen, strMac.c_str(), strMac.size() + 1); + if (ret != EOK) { + return ret; + } + + int idx = 0; + constexpr int bitWidth = 4; + char *ptr = nullptr; + char *p = strtok_s(tempArray, ":", &ptr); + while (p != nullptr) { + mac[idx++] = (ConvertStrChar(*p) << bitWidth) | ConvertStrChar(*(p + 1)); + p = strtok_s(nullptr, ":", &ptr); + } + return EOK; +} + +static char ConvertArrayChar(unsigned char ch) +{ + constexpr int maxDecNum = 9; + constexpr int numDiffForHexAlphabet = 10; + if (ch >= 0 && ch <= maxDecNum) { + return '0' + ch; + } + if (ch >= 0xa && ch <= 0xf) { + return ch + 'a' - numDiffForHexAlphabet; + } + return '0'; +} + +std::string MacArrayToStr(const unsigned char mac[WIFI_MAC_LEN]) +{ + constexpr int bitWidth = 4; + constexpr int noColonBit = 5; + std::stringstream ss; + for (int i = 0; i != WIFI_MAC_LEN; ++i) { + ss << ConvertArrayChar(mac[i] >> bitWidth) << ConvertArrayChar(mac[i] & 0xf); + if (i != noColonBit) { + ss << ":"; + } + } + return ss.str(); +} + +bool IsMacArrayEmpty(const unsigned char mac[WIFI_MAC_LEN]) +{ + for (int i = 0; i != WIFI_MAC_LEN; ++i) { + if (mac[i] != 0) { + return false; + } + } + return true; +} +} // namespace Wifi +} // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_utils.h b/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_utils.h new file mode 100755 index 000000000..f1b1958fb --- /dev/null +++ b/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_utils.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef WIFI_C_UTILS_H_ +#define WIFI_C_UTILS_H_ + +#include +#include "native_c/wifi_device_config.h" +#include "native_c/wifi_error_code.h" +#include "securec.h" +#include "wifi_errcode.h" + +namespace OHOS { +namespace Wifi { +#ifndef CHECK_PTR_RETURN +#define CHECK_PTR_RETURN(ptr, retValue) \ + if ((ptr) == nullptr) { \ + WIFI_LOGE("Error: the ptr is null!"); \ + return retValue; \ + } +#endif + +WifiErrorCode GetCErrorCode(ErrCode errCode); +errno_t MacStrToArray(const std::string& strMac, unsigned char mac[WIFI_MAC_LEN]); +std::string MacArrayToStr(const unsigned char mac[WIFI_MAC_LEN]); +bool IsMacArrayEmpty(const unsigned char mac[WIFI_MAC_LEN]); +} // namespace Wifi +} // namespace OHOS + +#endif diff --git a/ohos.build b/ohos.build index 015769612..c36b601d7 100755 --- a/ohos.build +++ b/ohos.build @@ -3,7 +3,7 @@ "parts": { "wifi_standard": { "module_list": [ - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/src:wifi_sdk", + "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard:wifi_sdk", "//foundation/communication/wifi/services/wifi_standard/wifi_framework:wifi_manage", "//foundation/communication/wifi/services/wifi_standard/wifi_framework:dhcp_manage", "//foundation/communication/wifi/services/wifi_standard/wifi_hal:wifi_hal_service", -- Gitee