remove unused file and function

Signed-off-by: shj07 <shihaojie11@huawei.com>
This commit is contained in:
shj07 2024-11-04 09:20:16 +00:00
parent cdd3f14c53
commit bc64aee981
25 changed files with 1 additions and 2325 deletions

View File

@ -19,7 +19,6 @@
#include <ctime>
#include <iostream>
#include <sstream>
#include "log_helper.h"
#include "wifi_ap_hal_interface.h"
#include "wifi_common_util.h"
#include "wifi_country_code_manager.h"

View File

@ -15,7 +15,6 @@
#include "scan_service.h"
#include <cinttypes>
#include "log_helper.h"
#include "wifi_global_func.h"
#include "wifi_internal_msg.h"
#include "wifi_logger.h"

View File

@ -27,7 +27,6 @@ StaAutoConnectService::StaAutoConnectService(StaStateMachine *staStateMachine, i
: pStaStateMachine(staStateMachine),
pSavedDeviceAppraisal(nullptr),
firmwareRoamFlag(true),
maxBlockedBssidNum(BLOCKLIST_INVALID_SIZE),
selectDeviceLastTime(0),
pAppraisals {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr},
m_instId(instId)
@ -46,11 +45,6 @@ ErrCode StaAutoConnectService::InitAutoConnectService()
{
WIFI_LOGI("Enter InitAutoConnectService.\n");
if (ObtainRoamCapFromFirmware()) {
WIFI_LOGI("Succeeded in obtaining firmware roaming information.\n");
}
SyncBlockedSsidFirmware();
pSavedDeviceAppraisal = new (std::nothrow) StaSavedDeviceAppraisal(firmwareRoamFlag);
if (pSavedDeviceAppraisal == nullptr) {
WIFI_LOGE("savedDeviceAppraisal is null\n");
@ -73,7 +67,6 @@ void StaAutoConnectService::SetAutoConnectStateCallback(const std::vector<StaSer
void StaAutoConnectService::OnScanInfosReadyHandler(const std::vector<InterScanInfo> &scanInfos)
{
WIFI_LOGI("Enter OnScanInfosReadyHandler.\n");
ClearOvertimeBlockedBssid(); /* Refreshing the BSSID Blocklist */
WifiLinkedInfo info;
WifiConfigCenter::GetInstance().GetLinkedInfo(info, m_instId);
@ -86,11 +79,7 @@ void StaAutoConnectService::OnScanInfosReadyHandler(const std::vector<InterScanI
return;
}
if (info.connState == ConnState::CONNECTED) {
ClearAllBlockedBssids();
}
std::vector<std::string> blockedBssids;
GetBlockedBssids(blockedBssids);
if (!AllowAutoSelectDevice(info) || !IsAllowAutoJoin()) {
return;
}
@ -125,208 +114,9 @@ bool StaAutoConnectService::EnableOrDisableBssid(std::string bssid, bool enable,
return false;
}
/* Updating the BSSID Blocklist */
if (!AddOrDelBlockedBssids(bssid, enable, reason)) {
WIFI_LOGI("The blocklist is not updated.\n");
return false;
}
/* The blocklist has been updated, so update the firmware roaming */
/* configuration */
SyncBlockedSsidFirmware();
return true;
}
bool StaAutoConnectService::AddOrDelBlockedBssids(std::string bssid, bool enable, int reason)
{
std::lock_guard<std::mutex> lock(m_blockBssidMapMutex);
WIFI_LOGI("Enter AddOrDelBlockedBssids.\n");
if (enable) {
if (blockedBssidMap.count(bssid) != 0) {
/* Removed the BSSID from the blocklist When the BSSID is enabled. */
blockedBssidMap.erase(bssid);
return true;
}
return false;
}
BlockedBssidInfo status;
auto iter = blockedBssidMap.find(bssid);
if (iter == blockedBssidMap.end()) {
blockedBssidMap.emplace(bssid, status);
}
auto iterator = blockedBssidMap.find(bssid);
if (iterator == blockedBssidMap.end()) {
return false;
}
iterator->second.count++;
time_t now = time(0);
iterator->second.blockedTime = (int)now;
if (!iterator->second.blockedFlag) {
if (iterator->second.count >= MAX_BSSID_BLOCKLIST_COUNT ||
reason == AP_CANNOT_HANDLE_NEW_STA) {
iterator->second.blockedFlag = true;
return true;
}
}
return false;
}
void StaAutoConnectService::GetBlockedBssids(std::vector<std::string> &blockedBssids)
{
std::lock_guard<std::mutex> lock(m_blockBssidMapMutex);
for (auto iter = blockedBssidMap.begin(); iter != blockedBssidMap.end(); ++iter) {
blockedBssids.push_back(iter->first);
}
WIFI_LOGD("GetBlockedBssids, blockedBssids count: %{public}d.", (int)blockedBssids.size());
return;
}
void StaAutoConnectService::ClearAllBlockedBssids()
{
std::lock_guard<std::mutex> lock(m_blockBssidMapMutex);
WIFI_LOGI("Enter ClearAllBlockedBssids.\n");
blockedBssidMap.clear();
return;
}
void StaAutoConnectService::ClearOvertimeBlockedBssid()
{
std::lock_guard<std::mutex> lock(m_blockBssidMapMutex);
WIFI_LOGI("Enter ClearOvertimeBlockedBssid.\n");
if (blockedBssidMap.empty()) {
WIFI_LOGI("blockedBssidMap is empty !\n");
return;
}
bool updated = false;
auto iter = blockedBssidMap.begin();
while (iter != blockedBssidMap.end()) {
BlockedBssidInfo status = iter->second;
time_t now = time(0);
int currentTimeStap = (int)now;
WIFI_LOGI("blockedFlag:%{public}d, currentTimeStap:%{public}d, blockedTime:%{public}d.\n",
status.blockedFlag, currentTimeStap, status.blockedTime);
if (status.blockedFlag && ((currentTimeStap - status.blockedTime) >= MAX_BSSID_BLOCKLIST_TIME)) {
blockedBssidMap.erase(iter++);
updated = true;
} else {
++iter;
}
}
if (updated) {
SyncBlockedSsidFirmware();
}
return;
}
void StaAutoConnectService::ConnectElectedDevice(WifiDeviceConfig &electedDevice)
{
WIFI_LOGI("Enter ConnectElectedDevice.\n");
if (electedDevice.bssid.empty()) {
WIFI_LOGE("electedDevice bssid is empty.");
return;
}
WifiLinkedInfo currentConnectedNetwork;
WifiConfigCenter::GetInstance().GetLinkedInfo(currentConnectedNetwork, m_instId);
if (currentConnectedNetwork.connState == ConnState::CONNECTED && electedDevice.networkId == INVALID_NETWORK_ID &&
currentConnectedNetwork.ssid == electedDevice.ssid && currentConnectedNetwork.bssid != electedDevice.bssid) {
/* Frameworks start roaming only when firmware is not supported */
if (!firmwareRoamFlag) {
WIFI_LOGI("Roaming connectTo, networkId: %{public}d.\n", electedDevice.networkId);
pStaStateMachine->StartRoamToNetwork(electedDevice.bssid);
}
} else if (currentConnectedNetwork.detailedState == DetailedState::DISCONNECTED ||
currentConnectedNetwork.detailedState == DetailedState::CONNECTION_TIMEOUT ||
currentConnectedNetwork.detailedState == DetailedState::FAILED ||
currentConnectedNetwork.detailedState == DetailedState::PASSWORD_ERROR ||
currentConnectedNetwork.detailedState == DetailedState::CONNECTION_FULL ||
currentConnectedNetwork.detailedState == DetailedState::CONNECTION_REJECT) {
pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_CONNECT_SAVED_NETWORK,
electedDevice.networkId,
NETWORK_SELECTED_BY_AUTO);
WIFI_LOGI("connectTo save networkId: %{public}d, preShareKey len: %{public}d.\n",
electedDevice.networkId, (int)electedDevice.preSharedKey.length());
} else {
WIFI_LOGE("The current connection status is %{public}d.\n", currentConnectedNetwork.detailedState);
}
return;
}
void StaAutoConnectService::SyncBlockedSsidFirmware()
{
WIFI_LOGI("Enter SyncBlockedSsidFirmware.\n");
if (!firmwareRoamFlag) {
return;
}
if (maxBlockedBssidNum <= 0) {
return;
}
std::vector<std::string> blockedBssids;
GetBlockedBssids(blockedBssids);
if (static_cast<int>(blockedBssids.size()) > maxBlockedBssidNum) {
blockedBssids.resize(maxBlockedBssidNum);
}
if (SetRoamBlockedBssidFirmware(blockedBssids)) {
WIFI_LOGE("Set firmware roaming configuration succeeded.\n");
} else {
WIFI_LOGI("Set firmware roaming configuration failed.\n");
}
return;
}
bool StaAutoConnectService::ObtainRoamCapFromFirmware()
{
WIFI_LOGI("Enter ObtainRoamCapFromFirmware.\n");
unsigned int capabilities;
if (WifiStaHalInterface::GetInstance().GetStaCapabilities(capabilities) == WIFI_HAL_OPT_OK) {
if ((capabilities & STA_CAP_ROAMING) == 0) {
WIFI_LOGE("Firmware roaming is not supported.\n");
return false;
}
}
WifiHalRoamCapability capability;
if (WifiStaHalInterface::GetInstance().GetRoamingCapabilities(capability) == WIFI_HAL_OPT_OK) {
if (capability.maxBlocklistSize > 0) {
firmwareRoamFlag = true;
maxBlockedBssidNum = capability.maxBlocklistSize;
WIFI_LOGI("Get firmware roaming capabilities succeeded.\n");
return true;
}
WIFI_LOGE("Invalid firmware roaming capabilities.\n");
}
WIFI_LOGE("Get firmware roaming capabilities failed.\n");
return false;
}
bool StaAutoConnectService::SetRoamBlockedBssidFirmware(const std::vector<std::string> &blocklistBssids) const
{
WIFI_LOGI("Enter SetRoamBlockedBssidFirmware.\n");
if (!firmwareRoamFlag) {
return false;
}
if (blocklistBssids.empty()) {
return false;
}
if (static_cast<int>(blocklistBssids.size()) > maxBlockedBssidNum) {
return false;
}
WifiHalRoamConfig capability;
capability.blocklistBssids = blocklistBssids;
if (WifiStaHalInterface::GetInstance().SetRoamConfig(capability) == WIFI_HAL_OPT_OK) {
return true;
}
return false;
}
bool StaAutoConnectService::RegisterDeviceAppraisal(StaDeviceAppraisal *appraisal, int priority)
{
WIFI_LOGI("Enter RegisterDeviceAppraisal.\n");
@ -495,10 +285,8 @@ bool StaAutoConnectService::AllowAutoSelectDevice(const std::vector<InterScanInf
WIFI_LOGI("Auto Select is allowed, detailedState: %{public}d\n", info.detailedState);
return true;
case DetailedState::PASSWORD_ERROR:
WIFI_LOGI("Password error, clear blocked bssids, auto connect to ap quickly.\n");
ClearAllBlockedBssids();
WIFI_LOGI("Password error, auto connect to ap quickly.\n");
return true;
case DetailedState::NOTWORKING:
WIFI_LOGI("The current network cannot access the Internet.\n");
/* Configure whether to automatically switch the network. */

View File

@ -23,7 +23,6 @@
#include "wifi_log.h"
#include "wifi_errcode.h"
#include "wifi_msg.h"
#include "log_helper.h"
#include "sta_define.h"
#include "sta_state_machine.h"
#include "sta_saved_device_appraisal.h"
@ -132,79 +131,12 @@ private:
StaDeviceAppraisal *pSavedDeviceAppraisal;
std::unique_ptr<NetworkSelectionManager> pNetworkSelectionManager = nullptr;
bool firmwareRoamFlag;
int maxBlockedBssidNum;
int selectDeviceLastTime;
StaDeviceAppraisal *pAppraisals[MAX_APPRAISAL_NUM];
int m_instId;
std::map<std::string, std::function<bool()>> autoJoinConditionsMap{};
std::mutex autoJoinMutex;
std::vector<StaServiceCallback> mStaCallbacks;
struct BlockedBssidInfo {
int count; /* Number of times the BSSID is rejected. */
bool blockedFlag;
int blockedTime;
BlockedBssidInfo()
{
count = 0;
blockedFlag = false;
blockedTime = 0;
}
~BlockedBssidInfo(){}
};
std::unordered_map<std::string, BlockedBssidInfo> blockedBssidMap;
std::mutex m_blockBssidMapMutex;
/**
* @Description Clear all BSSIDs in BSSID Blocklist
*
*/
void ClearAllBlockedBssids();
/**
* @Description Refreshing the BSSID Blocklist
*
*/
void ClearOvertimeBlockedBssid();
/**
* @Description Compiles and returns the hash set of the blocklist BSSID.
*
* @param blockedBssids - Blocklisted BSSID List(out)
*/
void GetBlockedBssids(std::vector<std::string> &blockedBssids);
/**
* @Description Update the BSSID blocklist when the BSSID is enabled or disabled.
*
* @param bssid - BSSID to be enabled/disabled(in)
* @param enable - true: Enable the BSSID. false: disable the BSSID.(in)
* @param reasonCode - Enable/Disable reason code.(in)
* @Return: If the blocklist is updated, The value is true. Otherwise, the value is false.
*/
bool AddOrDelBlockedBssids(std::string bssid, bool enable, int reason);
/**
* @Description If the firmware roaming function is supported,
update the firmware roaming config.
*
*/
void SyncBlockedSsidFirmware();
/**
* @Description Querying Firmware Information
*
* @Return: If the operation is successful, true is returned.
If firmware roaming is supported but the valid roaming
capability cannot be obtained, false is returned.
*/
bool ObtainRoamCapFromFirmware();
/**
* @Description Write Firmware Roaming Configuration to Firmware
*
* @param blocklistBssids - List of BSSIDs to Be Added to the Blocklist(in)
* @Return: True if successful, false otherwise
*/
bool SetRoamBlockedBssidFirmware(const std::vector<std::string> &blocklistBssids) const;
/**
* @Description Connect to an elected device
*
* @param electedDevice - Elected Device(in)
*/
void ConnectElectedDevice(WifiDeviceConfig &electedDevice);
/**
* @Description Get available device
*

View File

@ -18,7 +18,6 @@
#include <vector>
#include "wifi_errcode.h"
#include "wifi_msg.h"
#include "log_helper.h"
#include "sta_define.h"
#include "wifi_internal_msg.h"

View File

@ -19,7 +19,6 @@
#include "sta_state_machine.h"
#include "if_config.h"
#include "ip_tools.h"
#include "log_helper.h"
#include "mac_address.h"
#include "sta_monitor.h"
#include "wifi_common_util.h"

View File

@ -26,19 +26,15 @@ local_base_sources = [
"config/wifi_config_file_spec.cpp",
"config/wifi_scan_config.cpp",
"config/wifi_settings.cpp",
"log/log_helper.c",
"net_helper/arp_checker.cpp",
"net_helper/base_address.cpp",
"net_helper/dhcpd_interface.cpp",
"net_helper/dns_checker.cpp",
"net_helper/http_request.cpp",
"net_helper/if_config.cpp",
"net_helper/ip_tools.cpp",
"net_helper/ipv4_address.cpp",
"net_helper/ipv6_address.cpp",
"net_helper/mac_address.cpp",
"net_helper/network_interface.cpp",
"net_helper/raw_socket.cpp",
"utils/wifi_code_convert.cpp",
"utils/wifi_common_event_helper.cpp",
"utils/wifi_encryption_util.cpp",

View File

@ -1,65 +0,0 @@
/*
* Copyright (C) 2021-2022 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 "log_helper.h"
#include <securec.h>
#include <stdio.h>
#include <string.h>
const int MAX_REMAIN_CHARACTER_NUM = 3;
void EncryptLogMsg(const char *srcMsg, char *desMsg, int desLen)
{
if (desMsg == NULL || desLen <= 0) {
return;
}
if (srcMsg == NULL || strlen(srcMsg) == 0) {
desMsg[0] = '\0';
return;
}
int srcLen = strlen(srcMsg);
if (strncpy_s(desMsg, desLen, srcMsg, srcLen) != EOK) {
desMsg[0] = '\0';
return;
}
desMsg[desLen - 1] = '\0';
int i = 0;
int j = (srcLen > (desLen - 1)) ? (desLen - 1) : srcLen;
j -= 1;
int k = MAX_REMAIN_CHARACTER_NUM;
while (k > 0 && i < j) {
++i;
--j;
--k;
}
if (k == 0) {
if (i > j) {
desMsg[i] = '*';
desMsg[j] = '*';
}
while (i <= j) {
desMsg[i] = '*';
++i;
}
} else {
if (i > j) {
desMsg[i] = '*';
desMsg[j] = '*';
} else {
desMsg[i] = '*';
}
}
return;
}

View File

@ -1,34 +0,0 @@
/*
* Copyright (C) 2021-2022 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 LOG_HELPER_H
#define LOG_HELPER_H
#ifdef __cplusplus
extern "C" {
#endif
/**
* @Description : encrypt log message
*
* @param srcMsg : source log message
* @param desMsg : after encrypt log message
* @param desLen : destination log message length
*/
void EncryptLogMsg(const char *srcMsg, char *desMsg, int desLen);
#ifdef __cplusplus
}
#endif
#endif /* log_helper end */

View File

@ -1,228 +0,0 @@
/*
* Copyright (C) 2022 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 "dns_checker.h"
#include <arpa/inet.h>
#include <chrono>
#include <poll.h>
#include <net/if_arp.h>
#include <net/if.h>
#include <unistd.h>
#include "securec.h"
#include "wifi_log.h"
#include "wifi_config_center.h"
#ifdef LOG_TAG
#undef LOG_TAG
#endif
#define LOG_TAG "ohwifi_dns_checker"
namespace OHOS {
namespace Wifi {
const int DNS_SERVER_PORT = 53;
const int DNS_ADDRESS_TYPE = 1;
struct DNS_HEADER {
unsigned short id;
unsigned char rd : 1;
unsigned char tc : 1;
unsigned char aa : 1;
unsigned char opCode : 4;
unsigned char qr : 1;
unsigned char rCode : 4;
unsigned char cd : 1;
unsigned char ad : 1;
unsigned char z : 1;
unsigned char ra : 1;
unsigned short qCount;
unsigned short ansCount;
unsigned short authCount;
unsigned short addCount;
};
struct QUESTION {
unsigned short qtype;
unsigned short qclass;
};
DnsChecker::DnsChecker() : dnsSocket(0), socketCreated(false), isRunning(true)
{}
DnsChecker::~DnsChecker()
{
Stop();
}
void DnsChecker::Start(std::string priDns, std::string secondDns)
{
if (socketCreated) {
Stop();
}
isRunning = true;
dnsSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (dnsSocket < 0) {
LOGE("DnsChecker:socket error : %{public}d", errno);
dnsSocket = 0;
return;
}
std::string ifaceName = WifiConfigCenter::GetInstance().GetStaIfaceName();
struct ifreq ifaceReq;
if (strncpy_s(ifaceReq.ifr_name, sizeof(ifaceReq.ifr_name), ifaceName.c_str(), ifaceName.size()) != EOK) {
LOGE("DnsChecker copy ifaceReq failed.");
close(dnsSocket);
dnsSocket = 0;
return;
}
if (setsockopt(dnsSocket, SOL_SOCKET, SO_BINDTODEVICE, (char *)&ifaceReq, sizeof(ifaceReq)) == -1) {
LOGE("DnsChecker start SO_BINDTODEVICE error:%{public}d.", errno);
close(dnsSocket);
dnsSocket = 0;
return;
}
socketCreated = true;
primaryDnsAddress = priDns;
secondDnsAddress = secondDns;
}
void DnsChecker::Stop()
{
if (!socketCreated) {
return;
}
close(dnsSocket);
dnsSocket = 0;
socketCreated = false;
}
void DnsChecker::formatHostAdress(char* hostAddress, const char* host)
{
if (!hostAddress || !host) {
return;
}
int lock = 0;
int len = strlen(host);
for (int i = 0; i < len; i++) {
if (host[i] == '.') {
*hostAddress++ = i - lock;
for (; lock < i; lock++) {
*hostAddress++ = host[lock];
}
lock++;
}
}
*hostAddress++ = '\0';
}
void DnsChecker::StopDnsCheck()
{
isRunning = false;
}
bool DnsChecker::DoDnsCheck(std::string url, int timeoutMillis)
{
LOGI("DoDnsCheck Enter.");
int len1 = (int)url.find("/generate_204");
int len = len1 - strlen("http://");
std::string host = url.substr(strlen("http://"), len);
host = host + ".";
LOGD("DoDnsCheck url=%{public}s", host.c_str());
if (!isRunning) {
return false;
}
bool dnsValid = checkDnsValid(host, primaryDnsAddress, timeoutMillis) ||
checkDnsValid(host, secondDnsAddress, timeoutMillis);
if (!dnsValid) {
LOGE("all dns can not work.");
}
return dnsValid;
}
int DnsChecker::recvDnsData(char* buff, int size, int timeout)
{
if (dnsSocket < 0) {
LOGE("invalid socket fd");
return 0;
}
pollfd fds[1];
fds[0].fd = dnsSocket;
fds[0].events = POLLIN;
if (poll(fds, 1, timeout) <= 0) {
return 0;
}
int nBytes;
do {
nBytes = read(dnsSocket, buff, size);
if (nBytes < 0) {
LOGE("recvfrom failed %{public}d", errno);
return false;
}
} while (nBytes == -1 && isRunning);
return nBytes < 0 ? 0 : nBytes;
}
bool DnsChecker::checkDnsValid(std::string host, std::string dnsAddress, int timeoutMillis)
{
if (!socketCreated && !isRunning) {
LOGE("DnsChecker checkDnsValid failed, socket not created");
return false;
}
if (dnsAddress.empty()) {
LOGE("DnsChecker dnsAddress is empty!");
return false;
}
struct sockaddr_in dest;
dest.sin_family = AF_INET;
dest.sin_port = htons(DNS_SERVER_PORT);
dest.sin_addr.s_addr = inet_addr(dnsAddress.c_str());
char buff[2048] = {0};
struct DNS_HEADER *dns = (struct DNS_HEADER*)&buff;
dns->id = (unsigned short)htons(getpid());
dns->rd = 1;
dns->qCount = htons(1);
char* hostAddress = (char*)&buff[sizeof(struct DNS_HEADER)];
formatHostAdress(hostAddress, host.c_str());
struct QUESTION *qinfo = (struct QUESTION *)&buff[sizeof(struct DNS_HEADER) +
(strlen((const char*)hostAddress) + 1)];
qinfo->qtype = htons(DNS_ADDRESS_TYPE);
qinfo->qclass = htons(1);
int len = (int)(sizeof(struct DNS_HEADER) + (strlen((const char*)hostAddress) + 1) + sizeof(QUESTION));
if (sendto(dnsSocket, buff, len, 0, (struct sockaddr*)&dest, sizeof(dest)) < 0) {
LOGE("send dns data failed.");
return false;
}
int64_t elapsed = 0;
int leftMillis = timeoutMillis;
std::chrono::steady_clock::time_point startTime = std::chrono::steady_clock::now();
while (leftMillis > 0 && isRunning) {
int readLen = recvDnsData(buff, sizeof(buff), leftMillis);
if (readLen >= static_cast<int>(sizeof(struct DNS_HEADER))) {
dns = (struct DNS_HEADER*)buff;
LOGI("dns recv ansCount:%{public}d", dns->ansCount);
return dns->ansCount > 0;
}
std::chrono::steady_clock::time_point current = std::chrono::steady_clock::now();
elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(current - startTime).count();
leftMillis -= static_cast<int>(elapsed);
}
return false;
}
}
}

View File

@ -1,46 +0,0 @@
/*
* Copyright (C) 2022 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_DNS_CHECKER_H
#define OHOS_WIFI_DNS_CHECKER_H
#include <arpa/inet.h>
#include <netinet/if_ether.h>
#include <string>
#include <atomic>
namespace OHOS {
namespace Wifi {
class DnsChecker {
public:
DnsChecker();
~DnsChecker();
void Start(std::string priDns, std::string secondDns);
void Stop();
void StopDnsCheck();
bool DoDnsCheck(std::string url, int timeoutMillis);
private:
void formatHostAdress(char* hostAddress, const char* host);
bool checkDnsValid(std::string host, std::string dnsAddress, int timeoutMillis);
int recvDnsData(char* buff, int size, int timeout);
private:
int dnsSocket;
std::string primaryDnsAddress;
std::string secondDnsAddress;
bool socketCreated;
std::atomic<bool> isRunning;
};
}
}
#endif

View File

@ -1,454 +0,0 @@
/*
* 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 "http_request.h"
#include <thread>
#include <unordered_set>
#include <sys/time.h>
#include "securec.h"
#include "wifi_log.h"
#include "wifi_common_util.h"
#include <netdb.h>
#undef LOG_TAG
#define LOG_TAG "OHWIFI_UTILS_HTTP_REQ"
namespace OHOS {
namespace Wifi {
HttpRequest::HttpRequest()
: mISocketFd(INVALID_SOCKET), iPort(0), strHost(""), strIp(""), strRes(""), strParam(""), httpHead("")
{}
HttpRequest::~HttpRequest()
{
if (mISocketFd > 0) {
close(mISocketFd);
}
mISocketFd = INVALID_SOCKET;
}
int HttpRequest::HttpGet(const std::string &strUrl, std::string &strResponse)
{
return HttpRequestExec("GET", strUrl, "", strResponse);
}
int HttpRequest::HttpPost(const std::string &strUrl, const std::string &strData, std::string &strResponse)
{
return HttpRequestExec("POST", strUrl, strData, strResponse);
}
int HttpRequest::HttpRequestExec(
const std::string &strMethod, const std::string &strUrl, const std::string &strData, std::string &strResponse)
{
int iRet = 0;
/* Check whether the URL is valid. */
if (strUrl.empty()) {
LOGE("HttpRequest::HttpRequestExec URL is null\n");
return -1;
}
/* Limit the URL length. */
if (URLSIZE < strUrl.length()) {
LOGE("HttpRequest::HttpRequestExec URL length > %{public}d, error\n", URLSIZE);
return -1;
}
iRet = GetHostAddrFromUrl(strUrl);
if (iRet != 0) {
LOGE("HttpRequest::HttpRequestExec get HostAddr failed.\n");
return -1;
}
/* Create an HTTP protocol header. */
HttpHeadCreate(strMethod, strData);
/* Create socket */
mISocketFd = socket(AF_INET, SOCK_STREAM, 0);
if (mISocketFd < 0) {
LOGE("HttpRequest::HttpRequestExec socket error! Error code: %{public}d.", errno);
return -1;
}
/* Bind address and port */
GetPortFromUrl();
if (iPort < 0) {
LOGE("HttpRequest::HttpRequestExec get port failed from URL!\n");
close(mISocketFd);
mISocketFd = INVALID_SOCKET;
return -1;
}
iRet = GetIPFromUrl();
if (iRet != 0) {
LOGE("HttpRequest::HttpRequestExec get ip failed from URL!\n");
close(mISocketFd);
mISocketFd = INVALID_SOCKET;
return -1;
}
LOGI("iPort= [%{public}d],strIP= [%s]\n", iPort, strIp.c_str());
iRet = HttpConnect(strResponse);
if (iRet != 0) {
LOGE("HttpRequest::HttpConnect failed!\n");
close(mISocketFd);
mISocketFd = INVALID_SOCKET;
return -1;
}
close(mISocketFd);
mISocketFd = INVALID_SOCKET;
LOGD("HttpRequest::HttpConnect success!\n");
return 0;
}
int HttpRequest::HttpConnect(std::string &strResponse)
{
int flags = 0;
struct sockaddr_in servaddr = {0};
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(iPort);
if (inet_pton(AF_INET, strIp.c_str(), &servaddr.sin_addr) <= 0) {
LOGE("HttpConnect inet_pton error! errno: %{public}d", errno);
return -1;
}
/* Set non-blocking */
flags = fcntl(mISocketFd, F_GETFL, 0);
if (fcntl(mISocketFd, F_SETFL, static_cast<size_t>(flags) | O_NONBLOCK) == -1) {
LOGE("HttpConnect fcntl error! Error code: %{public}d", errno);
return -1;
}
/* Non-blocking connection */
int iRet = connect(mISocketFd, reinterpret_cast<struct sockaddr *>(&servaddr), sizeof(servaddr));
if (iRet == 0) {
iRet = HttpDataTransmit(mISocketFd);
if (iRet != 0) {
LOGE("HttpConnect HttpDataTransmit error\n");
return -1;
}
strResponse = strRes;
return 0;
} else if (iRet < 0) {
if (errno != EINPROGRESS) {
LOGE("HttpDataTransmit connect error! Error code: %{public}d", errno);
return -1;
}
}
iRet = SocketFdCheck(mISocketFd);
if (iRet > 0) {
iRet = HttpDataTransmit(mISocketFd);
if (iRet != 0) {
LOGE("HttpRequest::HttpDataTransmit HttpDataTransmit error!");
return -1;
}
strResponse = strRes;
return 0;
} else {
LOGE("HttpRequest::HttpDataTransmit SocketFdCheck error!");
return -1;
}
return 0;
}
void HttpRequest::HttpHeadCreate(const std::string &strMethod, const std::string &strData)
{
std::string strHttpHead;
strHttpHead += strMethod;
strHttpHead += " /";
strHttpHead += strParam;
strHttpHead += " HTTP/1.1\r\n";
strHttpHead += "Accept: */*\r\n";
strHttpHead += "Accept-Language: cn\r\n";
strHttpHead += "User-Agent: Mozilla/4.0\r\n";
strHttpHead += "Host: ";
strHttpHead += strHost;
strHttpHead += "\r\n";
strHttpHead += "Cache-Control: no-cache\r\n";
strHttpHead += "Connection: Keep-Alive\r\n";
if (strMethod == "POST") {
std::size_t uLen = strData.length();
strHttpHead += "Content-Type: application/x-www-form-urlencoded\r\n";
strHttpHead += "Content-Length: ";
strHttpHead += std::to_string(uLen);
strHttpHead += "\r\n\r\n";
strHttpHead += strData;
}
strHttpHead += "\r\n\r\n";
httpHead = strHttpHead;
}
int HttpRequest::HttpDataTransmit(const int &iSockFd)
{
int ret = send(iSockFd, httpHead.c_str(), httpHead.length() + 1, 0);
if (ret < 0) {
LOGE("HttpRequest::HttpDataTransmit send error! Error code: %{public}d", errno);
return -1;
}
char *buf = new char[BUFSIZE]();
if (buf == nullptr) {
return -1;
}
constexpr int timeoutMs = 500;
constexpr int timeRate = 1000;
struct timeval tv;
struct timeval tvEnd;
gettimeofday(&tv, nullptr);
long long tvTime = tv.tv_sec * timeRate + tv.tv_usec / timeRate;
long long tvEndTime;
bool bDataRec = false;
while (1) {
gettimeofday(&tvEnd, nullptr);
tvEndTime = tvEnd.tv_sec * timeRate + tvEnd.tv_usec / timeRate;
if (tvEndTime - tvTime > timeoutMs) {
LOGE("HttpRequest::HttpDataTransmit recv timeout\n");
delete[] buf;
buf = nullptr;
return -1;
}
if (memset_s(buf, BUFSIZE, 0, BUFSIZE) != EOK) {
LOGE("HttpDataTransmit memset_s is failed \n");
delete[] buf;
buf = nullptr;
return -1;
}
ret = recv(iSockFd, buf, BUFSIZE, 0);
if (ret == 0) {
/* The connection is closed. */
if (!bDataRec) {
LOGE("HttpRequest::HttpDataTransmit recv error! Error code: %{public}d", errno);
delete[] buf;
buf = nullptr;
return -1;
} else {
LOGD("HttpRequest::HttpDataTransmit recv success\n");
delete[] buf;
buf = nullptr;
return 0;
}
} else if (ret > 0) {
bDataRec = true;
strRes += buf;
} else if (ret < 0) {
/* Error */
if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN) {
LOGD("HttpRequest::HttpDataTransmit recv not finish!\n");
continue;
} else {
LOGE("HttpRequest::HttpDataTransmit recv error! Error code: %{public}d", errno);
delete[] buf;
buf = nullptr;
return -1;
}
}
}
}
int HttpRequest::GetHostAddrFromUrl(const std::string &strUrl)
{
std::string urlTmp(strUrl);
std::string urlTmp2;
if (urlTmp.find("https://") != std::string::npos) {
urlTmp2 = urlTmp.substr(HTTPS_HEADER_LENGTH);
} else if (urlTmp.find("http://") != std::string::npos) {
urlTmp2 = urlTmp.substr(HTTP_HEADER_LENGTH);
} else {
urlTmp2 = urlTmp;
}
LOGI("GetHostAddrFromUrl urlTmp2 = [%s].\n", urlTmp2.c_str());
if (!urlTmp2.empty()) {
strHost = urlTmp2.substr(0, urlTmp2.find("/"));
strParam = urlTmp2.substr(urlTmp2.find("/") + 1);
} else {
LOGE("GetHostAddrFromUrl url is wrong\n");
return -1;
}
return 0;
}
void HttpRequest::GetPortFromUrl()
{
if (strHost.find(":") != std::string::npos) {
std::string strPort = strHost.substr(strHost.find(":") + 1);
iPort = CheckDataLegal(strPort);
} else {
iPort = DEFAULT_PORT;
}
}
std::mutex gMutex;
std::unordered_set<HostData*> gHostDataSet;
void GetHostThread(HostData* pThreadData)
{
std::string ipOrDomain;
{
std::unique_lock<std::mutex> lck(gMutex);
if (gHostDataSet.find(pThreadData) == gHostDataSet.end()) {
LOGE("GetHostThread Error.");
return;
}
ipOrDomain = pThreadData->strIpOrDomain;
}
LOGE("GetHostThread ipOrDomain is %{public}s.", ipOrDomain.c_str());
addrinfo *res = nullptr;
int status = getaddrinfo(ipOrDomain.c_str(), nullptr, nullptr, &res);
if (status < 0) {
LOGE("getaddrinfo errno %{public}d %{public}s", errno, strerror(errno));
return;
}
for (addrinfo *tmp = res; tmp != nullptr; tmp = tmp->ai_next) {
if (tmp->ai_family == AF_INET) {
auto addr = reinterpret_cast<sockaddr_in *>(tmp->ai_addr);
char ip[50] = {0};
inet_ntop(AF_INET, &addr->sin_addr, ip, sizeof(ip));
pThreadData->strIp = ip;
} else if (tmp->ai_family == AF_INET6) {
auto addr = reinterpret_cast<sockaddr_in6 *>(tmp->ai_addr);
char ip[200] = {0};
inet_ntop(AF_INET6, &addr->sin6_addr, ip, sizeof(ip));
pThreadData->strIp = ip;
}
}
freeaddrinfo(res);
LOGE("GetHostThread ipaddr is %{public}s.", pThreadData->strIp.c_str());
pThreadData->bIp = true;
pThreadData->mWait_timeout.notify_one();
return;
}
int HttpRequest::GetIPFromUrl()
{
std::string strIpOrDomain;
if (strHost.find(":") != std::string::npos) {
strIpOrDomain = strHost.substr(0, strHost.find(":"));
} else {
strIpOrDomain = strHost;
}
if (strIpOrDomain.empty()) {
LOGE("GetIPFromUrl strIpOrDomain is null.\n");
return -1;
}
if (inet_addr(strIpOrDomain.c_str()) == INADDR_NONE) {
LOGI("GetIPFromUrl Url maybe contain Domain.");
HostData* pData = nullptr;
{
std::unique_lock<std::mutex> lck(gMutex);
pData = new HostData;
if (pData == nullptr) {
LOGE("GetIPFromUrl new HostData error.\n");
return -1;
}
gHostDataSet.emplace(pData);
pData->strIpOrDomain = strIpOrDomain;
}
int iRlt = -1;
std::thread getHost = std::thread(&GetHostThread, pData);
pthread_setname_np(getHost.native_handle(), "GetHostThread");
getHost.detach();
bool bTimeOut = false;
const int timeoutMs = 150;
{
std::unique_lock<std::mutex> lck(gMutex);
if (pData->mWait_timeout.wait_for(lck, std::chrono::milliseconds(timeoutMs)) == std::cv_status::timeout) {
bTimeOut = true;
}
}
if (!bTimeOut) {
std::unique_lock<std::mutex> lck(gMutex);
if (gHostDataSet.find(pData) == gHostDataSet.end()) {
if (pData != nullptr) {
delete pData;
pData = nullptr;
}
LOGD("GetHostThread None.");
return -1;
}
if (pData->bIp) {
iRlt = 0;
strIp = pData->strIp;
gHostDataSet.erase(pData);
delete pData;
pData = nullptr;
LOGD("Get ip ok.");
}
}
return iRlt;
} else {
LOGI("GetIPFromUrl Url contain ip\n");
strIp = strIpOrDomain;
return 0;
}
}
int HttpRequest::SocketFdCheck(const int &iSockFd) const
{
struct timeval timeout = {0};
fd_set rSet, wSet;
FD_ZERO(&rSet);
FD_ZERO(&wSet);
FD_SET(iSockFd, &rSet);
FD_SET(iSockFd, &wSet);
timeout.tv_sec = SEND_HTTP_DELAY_TIME;
timeout.tv_usec = 0;
int iRet = select(iSockFd + 1, &rSet, &wSet, nullptr, &timeout);
if (iRet < 0) {
LOGE("HttpRequest::SocketFdCheck select failed");
/* An error occurs during the selection. All descriptor sets are cleared. */
return -1;
} else if (iRet == 0) {
LOGE("HttpRequest::SocketFdCheck time out");
/* Timeout */
return -1;
}
/* Check whether SocketFd is writable and unreadable. */
int iW = FD_ISSET(iSockFd, &wSet);
int iR = FD_ISSET(iSockFd, &rSet);
if (iW && !iR) {
char error[4] = "";
socklen_t len = sizeof(error);
int ret = getsockopt(iSockFd, SOL_SOCKET, SO_ERROR, error, &len);
if (ret == 0) {
if (!strcmp(error, "")) {
/* Indicates the number of prepared descriptors. */
return iRet;
} else {
LOGE("HttpRequest::SocketFdCheck getsockopt failed. error code:%{public}d", errno);
return -1;
}
} else {
LOGE("HttpRequest::SocketFdCheck getsockopt failed. error code:%{public}d", errno);
return -1;
}
} else {
LOGE("HttpRequest::SocketFdCheck "
"Whether sockFd is in the writable character set: %{public}d, is it in the "
"readable character set: %{public}d\t (0 means not in)\n",
iW,
iR);
return -1;
}
}
} // namespace Wifi
} // namespace OHOS

