!155 feat(*): add WiFi dump feature

Merge pull request !155 from Zhangfeng/br1
This commit is contained in:
openharmony_ci 2021-11-20 10:43:31 +00:00 committed by Gitee
commit 2180868694
22 changed files with 780 additions and 85 deletions

View File

@ -32,8 +32,11 @@ The WLAN module provides basic WLAN functions, peer-to-peer \(P2P\) connection,
│   └── kits # WLAN APIs
├── services # Services
│   └── wifi_standard # Service implementation
└── tests # Test code
└── wifi_standard # Test code for the service implementation module
├── tests # Test code
│   └── wifi_standard # Test code for the service implementation module
└── utils # Utility functions
├── inc # Header directory for utility functions
└── src # Implementation directory for utility functions
```
## Usage<a name="section1312121216216"></a>

View File

@ -32,8 +32,11 @@ WLAN组件子系统为用户提供WLAN基础功能、P2Ppeer-to-peer功能
│   └── kits # WLAN组件接口的适配代码存放目录
├── services # service适配目录
│   └── wifi_standard # service实现目录
└── tests # 测试代码目录
└── wifi_standard # service实现模块测试代码
├── tests # 测试代码目录
│   └── wifi_standard # service实现模块测试代码
└── utils # 实用函数目录
├── inc # 实用函数头文件目录
└── src # 实用函数实现目录
```
## 说明<a name="section1312121216216"></a>

View File

