• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 form_item;
16 use std::collections::HashMap;
17 use std::future::Future;
18 use std::io::Write;
19 use std::time::{SystemTime, UNIX_EPOCH};
20 
21 pub(crate) use ffi::PublishStateChangeEvent;
22 
23 cfg_oh! {
24     pub(crate) mod url_policy;
25     #[cfg(not(test))]
26     pub(crate) use ffi::GetForegroundAbilities;
27 }
28 
29 pub(crate) mod task_id_generator;
30 use ylong_runtime::sync::oneshot::Receiver;
31 use ylong_runtime::task::JoinHandle;
32 
33 pub(crate) struct Recv<T> {
34     rx: Receiver<T>,
35 }
36 
37 impl<T> Recv<T> {
new(rx: Receiver<T>) -> Self38     pub(crate) fn new(rx: Receiver<T>) -> Self {
39         Self { rx }
40     }
41 
get(self) -> Option<T>42     pub(crate) fn get(self) -> Option<T> {
43         // Here `self.rx` can never be hung up.
44         ylong_runtime::block_on(self.rx).ok()
45     }
46 }
47 
build_vec<A, B, C>(ptr: *const A, len: usize, func: C) -> Vec<B> where C: Fn(&A) -> B,48 pub(crate) fn build_vec<A, B, C>(ptr: *const A, len: usize, func: C) -> Vec<B>
49 where
50     C: Fn(&A) -> B,
51 {
52     if ptr.is_null() || len == 0 {
53         return Vec::<B>::new();
54     }
55     let slice = unsafe { std::slice::from_raw_parts(ptr, len) };
56     slice.iter().map(func).collect()
57 }
58 
get_current_timestamp() -> u6459 pub(crate) fn get_current_timestamp() -> u64 {
60     match SystemTime::now().duration_since(UNIX_EPOCH) {
61         Ok(n) => n.as_millis() as u64,
62         Err(_) => panic!("SystemTime before UNIX EPOCH!"),
63     }
64 }
65 
hashmap_to_string(map: &HashMap<String, String>) -> String66 pub(crate) fn hashmap_to_string(map: &HashMap<String, String>) -> String {
67     let mut res = Vec::new();
68     for (n, (k, v)) in map.iter().enumerate() {
69         if n != 0 {
70             let _ = write!(res, "\r\n");
71         }
72         let _ = write!(res, "{k}\t{v}");
73     }
74     unsafe { String::from_utf8_unchecked(res) }
75 }
76 
string_to_hashmap(str: &mut str) -> HashMap<String, String>77 pub(crate) fn string_to_hashmap(str: &mut str) -> HashMap<String, String> {
78     let mut map = HashMap::<String, String>::new();
79     if str.is_empty() {
80         return map;
81     }
82     for item in str.split("\r\n") {
83         let (k, v) = item.split_once('\t').unwrap();
84         map.insert(k.into(), v.into());
85     }
86     map
87 }
88 
split_string(str: &mut str) -> std::str::Split<'_, &str>89 pub(crate) fn split_string(str: &mut str) -> std::str::Split<'_, &str> {
90     let pat: &[_] = &['[', ']'];
91     str.trim_matches(pat).split(", ")
92 }
93 
94 #[inline(always)]
runtime_spawn<F: Future<Output = ()> + Send + Sync + 'static>( fut: F, ) -> JoinHandle<()>95 pub(crate) fn runtime_spawn<F: Future<Output = ()> + Send + Sync + 'static>(
96     fut: F,
97 ) -> JoinHandle<()> {
98     ylong_runtime::spawn(Box::into_pin(
99         Box::new(fut) as Box<dyn Future<Output = ()> + Send + Sync>
100     ))
101 }
102 
103 #[cfg(feature = "oh")]
query_calling_bundle() -> String104 pub(crate) fn query_calling_bundle() -> String {
105     let token_id = ipc::Skeleton::calling_full_token_id();
106     ffi::GetCallingBundle(token_id)
107 }
108 
109 #[cfg(feature = "oh")]
is_system_api() -> bool110 pub(crate) fn is_system_api() -> bool {
111     let token_id = ipc::Skeleton::calling_full_token_id();
112     ffi::IsSystemAPI(token_id)
113 }
114 
115 #[cfg(feature = "oh")]
check_permission(permission: &str) -> bool116 pub(crate) fn check_permission(permission: &str) -> bool {
117     let token_id = ipc::Skeleton::calling_full_token_id();
118     ffi::CheckPermission(token_id, permission)
119 }
120 
121 #[allow(unused)]
122 #[cxx::bridge(namespace = "OHOS::Request")]
123 mod ffi {
124 
125     unsafe extern "C++" {
126         include!("request_utils.h");
PublishStateChangeEvent(bundleName: &str, taskId: u32, state: i32, uid: i32) -> bool127         fn PublishStateChangeEvent(bundleName: &str, taskId: u32, state: i32, uid: i32) -> bool;
GetForegroundAbilities(uid: &mut Vec<i32>) -> i32128         fn GetForegroundAbilities(uid: &mut Vec<i32>) -> i32;
GetCallingBundle(token_id: u64) -> String129         fn GetCallingBundle(token_id: u64) -> String;
IsSystemAPI(token_id: u64) -> bool130         fn IsSystemAPI(token_id: u64) -> bool;
CheckPermission(token_id: u64, permission: &str) -> bool131         fn CheckPermission(token_id: u64, permission: &str) -> bool;
132     }
133 }
134 
135 #[cfg(feature = "oh")]
136 #[cfg(test)]
137 mod test {
138     use super::*;
139     use crate::tests::test_init;
140     #[test]
ut_utils_oh()141     fn ut_utils_oh() {
142         assert!(!is_system_api());
143         assert_eq!(query_calling_bundle(), "");
144     }
145 
146     #[test]
ut_utils_check_permission()147     fn ut_utils_check_permission() {
148         assert!(!check_permission("ohos.permission.INTERNET"));
149         assert!(!check_permission("ohos.permission.GET_NETWORK_INFO"));
150         assert!(!check_permission("ohos.permission.READ_MEDIA"));
151         assert!(!check_permission("ohos.permission.WRITE_MEDIA"));
152         assert!(!check_permission("ohos.permission.RUNNING_STATE_OBSERVER"));
153         assert!(!check_permission("ohos.permission.GET_NETWORK_INFO"));
154         assert!(!check_permission("ohos.permission.CONNECTIVITY_INTERNAL"));
155         assert!(!check_permission(
156             "ohos.permission.SEND_TASK_COMPLETE_EVENT"
157         ));
158         assert!(!check_permission("ohos.permission.ACCESS_CERT_MANAGER"));
159         assert!(!check_permission(
160             "ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS"
161         ));
162         assert!(!check_permission("ohos.permission.MANAGE_LOCAL_ACCOUNTS"));
163     }
164 
165     #[test]
ut_utils_check_permission_oh()166     fn ut_utils_check_permission_oh() {
167         test_init();
168         assert!(check_permission("ohos.permission.INTERNET"));
169         assert!(check_permission("ohos.permission.GET_NETWORK_INFO"));
170         assert!(check_permission("ohos.permission.READ_MEDIA"));
171         assert!(check_permission("ohos.permission.WRITE_MEDIA"));
172         assert!(check_permission("ohos.permission.RUNNING_STATE_OBSERVER"));
173         assert!(check_permission("ohos.permission.GET_NETWORK_INFO"));
174         assert!(check_permission("ohos.permission.CONNECTIVITY_INTERNAL"));
175         assert!(check_permission("ohos.permission.SEND_TASK_COMPLETE_EVENT"));
176         assert!(check_permission("ohos.permission.ACCESS_CERT_MANAGER"));
177         assert!(check_permission(
178             "ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS"
179         ));
180         assert!(check_permission("ohos.permission.MANAGE_LOCAL_ACCOUNTS"));
181         assert!(!check_permission(
182             "ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION"
183         ));
184     }
185 }
186