View File

@ -1,164 +0,0 @@
/*
* 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_HTTPREQ_H
#define OHOS_HTTPREQ_H
#include <fcntl.h>
#include <unistd.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstdarg>
#include <sys/socket.h>
#include <sys/types.h>
#include <condition_variable>
#define BUFSIZE 1024
#define URLSIZE 1024
#define INVALID_SOCKET (-1)
inline const int HTTP_HEADER_LENGTH = 7;
inline const int HTTPS_HEADER_LENGTH = 8;
inline const int DEFAULT_PORT = 80;
inline const int SEND_HTTP_DELAY_TIME = 1;
namespace OHOS {
namespace Wifi {
class HttpRequest {
public:
/**
* @Description : Constructs a new Http Request object.
*
*/
HttpRequest();
/**
* @Description : Destroy the Http Request object.
*
*/
~HttpRequest();
/**
* @Description : HttpGet request.
*
* @param strUrl - HTTP request URL.[in]
* @param strResponse - HTTP request response.[in]
* @return int
*/
int HttpGet(const std::string &strUrl, std::string &strResponse);
/**
* @Description : HttpPost request
*
* @param strUrl - HTTP request URL.[in]
* @param strData - Data sent in a POST request.[in]
* @param strResponse - HTTP request response.[in]
* @return int
*/
int HttpPost(const std::string &strUrl, const std::string &strData, std::string &strResponse);
private:
/**
* @Description : Executes HTTP requests, GET or POST.
*
* @param strMethod - The Http request type.[in]
* @param strUrl - HTTP request URL.[in]
* @param strData - Data sent in a POST request.[in]
* @param strResponse - HTTP request response.[in]
* @return int
*/
int HttpRequestExec(
const std::string &strMethod, const std::string &strUrl, const std::string &strData, std::string &strResponse);
/**
* @Description : Constructing an HTTP Message Header
*
* @param strMethod - The Http request type.[in]
* @param strData - Data sent in a POST request.[in]
*/
void HttpHeadCreate(const std::string &strMethod, const std::string &strData);
/**
* @Description : Send an HTTP request and receive a response.
*
* @param iSockFd - a sign.[in]
* @return int
*/
int HttpDataTransmit(const int &iSockFd);
/**
* @Description : Http connection processing function.
*
* @param strResponse - HTTP request response.[in]
* @return int
*/
int HttpConnect(std::string &strResponse);
/**
* @Description : Obtain the port number from the HTTP request URL object
*
* @param strUrl - HTTP request URL.[in]
* @return none
*/
void GetPortFromUrl();
/**
* @Description : Obtain the IP address from the HTTP request URL.
*
* @param strUrl - HTTP request URL.[in]
* @return int
*/
int GetIPFromUrl();
/**
* @Description : Obtain the host address, website address, or IP address in
* dotted decimal notation from the HTTP request URL.
*
* @param strUrl - HTTP request URL.[in]
* @return int
*/
int GetHostAddrFromUrl(const std::string &strUrl);
/**
* @Description : Check whether SocketFd is writable and unreadable.
*
* @param iSockFd - a sign.[in]
* @return int
*/
int SocketFdCheck(const int &iSockFd) const;
private:
int mISocketFd;
int iPort;
std::string strHost;
std::string strIp;
std::string strRes;
std::string strParam;
std::string httpHead;
};
struct HostData {
bool bIp = false;
std::string strIp;
std::string strIpOrDomain;
std::condition_variable mWait_timeout;
};
}
} /* namespace OHOS */
#endif

