1 /*
2  * Copyright (C) 2023 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 
16 /// provide C interface to C++ for calling
17 pub mod ffi;
18 use hilog_rust::{info, error, hilog, HiLogLabel, LogType};
19 use std::ffi::{CString, c_char};
20 use libc::c_int;
21 const ONCE_PROCESS_NETPACKET_LIMIT: i32 = 100;
22 const MAX_PACKET_BUF_SIZE: usize = 256;
23 const SEND_RETRY_SLEEP_TIME: u64 = 10000;
24 const SEND_RETRY_LIMIT: i32 = 32;
25 const RET_ERR: i32 = -1;
26 const RET_OK: i32 = 0;
27 
28 const LOG_LABEL: HiLogLabel = HiLogLabel {
29     log_type: LogType::LogCore,
30     domain: 0xD002700,
31     tag: "EpollManager"
32 };
33 
34 /// struct EpollManager
35 #[repr(C)]
36 pub struct EpollManager {
37     socket_fd: i32,
38     epoll_fd: i32,
39 }
40 
41 impl Default for EpollManager {
default() -> Self42     fn default() -> Self {
43         Self {
44             socket_fd: -1,
45             epoll_fd: -1,
46         }
47     }
48 }
49 
50 impl EpollManager {
as_ref<'a>(object: *const Self) -> Option<&'a Self>51     fn as_ref<'a>(object: *const Self) -> Option<&'a Self> {
52         // SAFETY: as_ref has already done no-null verification inside
53         unsafe {
54             object.as_ref()
55         }
56     }
as_mut<'a>(object: *mut Self) -> Option<&'a mut Self>57     fn as_mut<'a>(object: *mut Self) -> Option<&'a mut Self> {
58         // SAFETY: as_mut has already done no-null verification inside
59         unsafe {
60             object.as_mut()
61         }
62     }
socket_fd(&self) -> i3263     fn socket_fd(&self) -> i32 {
64         self.socket_fd
65     }
socket_set_fd(&mut self, fd: i32)66     fn socket_set_fd(&mut self, fd: i32) {
67         self.socket_fd = fd
68     }
socket_close(&mut self)69     fn socket_close(&mut self) {
70         if self.socket_fd >= RET_OK {
71             // safety: call unsafe function
72             let result = unsafe {
73                 libc::close(self.socket_fd as c_int)
74             };
75             if result > RET_OK {
76                 error!(LOG_LABEL, "Socket close failed result:{}", result);
77             }
78             self.socket_fd = RET_ERR;
79         }
80     }
81 }
82