1 /*
2 * Copyright (C) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 //! bridge
16
17 #[allow(unused)]
18 use crate::config::*;
19 #[allow(unused)]
20 use crate::serializer;
21 #[allow(unused)]
22 use crate::serializer::serialize::Serialization;
23 use crate::serializer::serialize::SerializedBuffer;
24 use crate::transfer::base;
25 use crate::transfer::base::Writer;
26 use crate::transfer::buffer::ConnectTypeMap;
27 use crate::utils;
28 #[allow(unused)]
29 use crate::utils::hdc_log::*;
30 use std::collections::HashMap;
31 #[allow(unused)]
32 use std::io::{self, Error, ErrorKind};
33 use std::sync::Arc;
34 use ylong_runtime::sync::{Mutex, RwLock};
35
36 #[repr(C)]
37 pub struct PersistBuffer {
38 pub ptr: *const libc::c_char,
39 pub size: libc::c_ulonglong,
40 }
41
42 #[allow(unused)]
buf_to_vecnull43 pub fn buf_to_vec(buf: PersistBuffer) -> Vec<u8> {
44 let slice =
45 unsafe { std::slice::from_raw_parts(buf.ptr as *const libc::c_uchar, buf.size as usize) };
46 slice.to_vec()
47 }
48
49 #[allow(unused)]
50 extern "C" {
InitBridgenull51 fn InitBridge() -> *mut libc::c_void;
StartListennull52 fn StartListen(ptr: *mut libc::c_void) -> libc::c_int;
AcceptServerSocketFdnull53 fn AcceptServerSocketFd(ptr: *mut libc::c_void, pipeFd: i32) -> libc::c_int;
InitClientFdnull54 fn InitClientFd(ptr: *mut libc::c_void, socketFd: i32) -> libc::c_int;
ReadClientnull55 fn ReadClient(ptr: *mut libc::c_void, fd: i32, excepted_size: i32) -> PersistBuffer;
WriteClientnull56 fn WriteClient(ptr: *mut libc::c_void, fd: i32, buf: SerializedBuffer) -> libc::c_int;
Stopnull57 fn Stop(ptr: *mut libc::c_void) -> libc::c_int;
58 }
59
60 #[allow(unused)]
init_bridgenull61 pub fn init_bridge() -> *mut libc::c_void {
62 unsafe { InitBridge() }
63 }
64
65 #[allow(unused)]
start_listennull66 pub fn start_listen(ptr: u64) -> i32 {
67 unsafe { StartListen(ptr as *mut libc::c_void) }
68 }
69
70 #[allow(unused)]
accept_server_socket_fdnull71 pub fn accept_server_socket_fd(ptr: u64, pipe_fd: i32) -> i32 {
72 unsafe { AcceptServerSocketFd(ptr as *mut libc::c_void, pipe_fd) }
73 }
74
75 #[allow(unused)]
init_client_fdnull76 pub fn init_client_fd(ptr: u64, socket_fd: i32) -> i32 {
77 unsafe { InitClientFd(ptr as *mut libc::c_void, socket_fd) }
78 }
79
80 #[allow(unused)]
write_clientnull81 pub fn write_client(ptr: u64, fd: i32, buf: SerializedBuffer) -> i32 {
82 unsafe { WriteClient(ptr as *mut libc::c_void, fd, buf) }
83 }
84
85 #[allow(unused)]
read_clientnull86 pub fn read_client(ptr: u64, fd: i32, excepted_size: i32) -> PersistBuffer {
87 unsafe { ReadClient(ptr as *mut libc::c_void, fd, excepted_size) }
88 }
89
90 #[allow(unused)]
stopnull91 pub fn stop(ptr: u64) -> i32 {
92 unsafe { Stop(ptr as *mut libc::c_void) }
93 }
94
95 pub struct BridgeReader {
96 pub ptr: u64,
97 pub fd: i32,
98 }
99 pub struct BridgeWriter {
100 pub ptr: u64,
101 pub fd: i32,
102 }
103
104 impl base::Reader for BridgeReader {
read_framenull105 fn read_frame(&self, _expected_size: usize) -> io::Result<Vec<u8>> {
106 let buf = read_client(self.ptr, self.fd, _expected_size as i32);
107 if buf.size == 0 {
108 crate::warn!("bridge read result <= 0");
109 return Err(utils::error_other("bridge read error".to_string()));
110 }
111
112 Ok(buf_to_vec(buf))
113 }
114
check_protocol_headnull115 fn check_protocol_head(&mut self) -> io::Result<(u32, u32, u32)> {
116 Ok((0, 0, 0))
117 }
118 }
119
120 impl base::Writer for BridgeWriter {
write_allnull121 fn write_all(&self, data: Vec<u8>) -> io::Result<i32> {
122 let buf = SerializedBuffer {
123 ptr: data.as_ptr() as *const libc::c_char,
124 size: data.len() as u64,
125 };
126 let ret = write_client(self.ptr, self.fd, buf);
127 if ret <= 0 {
128 Err(utils::error_other("usb write failed".to_string()))
129 } else {
130 Ok(ret)
131 }
132 }
133 }
134
135 type BridgeWriter_ = Arc<Mutex<BridgeWriter>>;
136 type BridgeMap_ = Arc<RwLock<HashMap<u32, BridgeWriter_>>>;
137
138 pub struct BridgeMap {}
139 impl BridgeMap {
get_instancenull140 fn get_instance() -> BridgeMap_ {
141 static mut BRIDGE_MAP: Option<BridgeMap_> = None;
142 unsafe {
143 BRIDGE_MAP
144 .get_or_insert_with(|| Arc::new(RwLock::new(HashMap::new())))
145 .clone()
146 }
147 }
148
149 pub async fn put(session_id: u32, data: TaskMessage) {
150 let send = serializer::concat_pack(data);
151 let instance = Self::get_instance();
152 let map = instance.read().await;
153 let Some(arc_wr) = map.get(&session_id) else {
154 return;
155 };
156 let wr = arc_wr.lock().await;
157 let _ = wr.write_all(send);
158 }
159
160 pub async fn send_channel_message(channel_id: u32, buf: Vec<u8>) -> io::Result<()> {
161 crate::trace!(
162 "send channel msg: {:?}",
163 buf.iter()
164 .map(|&c| format!("{c:02X}"))
165 .collect::<Vec<_>>()
166 .join(" ")
167 );
168 let send = [
169 u32::to_be_bytes(buf.len() as u32).as_slice(),
170 buf.as_slice(),
171 ]
172 .concat();
173 let instance = Self::get_instance();
174 let map = instance.read().await;
175 if let Some(guard) = map.get(&channel_id) {
176 let wr = guard.lock().await;
177 let _ = wr.write_all(send);
178 return Ok(());
179 }
180 Err(Error::new(ErrorKind::NotFound, "channel not found"))
181 }
182
183 pub async fn start(id: u32, wr: BridgeWriter) {
184 let instance = Self::get_instance();
185 let mut map = instance.write().await;
186 let arc_wr = Arc::new(Mutex::new(wr));
187 map.insert(id, arc_wr);
188 ConnectTypeMap::put(id, ConnectType::Bridge).await;
189 }
190
191 pub async fn end(id: u32) {
192 let instance = Self::get_instance();
193 let mut map = instance.write().await;
194 if let Some(arc_wr) = map.remove(&id) {
195 let mut _wr = arc_wr.lock().await;
196 }
197 }
198 }
199