1#![allow(unused)]
2
3use crate::kcp2k::Kcp2KMode;
4use crate::kcp2k_config::Kcp2KConfig;
5use crate::kcp2k_connection::Kcp2kConnection;
6use log::info;
7use revel_cell::arc::Arc;
8use socket2::{SockAddr, Socket};
9use std::fmt::{Display, Formatter};
10use std::hash::{DefaultHasher, Hash, Hasher};
11use std::io::Error;
12use std::time::{SystemTime, UNIX_EPOCH};
13
14#[derive(Debug, PartialEq, Clone, Copy)]
15#[repr(u8)]
16pub(crate) enum Kcp2KConnectionStates {
17 None = 0,
18 Authenticated = 1,
19 Connected = 2,
20 Disconnected = 3,
21}
22
23#[derive(Debug, PartialEq, Clone, Copy)]
24#[repr(u8)]
25pub(crate) enum Kcp2KReliableHeader {
26 None = 0,
27 Hello = 1,
28 Ping = 2,
29 Data = 3,
30}
31impl Into<u8> for Kcp2KReliableHeader {
32 fn into(self) -> u8 {
33 self as u8
34 }
35}
36impl From<u8> for Kcp2KReliableHeader {
37 fn from(value: u8) -> Self {
38 match value {
39 1 => Kcp2KReliableHeader::Hello,
40 2 => Kcp2KReliableHeader::Ping,
41 3 => Kcp2KReliableHeader::Data,
42 _ => Kcp2KReliableHeader::None,
43 }
44 }
45}
46
47#[derive(Debug, PartialEq, Clone, Copy)]
48#[repr(u8)]
49pub(crate) enum Kcp2KUnreliableHeader {
50 Data = 4,
51 Disconnect = 5,
52 Ping = 6,
53}
54impl Into<u8> for Kcp2KUnreliableHeader {
55 fn into(self) -> u8 {
56 self as u8
57 }
58}
59impl From<u8> for Kcp2KUnreliableHeader {
60 fn from(value: u8) -> Self {
61 match value {
62 4 => Kcp2KUnreliableHeader::Data,
63 5 => Kcp2KUnreliableHeader::Disconnect,
64 6 => Kcp2KUnreliableHeader::Ping,
65 _ => Kcp2KUnreliableHeader::Disconnect,
66 }
67 }
68}
69
70#[derive(Debug, PartialEq, Clone, Copy)]
71#[repr(u8)]
72pub enum Kcp2KChannel {
73 None = 0,
74 Reliable = 1,
75 Unreliable = 2,
76}
77
78impl Into<u8> for Kcp2KChannel {
79 fn into(self) -> u8 {
80 self as u8
81 }
82}
83
84impl From<u8> for Kcp2KChannel {
85 fn from(value: u8) -> Self {
86 match value {
87 1 => Kcp2KChannel::Reliable,
88 2 => Kcp2KChannel::Unreliable,
89 _ => Kcp2KChannel::Reliable,
90 }
91 }
92}
93
94#[derive(Clone)]
96pub enum Kcp2KError {
97 None(String), DnsResolve(String), Timeout(String), Congestion(String), InvalidReceive(String), InvalidSend(String), ConnectionClosed(String), Unexpected(String), SendError(String), ConnectionNotFound(String), }
108
109impl Display for Kcp2KError {
110 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
111 match self {
112 Kcp2KError::None(msg) => write!(f, "None: {}", msg),
113 Kcp2KError::DnsResolve(msg) => write!(f, "DnsResolve: {}", msg),
114 Kcp2KError::Timeout(msg) => write!(f, "Timeout: {}", msg),
115 Kcp2KError::Congestion(msg) => write!(f, "Congestion: {}", msg),
116 Kcp2KError::InvalidReceive(msg) => write!(f, "InvalidReceive: {}", msg),
117 Kcp2KError::InvalidSend(msg) => write!(f, "InvalidSend: {}", msg),
118 Kcp2KError::ConnectionClosed(msg) => write!(f, "ConnectionClosed: {}", msg),
119 Kcp2KError::Unexpected(msg) => write!(f, "Unexpected: {}", msg),
120 Kcp2KError::SendError(msg) => write!(f, "SendError: {}", msg),
121 Kcp2KError::ConnectionNotFound(msg) => write!(f, "ConnectionNotFound: {}", msg),
122 }
123 }
124}
125
126impl Default for Kcp2KError {
127 fn default() -> Self {
128 Kcp2KError::None("None".to_string())
129 }
130}
131pub type CallbackFuncType = fn(&Kcp2kConnection, Callback);
132
133#[derive(Debug)]
134pub enum CallbackType {
135 OnConnected,
136 OnData,
137 OnError,
138 OnDisconnected,
139}
140pub struct Callback {
142 pub r#type: CallbackType,
143 pub conn_id: u64,
144 pub channel: Kcp2KChannel,
145 pub data: Vec<u8>,
146 pub error: Kcp2KError,
147}
148
149impl Display for Callback {
150 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
151 match self.r#type {
152 CallbackType::OnConnected => {
153 write!(f, "OnConnected: id {} ", self.conn_id)
154 }
155 CallbackType::OnData => {
156 write!(f, "OnData: id {} {:?} {:?}", self.conn_id, self.channel, self.data.to_vec())
157 }
158 CallbackType::OnDisconnected => {
159 write!(f, "OnDisconnected: id {}", self.conn_id)
160 }
161 CallbackType::OnError => {
162 write!(f, "OnError: id {} - {}", self.conn_id, self.error)
163 }
164 }
165 }
166}
167
168impl Default for Callback {
169 fn default() -> Self {
170 Self {
171 r#type: CallbackType::OnError,
172 conn_id: 0,
173 channel: Kcp2KChannel::None,
174 data: Vec::new(),
175 error: Kcp2KError::default(),
176 }
177 }
178}
179
180pub(crate) fn configure_socket_buffers(socket: &Socket, config: &Kcp2KConfig) -> Result<(), Error> {
181 let initial_receive = socket.recv_buffer_size()?;
183 let initial_send = socket.send_buffer_size()?;
184
185 socket.set_recv_buffer_size(config.recv_buffer_size)?;
187 socket.set_send_buffer_size(config.send_buffer_size)?;
188
189 info!(
190 "[KCP2K] RecvBuf = {}=>{} ({}x) SendBuf = {}=>{} ({}x)",
191 initial_receive,
192 socket.recv_buffer_size()?,
193 socket.recv_buffer_size()? / initial_receive,
194 initial_send,
195 socket.send_buffer_size()?,
196 socket.send_buffer_size()? / initial_send
197 );
198 Ok(())
199}
200
201pub(crate) fn connection_hash(sock_addr: &SockAddr) -> u64 {
203 let mut hasher = DefaultHasher::new();
205 sock_addr.hash(&mut hasher);
206 hasher.finish()
207}
208
209pub(crate) fn generate_cookie() -> u32 {
211 let start = SystemTime::now();
212 let since_the_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards");
213
214 let nanos = since_the_epoch.as_nanos(); let cookie_val = (nanos as u32)
220 ^ ((nanos >> 32) as u32) ^ ((nanos >> 64) as u32)
222 ^ ((nanos >> 96) as u32);
223
224 cookie_val
225}