@ -104,7 +104,10 @@ ohos_source_set("wifi_p2p_proxy_impl") {
ohos_shared_library("wifi_sdk") {
install_enable = true
include_dirs = [ "//foundation/communication/wifi/interfaces/innerkits" ]
include_dirs = [
"//foundation/communication/wifi/interfaces/innerkits",
"//foundation/communication/wifi/utils/inc",
]
sources = [
"c_adapter/wifi_c_device.cpp",
@ -132,6 +135,7 @@ ohos_shared_library("wifi_sdk") {
"//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/communication/wifi/utils/src:wifi_utils",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//third_party/bounds_checking_function:libsec_static",
"//utils/native/base:utils",

View File

@ -20,7 +20,7 @@
#include "native_c/wifi_device_config.h"
#include "wifi_logger.h"
#include "wifi_c_utils.h"
#include "securec.h"
#include "wifi_common_util.h"
DEFINE_WIFILOG_LABEL("WifiCDevice");

View File

@ -19,8 +19,8 @@
#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"
#include "wifi_common_util.h"
DEFINE_WIFILOG_LABEL("WifiCHotspot");

View File

@ -15,7 +15,6 @@
#include "wifi_c_utils.h"
#include <map>
#include <sstream>
namespace OHOS {
namespace Wifi {
@ -42,77 +41,5 @@ WifiErrorCode GetCErrorCode(ErrCode errCode)
std::map<ErrCode, WifiErrorCode>::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

View File

@ -19,7 +19,6 @@
#include <string>
#include "native_c/wifi_device_config.h"
#include "native_c/wifi_error_code.h"
#include "securec.h"
#include "wifi_errcode.h"
namespace OHOS {
@ -33,9 +32,6 @@ namespace Wifi {
#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

View File

@ -63,6 +63,18 @@
}
}
],
"wifi_utils": [
{
"type": "so",
"name": "//foundation/communication/wifi/utils/src:wifi_utils",
"header": {
"header_files": [
"wifi_common_util.h"
],
"header_base": "//foundation/communication/wifi/utils/inc/"
}
}
],
"test_list": [
"//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan:unittest",
"//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta:unittest",

View File

@ -42,6 +42,7 @@ config("wifi_manager_service_header") {
"//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p",
"//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",
"//foundation/communication/wifi/utils/inc",
"${aafwk_path}/interfaces/innerkits/want/include",
"${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content",
"//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include",
@ -143,6 +144,7 @@ ohos_shared_library("wifi_manager_service") {
"//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_utils.cpp",
"wifi_auth_center.cpp",
"wifi_config_center.cpp",
"wifi_dumper.cpp",
"wifi_internal_event_dispatcher.cpp",
"wifi_manager.cpp",
"wifi_service_manager.cpp",
@ -177,6 +179,7 @@ ohos_shared_library("wifi_device_ability") {
":wifi_manager_service",
"//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog",
"//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client",
"//foundation/communication/wifi/utils/src:wifi_utils",
"//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//utils/native/base:utils",
]
@ -206,6 +209,7 @@ ohos_shared_library("wifi_hotspot_ability") {
":wifi_hotspot_service_impl",
":wifi_manager_service",
"//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog",
"//foundation/communication/wifi/utils/src:wifi_utils",
"//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//utils/native/base:utils",
]

View File

@ -15,6 +15,7 @@
#include "wifi_device_service_impl.h"
#include <unistd.h>
#include <file_ex.h>
#include "wifi_permission_utils.h"
#include "wifi_internal_msg.h"
#include "wifi_auth_center.h"
@ -25,6 +26,8 @@
#include "wifi_protect_manager.h"
#include "wifi_logger.h"
#include "define.h"
#include "wifi_dumper.h"
#include "wifi_common_util.h"
DEFINE_WIFILOG_LABEL("WifiDeviceServiceImpl");
namespace OHOS {
@ -667,5 +670,78 @@ bool WifiDeviceServiceImpl::IsScanServiceRunning()
}
return true;
}
void WifiDeviceServiceImpl::SaBasicDump(std::string& result)
{
WifiDeviceServiceImpl impl;
bool isActive = impl.IsStaServiceRunning();
result.append("WiFi active state: ");
std::string strActive = isActive ? "activated" : "inactive";
result += strActive + "\n\n";
WifiLinkedInfo linkedInfo;
WifiConfigCenter::GetInstance().GetLinkedInfo(linkedInfo);
bool isConnected = linkedInfo.connState == ConnState::CONNECTED;
result.append("WiFi connection status: ");
std::string strIsConnected = isConnected ? "connected" : "not connected";
result += strIsConnected + "\n";
if (isConnected) {
std::stringstream ss;
ss << " Connection.ssid: " << linkedInfo.ssid << "\n";
ss << " Connection.bssid: " << MacAnonymize(linkedInfo.bssid) << "\n";
ss << " Connection.rssi: " << linkedInfo.rssi << "\n";
enum {BAND_2GHZ = 1, BAND_5GHZ = 2, BAND_ANY = 3};
auto funcStrBand = [](int band) {
std::string retStr;
switch (band) {
case BAND_2GHZ:
retStr = "2.4GHz";
break;
case BAND_5GHZ:
retStr = "5GHz";
break;
case BAND_ANY:
retStr = "dual-mode frequency band";
break;
default:
retStr = "unknown band";
}
return retStr;
};
ss << " Connection.band: " << funcStrBand(linkedInfo.band) << "\n";
ss << " Connection.frequency: " << linkedInfo.frequency << "\n";
ss << " Connection.linkSpeed: " << linkedInfo.linkSpeed << "\n";
ss << " Connection.macAddress: " << MacAnonymize(linkedInfo.macAddress) << "\n";
ss << " Connection.isHiddenSSID: " << (linkedInfo.ifHiddenSSID ? "true" : "false") << "\n";
int level = WifiConfigCenter::GetInstance().GetSignalLevel(linkedInfo.rssi, linkedInfo.band);
ss << " Connection.signalLevel: " << level << "\n";
result += ss.str();
}
result += "\n";
std::string cc;
WifiConfigCenter::GetInstance().GetCountryCode(cc);
result.append("Country Code: ").append(cc);
result += "\n";
}
int32_t WifiDeviceServiceImpl::Dump(int32_t fd, const std::vector<std::u16string>& args)
{
std::vector<std::string> vecArgs;
std::transform(args.begin(), args.end(), std::back_inserter(vecArgs), [](const std::u16string &arg) {
return Str16ToStr8(arg);
});
WifiDumper dumper;
std::string result;
dumper.DeviceDump(SaBasicDump, vecArgs, result);
if (!SaveStringToFd(fd, result)) {
WIFI_LOGE("WiFi device save string to fd failed.");
return ERR_OK;
}
return ERR_OK;
}
} // namespace Wifi
} // namespace OHOS

View File

@ -95,11 +95,14 @@ public:
ErrCode GetDeviceMacAddress(std::string &result) override;
int32_t Dump(int32_t fd, const std::vector<std::u16string>& args) override;
private:
bool Init();
ErrCode CheckCanEnableWifi(void);
bool IsStaServiceRunning();
bool IsScanServiceRunning();
static void SaBasicDump(std::string& result);
private:
static sptr<WifiDeviceServiceImpl> g_instance;

View File

@ -0,0 +1,126 @@
/*
* 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_dumper.h"
#include <functional>
#include "wifi_logger.h"
DEFINE_WIFILOG_LABEL("WifiDumper");
namespace OHOS {
namespace Wifi {
const std::string ARGS_HELP = "-h";
void WifiDumper::PrintArgs(const std::vector<std::string>& vecArgs)
{
std::string strArgs;
for (auto& each: vecArgs) {
strArgs += each + "|";
}
WIFI_LOGD("Dumper[%{public}zu] args: %{public}s", vecArgs.size(), strArgs.c_str());
}
std::string WifiDumper::ShowDeviceDumpUsage() const
{
std::string help;
return help.append("WiFi device dump options:\n")
.append(" [-h]\n")
.append(" description of the cmd option:\n")
.append(" -h: show help.\n");
}
bool WifiDumper::DeviceDump(std::function<void(std::string&)> saBasicDumpFunc,
const std::vector<std::string>& vecArgs, std::string& result)
{
PrintArgs(vecArgs);
result.clear();
if (!vecArgs.empty() && vecArgs[0] == ARGS_HELP) {
result = ShowDeviceDumpUsage();
return true;
}
saBasicDumpFunc(result);
return true;
}
std::string WifiDumper::ShowScanDumpUsage() const
{
std::string help;
return help.append("WiFi scan dump options:\n")
.append(" [-h]\n")
.append(" description of the cmd option:\n")
.append(" -h: show help.\n");
}
bool WifiDumper::ScanDump(std::function<void(std::string&)> saBasicDumpFunc,
const std::vector<std::string>& vecArgs, std::string& result)
{
PrintArgs(vecArgs);
result.clear();
if (!vecArgs.empty() && vecArgs[0] == ARGS_HELP) {
result = ShowScanDumpUsage();
return true;
}
saBasicDumpFunc(result);
return true;
}
std::string WifiDumper::ShowP2pDumpUsage() const
{
std::string help;
return help.append("WiFi P2P dump options:\n")
.append(" [-h]\n")
.append(" description of the cmd option:\n")
.append(" -h: show help.\n");
}
bool WifiDumper::P2pDump(std::function<void(std::string&)> saBasicDumpFunc,
const std::vector<std::string>& vecArgs, std::string& result)
{
PrintArgs(vecArgs);
result.clear();
if (!vecArgs.empty() && vecArgs[0] == ARGS_HELP) {
result = ShowP2pDumpUsage();
return true;
}
saBasicDumpFunc(result);
return true;
}
std::string WifiDumper::ShowHotspotDumpUsage() const
{
std::string help;
return help.append("WiFi hotspot dump options:\n")
.append(" [-h]\n")
.append(" description of the cmd option:\n")
.append(" -h: show help.\n");
}
bool WifiDumper::HotspotDump(std::function<void(std::string&)> saBasicDumpFunc,
const std::vector<std::string>& vecArgs, std::string& result)
{
PrintArgs(vecArgs);
result.clear();
if (!vecArgs.empty() && vecArgs[0] == ARGS_HELP) {
result = ShowHotspotDumpUsage();
return true;
}
saBasicDumpFunc(result);
return true;
}
} // namespace Wifi
} // namespace OHOS

View File

@ -0,0 +1,47 @@
/*
* 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_DUMPER_H
#define OHOS_WIFI_DUMPER_H
#include <vector>
#include <string>
namespace OHOS {
namespace Wifi {
class WifiDumper {
public:
bool DeviceDump(std::function<void(std::string&)> saBasicDumpFunc,
const std::vector<std::string> &vecArgs, std::string &result);
bool ScanDump(std::function<void(std::string&)> saBasicDumpFunc,
const std::vector<std::string> &vecArgs, std::string &result);
bool P2pDump(std::function<void(std::string&)> saBasicDumpFunc,
const std::vector<std::string> &vecArgs, std::string &result);
bool HotspotDump(std::function<void(std::string&)> saBasicDumpFunc,
const std::vector<std::string> &vecArgs, std::string &result);
private:
std::string ShowDeviceDumpUsage() const;
std::string ShowScanDumpUsage() const;
std::string ShowP2pDumpUsage() const;
std::string ShowHotspotDumpUsage() const;
void PrintArgs(const std::vector<std::string>& vecArgs);
};
} // namespace Wifi
} // namespace OHOS
#endif

View File

@ -14,6 +14,7 @@
*/
#include "wifi_hotspot_service_impl.h"
#include <file_ex.h>
#include "wifi_permission_utils.h"
#include "wifi_global_func.h"
#include "wifi_auth_center.h"
@ -24,6 +25,8 @@
#include "wifi_logger.h"
#include "define.h"
#include "wifi_logger.h"
#include "wifi_dumper.h"
#include "wifi_common_util.h"
DEFINE_WIFILOG_HOTSPOT_LABEL("WifiHotspotServiceImpl");
@ -433,7 +436,7 @@ ErrCode WifiHotspotServiceImpl::GetBlockLists(std::vector<StationInfo> &infos)
}
if (WifiConfigCenter::GetInstance().GetBlockLists(infos) < 0) {
WIFI_LOGE("Delete block list failed!");
WIFI_LOGE("Get block list failed!");
return WIFI_OPT_FAILED;
}
return WIFI_OPT_SUCCESS;
@ -473,5 +476,119 @@ ErrCode WifiHotspotServiceImpl::GetSupportedFeatures(long &features)
}
return WIFI_OPT_SUCCESS;
}
void WifiHotspotServiceImpl::ConfigInfoDump(std::string& result)
{
HotspotConfig config;
WifiConfigCenter::GetInstance().GetHotspotConfig(config);
std::stringstream ss;
ss << "Hotspot config: " << "\n";
ss << " Config.ssid: " << config.GetSsid() << "\n";
std::map<KeyMgmt, std::string> mapKeyMgmtToStr = {
{KeyMgmt::NONE, "Open"}, {KeyMgmt::WPA_PSK, "WPA_PSK"}, {KeyMgmt::WPA_EAP, "WPA_EAP"},
{KeyMgmt::IEEE8021X, "IEEE8021X"}, {KeyMgmt::WPA2_PSK, "WPA2_PSK"}, {KeyMgmt::OSEN, "OSEN"},
{KeyMgmt::FT_PSK, "FT_PSK"}, {KeyMgmt::FT_EAP, "FT_EAP"}
};
auto funcStrKeyMgmt = [&mapKeyMgmtToStr](KeyMgmt secType) {
std::map<KeyMgmt, std::string>::iterator iter = mapKeyMgmtToStr.find(secType);
return (iter != mapKeyMgmtToStr.end()) ? iter->second : "Unknow";
};
ss << " Config.security_type: " << funcStrKeyMgmt(config.GetSecurityType()) << "\n";
auto funcStrBand = [](BandType band) {
std::string retStr;
switch (band) {
case BandType::BAND_2GHZ:
retStr = "2.4GHz";
break;
case BandType::BAND_5GHZ:
retStr = "5GHz";
break;
case BandType::BAND_ANY:
retStr = "dual-mode frequency band";
break;
default:
retStr = "unknown band";
}
return retStr;
};
ss << " Config.band: " << funcStrBand(config.GetBand()) << "\n";
ss << " Config.channel: " << config.GetChannel() << "\n";
ss << " Config.max_conn: " << config.GetMaxConn() << "\n";
result += "\n";
result += ss.str();
result += "\n";
}
void WifiHotspotServiceImpl::StationsInfoDump(std::string& result)
{
IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst();
if (pService != nullptr) {
std::stringstream ss;
std::vector<StationInfo> vecStations;
pService->GetStationList(vecStations);
ss << "Station list size: " << vecStations.size() << "\n";
int idx = 0;
for (auto& each : vecStations) {
++idx;
ss << " Station[" << idx << "].deviceName: " << each.deviceName << "\n";
ss << " Station[" << idx << "].bssid: " << MacAnonymize(each.bssid) << "\n";
ss << " Station[" << idx << "].ipAddr: " << IpAnonymize(each.ipAddr) << "\n";
ss << "\n";
}
result += ss.str();
result += "\n";
}
std::vector<StationInfo> vecBlockStations;
WifiConfigCenter::GetInstance().GetBlockLists(vecBlockStations);
if (!vecBlockStations.empty()) {
std::stringstream ss;
ss << "Block station list size: " << vecBlockStations.size() << "\n";
int idx = 0;
for (auto& each : vecBlockStations) {
++idx;
ss << " BlockStation[" << idx << "].deviceName: " << each.deviceName << "\n";
ss << " BlockStation[" << idx << "].bssid: " << MacAnonymize(each.bssid) << "\n";
ss << " BlockStation[" << idx << "].ipAddr: " << IpAnonymize(each.ipAddr) << "\n";
ss << "\n";
}
result += ss.str();
result += "\n";
}
}
void WifiHotspotServiceImpl::SaBasicDump(std::string& result)
{
WifiHotspotServiceImpl impl;
bool isActive = impl.IsApServiceRunning();
result.append("WiFi hotspot active state: ");
std::string strActive = isActive ? "activated" : "inactive";
result += strActive + "\n";
if (isActive) {
ConfigInfoDump(result);
StationsInfoDump(result);
}
}
int32_t WifiHotspotServiceImpl::Dump(int32_t fd, const std::vector<std::u16string>& args)
{
std::vector<std::string> vecArgs;
std::transform(args.begin(), args.end(), std::back_inserter(vecArgs), [](const std::u16string &arg) {
return Str16ToStr8(arg);
});
WifiDumper dumper;
std::string result;
dumper.HotspotDump(SaBasicDump, vecArgs, result);
if (!SaveStringToFd(fd, result)) {
WIFI_LOGE("WiFi hotspot save string to fd failed.");
return ERR_OK;
}
return ERR_OK;
}
} // namespace Wifi
} // namespace OHOS

