1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
use anyhow::anyhow;
use std::convert::TryFrom;
use std::mem::size_of;
use std::net::{IpAddr, SocketAddr};
use std::str::FromStr;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering::SeqCst;

use bytes::BytesMut;
use prost::encoding::{decode_key, encode_key, WireType};

use crate::codec::DecodeError;

pub use ya_relay_util::Payload;

include!(concat!(env!("OUT_DIR"), "/ya_relay_proto.rs"));

pub const FORWARD_SLOT_ID: SlotId = 0;
pub const FORWARD_TAG: u32 = 1;
pub const MAX_TAG_SIZE: usize = 5;
pub const SESSION_ID_SIZE: usize = 16;
pub const KEY_SIZE: usize = 1;
pub const UNRELIABLE_FLAG: u16 = 0x01;
pub const ENCRYPTED_FLAG: u16 = 0x02;

static REQUEST_ID: AtomicU64 = AtomicU64::new(0);

pub type RequestId = u64;
pub type SlotId = u32;

#[derive(Clone, Default, PartialEq)]
#[repr(C)]
pub struct Forward {
    pub session_id: [u8; SESSION_ID_SIZE],
    pub slot: u32,
    pub flags: u16,
    pub payload: Payload,
}

impl Forward {
    #[inline]
    pub const fn header_size() -> usize {
        KEY_SIZE + SESSION_ID_SIZE + size_of::<u32>() + size_of::<u16>()
    }

    pub fn new(
        session_id: impl Into<[u8; SESSION_ID_SIZE]>,
        slot: u32,
        payload: impl Into<Payload>,
    ) -> Self {
        Self {
            session_id: session_id.into(),
            slot,
            flags: 0,
            payload: payload.into(),
        }
    }

    pub fn unreliable(
        session_id: impl Into<[u8; SESSION_ID_SIZE]>,
        slot: u32,
        payload: impl Into<Payload>,
    ) -> Self {
        Self {
            session_id: session_id.into(),
            slot,
            flags: UNRELIABLE_FLAG,
            payload: payload.into(),
        }
    }

    #[inline]
    pub fn is_reliable(&self) -> bool {
        self.flags & UNRELIABLE_FLAG != UNRELIABLE_FLAG
    }

    #[inline]
    pub fn encoded_len(&self) -> usize {
        Self::header_size() + self.payload.len()
    }

    pub fn encode(self, buf: &mut BytesMut) {
        encode_key(FORWARD_TAG, WireType::LengthDelimited, buf);
        buf.extend_from_slice(&self.session_id);
        buf.extend_from_slice(&self.slot.to_be_bytes());
        buf.extend_from_slice(&self.flags.to_be_bytes());
        buf.extend_from_slice(self.payload.as_ref());
    }

    pub fn decode(mut buf: BytesMut) -> Result<Self, DecodeError> {
        if buf.len() < Self::header_size() {
            return Err(DecodeError::PacketTooShort);
        }

        let (tag, _) = decode_key(&mut buf).map_err(|_| DecodeError::PacketFormatInvalid)?;
        if tag != FORWARD_TAG {
            return Err(DecodeError::PacketFormatInvalid);
        }

        let mut session_id = [0u8; SESSION_ID_SIZE];
        session_id.copy_from_slice(&buf.split_to(SESSION_ID_SIZE));

        let slot = buf.split_to(4);
        let slot = u32::from_be_bytes([slot[0], slot[1], slot[2], slot[3]]);
        let flags = buf.split_to(2);
        let flags = u16::from_be_bytes([flags[0], flags[1]]);

        Ok(Forward {
            session_id,
            slot,
            flags,
            payload: buf.into(),
        })
    }
}

impl std::fmt::Debug for Forward {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Forward( ")?;
        write!(f, "session_id: {:2x?}, ", self.session_id)?;
        write!(
            f,
            "slot: {}, flags: {:16b}, payload: ({} B) ",
            self.slot,
            self.flags,
            self.payload.len()
        )?;
        write_payload_fmt(f, &self.payload)?;
        write!(f, " )")
    }
}

