code refactor

Change-Id: Idb15d7921309711b2eb5e824f502ab6ac04e5275

Match-id-56770f493827f947eda5064d7e9188deb40a7f9e
This commit is contained in:
authName 2023-10-20 11:48:58 +08:00 committed by userName
parent b84bcaea6d
commit 9d0b04133f
10 changed files with 82 additions and 89 deletions

View File

@ -16,7 +16,7 @@
//! This crate implements the sha256
#![allow(dead_code)]
// todo framework 创建一个utils目录将该文件放进去新建一个BUILD.gn文件
// todo zwz framework 创建一个utils目录将该文件放进去新建一个BUILD.gn文件
const LOWER_BYTES_MASK: u32 = 0xff;
const BITS_PER_U8: usize = 8;

View File

@ -6,4 +6,5 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
asset_common = { path = "../../frameworks/common" }
asset_common = { path = "../../frameworks/common" }
ipc_rust = { path = "../../../../../foundation/communication/ipc/interfaces/innerkits/rust/" }

View File

@ -22,46 +22,40 @@ use asset_common::{
loge,
};
const ROOT_PATH: &str = "data/service/el1/public/asset_service";
/// the function to create user database directory
/// Create user database directory.
pub fn create_user_db_dir(user_id: i32) -> Result<()> {
let path = format!("{}/{}", ROOT_PATH, user_id);
let path = Path::new(&path);
if !path.exists() {
match fs::create_dir(path) {
Err(e) if e.kind() != std::io::ErrorKind::AlreadyExists => {
loge!("[FATAL]Create dir failed! error is [{}]", e);
return Err(ErrCode::FileOperationError);
},
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
return Ok(());
},
_ => return Ok(()),
}
if path.exists() {
return Ok(())
}
match fs::create_dir(path) {
Ok(_) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
Err(e) => {
loge!("[FATAL]Create dir failed! error is [{}]", e);
Err(ErrCode::FileOperationError)
},
}
Ok(())
}
/// the function to delete user directory
pub fn delete_user_db_dir(user_id: i32) -> bool {
/// Delete user databse directory.
pub fn delete_user_db_dir(user_id: i32) -> Result<()> {
let path_str = format!("{}/{}", ROOT_PATH, user_id);
let path = Path::new(&path_str);
if path.exists() {
match fs::remove_dir_all(path) {
Ok(_) => {
return true
},
Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
return true
},
Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
loge!("remove dir failed! permission denied");
return false
},
_ => { return true }
}
if !path.exists() {
return Ok(());
}
match fs::remove_dir_all(path) {
Ok(_) => Ok(()),
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Ok(()),
Err(e) => {
loge!("[FATAL]Delete dir failed! error is [{}]", e);
Err(ErrCode::FileOperationError)
},
}
true
}

View File

