1 // Copyright (C) 2023 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 pub(crate) mod c_wrapper;
15 pub(crate) mod common_event;
16 pub(crate) mod form_item;
17 use std::collections::HashMap;
18 use std::future::Future;
19 use std::io::Write;
20 use std::time::{SystemTime, UNIX_EPOCH};
21
22 pub(crate) use common_event::{
23 subscribe_common_event, CommonEventSubscriber, Want as CommonEventWant,
24 };
25 pub(crate) use ffi::PublishStateChangeEvent;
26
27 cfg_oh! {
28 pub(crate) mod url_policy;
29 #[cfg(not(test))]
30 pub(crate) use ffi::GetForegroundAbilities;
31 }
32
33 pub(crate) mod task_id_generator;
34 use ylong_runtime::sync::oneshot::Receiver;
35 use ylong_runtime::task::JoinHandle;
36
37 pub(crate) struct Recv<T> {
38 rx: Receiver<T>,
39 }
40
41 impl<T> Recv<T> {
new(rx: Receiver<T>) -> Self42 pub(crate) fn new(rx: Receiver<T>) -> Self {
43 Self { rx }
44 }
45
get(self) -> Option<T>46 pub(crate) fn get(self) -> Option<T> {
47 // Here `self.rx` can never be hung up.
48 ylong_runtime::block_on(self.rx).ok()
49 }
50 }
51
build_vec<A, B, C>(ptr: *const A, len: usize, func: C) -> Vec<B> where C: Fn(&A) -> B,52 pub(crate) fn build_vec<A, B, C>(ptr: *const A, len: usize, func: C) -> Vec<B>
53 where
54 C: Fn(&A) -> B,
55 {
56 if ptr.is_null() || len == 0 {
57 return Vec::<B>::new();
58 }
59 let slice = unsafe { std::slice::from_raw_parts(ptr, len) };
60 slice.iter().map(func).collect()
61 }
62
get_current_timestamp() -> u6463 pub(crate) fn get_current_timestamp() -> u64 {
64 match SystemTime::now().duration_since(UNIX_EPOCH) {
65 Ok(n) => n.as_millis() as u64,
66 Err(_) => panic!("SystemTime before UNIX EPOCH!"),
67 }
68 }
69
hashmap_to_string(map: &HashMap<String, String>) -> String70 pub(crate) fn hashmap_to_string(map: &HashMap<String, String>) -> String {
71 let mut res = Vec::new();
72 for (n, (k, v)) in map.iter().enumerate() {
73 if n != 0 {
74 let _ = write!(res, "\r\n");
75 }
76 let _ = write!(res, "{k}\t{v}");
77 }
78 unsafe { String::from_utf8_unchecked(res) }
79 }
80
string_to_hashmap(str: &mut str) -> HashMap<String, String>81 pub(crate) fn string_to_hashmap(str: &mut str) -> HashMap<String, String> {
82 let mut map = HashMap::<String, String>::new();
83 if str.is_empty() {
84 return map;
85 }
86 for item in str.split("\r\n") {
87 let (k, v) = item.split_once('\t').unwrap();
88 map.insert(k.into(), v.into());
89 }
90 map
91 }
92
split_string(str: &mut str) -> std::str::Split<'_, &str>93 pub(crate) fn split_string(str: &mut str) -> std::str::Split<'_, &str> {
94 let pat: &[_] = &['[', ']'];
95 str.trim_matches(pat).split(", ")
96 }
97
98 #[inline(always)]
runtime_spawn<F: Future<Output = ()> + Send + Sync + 'static>( fut: F, ) -> JoinHandle<()>99 pub(crate) fn runtime_spawn<F: Future<Output = ()> + Send + Sync + 'static>(
100 fut: F,
101 ) -> JoinHandle<()> {
102 ylong_runtime::spawn(Box::into_pin(
103 Box::new(fut) as Box<dyn Future<Output = ()> + Send + Sync>
104 ))
105 }
106
107 #[cfg(feature = "oh")]
query_calling_bundle() -> String108 pub(crate) fn query_calling_bundle() -> String {
109 let token_id = ipc::Skeleton::calling_full_token_id();
110 ffi::GetCallingBundle(token_id)
111 }
112
113 #[cfg(feature = "oh")]
is_system_api() -> bool114 pub(crate) fn is_system_api() -> bool {
115 let token_id = ipc::Skeleton::calling_full_token_id();
116 ffi::IsSystemAPI(token_id)
117 }
118
119 #[cfg(feature = "oh")]
check_permission(permission: &str) -> bool120 pub(crate) fn check_permission(permission: &str) -> bool {
121 let token_id = ipc::Skeleton::calling_full_token_id();
122 ffi::CheckPermission(token_id, permission)
123 }
124
125 #[cfg(feature = "oh")]
update_policy(any_tasks: bool) -> i32126 pub(crate) fn update_policy(any_tasks: bool) -> i32 {
127 ffi::UpdatePolicy(any_tasks)
128 }
129
130 #[allow(unused)]
131 #[cxx::bridge(namespace = "OHOS::Request")]
132 mod ffi {
133
134 unsafe extern "C++" {
135 include!("request_utils.h");
136
PublishStateChangeEvent(bundleName: &str, taskId: u32, state: i32, uid: i32) -> bool137 fn PublishStateChangeEvent(bundleName: &str, taskId: u32, state: i32, uid: i32) -> bool;
GetForegroundAbilities(uid: &mut Vec<i32>) -> i32138 fn GetForegroundAbilities(uid: &mut Vec<i32>) -> i32;
GetCallingBundle(token_id: u64) -> String139 fn GetCallingBundle(token_id: u64) -> String;
IsSystemAPI(token_id: u64) -> bool140 fn IsSystemAPI(token_id: u64) -> bool;
CheckPermission(token_id: u64, permission: &str) -> bool141 fn CheckPermission(token_id: u64, permission: &str) -> bool;
UpdatePolicy(any_tasks: bool) -> i32142 fn UpdatePolicy(any_tasks: bool) -> i32;
143 }
144 }
145
146 #[cfg(feature = "oh")]
147 #[cfg(test)]
148 mod test {
149 use super::*;
150 use crate::tests::test_init;
151 #[test]
ut_utils_oh()152 fn ut_utils_oh() {
153 assert!(!is_system_api());
154 assert_eq!(query_calling_bundle(), "");
155 }
156
157 #[test]
ut_utils_check_permission()158 fn ut_utils_check_permission() {
159 assert!(!check_permission("ohos.permission.INTERNET"));
160 assert!(!check_permission("ohos.permission.GET_NETWORK_INFO"));
161 assert!(!check_permission("ohos.permission.READ_MEDIA"));
162 assert!(!check_permission("ohos.permission.WRITE_MEDIA"));
163 assert!(!check_permission("ohos.permission.RUNNING_STATE_OBSERVER"));
164 assert!(!check_permission("ohos.permission.GET_NETWORK_INFO"));
165 assert!(!check_permission("ohos.permission.CONNECTIVITY_INTERNAL"));
166 assert!(!check_permission(
167 "ohos.permission.SEND_TASK_COMPLETE_EVENT"
168 ));
169 assert!(!check_permission("ohos.permission.ACCESS_CERT_MANAGER"));
170 assert!(!check_permission(
171 "ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS"
172 ));
173 assert!(!check_permission("ohos.permission.MANAGE_LOCAL_ACCOUNTS"));
174 }
175
176 #[test]
ut_utils_check_permission_oh()177 fn ut_utils_check_permission_oh() {
178 test_init();
179 assert!(check_permission("ohos.permission.INTERNET"));
180 assert!(check_permission("ohos.permission.GET_NETWORK_INFO"));
181 assert!(check_permission("ohos.permission.READ_MEDIA"));
182 assert!(check_permission("ohos.permission.WRITE_MEDIA"));
183 assert!(check_permission("ohos.permission.RUNNING_STATE_OBSERVER"));
184 assert!(check_permission("ohos.permission.GET_NETWORK_INFO"));
185 assert!(check_permission("ohos.permission.CONNECTIVITY_INTERNAL"));
186 assert!(check_permission("ohos.permission.SEND_TASK_COMPLETE_EVENT"));
187 assert!(check_permission("ohos.permission.ACCESS_CERT_MANAGER"));
188 assert!(check_permission(
189 "ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS"
190 ));
191 assert!(check_permission("ohos.permission.MANAGE_LOCAL_ACCOUNTS"));
192 assert!(!check_permission(
193 "ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION"
194 ));
195 }
196 }
197