View File

@ -158,10 +158,22 @@ public:
*/
ErrCode GetSupportedFeatures(long &features) override;
/**
* @Description dump p2p information
*
* @param fd - file descriptor
* @param args - dump arguments
* @return ErrCode - operate result
*/
int32_t Dump(int32_t fd, const std::vector<std::u16string>& args) override;
private:
bool Init();
ErrCode CheckCanEnableHotspot(void);
bool IsApServiceRunning();
static void SaBasicDump(std::string& result);
static void ConfigInfoDump(std::string& result);
static void StationsInfoDump(std::string& result);
private:
static sptr<WifiHotspotServiceImpl> g_instance;

View File

@ -13,6 +13,7 @@
* limitations under the License.
*/
#include "wifi_p2p_service_impl.h"
#include <file_ex.h>
#include "wifi_permission_utils.h"
#include "wifi_auth_center.h"
#include "wifi_config_center.h"
@ -21,6 +22,7 @@
#include "wifi_internal_event_dispatcher.h"
#include "wifi_logger.h"
#include "define.h"
#include "wifi_dumper.h"
DEFINE_WIFILOG_P2P_LABEL("WifiP2pServiceImpl");
@ -624,6 +626,7 @@ ErrCode WifiP2pServiceImpl::SetP2pDeviceName(const std::string &deviceName)
}
return pService->SetP2pDeviceName(deviceName);
}
ErrCode WifiP2pServiceImpl::SetP2pWfdInfo(const WifiP2pWfdInfo &wfdInfo)
{
WIFI_LOGI("SetP2pWfdInfo");
@ -638,5 +641,31 @@ ErrCode WifiP2pServiceImpl::SetP2pWfdInfo(const WifiP2pWfdInfo &wfdInfo)
}
return pService->SetP2pWfdInfo(wfdInfo);
}
void WifiP2pServiceImpl::SaBasicDump(std::string& result)
{
result.append("P2P enable status: ");
int status = WifiConfigCenter::GetInstance().GetP2pState();
std::string strStatus = (status == static_cast<int>(P2pState::P2P_STATE_STARTED)) ? "enable" : "disable";
result.append(strStatus);
result += "\n";
}
int32_t WifiP2pServiceImpl::Dump(int32_t fd, const std::vector<std::u16string>& args)
{
std::vector<std::string> vecArgs;
std::transform(args.begin(), args.end(), std::back_inserter(vecArgs), [](const std::u16string &arg) {
return Str16ToStr8(arg);
});
WifiDumper dumper;
std::string result;
dumper.P2pDump(SaBasicDump, vecArgs, result);
if (!SaveStringToFd(fd, result)) {
WIFI_LOGE("WiFi P2p save string to fd failed.");
return ERR_OK;
}
return ERR_OK;
}
} // namespace Wifi
} // namespace OHOS

