Merge branch 'master' of gitee.com:openharmony/base_location into master

Signed-off-by: liuxinbing <liuxinbing4@huawei.com>
This commit is contained in:
liuxinbing 2024-07-30 03:40:38 +00:00 committed by Gitee
commit ab9d04445d
17 changed files with 188 additions and 30 deletions

View File

@ -28,6 +28,7 @@
#include "constant_definition.h"
#include "parameter.h"
#include "location_sa_load_manager.h"
#include "hook_utils.h"
#include "accesstoken_kit.h"
#include "os_account_manager.h"
@ -128,7 +129,7 @@ bool CommonUtils::GetCurrentUserId(int &userId)
std::vector<int> activeIds;
int ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeIds);
if (ret != 0) {
LBSLOGE(COMMON_UTILS, "QueryActiveOsAccountIds failed ret:%{public}d", ret);
LBSLOGI(COMMON_UTILS, "GetCurrentUserId failed ret:%{public}d", ret);
return false;
}
if (activeIds.empty()) {
@ -403,6 +404,24 @@ std::string CommonUtils::GenerateUuid()
return ss.str();
}
bool CommonUtils::CheckAppForUser(int32_t uid)
{
int currentUserId = 0;
int userId = 0;
bool ret = GetCurrentUserId(currentUserId);
if (!ret) {
return true;
}
auto result = AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId);
if (result != ERR_OK) {
return true;
}
if (userId != currentUserId) {
return false;
}
return true;
}
int64_t CommonUtils::GetSinceBootTime()
{
int result;

View File

@ -21,9 +21,11 @@
namespace OHOS {
namespace Location {
const int DEFAULT_USERID = 100;
const int DEFAULT_SWITCHMODE = 2;
const int UNKNOW_ERROR = -1;
const int MAX_SIZE = 100;
const char* LOCATION_SWITCH_MODE = "persist.location.switch_mode";
std::mutex LocationDataRdbManager::mutex_;
const std::string LOCATION_ENHANCE_STATUS = "location_enhance_status";
std::string LocationDataRdbManager::GetLocationDataUri(std::string key)
@ -98,6 +100,7 @@ int LocationDataRdbManager::GetSwitchMode()
{
char result[MAX_SIZE] = {0};
std::string value = "";
std::unique_lock<std::mutex> lock(mutex_);
auto res = GetParameter(LOCATION_SWITCH_MODE, "", result, MAX_SIZE);
if (res <= 0 || strlen(result) == 0) {
LBSLOGE(COMMON_UTILS, "%{public}s get para value failed, res: %{public}d", __func__, res);
@ -120,6 +123,7 @@ bool LocationDataRdbManager::SetSwitchMode(int value)
{
char valueArray[MAX_SIZE] = {0};
(void)sprintf_s(valueArray, sizeof(valueArray), "%d", value);
std::unique_lock<std::mutex> lock(mutex_);
int res = SetParameter(LOCATION_SWITCH_MODE, valueArray);
if (res < 0) {
LBSLOGE(COMMON_UTILS, "%{public}s failed, res: %{public}d", __func__, res);
@ -128,6 +132,21 @@ bool LocationDataRdbManager::SetSwitchMode(int value)
return true;
}
bool LocationDataRdbManager::ClearSwitchMode()
{
char valueArray[MAX_SIZE] = {0};
int code = sprintf_s(valueArray, sizeof(valueArray), "%d", DEFAULT_SWITCHMODE);
if (code <= 0) {
return false;
}
std::unique_lock<std::mutex> lock(mutex_);
int res = SetParameter(LOCATION_SWITCH_MODE, valueArray);
if (res < 0) {
return false;
}
return true;
}
bool LocationDataRdbManager::SetLocationEnhanceStatus(int32_t state)
{
Uri locationWorkingStateUri(GetLocationDataSecureUri(LOCATION_ENHANCE_STATUS));

View File

@ -176,7 +176,8 @@ public:
static bool GetStringParameter(const std::string& type, std::string& value);
static bool GetEdmPolicy(std::string& name);
static std::string GenerateUuid();
static int64_t GetSinceBootTime();
static bool CheckAppForUser(int32_t uid);
static int64_t GetSinceBootTime();
};
class CountDownLatch {

View File

@ -17,6 +17,7 @@
#define LOCATION_DATA_RDB_MANAGER_H
#include <unistd.h>
#include <string>
#include <mutex>
#include "constant_definition.h"
@ -35,9 +36,12 @@ public:
static bool GetLocationWorkingState(int32_t& state);
static int GetSwitchMode();
static bool SetSwitchMode(int value);
static bool ClearSwitchMode();
static std::string GetLocationDataSecureUri(std::string key);
static bool SetLocationEnhanceStatus(int32_t state);
static bool GetLocationEnhanceStatus(int32_t& state);
private:
static std::mutex mutex_;
};
} // namespace Location
} // namespace OHOS

View File

@ -20,6 +20,8 @@
"ohos.permission.MANAGE_SECURE_SETTINGS",
"ohos.permission.GET_TELEPHONY_STATE",
"ohos.permission.LOCATION",
"ohos.permission.APPROXIMATELY_LOCATION",
"ohos.permission.LOCATION_IN_BACKGROUND",
"ohos.permission.GET_WIFI_INFO",
"ohos.permission.SET_WIFI_INFO",
"ohos.permission.GET_RUNNING_INFO",

View File

@ -81,7 +81,7 @@ private:
double minLatitude_;
double minLongitude_;
std::string bundleName_;
sptr<IRemoteObject> callback_ = nullptr;
sptr<IRemoteObject> callback_;
std::string transId_;
std::string country_;
GeoCodeType requestType_;

View File

@ -86,6 +86,7 @@ public:
bool ConnectService();
void NotifyConnected(const sptr<IRemoteObject>& remoteObject);
void DisconnectAbilityConnect();
void NotifyDisConnected();
bool ResetServiceProxy();
bool SendGeocodeRequest(int code, MessageParcel& dataParcel, MessageParcel& replyParcel, MessageOption& option);

View File

@ -18,7 +18,23 @@
namespace OHOS {
namespace Location {
GeoConvertRequest::GeoConvertRequest() {}
GeoConvertRequest::GeoConvertRequest()
{
locale_ = "";
latitude_ = 0.0;
longitude_ = 0.0;
maxItems_ = 0;
description_ = "";
maxLatitude_ = 0.0;
maxLongitude_ = 0.0;
minLatitude_ = 0.0;
minLongitude_ = 0.0;
bundleName_ = "";
callback_ = nullptr;
transId_ = "";
country_ = "";
requestType_ = GeoCodeType::REQUEST_GEOCODE;
}
GeoConvertRequest::~GeoConvertRequest() {}

View File

@ -32,7 +32,10 @@ namespace Location {
const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(
GeoConvertService::GetInstance());
const uint32_t EVENT_SEND_GEOREQUEST = 0x0100;
const char* UNLOAD_GEOCONVERT_TASK = "geoconvert_sa_unload";
const int GEOCONVERT_CONNECT_TIME_OUT = 1;
const uint32_t EVENT_INTERVAL_UNITE = 1000;
const int UNLOAD_GEOCONVERT_DELAY_TIME = 5 * EVENT_INTERVAL_UNITE;
GeoConvertService* GeoConvertService::GetInstance()
{
static GeoConvertService data;
@ -48,6 +51,9 @@ GeoConvertService::GeoConvertService() : SystemAbility(LOCATION_GEO_CONVERT_SA_I
GeoConvertService::~GeoConvertService()
{
if (geoConvertHandler_ != nullptr) {
geoConvertHandler_->RemoveTask(UNLOAD_GEOCONVERT_TASK);
}
conn_ = nullptr;
}
@ -320,8 +326,26 @@ bool GeoConvertService::CancelIdleState()
void GeoConvertService::UnloadGeoConvertSystemAbility()
{
if (!CheckIfGeoConvertConnecting()) {
if (geoConvertHandler_ == nullptr) {
LBSLOGE(GEO_CONVERT, "%{public}s geoConvertHandler_ is nullptr", __func__);
return;
}
geoConvertHandler_->RemoveTask(UNLOAD_GEOCONVERT_TASK);
if (CheckIfGeoConvertConnecting()) {
return;
}
auto task = [this]() {
LocationSaLoadManager::UnInitLocationSa(LOCATION_GEO_CONVERT_SA_ID);
GeoConvertService::GetInstance()->DisconnectAbilityConnect();
};
geoConvertHandler_->PostTask(task, UNLOAD_GEOCONVERT_TASK, UNLOAD_GEOCONVERT_DELAY_TIME);
}
void GeoConvertService::DisconnectAbilityConnect()
{
if (conn_ != nullptr) {
AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(conn_);
LBSLOGI(GEO_CONVERT, "UnloadGeoConvert OnStop and disconnect");
}
}

View File

@ -116,6 +116,8 @@ private:
void ConstructLocatorEnhanceHandleMap();
void ConstructLocatorMockHandleMap();
void ConstructGeocodeHandleMap();
bool IsStopAction(uint32_t code);
bool CheckRequestAvailable(uint32_t code, AppIdentity &identity);
void ConstructGnssHandleMap();
void ConstructGnssEnhanceHandleMap();
sptr<IRemoteObject::DeathRecipient> scanRecipient_ = new (std::nothrow) ScanCallbackDeathRecipient();

View File

@ -24,6 +24,7 @@
#include "i_locator_callback.h"
#include "location.h"
#include "request.h"
#include <mutex>
namespace OHOS {
namespace Location {
@ -49,9 +50,10 @@ public:
private:
struct timespec lastUpdateTime_;
double offsetRandom_;
Location lastLocation_;
std::map<int, std::shared_ptr<Location>> lastLocationsMap_;
Location cacheGnssLocation_;
Location cacheNlpLocation_;
std::mutex lastLocationMutex_;
std::unique_ptr<Location> ApproximatelyLocation(const std::unique_ptr<Location>& location);
bool ProcessRequestForReport(std::shared_ptr<Request>& request,
std::unique_ptr<std::list<std::shared_ptr<Request>>>& deadRequests,
@ -60,6 +62,7 @@ private:
const std::unique_ptr<Location>& location);
std::unique_ptr<Location> ExecuteReportProcess(std::shared_ptr<Request>& request,
std::unique_ptr<Location>& location, std::string abilityName);
void UpdateLastLocation(const std::unique_ptr<Location>& location);
};
} // namespace OHOS
} // namespace Location

View File

@ -30,6 +30,7 @@
#include "locator_ability.h"
#include "request_manager.h"
#include "permission_manager.h"
#include "location_data_rdb_manager.h"
#include "accesstoken_kit.h"
#include "tokenid_kit.h"
@ -284,6 +285,11 @@ int32_t LocatorBackgroundProxy::GetUserId(int32_t uid) const
void LocatorBackgroundProxy::OnUserSwitch(int32_t userId)
{
UpdateListOnUserSwitch(userId);
LocationDataRdbManager::ClearSwitchMode();
auto locatorAbility = LocatorAbility::GetInstance();
if (locatorAbility != nullptr) {
locatorAbility->ApplyRequests(1);
}
if (!requestsList_->empty()) {
StartLocator();
} else {

View File

@ -1307,6 +1307,32 @@ int LocatorAbilityStub::PreReportLocationError(MessageParcel &data, MessageParce
return ERRCODE_SUCCESS;
}
bool LocatorAbilityStub::IsStopAction(uint32_t code)
{
if (code == static_cast<uint32_t>(LocatorInterfaceCode::UNREG_SWITCH_CALLBACK) ||
code == static_cast<uint32_t>(LocatorInterfaceCode::STOP_LOCATING) ||
code == static_cast<uint32_t>(LocatorInterfaceCode::STOP_LOCATING) ||
code == static_cast<uint32_t>(LocatorInterfaceCode::DISABLE_LOCATION_MOCK) ||
code == static_cast<uint32_t>(LocatorInterfaceCode::UNREG_LOCATION_ERROR) ||
code == static_cast<uint32_t>(LocatorInterfaceCode::UNREG_LOCATING_REQUIRED_DATA_CALLBACK)) {
return true;
}
return false;
}
bool LocatorAbilityStub::CheckRequestAvailable(uint32_t code, AppIdentity &identity)
{
if (IsStopAction(code)) {
return true;
}
if (PermissionManager::CheckSystemPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
return true;
}
if (!CommonUtils::CheckAppForUser(identity.GetUid())) {
return false;
}
return true;
}
int32_t LocatorAbilityStub::OnRemoteRequest(uint32_t code,
MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
@ -1316,16 +1342,21 @@ int32_t LocatorAbilityStub::OnRemoteRequest(uint32_t code,
uint32_t callingTokenId = IPCSkeleton::GetCallingTokenID();
uint64_t callingTokenIdEx = IPCSkeleton::GetCallingFullTokenID();
uint32_t callingFirstTokenid = IPCSkeleton::GetFirstTokenID();
// first token id is invalid
if (callingUid == callingFirstTokenid && callingUid == static_cast<pid_t>(getuid())
&& callingPid == getpid()) {
callingFirstTokenid = 0;
}
AppIdentity identity;
identity.SetPid(callingPid);
identity.SetUid(callingUid);
identity.SetTokenId(callingTokenId);
identity.SetTokenIdEx(callingTokenIdEx);
identity.SetFirstTokenId(callingFirstTokenid);
identity.SetPid(IPCSkeleton::GetCallingPid());
identity.SetUid(IPCSkeleton::GetCallingUid());
identity.SetTokenId(IPCSkeleton::GetCallingTokenID());
identity.SetTokenIdEx(IPCSkeleton::GetCallingFullTokenID());
identity.SetFirstTokenId(IPCSkeleton::GetFirstTokenID());
std::string bundleName = "";
if (!CommonUtils::GetBundleNameByUid(callingUid, bundleName)) {
LBSLOGD(LOCATOR, "Fail to Get bundle name: uid = %{public}d.", callingUid);
if (!CommonUtils::GetBundleNameByUid(identity.GetUid(), bundleName)) {
LBSLOGD(LOCATOR, "Fail to Get bundle name: uid = %{public}d.", identity.GetUid());
}
identity.SetBundleName(bundleName);
if (code != static_cast<uint32_t>(LocatorInterfaceCode::PROXY_PID_FOR_FREEZE)) {
@ -1335,15 +1366,18 @@ int32_t LocatorAbilityStub::OnRemoteRequest(uint32_t code,
std::to_string(CommonUtils::GetCurrentTimeStamp()).c_str());
}
std::string callingIdentity = IPCSkeleton::ResetCallingIdentity();
if (data.ReadInterfaceToken() != GetDescriptor()) {
LBSLOGE(LOCATOR, "invalid token.");
IPCSkeleton::SetCallingIdentity(callingIdentity);
return ERRCODE_SERVICE_UNAVAILABLE;
}
if (!CheckRequestAvailable(code, identity)) {
IPCSkeleton::SetCallingIdentity(callingIdentity);
reply.WriteInt32(ERRCODE_PERMISSION_DENIED);
return ERRCODE_PERMISSION_DENIED;
}
CancelIdleState();
RemoveUnloadTask(code);
auto handleFunc = locatorHandleMap_.find(static_cast<LocatorInterfaceCode>(code));
if (handleFunc != locatorHandleMap_.end() && handleFunc->second != nullptr) {
auto memberFunc = handleFunc->second;

View File

@ -209,6 +209,10 @@ std::unique_ptr<Location> ReportManager::GetPermittedLocation(const std::shared_
}
return nullptr;
}
if (!PermissionManager::CheckSystemPermission(tokenId, tokenIdEx) &&
!CommonUtils::CheckAppForUser(uid)) {
return nullptr;
}
std::unique_ptr<Location> finalLocation = std::make_unique<Location>(*location);
// for api8 and previous version, only ACCESS_LOCATION permission granted also report original location info.
if (PermissionManager::CheckLocationPermission(tokenId, firstTokenId)) {
@ -302,25 +306,42 @@ void ReportManager::UpdateCacheLocation(const std::unique_ptr<Location>& locatio
if (abilityName == GNSS_ABILITY) {
if (HookUtils::CheckGnssLocationValidity(location)) {
cacheGnssLocation_ = *location;
lastLocation_ = *location;
UpdateLastLocation(location);
}
} else if (abilityName == NETWORK_ABILITY &&
location->GetLocationSourceType() != LocationSourceType::INDOOR_TYPE) {
cacheNlpLocation_ = *location;
lastLocation_ = *location;
UpdateLastLocation(location);
} else {
lastLocation_ = *location;
UpdateLastLocation(location);
}
}
void ReportManager::UpdateLastLocation(const std::unique_ptr<Location>& location)
{
int currentUserId = 0;
if (CommonUtils::GetCurrentUserId(currentUserId)) {
std::unique_lock<std::mutex> lock(lastLocationMutex_);
lastLocationsMap_.insert(std::make_pair(currentUserId, std::make_shared<Location>(*location)));
}
}
std::unique_ptr<Location> ReportManager::GetLastLocation()
{
auto lastLocation = std::make_unique<Location>(lastLocation_);
if (CommonUtils::DoubleEqual(lastLocation->GetLatitude(), MIN_LATITUDE - 1)) {
LBSLOGE(REPORT_MANAGER, "%{public}s no valid cache location", __func__);
return nullptr;
int currentUserId = 0;
if (CommonUtils::GetCurrentUserId(currentUserId)) {
std::unique_lock<std::mutex> lock(lastLocationMutex_);
auto iter = lastLocationsMap_.find(currentUserId);
if (iter == lastLocationsMap_.end()) {
return nullptr;
}
std::unique_ptr<Location> lastLocation = std::make_unique<Location>(*(iter->second));
if (CommonUtils::DoubleEqual(lastLocation->GetLatitude(), MIN_LATITUDE - 1)) {
return nullptr;
}
return lastLocation;
}
return lastLocation;
return nullptr;
}
std::unique_ptr<Location> ReportManager::GetCacheLocation(const std::shared_ptr<Request>& request)

View File

@ -403,6 +403,9 @@ bool RequestManager::ActiveLocatingStrategies(const std::shared_ptr<Request>& re
*/
bool RequestManager::IsRequestAvailable(std::shared_ptr<Request>& request)
{
if (!request->GetIsRequesting()) {
return false;
}
// for frozen app, do not add to workRecord
if (LocatorAbility::GetInstance()->IsProxyPid(request->GetPid())) {
return false;
@ -441,13 +444,9 @@ bool RequestManager::AddRequestToWorkRecord(std::string abilityName, std::shared
if (request == nullptr) {
return false;
}
if (!request->GetIsRequesting()) {
return false;
}
if (!IsRequestAvailable(request)) {
return false;
}
auto locationErrorCallback = request->GetLocationErrorCallBack();
int switchState = DISABLED;
auto locatorAbility = LocatorAbility::GetInstance();
@ -493,6 +492,13 @@ bool RequestManager::AddRequestToWorkRecord(std::string abilityName, std::shared
if (requestConfig == nullptr) {
return false;
}
if (!PermissionManager::CheckSystemPermission(tokenId, request->GetTokenIdEx()) &&
!CommonUtils::CheckAppForUser(uid)) {
LBSLOGD(REPORT_MANAGER, "AddRequestToWorkRecord uid: %{public}d ,CheckAppIsCurrentUser fail", uid);
return false;
}
if (HookUtils::ExecuteHookWhenAddWorkRecord(isDeviceStillState_.load(), isDeviceIdleMode_.load(),
abilityName, bundleName)) {
LBSLOGI(REQUEST_MANAGER, "Enter idle and still status, not add request");

View File

@ -285,7 +285,7 @@ void NetworkAbility::RequestRecord(WorkRecord &workRecord, bool isAdded)
} else {
RemoveNetworkLocation(workRecord);
if (GetRequestNum() == 0 && conn_ != nullptr) {
LBSLOGD(NETWORK, "RequestRecord disconnect");
LBSLOGI(NETWORK, "RequestRecord disconnect");
AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(conn_);
}
}

View File

@ -2,8 +2,8 @@
"app": {
"bundleName": "com.ohos.locationdialog",
"vendor": "example",
"versionCode": 1000000,
"versionName": "1.0.0",
"versionCode": 1000001,
"versionName": "1.0.1",
"icon": "$media:app_icon",
"label": "$string:app_name",
"distributedNotificationEnabled": true,