pso2packetlib 0.5.0

A library for working with the PSO2 network protocol
Documentation
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
//! Client <-> Server connection handling.

pub use crate::encryption::EncryptionError;

pub(crate) mod conn_impl;
#[cfg(feature = "split_connection")]
use crate::encryption::{DecryptorType, EncryptorType};
#[cfg(feature = "ppac")]
use crate::ppac::{Direction, PPACWriter};
use crate::{
    encryption::{encrypt, Encryption},
    protocol::{login::EncryptionRequestPacket, Packet, PacketType, ProtocolRW},
};
use conn_impl::{ConnectionReader, ConnectionWriter};
use rsa::{
    pkcs8::{DecodePrivateKey, DecodePublicKey},
    BigUint, RsaPrivateKey, RsaPublicKey,
};
#[cfg(all(feature = "split_connection", not(feature = "tokio")))]
use std::sync::mpsc::{Receiver, Sender};
#[cfg(all(feature = "split_connection", feature = "ppac"))]
use std::sync::{Arc, Mutex};
#[cfg(all(feature = "split_connection", feature = "tokio"))]
use tokio::{
    net::tcp::{OwnedReadHalf, OwnedWriteHalf},
    sync::mpsc::{UnboundedReceiver as Receiver, UnboundedSender as Sender},
};