View File

@ -254,10 +254,20 @@ public:
*/
ErrCode SetP2pWfdInfo(const WifiP2pWfdInfo &wfdInfo) override;
/**
* @Description dump p2p information
*
* @param fd - file descriptor
* @param args - dump arguments
* @return ErrCode - operate result
*/
int32_t Dump(int32_t fd, const std::vector<std::u16string>& args) override;
private:
bool Init();
ErrCode CheckCanEnableP2p(void);
bool IsP2pServiceRunning();
static void SaBasicDump(std::string& result);
private:
static sptr<WifiP2pServiceImpl> instance;

View File

@ -14,6 +14,7 @@
*/
#include "wifi_scan_service_impl.h"
#include <file_ex.h>
#include "wifi_msg.h"
#include "permission_def.h"
#include "wifi_permission_utils.h"
@ -26,6 +27,7 @@
#include "wifi_logger.h"
#include "define.h"
#include "wifi_scan_callback_proxy.h"
#include "wifi_dumper.h"
DEFINE_WIFILOG_SCAN_LABEL("WifiScanServiceImpl");
namespace OHOS {
@ -205,5 +207,31 @@ bool WifiScanServiceImpl::IsScanServiceRunning()
}
return true;
}
void WifiScanServiceImpl::SaBasicDump(std::string& result)
{
WifiScanServiceImpl impl;
bool isRunning = impl.IsScanServiceRunning();
result.append("Is scan service running: ");
std::string strRunning = isRunning ? "true" : "false";
result += strRunning + "\n";
}
int32_t WifiScanServiceImpl::Dump(int32_t fd, const std::vector<std::u16string>& args)
{
std::vector<std::string> vecArgs;
std::transform(args.begin(), args.end(), std::back_inserter(vecArgs), [](const std::u16string &arg) {
return Str16ToStr8(arg);
});
WifiDumper dumper;
std::string result;
dumper.ScanDump(SaBasicDump, vecArgs, result);
if (!SaveStringToFd(fd, result)) {
WIFI_LOGE("WiFi scan save string to fd failed.");
return ERR_OK;
}
return ERR_OK;
}
} // namespace Wifi
} // namespace OHOS

