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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
use blaze_pk::{
    codec::{Decodable, Encodable},
    error::DecodeResult,
    reader::TdfReader,
    tag::TdfType,
    types::Union,
    value_type,
    writer::TdfWriter,
};
use serde::{ser::SerializeStruct, Serialize};
use std::{
    fmt::{Debug, Display},
    str::Split,
};
use utils::types::PlayerID;

/// Networking information for an instance. Contains the
/// host address and the port
pub struct InstanceNet {
    pub host: InstanceHost,
    pub port: Port,
}

impl From<(String, Port)> for InstanceNet {
    fn from((host, port): (String, Port)) -> Self {
        let host = InstanceHost::from(host);
        Self { host, port }
    }
}

impl Encodable for InstanceNet {
    fn encode(&self, writer: &mut TdfWriter) {
        self.host.encode(writer);
        writer.tag_u16(b"PORT", self.port);
        writer.tag_group_end();
    }
}

impl Decodable for InstanceNet {
    fn decode(reader: &mut TdfReader) -> DecodeResult<Self> {
        let host: InstanceHost = InstanceHost::decode(reader)?;
        let port: u16 = reader.tag("PORT")?;
        reader.read_byte()?;
        Ok(Self { host, port })
    }
}

value_type!(InstanceNet, TdfType::Group);

/// Type of instance details provided either hostname
/// encoded as string or IP address encoded as NetAddress
pub enum InstanceHost {
    Host(String),
    Address(NetAddress),
}

/// Attempts to convert the provided value into a instance type. If
/// the provided value is an IPv4 value then Address is used otherwise
/// Host is used.
impl From<String> for InstanceHost {
    fn from(value: String) -> Self {
        if let Some(address) = NetAddress::try_from_ipv4(&value) {
            Self::Address(address)
        } else {
            Self::Host(value)
        }
    }
}

/// Function for converting an instance type into its address
/// string value for use in connections
impl From<InstanceHost> for String {
    fn from(value: InstanceHost) -> Self {
        match value {
            InstanceHost::Address(value) => value.to_ipv4(),
            InstanceHost::Host(value) => value,
        }
    }
}

impl Encodable for InstanceHost {
    fn encode(&self, writer: &mut TdfWriter) {
        match self {
            InstanceHost::Host(value) => writer.tag_str(b"HOST", value),
            InstanceHost::Address(value) => writer.tag_u32(b"IP", value.0),
        }
    }
}

impl Decodable for InstanceHost {
    fn decode(reader: &mut TdfReader) -> DecodeResult<Self> {
        let host: Option<String> = reader.try_tag("HOST")?;
        if let Some(host) = host {
            return Ok(Self::Host(host));
        }
        let ip: NetAddress = reader.tag("IP")?;
        Ok(Self::Address(ip))
    }
}

/// Details about an instance. This is used for the redirector system
/// to both encode for redirections and decode for the retriever system
pub struct InstanceDetails {
    /// The networking information for the instance
    pub net: InstanceNet,
    /// Whether the host requires a secure connection (SSLv3)
    pub secure: bool,
}

impl Encodable for InstanceDetails {
    fn encode(&self, writer: &mut TdfWriter) {
        writer.tag_union_start(b"ADDR", NetworkAddressType::Server.into());
        writer.tag_value(b"VALU", &self.net);

        writer.tag_bool(b"SECU", self.secure);
        writer.tag_bool(b"XDNS", false);
    }
}

impl Decodable for InstanceDetails {
    fn decode(reader: &mut TdfReader) -> DecodeResult<Self> {
        let net: InstanceNet = match reader.tag::<Union<InstanceNet>>("ADDR")? {
            Union::Set { value, .. } => value,
            Union::Unset => {
                return Err(blaze_pk::error::DecodeError::MissingTag {
                    tag: "ADDR".to_string(),
                    ty: TdfType::Union,
                })
            }
        };
        let secure: bool = reader.tag("SECU")?;
        Ok(InstanceDetails { net, secure })
    }
}

pub struct UpdateExtDataAttr {
    pub flags: u8,
    pub player_id: PlayerID,
}

impl Encodable for UpdateExtDataAttr {
    fn encode(&self, writer: &mut TdfWriter) {
        writer.tag_u8(b"FLGS", self.flags);
        writer.tag_u32(b"ID", self.player_id);
    }
}