#[derive(Debug, thiserror::Error)]
pub enum ConnectionError {
    #[error("packet error occured: {0}")]
    PacketError(#[from] crate::protocol::PacketError),
    #[error("encryption error occured: {0}")]
    EncryptionError(#[from] crate::encryption::EncryptionError),
    #[error(transparent)]
    Io(#[from] std::io::Error),
    #[cfg(feature = "ppac")]
    #[error("error occured while storing a packet: {0}")]
    PPACError(#[from] crate::ppac::PPACError),
}

/// Represents a connection between a client and a server.
#[derive(Debug)]
pub struct Connection<P: ProtocolRW + Send> {
    // this is probably not the best way to do this
    #[cfg(not(feature = "tokio"))]
    stream: std::net::TcpStream,
    #[cfg(feature = "tokio")]
    stream: tokio::net::TcpStream,
    encryption: Encryption,
    read: ConnectionReader,
    write: ConnectionWriter,
    read_packets: Vec<P>,
    in_keyfile: PrivateKey,
    out_keyfile: PublicKey,
    packet_type: PacketType,
    #[cfg(feature = "ppac")]
    ppac: Option<PPACWriter<std::fs::File>>,
    #[cfg(feature = "ppac")]
    direction: Direction,
}

/// Possible RSA public key formats.
#[derive(Debug, Clone)]
pub enum PublicKey {
    /// No public key provided.
    None,
    /// Path to the RSA key in the PEM-encoded PKCS#8 file.
    Path(std::path::PathBuf),
    /// RSA key in component form. All values are in little endian form.
    Params {
        /// RSA modulus 'n'.
        n: Vec<u8>,
        /// Public exponent 'e'.
        e: Vec<u8>,
    },
    Key(RsaPublicKey),
}

/// Possible RSA private key formats.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum PrivateKey {
    /// No private key provided.
    None,
    /// Path to the RSA key in the PEM-encoded PKCS#8 file.
    Path(std::path::PathBuf),
    /// RSA key in component form. All values are in little endian form.
    Params {
        /// RSA modulus 'n'.
        n: Vec<u8>,
        /// Public exponent 'e'.
        e: Vec<u8>,
        /// Private exponent 'd'.
        d: Vec<u8>,
        /// First prime 'p'.
        p: Vec<u8>,
        /// Second prime 'q'.
        q: Vec<u8>,
    },
    Key(RsaPrivateKey),
}

impl<P: ProtocolRW + Send> Connection<P> {
    /// Creates a new connection.
    /// `in_keyfile` is the RSA key to decrypt encryption request.
    /// `out_keyfile` is the RSA key to encrypt encryption request.
    ///
    /// # Note
    ///
    /// If the provided stream is not set to a nonblocking mode then any read/write operation will
    /// block.
    ///
    /// # Panics
    ///
    /// If `tokio` feature is enabled then this function will implicitly convert a stream to an
    /// async stream. This function panics if this conversion fails.
    pub fn new(
        stream: std::net::TcpStream,
        packet_type: PacketType,
        in_keyfile: PrivateKey,
        out_keyfile: PublicKey,
    ) -> Self {
        #[cfg(feature = "tokio")]
        let stream = {
            stream
                .set_nonblocking(true)
                .expect("set_nonblocking failed");
            tokio::net::TcpStream::from_std(stream).expect("Failed to make async stream")
        };
        Self {
            stream,
            encryption: Encryption::None,
            read: ConnectionReader::default(),
            write: ConnectionWriter::default(),
            read_packets: Vec::new(),
            in_keyfile,
            out_keyfile,
            packet_type,
            #[cfg(feature = "ppac")]
            ppac: None,
            #[cfg(feature = "ppac")]
            direction: Direction::ToServer,
        }
    }

    /// Creates a new connection.
    /// `in_keyfile` is the RSA key to decrypt encryption request.
    /// `out_keyfile` is the RSA key to encrypt encryption request.
    #[cfg(feature = "tokio")]
    #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
    pub fn new_async(
        stream: tokio::net::TcpStream,
        packet_type: PacketType,
        in_keyfile: PrivateKey,
        out_keyfile: PublicKey,
    ) -> Self {
        Self {
            stream,
            encryption: Encryption::None,
            read: ConnectionReader::default(),
            write: ConnectionWriter::default(),
            read_packets: Vec::new(),
            in_keyfile,
            out_keyfile,
            packet_type,
            #[cfg(feature = "ppac")]
            ppac: None,
            #[cfg(feature = "ppac")]
            direction: Direction::ToServer,
        }
    }

    /// Returns the ip address of the client.
    pub fn get_ip(&self) -> std::io::Result<std::net::Ipv4Addr> {
        let ip = self.stream.peer_addr()?.ip();
        let ip = match ip {
            std::net::IpAddr::V4(x) => x,
            std::net::IpAddr::V6(_) => std::net::Ipv4Addr::UNSPECIFIED,
        };
        Ok(ip)
    }

    /// Changes connection type.
    pub fn change_packet_type(&mut self, packet_type: PacketType) {
        #[cfg(feature = "ppac")]
        if let Some(writer) = &mut self.ppac {
            let _ = writer.change_packet_type(packet_type);
        }
        self.packet_type = packet_type;
    }

    /// Splits the connection into separate read and write components.
    #[cfg(feature = "split_connection")]
    #[cfg_attr(docsrs, doc(cfg(feature = "split_connection")))]
    pub fn into_split(self) -> std::io::Result<(ConnectionRead<P>, ConnectionWrite)> {
        #[cfg(feature = "tokio")]
        let (read, write) = self.stream.into_split();
        #[cfg(not(feature = "tokio"))]
        let (read, write) = (self.stream.try_clone()?, self.stream);
        #[cfg(feature = "ppac")]
        let ppac = self
            .ppac
            .map(|p| std::sync::Arc::new(std::sync::Mutex::new(p)));
        #[cfg(feature = "tokio")]
        let ((reader_send, writer_recv), (writer_send, reader_recv)) = (
            tokio::sync::mpsc::unbounded_channel(),
            tokio::sync::mpsc::unbounded_channel(),
        );
        #[cfg(not(feature = "tokio"))]
        let ((reader_send, writer_recv), (writer_send, reader_recv)) =
            (std::sync::mpsc::channel(), std::sync::mpsc::channel());
        #[cfg(feature = "tokio")]
        let ((readpt_send, writept_recv), (writept_send, readpt_recv)) = (
            tokio::sync::mpsc::unbounded_channel(),
            tokio::sync::mpsc::unbounded_channel(),
        );
        #[cfg(not(feature = "tokio"))]
        let ((readpt_send, writept_recv), (writept_send, readpt_recv)) =
            (std::sync::mpsc::channel(), std::sync::mpsc::channel());
        let (enc, dec) = self.encryption.into_split();
        let reader = ConnectionRead {
            stream: read,
            enc_channel: (reader_send, reader_recv),
            packettype_channel: (readpt_send, readpt_recv),
            encryption: dec,
            read: self.read,
            read_packets: self.read_packets,
            in_keyfile: self.in_keyfile.clone(),
            packet_type: self.packet_type,
            #[cfg(feature = "ppac")]
            ppac: ppac.clone(),
            #[cfg(feature = "ppac")]
            direction: self.direction,
        };
        let writer = ConnectionWrite {
            stream: write,
            enc_channel: (writer_send, writer_recv),
            packettype_channel: (writept_send, writept_recv),
            write: self.write,
            encryption: enc,
            out_keyfile: self.out_keyfile,
            packet_type: self.packet_type,
            #[cfg(feature = "ppac")]
            ppac,
            #[cfg(feature = "ppac")]
            direction: self.direction,
        };
        Ok((reader, writer))
    }

    /// Reads a packet from the stream.
    ///
    /// # Note
    ///
    /// If `tokio` feature is enabled this function becomes nonblocking
    pub fn read_packet(&mut self) -> Result<P, ConnectionError> {
        if !self.read_packets.is_empty() {
            return Ok(self.read_packets.remove(0));
        }
        let data = self
            .read
            .try_read_data(&mut self.stream, &mut self.encryption)?;
        #[cfg(feature = "ppac")]
        if let Some(writer) = &mut self.ppac {
            let direction = match self.direction {
                Direction::ToServer => Direction::ToClient,
                Direction::ToClient => Direction::ToServer,
            };
            writer.write_data(crate::ppac::get_now(), direction, &data)?;
        }
        self.parse_packet(&data)
    }

    /// Reads a packet from the stream.
    #[cfg(feature = "tokio")]
    #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
    pub async fn read_packet_async(&mut self) -> Result<P, ConnectionError> {
        if !self.read_packets.is_empty() {
            return Ok(self.read_packets.remove(0));
        }
        let data = self
            .read
            .read_data_async(&mut self.stream, &mut self.encryption)
            .await?;
        #[cfg(feature = "ppac")]
        if let Some(writer) = &mut self.ppac {
            let direction = match self.direction {
                Direction::ToServer => Direction::ToClient,
                Direction::ToClient => Direction::ToServer,
            };
            writer.write_data(crate::ppac::get_now(), direction, &data)?;
        }
        self.parse_packet(&data)
    }
    fn parse_packet(&mut self, data: &[u8]) -> Result<P, ConnectionError> {
        let mut packets = P::read(data, self.packet_type)?;
        let mut packet = packets.remove(0);
        self.read_packets.append(&mut packets);
        if let Some(data) = packet.mut_enc_data() {
            if !matches!(&self.in_keyfile, PrivateKey::None) {
                let dec_data = Encryption::decrypt_rsa_data(data, &self.in_keyfile)?;
                self.encryption = Encryption::from_dec_data(
                    &dec_data,
                    matches!(self.packet_type, PacketType::NGS),
                )?;
                *data = dec_data;
            }
        }
        Ok(packet)
    }

    /// Creates a packet storage file. `direction` is the direction of the `write` side of the
    /// connection.
    #[cfg(feature = "ppac")]
    #[cfg_attr(docsrs, doc(cfg(feature = "ppac")))]
    pub fn create_ppac<PT: AsRef<std::path::Path>>(
        &mut self,
        path: PT,
        direction: Direction,
    ) -> Result<(), ConnectionError> {
        self.ppac = Some(PPACWriter::new(
            std::fs::File::create(path)?,
            self.packet_type,
            true,
        )?);
        self.direction = direction;
        Ok(())
    }

    /// Sends a packet.
    ///
    /// # Note
    ///
    /// If `tokio` feature is enabled this function becomes nonblocking
    pub fn write_packet(&mut self, packet: &impl ProtocolRW) -> Result<(), ConnectionError> {
        self.prepare_data(packet)?;
        self.write.flush(&mut self.stream)?;
        Ok(())
    }

    /// Sends a packet.
    #[cfg(feature = "tokio")]
    #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
    pub async fn write_packet_async(
        &mut self,
        packet: &(impl ProtocolRW + Sync),
    ) -> Result<(), ConnectionError> {
        self.prepare_data(packet)?;
        self.write.flush_async(&mut self.stream).await?;
        Ok(())
    }

    fn prepare_data(&mut self, packet: &impl ProtocolRW) -> Result<(), ConnectionError> {
        let _packet = if packet.is_enc_data() && !matches!(&self.out_keyfile, PublicKey::None) {
            let rsa_data = packet
                .as_enc_data()
                .expect("is_enc_data returned true while as_enc_data returned None");
            let mut new_packet = EncryptionRequestPacket::default();
            let enc =
                Encryption::from_dec_data(rsa_data, matches!(self.packet_type, PacketType::NGS))?;
            self.encryption = enc;
            new_packet.rsa_data = encrypt(rsa_data, &self.out_keyfile)?.into();
            let packet = Packet::EncryptionRequest(new_packet).write(self.packet_type);
            self.write.prepare_data(&packet, &mut Encryption::None)?;
            packet
        } else {
            let packet = packet.write(self.packet_type);
            self.write.prepare_data(&packet, &mut self.encryption)?;
            packet
        };
        #[cfg(feature = "ppac")]
        if let Some(writer) = &mut self.ppac {
            writer.write_data(crate::ppac::get_now(), self.direction, &_packet)?;
        }
        Ok(())
    }

    /// Returns the encryption key (for [`Packet::EncryptionResponse`]).
    pub fn get_key(&mut self) -> Vec<u8> {
        self.encryption.get_key()
    }
    /// Writes all pending packets.
    pub fn flush(&mut self) -> std::io::Result<()> {
        self.write.flush(&mut self.stream)
    }
    /// Writes all pending packets.
    #[cfg(feature = "tokio")]
    #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
    pub async fn flush_async(&mut self) -> std::io::Result<()> {
        self.write.flush_async(&mut self.stream).await
    }
}

/// Represents a reader portion of the connection between a client and a server.
#[cfg(feature = "split_connection")]
#[cfg_attr(docsrs, doc(cfg(feature = "split_connection")))]
#[derive(Debug)]
pub struct ConnectionRead<P: ProtocolRW + Send> {
    #[cfg(not(feature = "tokio"))]
    stream: std::net::TcpStream,
    #[cfg(feature = "tokio")]
    stream: OwnedReadHalf,
    enc_channel: (Sender<EncryptorType>, Receiver<DecryptorType>),
    packettype_channel: (Sender<PacketType>, Receiver<PacketType>),
    read: ConnectionReader,
    encryption: DecryptorType,
    read_packets: Vec<P>,
    in_keyfile: PrivateKey,
    packet_type: PacketType,
    #[cfg(feature = "ppac")]
    ppac: Option<Arc<Mutex<PPACWriter<std::fs::File>>>>,
    #[cfg(feature = "ppac")]
    direction: Direction,
}

/// Represents a writer portion of the connection between a client and a server.
#[cfg(feature = "split_connection")]
#[cfg_attr(docsrs, doc(cfg(feature = "split_connection")))]
#[derive(Debug)]
pub struct ConnectionWrite {
    #[cfg(not(feature = "tokio"))]
    stream: std::net::TcpStream,
    #[cfg(feature = "tokio")]
    stream: OwnedWriteHalf,
    enc_channel: (Sender<DecryptorType>, Receiver<EncryptorType>),
    packettype_channel: (Sender<PacketType>, Receiver<PacketType>),
    write: ConnectionWriter,
    encryption: EncryptorType,
    out_keyfile: PublicKey,
    packet_type: PacketType,
    #[cfg(feature = "ppac")]
    ppac: Option<Arc<Mutex<PPACWriter<std::fs::File>>>>,
    #[cfg(feature = "ppac")]
    direction: Direction,
}

#[cfg(feature = "split_connection")]
#[cfg_attr(docsrs, doc(cfg(feature = "split_connection")))]
impl<P: ProtocolRW + Send> ConnectionRead<P> {
    /// Returns the ip address of the client.
    pub fn get_ip(&self) -> std::io::Result<std::net::Ipv4Addr> {
        let ip = self.stream.peer_addr()?.ip();
        let ip = match ip {
            std::net::IpAddr::V4(x) => x,
            std::net::IpAddr::V6(_) => std::net::Ipv4Addr::UNSPECIFIED,
        };
        Ok(ip)
    }

    /// Changes connection type. Automatically changes the other side.
    pub fn change_packet_type(&mut self, packet_type: PacketType) {
        #[cfg(feature = "ppac")]
        if let Some(writer) = &mut self.ppac {
            let mut lock = writer.lock().unwrap();
            let _ = lock.change_packet_type(packet_type);
        }
        self.packet_type = packet_type;
        let _ = self.packettype_channel.0.send(packet_type);
    }

    /// Same as [`std::net::TcpStream::set_nonblocking`]. Does nothing if `tokio` feature is
    /// enabled.
    pub fn set_nonblocking(&self, _nonblocking: bool) -> std::io::Result<()> {
        #[cfg(not(feature = "tokio"))]
        self.stream.set_nonblocking(_nonblocking)?;
        Ok(())
    }

    /// Inserts a packet storage file. `direction` is the direction of the `write` side of the
    /// connection.
    #[cfg(feature = "ppac")]
    #[cfg_attr(docsrs, doc(cfg(feature = "ppac")))]
    pub fn set_ppac(
        &mut self,
        ppac: Arc<Mutex<PPACWriter<std::fs::File>>>,
        direction: Direction,
    ) -> std::io::Result<()> {
        self.ppac = Some(ppac);
        self.direction = direction;
        Ok(())
    }

    /// Reads a packet from stream.
    ///
    /// # Note
    ///
    /// If the encryption was not yet setup (i.e [`Packet::EncryptionResponse`] was not
    /// sent) and the stream is in a blocking mode then this function might not setup
    /// encryption correctly  
    pub fn read_packet(&mut self) -> Result<P, ConnectionError> {
        if !self.read_packets.is_empty() {
            return Ok(self.get_one_packet());
        }
        if let Ok(enc) = self.enc_channel.1.try_recv() {
            self.encryption = enc
        }
        let data = self
            .read
            .try_read_data(&mut self.stream, &mut self.encryption)?;
        if let Ok(packet_type) = self.packettype_channel.1.try_recv() {
            self.packet_type = packet_type
        }
        #[cfg(feature = "ppac")]
        if let Some(writer) = &self.ppac {
            let direction = match self.direction {
                Direction::ToServer => Direction::ToClient,
                Direction::ToClient => Direction::ToServer,
            };
            let mut lock = writer.lock().unwrap();
            lock.write_data(crate::ppac::get_now(), direction, &data)?;
        }
        self.parse_packet(&data)
    }
    /// Reads a packet from stream.
    #[cfg(feature = "tokio")]
    #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
    pub async fn read_packet_async(&mut self) -> Result<P, ConnectionError> {
        if !self.read_packets.is_empty() {
            return Ok(self.get_one_packet());
        }
        let data = loop {
            tokio::select! {
                result = self
                    .read
                    .read_data_async(&mut self.stream, &mut self.encryption) =>
                {
                    let data = result?;
                    break data;
                }

                Some(enc) = self.enc_channel.1.recv() => {
                    self.encryption = enc
                }

                Some(packet_type) = self.packettype_channel.1.recv() => {
                    self.packet_type = packet_type
                }
            }
        };
        #[cfg(feature = "ppac")]
        if let Some(writer) = &self.ppac {
            let direction = match self.direction {
                Direction::ToServer => Direction::ToClient,
                Direction::ToClient => Direction::ToServer,
            };
            let mut lock = writer.lock().unwrap();
            lock.write_data(crate::ppac::get_now(), direction, &data)?;
        }
        self.parse_packet(&data)
    }
    fn parse_packet(&mut self, data: &[u8]) -> Result<P, ConnectionError> {
        let mut packets = P::read(data, self.packet_type)?;
        let mut packet = packets.remove(0);
        self.read_packets.append(&mut packets);
        if let Some(data) = packet.mut_enc_data() {
            if !matches!(&self.in_keyfile, PrivateKey::None) {
                let dec_data = Encryption::decrypt_rsa_data(data, &self.in_keyfile)?;
                let (enc, dec) = Encryption::from_dec_data(
                    &dec_data,
                    matches!(self.packet_type, PacketType::NGS),
                )?
                .into_split();
                *data = dec_data;
                let _ = self.enc_channel.0.send(enc);
                self.encryption = dec;
            }
        }
        Ok(packet)
    }

    /// Returns the encryption key (for [`Packet::EncryptionResponse`]).
    pub fn get_key(&mut self) -> Vec<u8> {
        if matches!(self.encryption, DecryptorType::None) {
            if let Ok(enc) = self.enc_channel.1.try_recv() {
                self.encryption = enc
            }
        }
        self.encryption.get_key()
    }
    fn get_one_packet(&mut self) -> P {
        self.read_packets.remove(0)
    }
}

#[cfg(feature = "split_connection")]
#[cfg_attr(docsrs, doc(cfg(feature = "split_connection")))]
impl ConnectionWrite {
    /// Returns the ip address of the client.
    pub fn get_ip(&self) -> std::io::Result<std::net::Ipv4Addr> {
        let ip = self.stream.peer_addr()?.ip();
        let ip = match ip {
            std::net::IpAddr::V4(x) => x,
            std::net::IpAddr::V6(_) => std::net::Ipv4Addr::UNSPECIFIED,
        };
        Ok(ip)
    }

    /// Changes connection type. Automatically changes the other side.
    pub fn change_packet_type(&mut self, packet_type: PacketType) {
        #[cfg(feature = "ppac")]
        if let Some(writer) = &mut self.ppac {
            let mut lock = writer.lock().unwrap();
            let _ = lock.change_packet_type(packet_type);
        }
        self.packet_type = packet_type;
        let _ = self.packettype_channel.0.send(packet_type);
    }

    /// Same as [`std::net::TcpStream::set_nonblocking`]. Does nothing if `tokio` feature is
    /// enabled.
    pub fn set_nonblocking(&self, _nonblocking: bool) -> std::io::Result<()> {
        #[cfg(not(feature = "tokio"))]
        self.stream.set_nonblocking(_nonblocking)?;
        Ok(())
    }

    /// Inserts a packet storage file. `direction` is the direction of the `write` side of the
    /// connection.
    #[cfg(feature = "ppac")]
    #[cfg_attr(docsrs, doc(cfg(feature = "ppac")))]
    pub fn set_ppac(
        &mut self,
        ppac: Arc<Mutex<PPACWriter<std::fs::File>>>,
        direction: Direction,
    ) -> std::io::Result<()> {
        self.ppac = Some(ppac);
        self.direction = direction;
        Ok(())
    }

    /// Sends a packet.
    ///
    /// # Note
    ///
    /// If `tokio` feature is enabled this function becomes nonblocking
    pub fn write_packet(&mut self, packet: &impl ProtocolRW) -> Result<(), ConnectionError> {
        self.prepare_data(packet)?;
        self.write.flush(&mut self.stream)?;
        Ok(())
    }

    /// Sends a packet.
    #[cfg(feature = "tokio")]
    #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
    pub async fn write_packet_async(
        &mut self,
        packet: &(impl ProtocolRW + Sync),
    ) -> Result<(), ConnectionError> {
        self.prepare_data(packet)?;
        self.write.flush_async(&mut self.stream).await?;
        Ok(())
    }
    fn prepare_data(&mut self, packet: &impl ProtocolRW) -> Result<(), ConnectionError> {
        if matches!(self.encryption, EncryptorType::None) {
            if let Ok(enc) = self.enc_channel.1.try_recv() {
                self.encryption = enc
            }
        }
        if let Ok(packet_type) = self.packettype_channel.1.try_recv() {
            self.packet_type = packet_type
        }
        let _packet = if packet.is_enc_data() && !matches!(&self.out_keyfile, PublicKey::None) {
            let rsa_data = packet
                .as_enc_data()
                .expect("is_enc_data returned true while as_enc_data returned None");
            let mut new_packet = EncryptionRequestPacket::default();
            let (enc, dec) =
                Encryption::from_dec_data(rsa_data, matches!(self.packet_type, PacketType::NGS))?
                    .into_split();
            let _ = self.enc_channel.0.send(dec);
            self.encryption = enc;
            new_packet.rsa_data = encrypt(rsa_data, &self.out_keyfile)?.into();
            let packet = Packet::EncryptionRequest(new_packet).write(self.packet_type);
            self.write.prepare_data(&packet, &mut EncryptorType::None)?;
            packet
        } else {
            let packet = packet.write(self.packet_type);
            self.write.prepare_data(&packet, &mut self.encryption)?;
            packet
        };
        #[cfg(feature = "ppac")]
        if let Some(writer) = &self.ppac {
            let mut lock = writer.lock().unwrap();
            lock.write_data(crate::ppac::get_now(), self.direction, &_packet)?;
        }

        Ok(())
    }

    /// Returns the encryption key (for [`Packet::EncryptionResponse`]).
    pub fn get_key(&mut self) -> Vec<u8> {
        if matches!(self.encryption, EncryptorType::None) {
            if let Ok(enc) = self.enc_channel.1.try_recv() {
                self.encryption = enc
            }
        }
        self.encryption.get_key()
    }
    /// Writes all pending packets.
    pub fn flush(&mut self) -> std::io::Result<()> {
        self.write.flush(&mut self.stream)
    }
    /// Writes all pending packets.
    #[cfg(feature = "tokio")]
    #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
    pub async fn flush_async(&mut self) -> std::io::Result<()> {
        self.write.flush_async(&mut self.stream).await
    }
}

impl PublicKey {
    pub fn into_key(&self) -> rsa::errors::Result<Option<RsaPublicKey>> {
        match self {
            Self::None => Ok(None),
            Self::Path(p) => Ok(Some(
                RsaPublicKey::read_public_key_pem_file(p)
                    .map_err(|e| rsa::Error::Pkcs8(rsa::pkcs8::Error::PublicKey(e)))?,
            )),
            Self::Params { n, e } => Ok(Some(RsaPublicKey::new(
                BigUint::from_bytes_le(n),
                BigUint::from_bytes_le(e),
            )?)),
            Self::Key(k) => Ok(Some(k.clone())),
        }
    }
}

impl PrivateKey {
    pub fn into_key(&self) -> rsa::errors::Result<Option<RsaPrivateKey>> {
        match self {
            Self::None => Ok(None),
            Self::Path(p) => Ok(Some(RsaPrivateKey::read_pkcs8_pem_file(p)?)),
            Self::Params { n, e, d, p, q } => Ok(Some(RsaPrivateKey::from_components(
                BigUint::from_bytes_le(n),
                BigUint::from_bytes_le(e),
                BigUint::from_bytes_le(d),
                vec![BigUint::from_bytes_le(p), BigUint::from_bytes_le(q)],
            )?)),
            Self::Key(k) => Ok(Some(k.clone())),
        }
    }
}