View File

@ -45,10 +45,12 @@ public:
ErrCode GetScanInfoList(std::vector<WifiScanInfo> &result) override;
ErrCode RegisterCallBack(const sptr<IWifiScanCallback> &callback) override;
ErrCode GetSupportedFeatures(long &features) override;
int32_t Dump(int32_t fd, const std::vector<std::u16string>& args) override;
private:
bool Init();
bool IsScanServiceRunning();
static void SaBasicDump(std::string& result);
private:
static sptr<WifiScanServiceImpl> g_instance;

90
utils/inc/wifi_common_util.h Executable file
View File

@ -0,0 +1,90 @@
/*
* 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_COMMON_UTIL_H
#define OHOS_WIFI_COMMON_UTIL_H
#include <string>
#include "securec.h"
#ifndef WIFI_MAC_LEN
#define WIFI_MAC_LEN 6
#endif
namespace OHOS {
namespace Wifi {
/**
* @Description MAC address anonymization
*
* <p> eg: a2:7c:b0:98:e3:92 -> a2:7c:**:**:**:92
*
* @param str - Input MAC address
* @return std::string - Processed MAC
*/
std::string MacAnonymize(const std::string str);
/**
* @Description MAC address anonymization
*
* <p> eg: 192.168.0.1 -> 192.***.*.1
*
* @param str - Input MAC address
* @return std::string - Processed MAC
*/
std::string IpAnonymize(const std::string str);
/**
* @Description Converting string MAC to a C-style MAC address
*
* @param strMac - Input MAC address
* @param mac - conversion result
* @return errno_t - EOK for success, failure for other values.
*/
errno_t MacStrToArray(const std::string& strMac, unsigned char mac[WIFI_MAC_LEN]);
/**
* @Description Converting C-style MAC to a string MAC
*
* @param mac - Input MAC address
* @return string - conversion result.
*/
std::string MacArrayToStr(const unsigned char mac[WIFI_MAC_LEN]);
/**
* @Description Check whether the array of MAC address is empty
*
* @param mac - Input MAC address
* @return bool - true: empty, false: not empty
*/
bool IsMacArrayEmpty(const unsigned char mac[WIFI_MAC_LEN]);
/**
* @Description Converting a string IP Address to an integer IP address
*
* @param strIp - Input string IP address
* @return int - integer IP address
*/
int Ip2Number(const std::string& strIp);
/**
* @Description Converting an integer IP address to a string IP Address
*
* @param intIp - Input integer IP address
* @return string - string IP address
*/
std::string Number2Ip(int intIp);
} // namespace Wifi
} // namespace OHOS
#endif