#[derive(Debug, Copy, Clone, Serialize)]
pub enum NetworkAddressType {
    Server,
    Client,
    Pair,
    IpAddress,
    HostnameAddress,
    Unknown(u8),
}

impl NetworkAddressType {
    pub fn value(&self) -> u8 {
        match self {
            Self::Server => 0x0,
            Self::Client => 0x1,
            Self::Pair => 0x2,
            Self::IpAddress => 0x3,
            Self::HostnameAddress => 0x4,
            Self::Unknown(value) => *value,
        }
    }

    pub fn from_value(value: u8) -> Self {
        match value {
            0x0 => Self::Server,
            0x1 => Self::Client,
            0x2 => Self::Pair,
            0x3 => Self::IpAddress,
            0x4 => Self::HostnameAddress,
            value => Self::Unknown(value),
        }
    }
}

impl From<NetworkAddressType> for u8 {
    fn from(value: NetworkAddressType) -> Self {
        value.value()
    }
}

/// Structure for storing extended network data
#[derive(Debug, Copy, Clone, Default, Serialize)]
pub struct QosNetworkData {
    /// Downstream bits per second
    pub dbps: u16,
    /// Natt type
    pub natt: NatType,
    /// Upstream bits per second
    pub ubps: u16,
}

//
#[derive(Debug, Copy, Clone, Serialize)]
pub enum NatType {
    Open,
    Moderate,
    Sequential,
    Strict,
    Unknown(u8),
}

impl NatType {
    pub fn value(&self) -> u8 {
        match self {
            Self::Open => 0x1,
            Self::Moderate => 0x2,
            Self::Sequential => 0x3,
            Self::Strict => 0x4,
            Self::Unknown(value) => *value,
        }
    }

    pub fn from_value(value: u8) -> Self {
        match value {
            0x1 => Self::Open,
            0x2 => Self::Moderate,
            0x3 => Self::Sequential,
            0x4 => Self::Strict,
            value => Self::Unknown(value),
        }
    }
}

impl Default for NatType {
    fn default() -> Self {
        Self::Strict
    }
}

impl Encodable for NatType {
    #[inline]
    fn encode(&self, writer: &mut TdfWriter) {
        writer.write_u8(self.value());
    }
}

impl Decodable for NatType {
    #[inline]
    fn decode(reader: &mut TdfReader) -> DecodeResult<Self> {
        Ok(Self::from_value(reader.read_u8()?))
    }
}

value_type!(NatType, TdfType::VarInt);

impl Encodable for QosNetworkData {
    fn encode(&self, writer: &mut TdfWriter) {
        writer.tag_u16(b"DBPS", self.dbps);
        writer.tag_value(b"NATT", &self.natt);
        writer.tag_u16(b"UBPS", self.ubps);
        writer.tag_group_end();
    }
}

impl Decodable for QosNetworkData {
    fn decode(reader: &mut TdfReader) -> DecodeResult<Self> {
        let dbps: u16 = reader.tag("DBPS")?;
        let natt: NatType = reader.tag("NATT")?;
        let ubps: u16 = reader.tag("UBPS")?;
        reader.read_byte()?;
        Ok(Self { dbps, natt, ubps })
    }
}

value_type!(QosNetworkData, TdfType::Group);

/// Type alias for ports which are always u16
pub type Port = u16;

#[derive(Debug, Default, Copy, Clone, Serialize)]
pub struct NetData {
    pub groups: NetGroups,
    pub qos: QosNetworkData,
    pub hardware_flags: u16,
    pub is_set: bool,
}

#[derive(Debug, Default, Copy, Clone, Serialize)]
pub struct NetGroups {
    pub internal: NetGroup,
    pub external: NetGroup,
}

impl Encodable for NetGroups {
    fn encode(&self, writer: &mut TdfWriter) {
        writer.tag_group(b"EXIP");
        self.external.encode(writer);

        writer.tag_group(b"INIP");
        self.internal.encode(writer);

        writer.tag_group_end();
    }
}

impl Decodable for NetGroups {
    fn decode(reader: &mut TdfReader) -> DecodeResult<Self> {
        let external: NetGroup = reader.tag("EXIP")?;
        let internal: NetGroup = reader.tag("INIP")?;
        reader.read_byte()?;
        Ok(Self { external, internal })
    }
}