View File

@ -1,184 +0,0 @@
/*
* Copyright (C) 2022 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 "raw_socket.h"
#include <arpa/inet.h>
#include <cstdio>
#include <cerrno>
#include <fcntl.h>
#include <net/if.h>
#include <netinet/if_ether.h>
#include <netpacket/packet.h>
#include <poll.h>
#include <sys/socket.h>
#include <unistd.h>
#include "securec.h"
#include "wifi_log.h"
#ifdef LOG_TAG
#undef LOG_TAG
#endif
#define LOG_TAG "ohwifi_raw_socket"
namespace OHOS {
namespace Wifi {
constexpr int OPT_SUCC = 0;
constexpr int OPT_FAIL = -1;
RawSocket::RawSocket() : socketFd_(-1), ifaceIndex_(0), protocol_(0)
{
}
RawSocket::~RawSocket()
{
Close();
}
bool RawSocket::SetNonBlock(int fd)
{
int ret = fcntl(fd, F_GETFL);
if (ret < 0) {
return false;
}
uint32_t flags = (static_cast<uint32_t>(ret) | O_NONBLOCK);
return fcntl(fd, F_SETFL, flags);
}
int RawSocket::CreateSocket(const char *iface, uint16_t protocol)
{
if (iface == nullptr) {
LOGW("iface is null");
return OPT_FAIL;
}
unsigned int ifaceIndex = if_nametoindex(iface);
if (ifaceIndex == 0) {
LOGE("get iface index fail: %{public}s", iface);
return OPT_FAIL;
}
int socketFd = socket(PF_PACKET, SOCK_DGRAM, htons(protocol));
if (socketFd < 0) {
LOGE("create socket fail");
return OPT_FAIL;
}
if (SetNonBlock(socketFd)) {
LOGE("set non block fail");
(void)close(socketFd);
return OPT_FAIL;
}
struct sockaddr_ll rawAddr;
rawAddr.sll_ifindex = static_cast<int>(ifaceIndex);
rawAddr.sll_protocol = htons(protocol);
rawAddr.sll_family = AF_PACKET;
int ret = bind(socketFd, reinterpret_cast<struct sockaddr *>(&rawAddr), sizeof(rawAddr));
if (ret != 0) {
LOGE("bind fail");
(void)close(socketFd);
return OPT_FAIL;
}
socketFd_ = socketFd;
ifaceIndex_ = ifaceIndex;
protocol_ = protocol;
return OPT_SUCC;
}
int RawSocket::Send(uint8_t *buff, int count, uint8_t *destHwaddr)
{
if (buff == nullptr || destHwaddr == nullptr) {
LOGE("buff or dest hwaddr is null");
return OPT_FAIL;
}
if (socketFd_ < 0 || ifaceIndex_ == 0) {
LOGE("invalid socket fd");
return OPT_FAIL;
}
struct sockaddr_ll rawAddr;
if (memset_s(&rawAddr, sizeof(rawAddr), 0, sizeof(rawAddr)) != EOK) {
LOGE("Send memset_s is failed");
return OPT_FAIL;
}
rawAddr.sll_ifindex = ifaceIndex_;
rawAddr.sll_protocol = htons(protocol_);
rawAddr.sll_family = AF_PACKET;
if (memcpy_s(rawAddr.sll_addr, sizeof(rawAddr.sll_addr), destHwaddr, ETH_ALEN) != EOK) {
LOGE("Send: memcpy fail");
return OPT_FAIL;
}
int ret;
do {
ret = sendto(socketFd_, buff, count, 0, reinterpret_cast<struct sockaddr *>(&rawAddr), sizeof(rawAddr));
if (ret == -1) {
LOGE("Send: sendto fail");
if (errno != EINTR) {
break;
}
}
} while (ret == -1);
return ret > 0 ? OPT_SUCC : OPT_FAIL;
}
int RawSocket::Recv(uint8_t *buff, int count, int timeoutMillis)
{
if (socketFd_ < 0) {
LOGE("invalid socket fd");
return 0;
}
pollfd fds[1];
fds[0].fd = socketFd_;
fds[0].events = POLLIN;
if (poll(fds, 1, timeoutMillis) <= 0) {
return 0;
}
int nBytes;
do {
nBytes = read(socketFd_, buff, count);
if (nBytes == -1) {
if (errno != EINTR) {
break;
}
}
} while (nBytes == -1);
return nBytes < 0 ? 0 : nBytes;
}
int RawSocket::Close(void)
{
int ret = OPT_FAIL;
if (socketFd_ >= 0) {
ret = close(socketFd_);
if (ret != OPT_SUCC) {
LOGE("close fail.");
}
}
socketFd_ = -1;
ifaceIndex_ = 0;
protocol_ = 0;
return OPT_FAIL;
}
}
}

View File

@ -1,39 +0,0 @@
/*
* Copyright (C) 2022 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_RAW_SOCKET_H
#define OHOS_WIFI_RAW_SOCKET_H
#include <cstdint>
namespace OHOS {
namespace Wifi {
class RawSocket {
public:
RawSocket();
~RawSocket();
int CreateSocket(const char *iface, uint16_t protocol);
int Send(uint8_t *buff, int count, uint8_t *destHwaddr);
int Recv(uint8_t *buff, int count, int timeoutMillis);
int Close(void);
private:
bool SetNonBlock(int fd);
int socketFd_;
uint16_t ifaceIndex_;
uint16_t protocol_;
};
}
}
#endif

View File

@ -249,22 +249,12 @@ void StaAutoServerFuzzTest(const uint8_t* data, size_t size)
pStaAutoConnectService->AllowAutoSelectDevice(info);
pStaAutoConnectService->RoamingEncryptionModeCheck(config, scanInfoList, info);
pStaAutoConnectService->RoamingSelection(config, scanInfo, info);
pStaAutoConnectService->ConnectElectedDevice(config);
pStaAutoConnectService->ClearOvertimeBlockedBssid();
pStaAutoConnectService->ClearAllBlockedBssids();
pStaAutoConnectService->GetBlockedBssids(blocklistBssids);
pStaAutoConnectService->AddOrDelBlockedBssids(conditionName, attemptEnable, frequency);
pStaAutoConnectService->EnableOrDisableBssid(conditionName, attemptEnable, frequency);
pStaAutoConnectService->ClearOvertimeBlockedBssid();
pStaAutoConnectService->firmwareRoamFlag = true;
pStaAutoConnectService->SetRoamBlockedBssidFirmware(blocklistBssids);
pStaAutoConnectService->OnScanInfosReadyHandler(scanInfo);
pStaAutoConnectService->SyncBlockedSsidFirmware();
pStaAutoConnectService->ObtainRoamCapFromFirmware();
pStaAutoConnectService->AutoSelectDevice(config, scanInfo, blocklistBssids, info);
pStaAutoConnectService->WhetherDevice5GAvailable(scanInfo);
pStaAutoConnectService->GetAvailableScanInfos(scanInfo, scanInfo, blocklistBssids, info);
pStaAutoConnectService->ObtainRoamCapFromFirmware();
pStaService->AutoConnectService(scanInfo);
}
@ -281,19 +271,6 @@ void StaAppAccelerationFuzzTest(const uint8_t* data, size_t size)
pStaAppAcceleration->StopAllAppAcceleration();
}
void SyncBlockedSsidFirmwareTest(const uint8_t* data, size_t size)
{
pStaAutoConnectService->maxBlockedBssidNum = TWO;
pStaAutoConnectService->SyncBlockedSsidFirmware();
}
void SetRoamBlockedBssidFirmwareTest(const uint8_t* data, size_t size)
{
std::vector<std::string> blocklistBssids;
pStaAutoConnectService->maxBlockedBssidNum = TWO;
pStaAutoConnectService->SetRoamBlockedBssidFirmware(blocklistBssids);
}
void RegisterDeviceAppraisalTest(const uint8_t* data, size_t size)
{
StaDeviceAppraisal *appraisal = nullptr;
@ -510,8 +487,6 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
OHOS::Wifi::StaServerFuzzTest(data, size);
OHOS::Wifi::StaAutoServerFuzzTest(data, size);
OHOS::Wifi::StaAppAccelerationFuzzTest(data, size);
OHOS::Wifi::SyncBlockedSsidFirmwareTest(data, size);
OHOS::Wifi::SetRoamBlockedBssidFirmwareTest(data, size);
OHOS::Wifi::RegisterDeviceAppraisalTest(data, size);
OHOS::Wifi::AllowAutoSelectDeviceTest(data, size);
OHOS::Wifi::StaAutoConnectServiceFuzzTest(data, size);

View File

@ -15,7 +15,6 @@
#include "scan_service.h"
#include <cinttypes>
#include "log_helper.h"
#include "wifi_global_func.h"
#include "wifi_internal_msg.h"
#include "wifi_logger.h"

View File

@ -118,22 +118,6 @@ public:
void RegisterDeviceAppraisalSuccess();
void RegisterDeviceAppraisalFail1();
void RegisterDeviceAppraisalFail2();
void ClearOvertimeBlockedBssidSuccess1();
void ClearOvertimeBlockedBssidSuccess2();
void GetBlockedBssidsSuccess();
void AddOrDelBlockedBssidsSuccess();
void AddOrDelBlockedBssidsFail();
void ObtainRoamCapFromFirmwareSuccess();
void ObtainRoamCapFromFirmwareFail1();
void ObtainRoamCapFromFirmwareFail2();
void SetRoamBlockedBssidFirmwareSuccess();
void SetRoamBlockedBssidFirmwareFail1();
void SetRoamBlockedBssidFirmwareFail2();
void SetRoamBlockedBssidFirmwareFail3();
void SetRoamBlockedBssidFirmwareFail4();
void ConnectElectedDeviceSuccess1();
void ConnectElectedDeviceSuccess2();
void ConnectElectedDeviceFail1();
void GetAvailableScanInfosSuccess();
void GetAvailableScanInfosSuccess1();
void GetAvailableScanInfosSuccess2();
@ -165,8 +149,6 @@ public:
void RoamingSelectionFail2();
void RoamingSelectionFail3();
void RoamingSelectionFail4();
void SyncBlockedSsidFirmwareSuccess();
void SyncBlockedSsidFirmwareFail();
void DisableAutoJoinSuccess();
void EnableAutoJoinSuccess();
void RegisterAutoJoinConditionSuccess();
@ -236,7 +218,6 @@ void StaAutoConnectServiceTest::GetAllDeviceInfos(WifiDeviceConfig &deviceConfig
{
GetWifiDeviceConfig(deviceConfig);
GetInterScanInfoVector(scanInfos);
pStaAutoConnectService->GetBlockedBssids(blockedBssids);
GetWifiLinkedInfo(info);
}
@ -568,150 +549,6 @@ void StaAutoConnectServiceTest::RegisterDeviceAppraisalFail2()
EXPECT_TRUE(pStaAutoConnectService->RegisterDeviceAppraisal(appraisal, priority) == false);
}
void StaAutoConnectServiceTest::ClearOvertimeBlockedBssidSuccess1()
{
pStaAutoConnectService->ClearOvertimeBlockedBssid();
}
void StaAutoConnectServiceTest::ClearOvertimeBlockedBssidSuccess2()
{
std::string bssid = "2a:76:93:47:e2:8a";
bool enable = false;
int reason = AP_CANNOT_HANDLE_NEW_STA;
pStaAutoConnectService->AddOrDelBlockedBssids(bssid, enable, reason);
pStaAutoConnectService->ClearOvertimeBlockedBssid();
}
void StaAutoConnectServiceTest::GetBlockedBssidsSuccess()
{
std::vector<std::string> blockedBssids;
std::string bssid = "2a:76:93:47:e2:8a";
blockedBssids.push_back(bssid);
pStaAutoConnectService->GetBlockedBssids(blockedBssids);
}
void StaAutoConnectServiceTest::AddOrDelBlockedBssidsSuccess()
{
std::string bssid = "2a:76:93:47:e2:8a";
bool enable = false;
int reason = AP_CANNOT_HANDLE_NEW_STA;
EXPECT_TRUE(pStaAutoConnectService->AddOrDelBlockedBssids(bssid, enable, reason) == true);
}
void StaAutoConnectServiceTest::AddOrDelBlockedBssidsFail()
{
std::string bssid = "2a:76:93:47:e2:8a";
bool enable = true;
int reason = AP_CANNOT_HANDLE_NEW_STA;
EXPECT_TRUE(pStaAutoConnectService->AddOrDelBlockedBssids(bssid, enable, reason) == false);
}
void StaAutoConnectServiceTest::ObtainRoamCapFromFirmwareSuccess()
{
EXPECT_TRUE(pStaAutoConnectService->ObtainRoamCapFromFirmware() == false);
}
void StaAutoConnectServiceTest::ObtainRoamCapFromFirmwareFail1()
{
EXPECT_TRUE(pStaAutoConnectService->ObtainRoamCapFromFirmware() == false);
}
void StaAutoConnectServiceTest::ObtainRoamCapFromFirmwareFail2()
{
EXPECT_TRUE(pStaAutoConnectService->ObtainRoamCapFromFirmware() == false);
}
void StaAutoConnectServiceTest::SetRoamBlockedBssidFirmwareSuccess()
{
ObtainRoamCapFromFirmwareSuccess();
std::vector<std::string> blockedBssids;
std::string bssid = "2a:76:93:47:e2:8a";
blockedBssids.push_back(bssid);
pStaAutoConnectService->SetRoamBlockedBssidFirmware(blockedBssids);
}
void StaAutoConnectServiceTest::SetRoamBlockedBssidFirmwareFail1()
{
std::vector<std::string> blockedBssids;
std::string bssid = "2a:76:93:47:e2:8a";
blockedBssids.push_back(bssid);
EXPECT_TRUE(pStaAutoConnectService->SetRoamBlockedBssidFirmware(blockedBssids) == false);
}
void StaAutoConnectServiceTest::SetRoamBlockedBssidFirmwareFail2()
{
ObtainRoamCapFromFirmwareSuccess();
std::vector<std::string> blockedBssids = {}; // NULL
EXPECT_TRUE(pStaAutoConnectService->SetRoamBlockedBssidFirmware(blockedBssids) == false);
}
void StaAutoConnectServiceTest::SetRoamBlockedBssidFirmwareFail3()
{
ObtainRoamCapFromFirmwareSuccess();
std::vector<std::string> blockedBssids;
std::string bssid1 = "2a:76:93:47:e2:8a";
std::string bssid2 = "2a:76:93:47:e2:8a";
std::string bssid3 = "2a:76:93:47:e2:8a";
blockedBssids.push_back(bssid1);
blockedBssids.push_back(bssid2);
blockedBssids.push_back(bssid3);
EXPECT_TRUE(pStaAutoConnectService->SetRoamBlockedBssidFirmware(blockedBssids) == false);
}
void StaAutoConnectServiceTest::SetRoamBlockedBssidFirmwareFail4()
{
ObtainRoamCapFromFirmwareSuccess();
std::vector<std::string> blockedBssids;
std::string bssid1 = "2a:76:93:47:e2:8a";
blockedBssids.push_back(bssid1);
EXPECT_TRUE(pStaAutoConnectService->SetRoamBlockedBssidFirmware(blockedBssids) == false);
}
void StaAutoConnectServiceTest::ConnectElectedDeviceSuccess1()
{
WifiLinkedInfo info;
WifiDeviceConfig deviceConfig;
GetWifiLinkedInfo(info);
GetWifiDeviceConfig(deviceConfig);
info.connState = ConnState::CONNECTED;
info.bssid = "2a:76:93:47:e2:8b";
deviceConfig.networkId = INVALID_NETWORK_ID;
EXPECT_CALL(WifiConfigCenter::GetInstance(), GetLinkedInfo(_, _)).WillOnce(
DoAll(SetArgReferee<0>(info), Return(0)));
pStaAutoConnectService->ConnectElectedDevice(deviceConfig);
}
void StaAutoConnectServiceTest::ConnectElectedDeviceSuccess2()
{
WifiLinkedInfo info;
WifiDeviceConfig deviceConfig;
GetWifiLinkedInfo(info);
GetWifiDeviceConfig(deviceConfig);
info.connState = ConnState::CONNECTED;
info.detailedState = DetailedState::DISCONNECTED;
EXPECT_CALL(WifiConfigCenter::GetInstance(), GetLinkedInfo(_, _)).WillOnce(
DoAll(SetArgReferee<0>(info), Return(0)));
pStaAutoConnectService->ConnectElectedDevice(deviceConfig);
}
void StaAutoConnectServiceTest::ConnectElectedDeviceFail1()
{
WifiLinkedInfo info;
WifiDeviceConfig deviceConfig;
GetWifiLinkedInfo(info);
GetWifiDeviceConfig(deviceConfig);
info.detailedState = DetailedState::INVALID;
EXPECT_CALL(WifiConfigCenter::GetInstance(), GetLinkedInfo(_, _))
.Times(AtLeast(0))
.WillOnce(DoAll(SetArgReferee<0>(info), Return(0)))
.WillRepeatedly(DoAll(SetArgReferee<0>(info), Return(0)));
pStaAutoConnectService->ConnectElectedDevice(deviceConfig);
}
void StaAutoConnectServiceTest::GetAvailableScanInfosSuccess()
{
std::vector<InterScanInfo> availableScanInfos;
@ -1257,25 +1094,6 @@ void StaAutoConnectServiceTest::RoamingSelectionFail4()
EXPECT_TRUE(pStaAutoConnectService->RoamingSelection(deviceConfig, scanInfos, info) == false);
}
void StaAutoConnectServiceTest::SyncBlockedSsidFirmwareSuccess()
{
std::string bssid = "2a:76:93:47:e2:8a";
bool enable = false;
int reason = AP_CANNOT_HANDLE_NEW_STA;
pStaAutoConnectService->AddOrDelBlockedBssids(bssid, enable, reason);
pStaAutoConnectService->ObtainRoamCapFromFirmware();
pStaAutoConnectService->SyncBlockedSsidFirmware();
}
void StaAutoConnectServiceTest::SyncBlockedSsidFirmwareFail()
{
pStaAutoConnectService->ObtainRoamCapFromFirmware();
pStaAutoConnectService->SyncBlockedSsidFirmware();
}
void StaAutoConnectServiceTest::DisableAutoJoinSuccess()
{
std::string conditionName;
@ -1439,86 +1257,6 @@ HWTEST_F(StaAutoConnectServiceTest, RegisterDeviceAppraisalFail2, TestSize.Level
RegisterDeviceAppraisalFail2();
}
HWTEST_F(StaAutoConnectServiceTest, ClearOvertimeBlockedBssidSuccess1, TestSize.Level1)
{
ClearOvertimeBlockedBssidSuccess1();
}
HWTEST_F(StaAutoConnectServiceTest, ClearOvertimeBlockedBssidSuccess2, TestSize.Level1)
{
ClearOvertimeBlockedBssidSuccess2();
}
HWTEST_F(StaAutoConnectServiceTest, GetBlockedBssidsSuccess, TestSize.Level1)
{
GetBlockedBssidsSuccess();
}
HWTEST_F(StaAutoConnectServiceTest, AddOrDelBlockedBssidsSuccess, TestSize.Level1)
{
AddOrDelBlockedBssidsSuccess();
}
HWTEST_F(StaAutoConnectServiceTest, AddOrDelBlockedBssidsFail, TestSize.Level1)
{
AddOrDelBlockedBssidsFail();
}
HWTEST_F(StaAutoConnectServiceTest, ObtainRoamCapFromFirmwareSuccess, TestSize.Level1)
{
ObtainRoamCapFromFirmwareSuccess();
}
HWTEST_F(StaAutoConnectServiceTest, ObtainRoamCapFromFirmwareFail1, TestSize.Level1)
{
ObtainRoamCapFromFirmwareFail1();
}
HWTEST_F(StaAutoConnectServiceTest, ObtainRoamCapFromFirmwareFail2, TestSize.Level1)
{
ObtainRoamCapFromFirmwareFail2();
}
HWTEST_F(StaAutoConnectServiceTest, SetRoamBlockedBssidFirmwareSuccess, TestSize.Level1)
{
SetRoamBlockedBssidFirmwareSuccess();
}
HWTEST_F(StaAutoConnectServiceTest, SetRoamBlockedBssidFirmwareFail1, TestSize.Level1)
{
SetRoamBlockedBssidFirmwareFail1();
}
HWTEST_F(StaAutoConnectServiceTest, SetRoamBlockedBssidFirmwareFail2, TestSize.Level1)
{
SetRoamBlockedBssidFirmwareFail2();
}
HWTEST_F(StaAutoConnectServiceTest, SetRoamBlockedBssidFirmwareFail3, TestSize.Level1)
{
SetRoamBlockedBssidFirmwareFail3();
}
HWTEST_F(StaAutoConnectServiceTest, SetRoamBlockedBssidFirmwareFail4, TestSize.Level1)
{
SetRoamBlockedBssidFirmwareFail4();
}
HWTEST_F(StaAutoConnectServiceTest, ConnectElectedDeviceSuccess1, TestSize.Level1)
{
ConnectElectedDeviceSuccess1();
}
HWTEST_F(StaAutoConnectServiceTest, ConnectElectedDeviceSuccess2, TestSize.Level1)
{
ConnectElectedDeviceSuccess2();
}
HWTEST_F(StaAutoConnectServiceTest, ConnectElectedDeviceFail1, TestSize.Level1)
{
ConnectElectedDeviceFail1();
}
HWTEST_F(StaAutoConnectServiceTest, GetAvailableScanInfosSuccess, TestSize.Level1)
{
GetAvailableScanInfosSuccess();
@ -1675,16 +1413,6 @@ HWTEST_F(StaAutoConnectServiceTest, RoamingSelectionFail4, TestSize.Level1)
RoamingSelectionFail4();
}
HWTEST_F(StaAutoConnectServiceTest, SyncBlockedSsidFirmwareSuccess, TestSize.Level1)
{
SyncBlockedSsidFirmwareSuccess();
}
HWTEST_F(StaAutoConnectServiceTest, SyncBlockedSsidFirmwareFail, TestSize.Level1)
{
SyncBlockedSsidFirmwareFail();
}
HWTEST_F(StaAutoConnectServiceTest, DisableAutoJoinSuccess, TestSize.Level1)
{
DisableAutoJoinSuccess();

View File

@ -71,93 +71,6 @@ public:
StaStateMachine *pStaStateMachine;
};
HWTEST_F(StaAutoConnectServiceTest, GetBlockedBssidsTest01, TestSize.Level1)
{
std::vector<std::string> blockedBssids;
std::string bssid = "2a:76:93:47:e2:8a";
StaAutoConnectService::BlockedBssidInfo status;
pStaAutoConnectService->blockedBssidMap.emplace(bssid, status);
pStaAutoConnectService->GetBlockedBssids(blockedBssids);
}
HWTEST_F(StaAutoConnectServiceTest, ConnectElectedDeviceTest01, TestSize.Level1)
{
WifiDeviceConfig electedDevice;
electedDevice.bssid = {};
pStaAutoConnectService->ConnectElectedDevice(electedDevice);
}
HWTEST_F(StaAutoConnectServiceTest, ConnectElectedDeviceTest02, TestSize.Level1)
{
WifiDeviceConfig electedDevice;
WifiLinkedInfo currentConnectedNetwork;
electedDevice.bssid = "2a:76:93:47:e2:8b";
electedDevice.networkId = INVALID_NETWORK_ID;
electedDevice.ssid = "HMWIFI_W2_EAP_G2_03";
currentConnectedNetwork.connState = ConnState::CONNECTED;
currentConnectedNetwork.ssid = "HMWIFI_W2_EAP_G2_03";
currentConnectedNetwork.bssid = "2a:76:93:47:e2:8a";
pStaAutoConnectService->firmwareRoamFlag = false;
pStaAutoConnectService->ConnectElectedDevice(electedDevice);
}
HWTEST_F(StaAutoConnectServiceTest, SyncBlockedSsidFirmwareTest01, TestSize.Level1)
{
pStaAutoConnectService->firmwareRoamFlag = false;
pStaAutoConnectService->SyncBlockedSsidFirmware();
pStaAutoConnectService->firmwareRoamFlag = true;
pStaAutoConnectService->maxBlockedBssidNum = 1;
std::string bssid = "2a:76:93:47:e2:8a";
std::string bssid2 = "2a:76:93:47:e2:8b";
StaAutoConnectService::BlockedBssidInfo status;
pStaAutoConnectService->blockedBssidMap.emplace(bssid, status);
pStaAutoConnectService->blockedBssidMap.emplace(bssid2, status);
pStaAutoConnectService->SyncBlockedSsidFirmware();
}
HWTEST_F(StaAutoConnectServiceTest, ObtainRoamCapFromFirmwareTest01, TestSize.Level1)
{
MockWifiStaHalInterface::GetInstance().SetRetResult(WIFI_HAL_OPT_OK);
MockWifiStaHalInterface::GetInstance().SetStaCapabilities(WIFI_HAL_OPT_FAILED);
WifiStaHalInterface::GetInstance().mCapability.maxBlocklistSize = 1;
EXPECT_TRUE(pStaAutoConnectService->ObtainRoamCapFromFirmware() == true);
MockWifiStaHalInterface::GetInstance().SetRetResult(WIFI_HAL_OPT_OK);
EXPECT_TRUE(pStaAutoConnectService->ObtainRoamCapFromFirmware() == true);
}
HWTEST_F(StaAutoConnectServiceTest, SetRoamBlockedBssidFirmwareTest01, TestSize.Level1)
{
std::vector<std::string> blockedBssids;
std::string bssid = "2a:76:93:47:e2:8a";
std::string bssid2 = "2a:76:93:47:e2:8b";
blockedBssids.push_back(bssid);
blockedBssids.push_back(bssid2);
pStaAutoConnectService->firmwareRoamFlag = false;
EXPECT_TRUE(pStaAutoConnectService->SetRoamBlockedBssidFirmware(blockedBssids) == false);
pStaAutoConnectService->firmwareRoamFlag = true;
pStaAutoConnectService->maxBlockedBssidNum = 5;
MockWifiStaHalInterface::GetInstance().SetRetResult(WIFI_HAL_OPT_OK);
EXPECT_TRUE(pStaAutoConnectService->SetRoamBlockedBssidFirmware(blockedBssids) == true);
}
HWTEST_F(StaAutoConnectServiceTest, SetRoamBlockedBssidFirmwareTest02, TestSize.Level1)
{
std::vector<std::string> blockedBssids;
std::string bssid = "2a:76:93:47:e2:8a";
std::string bssid2 = "2a:76:93:47:e2:8b";
blockedBssids.push_back(bssid);
blockedBssids.push_back(bssid2);
pStaAutoConnectService->firmwareRoamFlag = true;
pStaAutoConnectService->maxBlockedBssidNum = 5;
MockWifiStaHalInterface::GetInstance().SetRetResult(WIFI_HAL_OPT_FAILED);
EXPECT_TRUE(pStaAutoConnectService->SetRoamBlockedBssidFirmware(blockedBssids) == false);
}
HWTEST_F(StaAutoConnectServiceTest, AutoSelectDeviceTest01, TestSize.Level1)
{
WifiDeviceConfig electedDevice;

View File

@ -34,19 +34,15 @@ ohos_unittest("toolkit_unittest") {
"$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_config_file_spec.cpp",
"$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_scan_config.cpp",
"$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_settings.cpp",
"$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log/log_helper.c",
"$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/arp_checker.cpp",
"$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/base_address.cpp",
"$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/dhcpd_interface.cpp",
"$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/dns_checker.cpp",
"$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/http_request.cpp",
"$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/if_config.cpp",
"$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ip_tools.cpp",
"$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ipv4_address.cpp",
"$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ipv6_address.cpp",
"$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/mac_address.cpp",
"$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/network_interface.cpp",
"$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/raw_socket.cpp",
"$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils/network_parser.cpp",
"$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils/package_parser.cpp",
"$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils/softap_parser.cpp",
@ -60,13 +56,11 @@ ohos_unittest("toolkit_unittest") {
"arp_checker_test.cpp",
"base_address_test.cpp",
"dhcpd_interface_test.cpp",
"http_request_test.cpp",
"if_config_test.cpp",
"ipv4_address_test.cpp",
"mac_address_test.cpp",
"network_interface_test.cpp",
"network_parser_test.cpp",
"raw_socket_test.cpp",
"softap_parser_test.cpp",
"wifi_app_parser_test.cpp",
"wifi_asset_manager_test.cpp",
@ -76,7 +70,6 @@ ohos_unittest("toolkit_unittest") {
"wifi_encryption_util_test.cpp",
"wifi_global_func_test.cpp",
"wifi_ip_tools_test.cpp",
"wifi_log_helper_test.cpp",
"wifi_randommac_helper_test.cpp",
"wifi_settings_test.cpp",
"xml_parser_test.cpp",

View File

@ -14,7 +14,6 @@
*/
#include <gtest/gtest.h>
#include "arp_checker.h"
#include "dns_checker.h"
using namespace testing::ext;
@ -33,18 +32,15 @@ public:
std::string gatewayAddr = "192.168.3.1";
std::string ipAddr = "10.3.1";
pArpChecker = std::make_unique<ArpChecker>();
pDnsChecker = std::make_unique<DnsChecker>();
pArpChecker->Start(ifname, hwAddr, ipAddr, gatewayAddr);
}
virtual void TearDown()
{
pArpChecker.reset();
pDnsChecker.reset();
}
public:
std::unique_ptr<ArpChecker> pArpChecker;
std::unique_ptr<DnsChecker> pDnsChecker;
};
HWTEST_F(ArpCheckerTest, DoArp_FAIL, TestSize.Level1)
@ -55,52 +51,6 @@ HWTEST_F(ArpCheckerTest, DoArp_FAIL, TestSize.Level1)
EXPECT_TRUE(pArpChecker->DoArpCheck(timeoutMillis, isFillSenderIp) == false);
}
HWTEST_F(ArpCheckerTest, Start_FAIL, TestSize.Level1)
{
std::string priDns = "192.168.3.66";
std::string secondDns = "socket";
pDnsChecker->Start(priDns, secondDns);
}
HWTEST_F(ArpCheckerTest, Stop_FAIL, TestSize.Level1)
{
pDnsChecker->Stop();
}
HWTEST_F(ArpCheckerTest, formatHostAdress_Test, TestSize.Level1)
{
char hostAddress[] = "192.168.3.66";
char host[] = "socket";
pDnsChecker->formatHostAdress(hostAddress, host);
EXPECT_NE(pDnsChecker->primaryDnsAddress, "ATEST");
}
HWTEST_F(ArpCheckerTest, DoDnsCheck_Test, TestSize.Level1)
{
std::string hostAddress = "192.168.3.66";
pDnsChecker->DoDnsCheck(hostAddress, 1);
}
HWTEST_F(ArpCheckerTest, recvDnsData_Test, TestSize.Level1)
{
char hostAddress[] = "192.168.3.66";
pDnsChecker->recvDnsData(hostAddress, 1, 0);
}
HWTEST_F(ArpCheckerTest, checkDnsValid_Test, TestSize.Level1)
{
std::string hostAddress = "192.168.3.66";
std::string secondDns = "socket";
pDnsChecker->checkDnsValid(hostAddress, secondDns, 0);
}
HWTEST_F(ArpCheckerTest, recvDnsData01_Test, TestSize.Level1)
{
char hostAddress[] = "192.168.3.66";
pDnsChecker->dnsSocket = -1;
pDnsChecker->recvDnsData(hostAddress, 1, 0);
}
HWTEST_F(ArpCheckerTest, DoArp_FAIL2, TestSize.Level1)
{
int timeoutMillis = 0;
@ -108,24 +58,5 @@ HWTEST_F(ArpCheckerTest, DoArp_FAIL2, TestSize.Level1)
bool isFillSenderIp = false;
EXPECT_TRUE(pArpChecker->DoArpCheck(timeoutMillis, isFillSenderIp) == false);
}
HWTEST_F(ArpCheckerTest, checkDnsValid_FAIL2, TestSize.Level1)
{
std::string hostAddress = "192.168.3.66";
std::string secondDns = "socket";
pDnsChecker->socketCreated = true;
pDnsChecker->checkDnsValid(hostAddress, "", 0);
pDnsChecker->checkDnsValid(hostAddress, secondDns, 0);
}
HWTEST_F(ArpCheckerTest, formatHostAdress_FAIL2, TestSize.Level1)
{
char hostAddress[] = "192.168.3.66";
char host[] = "socket";
pDnsChecker->socketCreated = true;
pDnsChecker->formatHostAdress(hostAddress, nullptr);
pDnsChecker->formatHostAdress(nullptr, host);
EXPECT_NE(pDnsChecker->primaryDnsAddress, "ATEST");
}
} // namespace Wifi
} // namespace OHOS