38
utils/src/BUILD.gn Executable file
View File

@ -0,0 +1,38 @@
# 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_shared_library("wifi_utils") {
install_enable = true
include_dirs = [
"//foundation/communication/wifi/utils/inc",
"//utils/native/base/include",
]
sources = [ "wifi_common_util.cpp" ]
deps = [ "//utils/native/base:utils" ]
cflags_cc = [
"-std=c++17",
"-fno-rtti",
]
ldflags = [
"-fPIC",
"-Wl,-E",
]
part_name = "wifi_standard"
subsystem_name = "communication"
}

168
utils/src/wifi_common_util.cpp Executable file
View File

@ -0,0 +1,168 @@
/*
* 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_common_util.h"
#include <sstream>
namespace OHOS {
namespace Wifi {
static std::string DataAnonymize(const std::string str, const char delim,
const char hiddenCh, const int startIdx = 0)
{
std::string s = str;
constexpr auto minDelimSize = 2;
constexpr auto minKeepSize = 6;
if (std::count(s.begin(), s.end(), delim) < minDelimSize) {
if (s.size() <= minKeepSize) {
return std::string(s.size(), hiddenCh);
}
auto idx1 = 2;
const auto idx2 = s.size() - 4;
while (idx1++ < idx2) {
s[idx1] = hiddenCh;
}
return s;
}
std::string::size_type begin = s.find_first_of(delim);
std::string::size_type end = s.find_last_of(delim);
int idx = 0;
while (idx++ < startIdx && begin < end) {
begin = s.find_first_of(delim, begin + 1);
}
while (begin++ != end) {
if (s[begin] != delim) {
s[begin] = hiddenCh;
}
}
return s;
}
std::string MacAnonymize(const std::string str)
{
return DataAnonymize(str, ':', '*', 1);
}
std::string IpAnonymize(const std::string str)
{
return DataAnonymize(str, '.', '*');
}
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;
}
int Ip2Number(const std::string& strIp)
{
std::string::size_type front = 0;
std::string::size_type back = 0;
int number = 0;
int size = 32;
constexpr int sectionSize = 8;
std::string ip(strIp + '.');
while ((back = ip.find_first_of('.', back)) != (std::string::size_type)std::string::npos) {
number |= atoi(ip.substr(front, back - front).c_str()) << (size -= sectionSize);
front = ++back;
}
return number;
}
std::string Number2Ip(int intIp)
{
constexpr int fourthPartMoveLen = 24;
constexpr int thirdPartMoveLen = 16;
constexpr int secondPartMoveLen = 8;
std::string ip;
ip.append(std::to_string(((unsigned int)intIp & 0xff000000) >> fourthPartMoveLen));
ip.push_back('.');
ip.append(std::to_string((intIp & 0x00ff0000) >> thirdPartMoveLen));
ip.push_back('.');
ip.append(std::to_string((intIp & 0x0000ff00) >> secondPartMoveLen));
ip.push_back('.');
ip.append(std::to_string(intIp & 0x000000ff));
return ip;
}
} // namespace Wifi
} // namespace OHOS