@ -20,14 +20,14 @@
#include "asset_log.h"
#include "asset_mem.h"
extern int32_t add_asset(const Asset_Attr *attributes, uint32_t attr_cnt);
extern int32_t remove_asset(const Asset_Attr *query, uint32_t query_cnt);
extern int32_t update_asset(const Asset_Attr *query, uint32_t query_cnt,
int32_t add_asset(const Asset_Attr *attributes, uint32_t attr_cnt);
int32_t remove_asset(const Asset_Attr *query, uint32_t query_cnt);
int32_t update_asset(const Asset_Attr *query, uint32_t query_cnt,
const Asset_Attr *attributes_to_update, uint32_t update_cnt);
extern int32_t pre_query_asset(const Asset_Attr *query, uint32_t query_cnt, Asset_Blob *challenge);
extern int32_t query_asset(const Asset_Attr *query, uint32_t query_cnt, Asset_ResultSet *result_set);
extern int32_t post_query_asset(const Asset_Attr *handle, uint32_t handle_cnt);
extern Asset_Version get_asset_version();
int32_t pre_query_asset(const Asset_Attr *query, uint32_t query_cnt, Asset_Blob *challenge);
int32_t query_asset(const Asset_Attr *query, uint32_t query_cnt, Asset_ResultSet *result_set);
int32_t post_query_asset(const Asset_Attr *handle, uint32_t handle_cnt);
Asset_Version get_asset_version();
int32_t OH_Asset_Add(const Asset_Attr *attributes, uint32_t attrCnt)
{

View File

@ -48,11 +48,10 @@ extern "C" {
) -> bool;
}
pub(crate) fn get_user_id() -> Result<i32> {
pub(crate) fn get_front_user_id() -> Result<i32> {
unsafe {
let mut user_id = 0;
if GetFrontUserId(&mut user_id) {
// todoyyd 获取前台用户的user_id
Ok(user_id)
} else {
Err(ErrCode::AccountError)
@ -63,7 +62,7 @@ pub(crate) fn get_user_id() -> Result<i32> {
impl CallingInfo {
pub(crate) fn build() -> Result<Self> {
let uid = get_calling_uid();
let user_id: i32 = get_user_id()?;
let user_id: i32 = get_front_user_id()?;
let mut owner_info = vec![0u8; 256];
let mut len = 256u32;
let mut owner_type = OwnerType::Hap;

View File

@ -63,14 +63,15 @@ pub(crate) fn update(query: &AssetMap, update: &AssetMap, calling_info: &Calling
add_system_attrs(&mut update_db_data)?;
if update.contains_key(&Tag::Secret) {
let results =
let mut results =
DefaultDatabaseHelper::query_columns_default_once(calling_info.user_id(), &vec![], &query_db_data, None)?;
if results.len() != 1 {
loge!("query to-be-updated asset failed, found [{}] assets", results.len());
return Err(ErrCode::NotFound);
}
let result = results.get(0).unwrap();
let result = results.get_mut(0).unwrap();
result.insert(COLUMN_SECRET, update[&Tag::Secret].clone());
let cipher = common::encrypt(calling_info, result)?;
update_db_data.insert(COLUMN_SECRET, Value::Bytes(cipher));
}

View File

@ -64,7 +64,7 @@ fn reply_handle(code: IpcCode, ret: Result<()>, reply: &mut BorrowedMsgParcel) -
result = e as i32;
}
logi!("[INFO]on_remote_request enter, calling function: {}, result code: {}", code, result);
logi!("[INFO]on_remote_request end, calling function: {}, result code: {}", code, result);
reply.write::<i32>(&result)?;
Ok(())
}
@ -77,7 +77,7 @@ fn on_remote_request(
) -> IpcResult<()> {
let ipc_code = IpcCode::try_from(code).map_err(ipc_err_handle)?;
let map = deserialize_map(data).map_err(ipc_err_handle)?;
logi!("[INFO]on_remote_request end, calling function: {}", ipc_code);
logi!("[INFO]on_remote_request enter, calling function: {}", ipc_code);
match ipc_code {
IpcCode::Add => reply_handle(ipc_code, stub.add(&map), reply),
IpcCode::Remove => reply_handle(ipc_code, stub.remove(&map), reply),

View File

@ -19,7 +19,7 @@ use std::ffi::{c_char, CString};
use asset_common::{
definition::{Accessibility, AuthType, Value},
hasher, logi,
hasher, loge,
};
use asset_crypto_manager::crypto::SecretKey;
use asset_db_operator::{
@ -30,23 +30,20 @@ use asset_file_operator::delete_user_db_dir;
fn delete_key(user_id: i32, owner: &Vec<u8>, auth_type: AuthType, access_type: Accessibility) {
let secret_key = SecretKey::new(user_id, owner, auth_type, access_type);
match secret_key.delete() {
Ok(true) => logi!("delete huks key pass"),
Ok(false) => logi!("delete huks key never reached"),
Err(res) => logi!("delete huks key fail error = {}", res),
};
if let Err(e) = secret_key.delete() {
loge!("Delete huks key failed, error = {}", e);
}
}
/// Function called from C programming language to Rust programming language for delete hap Asset.
/// # Safety
#[no_mangle]
pub unsafe extern "C" fn delete_by_owner(user_id: i32, owner: *const c_char) -> i32 {
// 1 delete data in db
let owner = CString::from_raw(owner as *mut c_char).into_string().unwrap();
let cond = DbMap::from([(COLUMN_OWNER, Value::Bytes(owner.as_bytes().to_vec()))]);
pub extern "C" fn delete_data_by_owner(user_id: i32, owner: *const c_char) -> i32 {
let owner = unsafe { CString::from_raw(owner as *mut c_char).into_string().unwrap() }; // todo: unwrap改掉
let mut cond = DbMap::new();
// cond.insert(COLUMN_OWNER_TYPE, Value::Number(OwnerType::Hap as u32)); // todo: 加个constants 文件 yzt
cond.insert(COLUMN_OWNER, Value::Bytes(owner.as_bytes().to_vec())); // todo: owner + ownerLen 一起通过函数参数传过来
match DefaultDatabaseHelper::delete_datas_default_once(user_id, &cond) {
Ok(remove_num) => {
// 2 delete data in huks
let owner = hasher::sha256(&owner.as_bytes().to_vec());
delete_key(user_id, &owner, AuthType::None, Accessibility::DeviceFirstUnlock);
delete_key(user_id, &owner, AuthType::None, Accessibility::DeviceUnlock);
@ -60,6 +57,6 @@ pub unsafe extern "C" fn delete_by_owner(user_id: i32, owner: *const c_char) ->
/// Function called from C programming language to Rust programming language for delete user Asset.
#[no_mangle]
pub extern "C" fn delete_by_user_dir(user_id: i32) -> bool {
delete_user_db_dir(user_id)
pub extern "C" fn delete_dir_by_user(user_id: i32) -> bool {
delete_user_db_dir(user_id).is_ok()
}

View File

@ -24,7 +24,7 @@ bool GetFrontUserId(int32_t *userId)
std::vector<int> ids;
int ret = OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(ids);
if (ret != 0 || ids.empty()) {
LOGE("Asset QueryActiveOsAccountIds Failed!! ret = %" LOG_PUBLIC "d", ret);
LOGE("[FATAL]Query active user id failed. ret = %{public}d", ret);
return false;
}
*userId = ids[0];

View File

@ -24,11 +24,30 @@
#include "asset_log.h"
extern "C" {
int32_t delete_by_owner(int32_t user_id, const char* owner);
bool delete_by_user_dir(int32_t user_id);
int32_t delete_data_by_owner(int32_t user_id, const char* owner);
bool delete_dir_by_user(int32_t user_id);
}
namespace {
const char *APP_ID = "appId";
void OnPackageRemoved(const OHOS::AAFwk::Want &want, bool isSandBoxApp)
{
int userId = want.GetIntParam(OHOS::AppExecFwk::Constants::USER_ID, -1);
std::string appId = want.GetStringParam(APP_ID);
int appIndex = isSandBoxApp ? want.GetIntParam(OHOS::AppExecFwk::Constants::SANDBOX_APP_INDEX, -1) : 0;
if (appId.empty() || userId == -1 || appIndex == -1) {
LOGE("[FATAL]Get removed owner info failed, userId=%{public}i, appId=%{public}s, appIndex=%{public}d",
userId, appId.c_str(), appIndex);
return;
}
std::string owner = appId + '_' + std::to_string(appIndex);
int totalDeleteNum = delete_data_by_owner(userId, owner.c_str());
LOGI("[INFO] Receive event: PACKAGE_REMOVED, userId=%{public}i, appId=%{public}s, appIndex=%{public}d, "
"deleteDataNum=%{public}d", userId, appId.c_str(), appIndex, totalDeleteNum);
}
class SystemEventHandler : public OHOS::EventFwk::CommonEventSubscriber {
public:
SystemEventHandler(const OHOS::EventFwk::CommonEventSubscribeInfo &subscribeInfo) :
@ -38,33 +57,16 @@ public:
{
auto want = data.GetWant();
std::string action = want.GetAction();
if (action == OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED ||
action == OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_SANDBOX_PACKAGE_REMOVED) {
int userId = want.GetIntParam(OHOS::AppExecFwk::Constants::USER_ID, -1);
const char *APP_ID = "appId";
std::string appId = want.GetStringParam(APP_ID);
int appIndex = action == OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_SANDBOX_PACKAGE_REMOVED ?
want.GetIntParam(OHOS::AppExecFwk::Constants::SANDBOX_APP_INDEX, -1) : 0;
if (appId.empty() || userId == -1 || appIndex == -1) {
LOGE("wrong appId %{public}s/userId %{public}i/appIndex %{public}d", appId.c_str(), userId, appIndex);
return;
}
LOGI("AssetService app removed");
std::string owner = appId + '_' + std::to_string(appIndex);
int totalDeleteNum = delete_by_owner(userId, owner.c_str());
LOGI("delete finish! total delete line: %{public}i", totalDeleteNum); // todo 要删掉
if (action == OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) {
OnPackageRemoved(want, false);
} else if (action == OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_SANDBOX_PACKAGE_REMOVED) {
OnPackageRemoved(want, true);
} else if (action == OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED) {
int userId = data.GetCode();
LOGE("AssetService user removed: userId is %{public}i", userId); // todo 要删掉
if (delete_by_user_dir(userId)) {
LOGI("delete user %{public}i dir finish!", userId); // todo 要删掉
};
bool ret = delete_dir_by_user(userId);
LOGI("[INFO] Receive event: USER_REMOVED, userId=%{public}i, deleteDirRet=%{public}d", userId, ret);
} else if (action == OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF) {
// todo: 监听锁屏广播中止session
LOGE("AssetService screen off"); // todo 要删掉
LOGE("AssetService screen off"); // // todo: 监听锁屏广播中止session
}
}
};
@ -87,7 +89,6 @@ bool SubscribeSystemEvent(void)
return false;
}
LOGE("register sub system event!"); // todo 要删掉
return OHOS::EventFwk::CommonEventManager::SubscribeCommonEvent(g_eventHandler);
}