value_type!(NetGroups, TdfType::Group);

impl NetData {
    pub fn tag_groups(&self, tag: &[u8], writer: &mut TdfWriter) {
        if !self.is_set {
            writer.tag_union_unset(tag);
            return;
        }

        writer.tag_union_value(tag, NetworkAddressType::Pair.into(), b"VALU", self.groups);
    }
}

/// Structure for a networking group which consists of a
/// networking address and port value
#[derive(Debug, Copy, Clone, Default, Eq, PartialEq)]
pub struct NetGroup(pub NetAddress, pub Port);

impl Encodable for NetGroup {
    fn encode(&self, writer: &mut TdfWriter) {
        writer.tag_u32(b"IP", self.0 .0);
        writer.tag_u16(b"PORT", self.1);
        writer.tag_group_end();
    }
}

impl Decodable for NetGroup {
    fn decode(reader: &mut TdfReader) -> DecodeResult<Self> {
        let ip: NetAddress = reader.tag("IP")?;
        let port: u16 = reader.tag("PORT")?;
        reader.read_byte()?;
        Ok(Self(ip, port))
    }
}

value_type!(NetGroup, TdfType::Group);

impl Serialize for NetGroup {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut s = serializer.serialize_struct("NetGroup", 2)?;
        s.serialize_field("address", &self.0)?;
        s.serialize_field("port", &self.1)?;
        s.end()
    }
}

/// Structure for wrapping a Blaze networking address
#[derive(Copy, Clone, Default, Eq, PartialEq)]
pub struct NetAddress(pub u32);

impl Encodable for NetAddress {
    fn encode(&self, writer: &mut TdfWriter) {
        writer.write_u32(self.0);
    }
}

impl Decodable for NetAddress {
    fn decode(reader: &mut TdfReader) -> DecodeResult<Self> {
        let value = reader.read_u32()?;
        Ok(Self(value))
    }
}

value_type!(NetAddress, TdfType::VarInt);

/// Debug trait implementation sample implementation as the Display
/// implementation so that is just called instead
impl Debug for NetAddress {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Display::fmt(self, f)
    }
}

/// Display trait implementation for NetAddress. If the value is valid
/// the value is translated into the IPv4 representation
impl Display for NetAddress {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let value = self.to_ipv4();
        f.write_str(&value)
    }
}

/// Serialization implementation for NetAddress which uses the IPv4
/// representation implemented in Display
impl Serialize for NetAddress {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let value = self.to_string();
        serializer.serialize_str(&value)
    }
}

impl NetAddress {
    /// Addresses where the value is zero are considered to be
    /// invalid addresses that could not be parsed. Parsing these
    /// addresses would result in the address 0.0.0.0
    pub fn is_invalid(&self) -> bool {
        self.0 == 0
    }

    /// Converts the provided IPv4 string into a NetAddress
    pub fn from_ipv4(value: &str) -> NetAddress {
        if let Some(value) = Self::try_from_ipv4(value) {
            value
        } else {
            NetAddress(0)
        }
    }

    /// Attempts to convert the provided IP address string into a
    /// NetAddress value. If the value is not a valid IPv4 address
    /// then None will be returned.
    pub fn try_from_ipv4(value: &str) -> Option<NetAddress> {
        let mut parts = value.split('.');
        let a = Self::next_ip_chunk(&mut parts)?;
        let b = Self::next_ip_chunk(&mut parts)?;
        let c = Self::next_ip_chunk(&mut parts)?;
        let d = Self::next_ip_chunk(&mut parts)?;

        let value = a << 24 | b << 16 | c << 8 | d;
        Some(NetAddress(value))
    }

    /// Obtains the next IPv4 (u8) chunk value from the provided
    /// split iterator
    fn next_ip_chunk(iter: &mut Split<char>) -> Option<u32> {
        iter.next()?
            .parse::<u32>()
            .ok()
            .filter(|value| 255.ge(value))
    }

    /// Converts the value stored in this NetAddress to an IPv4 string
    pub fn to_ipv4(&self) -> String {
        let a = ((self.0 >> 24) & 0xFF) as u8;
        let b = ((self.0 >> 16) & 0xFF) as u8;
        let c = ((self.0 >> 8) & 0xFF) as u8;
        let d = (self.0 & 0xFF) as u8;
        format!("{a}.{b}.{c}.{d}")
    }
}