View File

@ -1,165 +0,0 @@
/*
* Copyright (C) 2023 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 <gtest/gtest.h>
#include <gmock/gmock.h>
#include "securec.h"
#include "http_request.h"
#include "wifi_logger.h"
DEFINE_WIFILOG_DHCP_LABEL("HttpRequestTest");
using namespace testing::ext;
namespace OHOS {
namespace Wifi {
class HttpRequestTest : public testing::Test {
public:
static void SetUpTestCase()
{}
static void TearDownTestCase()
{}
virtual void SetUp()
{
pHttpRequest.reset(new HttpRequest());
}
virtual void TearDown()
{
pHttpRequest.reset();
}
public:
std::unique_ptr<HttpRequest> pHttpRequest;
};
/**
* @tc.name: HttpGet_001
* @tc.desc: test strUrl is empty
* @tc.type: FUNC
* @tc.require: issue
*/
HWTEST_F(HttpRequestTest, HttpGet_001, TestSize.Level1)
{
WIFI_LOGI("HttpGet_001");
std::string strUrl = "";
std::string strResponse = "";
EXPECT_TRUE(pHttpRequest->HttpGet(strUrl, strResponse) == -1);
}
/**
* @tc.name: HttpGet_002
* @tc.desc: test strUrl is over URLSIZE
* @tc.type: FUNC
* @tc.require: issue
*/
HWTEST_F(HttpRequestTest, HttpGet_002, TestSize.Level1)
{
WIFI_LOGI("HttpGet_002");
char str[URLSIZE + 1];
if (memset_s(str, URLSIZE + 1, '*', URLSIZE + 1) != EOK) {
return;
}
std::string url = str;
std::string strResponse = "";
EXPECT_TRUE(pHttpRequest->HttpGet(url, strResponse) == -1);
}
/**
* @tc.name: HttpGet_003
* @tc.desc: test GetHostAddrFromUrl error
* @tc.type: FUNC
* @tc.require: issue
*/
HWTEST_F(HttpRequestTest, HttpGet_003, TestSize.Level1)
{
WIFI_LOGI("HttpGet_003");
std::string strUrl = "https://";
std::string strResponse = "";
EXPECT_TRUE(pHttpRequest->HttpGet(strUrl, strResponse) == -1);
}
/**
* @tc.name: HttpGet_004
* @tc.desc: test GetHostAddrFromUrl error
* @tc.type: FUNC
* @tc.require: issue
*/
HWTEST_F(HttpRequestTest, HttpGet_004, TestSize.Level1)
{
WIFI_LOGI("HttpGet_004");
std::string strUrl = "http://";
std::string strResponse = "";
EXPECT_TRUE(pHttpRequest->HttpGet(strUrl, strResponse) == -1);
}
/**
* @tc.name: HttpGet_005
* @tc.desc: test GetHostAddrFromUrl error
* @tc.type: FUNC
* @tc.require: issue
*/
HWTEST_F(HttpRequestTest, HttpGet_005, TestSize.Level1)
{
WIFI_LOGI("HttpGet_005");
std::string strUrl = "http://192.168.62.0:-10";
std::string strResponse = "";
EXPECT_TRUE(pHttpRequest->HttpGet(strUrl, strResponse) == -1);
}
/**
* @tc.name: HttpGet_006
* @tc.desc: test GetHostAddrFromUrl error
* @tc.type: FUNC
* @tc.require: issue
*/
HWTEST_F(HttpRequestTest, HttpGet_006, TestSize.Level1)
{
WIFI_LOGI("HttpGet_006");
std::string strUrl = "http://:10";
std::string strResponse = "";
EXPECT_TRUE(pHttpRequest->HttpGet(strUrl, strResponse) == -1);
}
/**
* @tc.name: HttpPost_001
* @tc.desc: test GetHostAddrFromUrl error
* @tc.type: FUNC
* @tc.require: issue
*/
HWTEST_F(HttpRequestTest, HttpPost_001, TestSize.Level1)
{
WIFI_LOGI("HttpPost_001");
std::string strUrl = "http://192.168.62.0:10";
std::string strResponse = "";
EXPECT_TRUE(pHttpRequest->HttpPost(strUrl, "", strResponse) == -1);
}
/**
* @tc.name: HttpPost_001
* @tc.desc: test HttpDataTransmit error
* @tc.type: FUNC
* @tc.require: issue
*/
HWTEST_F(HttpRequestTest, HttpDataTransmit_001, TestSize.Level1)
{
WIFI_LOGI("HttpDataTransmit_001");
int iSockFd = 1;
pHttpRequest->httpHead = "Connection: Keep-Alive\r\n";
EXPECT_TRUE(pHttpRequest->HttpDataTransmit(iSockFd) == -1);
}
/**
* @tc.name: GetIPFromUrl_001
* @tc.desc: test GetIPFromUrl error
* @tc.type: FUNC
* @tc.require: issue
*/
HWTEST_F(HttpRequestTest, GetIPFromUrl_001, TestSize.Level1)
{
WIFI_LOGI("GetIPFromUrl_001");
pHttpRequest->strHost = "Connection: Keep-Alive\r\n";
pHttpRequest->GetIPFromUrl();
}
} // namespace Wifi
} // namespace OHOS