fn write_payload_fmt(f: &mut std::fmt::Formatter<'_>, buf: impl AsRef<[u8]>) -> std::fmt::Result {
    let buf = buf.as_ref();
    if buf.len() > 16 {
        let idx = 8.min(buf.len() / 2);
        write!(f, "{:02x?}..{:02x?}", &buf[..idx], &buf[buf.len() - idx..])
    } else {
        write!(f, "{:02x?}", &buf)
    }
}

impl Packet {
    pub fn request(session_id: Vec<u8>, kind: impl Into<request::Kind>) -> Self {
        Packet {
            session_id,
            kind: Some(packet::Kind::Request(Request::from(kind))),
        }
    }

    pub fn response(
        request_id: RequestId,
        session_id: Vec<u8>,
        code: impl Into<i32>,
        kind: impl Into<response::Kind>,
    ) -> Self {
        Packet {
            session_id,
            kind: Some(packet::Kind::Response(Response {
                request_id,
                code: code.into(),
                kind: Some(kind.into()),
            })),
        }
    }

    pub fn error(request_id: RequestId, session_id: Vec<u8>, code: impl Into<i32>) -> Self {
        Packet {
            session_id,
            kind: Some(packet::Kind::Response(Response {
                request_id,
                code: code.into(),
                // Probably we should send here packet response type matching request that we got.
                // We send at least anything, because client doesn't handle errors with None here.
                kind: Some(response::Kind::Pong(response::Pong {})),
            })),
        }
    }

    pub fn control(session_id: Vec<u8>, kind: impl Into<control::Kind>) -> Self {
        Packet {
            session_id,
            kind: Some(packet::Kind::Control(Control {
                kind: Some(kind.into()),
            })),
        }
    }
}

impl<T> From<T> for Request
where
    T: Into<request::Kind>,
{
    fn from(t: T) -> Self {
        Request {
            request_id: REQUEST_ID.fetch_add(1, SeqCst),
            kind: Some(t.into()),
        }
    }
}

impl TryFrom<Endpoint> for SocketAddr {
    type Error = anyhow::Error;

    fn try_from(endpoint: Endpoint) -> anyhow::Result<Self> {
        let ip = IpAddr::from_str(&endpoint.address)
            .map_err(|e| anyhow!("Unable to parse IP address. Error: {}", e))?;

        Ok(SocketAddr::new(ip, endpoint.port as u16))
    }
}

macro_rules! impl_convert_kind {
    ($module:ident, $ident:ident) => {
        impl From<$crate::proto::$module::$ident> for $crate::proto::$module::Kind {
            fn from(item: $crate::proto::$module::$ident) -> Self {
                $crate::proto::$module::Kind::$ident(item)
            }
        }

        impl std::convert::TryInto<$crate::proto::$module::$ident>
            for $crate::proto::$module::Kind
        {
            type Error = ();

            fn try_into(self) -> Result<$crate::proto::$module::$ident, Self::Error> {
                match self {
                    $crate::proto::$module::Kind::$ident(kind) => Ok(kind),
                    _ => Err(()),
                }
            }
        }
    };
}

impl_convert_kind!(request, Session);
impl_convert_kind!(request, Register);
impl_convert_kind!(request, Node);
impl_convert_kind!(request, Slot);
impl_convert_kind!(request, Neighbours);
impl_convert_kind!(request, ReverseConnection);
impl_convert_kind!(request, Ping);

impl_convert_kind!(response, Session);
impl_convert_kind!(response, Register);
impl_convert_kind!(response, Node);
impl_convert_kind!(response, Neighbours);
impl_convert_kind!(response, ReverseConnection);
impl_convert_kind!(response, Pong);

impl_convert_kind!(control, ReverseConnection);
impl_convert_kind!(control, PauseForwarding);
impl_convert_kind!(control, ResumeForwarding);
impl_convert_kind!(control, StopForwarding);
impl_convert_kind!(control, Disconnected);