View File

@ -1,110 +0,0 @@
/*
* Copyright (C) 2023 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 <gtest/gtest.h>
#include "raw_socket.h"
using namespace testing::ext;
namespace OHOS {
namespace Wifi {
uint8_t NUMBLE = 10;
uint8_t SIZE = 1;
class RawSocketTest : public testing::Test {
public:
static void SetUpTestCase()
{}
static void TearDownTestCase()
{}
virtual void SetUp()
{
pRawSocket.reset(new RawSocket());
}
virtual void TearDown()
{
pRawSocket.reset();
}
public:
std::unique_ptr<RawSocket> pRawSocket;
};
HWTEST_F(RawSocketTest, CreateSocket_Fail1, TestSize.Level1)
{
char *iface = nullptr;
uint16_t protocol = 0;
EXPECT_TRUE(pRawSocket->CreateSocket(iface, protocol) == -1);
}
HWTEST_F(RawSocketTest, CreateSocket_Fail2, TestSize.Level1)
{
char iface[] = "config";
uint16_t protocol = 0;
EXPECT_TRUE(pRawSocket->CreateSocket(iface, protocol) == -1);
}
HWTEST_F(RawSocketTest, Send_Fail1, TestSize.Level1)
{
uint8_t *buff = nullptr;
int count = 10;
uint8_t *destHwaddr = nullptr;
EXPECT_TRUE(pRawSocket->Send(buff, count, destHwaddr) == -1);
}
HWTEST_F(RawSocketTest, Send_Fail2, TestSize.Level1)
{
uint8_t *buff = &NUMBLE;
int count = 10;
uint8_t *destHwaddr = &SIZE;
pRawSocket->Close();
EXPECT_TRUE(pRawSocket->Send(buff, count, destHwaddr) == -1);
}
HWTEST_F(RawSocketTest, Recv_Fail, TestSize.Level1)
{
uint8_t *buff = &NUMBLE;
int count = 10;
int timeoutMillis = 10;
EXPECT_TRUE(pRawSocket->Recv(buff, count, timeoutMillis) == 0);
}
HWTEST_F(RawSocketTest, Close_Success, TestSize.Level1)
{
EXPECT_TRUE(pRawSocket->Close() == -1);
}
HWTEST_F(RawSocketTest, Send_Fail3, TestSize.Level1)
{
uint8_t *buff = &NUMBLE;
int count = 10;
uint8_t *destHwaddr = nullptr;
EXPECT_TRUE(pRawSocket->Send(buff, count, destHwaddr) == -1);
}
HWTEST_F(RawSocketTest, Send_Fail4, TestSize.Level1)
{
uint8_t *buff = &NUMBLE;
int count = 10;
uint8_t *destHwaddr = nullptr;
EXPECT_TRUE(pRawSocket->Send(buff, count, destHwaddr) == -1);
}
HWTEST_F(RawSocketTest, SetNonBlock_Test, TestSize.Level1)
{
EXPECT_FALSE(pRawSocket->SetNonBlock(1));
}
} // namespace Wifi
} // namespace OHOS

View File

@ -1,49 +0,0 @@
/*
* 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_log_helper_test.h"
#include "log_helper.h"
using namespace testing::ext;
namespace OHOS {
namespace Wifi {
HWTEST_F(WifiLogHelperTest, EncryptLogMsgTest, TestSize.Level1)
{
char msg[32] = {0};
EncryptLogMsg("", msg, sizeof(msg));
EXPECT_TRUE(msg == std::string(""));
EncryptLogMsg("a", msg, sizeof(msg));
EXPECT_TRUE(msg == std::string("*"));
EncryptLogMsg("ab", msg, sizeof(msg));
EXPECT_TRUE(msg == std::string("**"));
EncryptLogMsg("abc", msg, sizeof(msg));
EXPECT_TRUE(msg == std::string("a*c"));
EncryptLogMsg("abcd", msg, sizeof(msg));
EXPECT_TRUE(msg == std::string("a**d"));
EncryptLogMsg("abcde", msg, sizeof(msg));
EXPECT_TRUE(msg == std::string("ab*de"));
EncryptLogMsg("abcdef", msg, sizeof(msg));
EXPECT_TRUE(msg == std::string("ab**ef"));
EncryptLogMsg("abcdefg", msg, sizeof(msg));
EXPECT_TRUE(msg == std::string("abc*efg"));
EncryptLogMsg("abcdefgh", msg, sizeof(msg));
EXPECT_TRUE(msg == std::string("abc**fgh"));
EncryptLogMsg("abcdefghi", msg, sizeof(msg));
EXPECT_TRUE(msg == std::string("abc***ghi"));
EncryptLogMsg("abcdefghij", msg, sizeof(msg));
EXPECT_TRUE(msg == std::string("abc****hij"));
}
} // namespace Wifi
} // namespace OHOS

View File

@ -1,37 +0,0 @@
/*
* 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_LOG_HELPER_TEST_H
#define OHOS_WIFI_LOG_HELPER_TEST_H
#include <gtest/gtest.h>
namespace OHOS {
namespace Wifi {
class WifiLogHelperTest : public testing::Test {
public:
static void SetUpTestCase()
{}
static void TearDownTestCase()
{}
virtual void SetUp()
{}
virtual void TearDown()
{}
public:
};
} // namespace Wifi
} // namespace OHOS
#endif