Skip to main content

azalea_protocol/
connect.rs

1//! Connect to remote servers/clients.
2
3use std::{
4    fmt::{self, Debug, Display},
5    io::{self, Cursor},
6    marker::PhantomData,
7    net::SocketAddr,
8};
9
10#[cfg(feature = "online-mode")]
11use azalea_auth::{
12    game_profile::GameProfile,
13    sessionserver::{ClientSessionServerError, ServerSessionServerError},
14};
15use azalea_crypto::{Aes128CfbDec, Aes128CfbEnc};
16use thiserror::Error;
17use tokio::{
18    io::{AsyncWriteExt, BufStream},
19    net::{
20        TcpStream,
21        tcp::{OwnedReadHalf, OwnedWriteHalf, ReuniteError},
22    },
23};
24use tracing::{error, info};
25#[cfg(feature = "online-mode")]
26use uuid::Uuid;
27
28#[cfg(feature = "online-mode")]
29use crate::packets::login::ClientboundHello;
30use crate::{
31    packets::{
32        ProtocolPacket,
33        config::{ClientboundConfigPacket, ServerboundConfigPacket},
34        game::{ClientboundGamePacket, ServerboundGamePacket},
35        handshake::{ClientboundHandshakePacket, ServerboundHandshakePacket},
36        login::{ClientboundLoginPacket, ServerboundLoginPacket},
37        status::{ClientboundStatusPacket, ServerboundStatusPacket},
38    },
39    read::{ReadPacketError, deserialize_packet, read_raw_packet, try_read_raw_packet},
40    write::{serialize_packet, write_raw_packet, write_raw_packets},
41};
42
43pub struct RawReadConnection {
44    pub read_stream: OwnedReadHalf,
45    pub buffer: Cursor<Vec<u8>>,
46    pub compression_threshold: Option<u32>,
47    pub dec_cipher: Option<Aes128CfbDec>,
48}
49
50pub struct RawWriteConnection {
51    pub write_stream: OwnedWriteHalf,
52    pub compression_threshold: Option<u32>,
53    pub enc_cipher: Option<Aes128CfbEnc>,
54}
55
56/// The read half of a connection.
57pub struct ReadConnection<R: ProtocolPacket> {
58    pub raw: RawReadConnection,
59    _reading: PhantomData<R>,
60}
61
62/// The write half of a connection.
63pub struct WriteConnection<W: ProtocolPacket> {
64    pub raw: RawWriteConnection,
65    _writing: PhantomData<W>,
66}
67
68/// A connection that can read and write packets.
69///
70/// # Examples
71///
72/// Join an offline-mode server and go through the handshake.
73/// ```rust,no_run
74/// use azalea_protocol::{
75///     connect::Connection,
76///     packets::{
77///         self, ClientIntention, PROTOCOL_VERSION,
78///         handshake::ServerboundIntention,
79///         login::{ClientboundLoginPacket, ServerboundHello, ServerboundKey},
80///     },
81///     resolve,
82/// };
83///
84/// #[tokio::main]
85/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
86///     let resolved_address = resolve::resolve_address(&"localhost".try_into().unwrap()).await?;
87///     let mut conn = Connection::new(&resolved_address).await?;
88///
89///     // handshake
90///     conn.write(
91///         Default::default(),
92///         ServerboundIntention {
93///             protocol_version: PROTOCOL_VERSION,
94///             hostname: resolved_address.ip().to_string(),
95///             port: resolved_address.port(),
96///             intention: ClientIntention::Login,
97///         },
98///     )
99///     .await?;
100///
101///     let mut conn = conn.login();
102///
103///     // login
104///     conn.write(
105///         Default::default(),
106///         ServerboundHello {
107///             name: "bot".to_owned(),
108///             profile_id: uuid::Uuid::nil(),
109///         },
110///     )
111///     .await?;
112///
113///     let (conn, game_profile) = loop {
114///         let packet = conn.read(Default::default()).await?;
115///         match packet {
116///             ClientboundLoginPacket::Hello(p) => {
117///                 let e = azalea_crypto::encrypt(&p.public_key, &p.challenge).unwrap();
118///
119///                 conn.write(
120///                     Default::default(),
121///                     ServerboundKey {
122///                         key_bytes: e.encrypted_public_key,
123///                         encrypted_challenge: e.encrypted_challenge,
124///                     },
125///                 )
126///                 .await?;
127///                 conn.set_encryption_key(e.secret_key);
128///             }
129///             ClientboundLoginPacket::LoginCompression(p) => {
130///                 conn.set_compression_threshold(p.compression_threshold);
131///             }
132///             ClientboundLoginPacket::LoginFinished(p) => {
133///                 break (conn.config(), p.game_profile);
134///             }
135///             ClientboundLoginPacket::LoginDisconnect(p) => {
136///                 eprintln!("login disconnect: {}", p.reason);
137///                 return Err("login disconnect".into());
138///             }
139///             ClientboundLoginPacket::CustomQuery(p) => {}
140///             ClientboundLoginPacket::CookieRequest(p) => {
141///                 conn.write(
142///                     Default::default(),
143///                     packets::login::ServerboundCookieResponse {
144///                         key: p.key,
145///                         payload: None,
146///                     },
147///                 )
148///                 .await?;
149///             }
150///         }
151///     };
152///
153///     Ok(())
154/// }
155/// ```
156pub struct Connection<R: ProtocolPacket, W: ProtocolPacket> {
157    pub reader: ReadConnection<R>,
158    pub writer: WriteConnection<W>,
159}
160
161impl RawReadConnection {
162    pub async fn read(&mut self) -> Result<Box<[u8]>, Box<ReadPacketError>> {
163        read_raw_packet::<_>(
164            &mut self.read_stream,
165            &mut self.buffer,
166            self.compression_threshold,
167            &mut self.dec_cipher,
168        )
169        .await
170    }
171
172    pub fn try_read(&mut self) -> Result<Option<Box<[u8]>>, Box<ReadPacketError>> {
173        try_read_raw_packet::<_>(
174            &mut self.read_stream,
175            &mut self.buffer,
176            self.compression_threshold,
177            &mut self.dec_cipher,
178        )
179    }
180}
181
182impl RawWriteConnection {
183    pub async fn write(&mut self, ctx: azalea_buf::Ctx<'_>, packet: &[u8]) -> io::Result<()> {
184        if let Err(e) = write_raw_packet(
185            ctx,
186            packet,
187            &mut self.write_stream,
188            self.compression_threshold,
189            &mut self.enc_cipher,
190        )
191        .await
192        {
193            // detect broken pipe
194            if e.kind() == io::ErrorKind::BrokenPipe {
195                info!("Broken pipe, shutting down connection.");
196                if let Err(e) = self.shutdown().await {
197                    error!("Couldn't shut down: {}", e);
198                }
199            }
200            return Err(e);
201        }
202        Ok(())
203    }
204
205    pub async fn write_batch(
206        &mut self,
207        ctx: azalea_buf::Ctx<'_>,
208        packets: impl Iterator<Item = &[u8]>,
209    ) -> io::Result<()> {
210        if let Err(e) = write_raw_packets(
211            ctx,
212            packets,
213            &mut self.write_stream,
214            self.compression_threshold,
215            &mut self.enc_cipher,
216        )
217        .await
218        {
219            // detect broken pipe
220            if e.kind() == io::ErrorKind::BrokenPipe {
221                info!("Broken pipe, shutting down connection.");
222                if let Err(e) = self.shutdown().await {
223                    error!("Couldn't shut down: {}", e);
224                }
225            }
226            return Err(e);
227        }
228        Ok(())
229    }
230
231    /// End the connection.
232    pub async fn shutdown(&mut self) -> io::Result<()> {
233        self.write_stream.shutdown().await
234    }
235}
236
237impl<R> ReadConnection<R>
238where
239    R: ProtocolPacket + Debug,
240{
241    /// Read a packet from the stream.
242    pub async fn read(&mut self, ctx: azalea_buf::Ctx<'_>) -> Result<R, Box<ReadPacketError>> {
243        let raw_packet = self.raw.read().await?;
244        deserialize_packet(ctx, &mut Cursor::new(&raw_packet))
245    }
246
247    /// Try to read a packet from the stream, or return Ok(None) if there's no
248    /// packet.
249    pub fn try_read(
250        &mut self,
251        ctx: azalea_buf::Ctx<'_>,
252    ) -> Result<Option<R>, Box<ReadPacketError>> {
253        let Some(raw_packet) = self.raw.try_read()? else {
254            return Ok(None);
255        };
256        Ok(Some(deserialize_packet(
257            ctx,
258            &mut Cursor::new(&raw_packet),
259        )?))
260    }
261}
262impl<W> WriteConnection<W>
263where
264    W: ProtocolPacket + Debug,
265{
266    /// Write a packet to the server.
267    pub async fn write(&mut self, ctx: azalea_buf::Ctx<'_>, packet: W) -> io::Result<()> {
268        self.raw
269            .write(ctx, &serialize_packet(ctx, &packet).unwrap())
270            .await
271    }
272
273    /// Write a batch of packets to the server
274    pub async fn write_batch(&mut self, ctx: azalea_buf::Ctx<'_>, packets: &[W]) -> io::Result<()> {
275        let serialized_packets: Vec<Box<[u8]>> = packets
276            .iter()
277            .map(|packet| serialize_packet(ctx, packet).unwrap())
278            .collect();
279        self.raw
280            .write_batch(ctx, serialized_packets.iter().map(|data| data.as_ref()))
281            .await
282    }
283
284    /// End the connection.
285    pub async fn shutdown(&mut self) -> io::Result<()> {
286        self.raw.shutdown().await
287    }
288}
289
290impl<R, W> Connection<R, W>
291where
292    R: ProtocolPacket + Debug,
293    W: ProtocolPacket + Debug,
294{
295    /// Read a packet from the other side of the connection.
296    pub async fn read(&mut self, ctx: azalea_buf::Ctx<'_>) -> Result<R, Box<ReadPacketError>> {
297        self.reader.read(ctx).await
298    }
299
300    /// Try to read a packet from the other side of the connection, or return
301    /// Ok(None) if there's no packet to read.
302    pub fn try_read(
303        &mut self,
304        ctx: azalea_buf::Ctx<'_>,
305    ) -> Result<Option<R>, Box<ReadPacketError>> {
306        self.reader.try_read(ctx)
307    }
308
309    /// Write a packet to the other side of the connection.
310    pub async fn write(
311        &mut self,
312        ctx: azalea_buf::Ctx<'_>,
313        packet: impl crate::packets::Packet<W>,
314    ) -> io::Result<()> {
315        let packet = packet.into_variant();
316        self.writer.write(ctx, packet).await
317    }
318
319    /// Write a batch of packets to the other side of the connection.
320    pub async fn write_batch(&mut self, ctx: azalea_buf::Ctx<'_>, packets: &[W]) -> io::Result<()> {
321        self.writer.write_batch(ctx, packets).await
322    }
323
324    /// Split the reader and writer into two objects.
325    ///
326    /// This doesn't allocate.
327    #[must_use]
328    pub fn into_split(self) -> (ReadConnection<R>, WriteConnection<W>) {
329        (self.reader, self.writer)
330    }
331
332    /// Split the reader and writer into the state-agnostic
333    /// [`RawReadConnection`] and [`RawWriteConnection`] types.
334    ///
335    /// This is meant to help with some types of proxies.
336    #[must_use]
337    pub fn into_split_raw(self) -> (RawReadConnection, RawWriteConnection) {
338        (self.reader.raw, self.writer.raw)
339    }
340}
341
342#[derive(Debug, Error)]
343pub enum ConnectionError {
344    #[error("{0}")]
345    Io(#[from] io::Error),
346}
347
348use socks5_impl::UserKey;
349
350/// An address and authentication method for connecting to a SOCKS5 proxy.
351#[derive(Clone, Debug)]
352pub struct Proxy {
353    pub addr: SocketAddr,
354    pub auth: Option<UserKey>,
355}
356
357impl Proxy {
358    pub fn new(addr: SocketAddr, auth: Option<UserKey>) -> Self {
359        Self { addr, auth }
360    }
361}
362impl Display for Proxy {
363    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
364        write!(f, "socks5://")?;
365        if let Some(auth) = &self.auth {
366            write!(f, "{auth}@")?;
367        }
368        write!(f, "{}", self.addr)
369    }
370}
371
372#[cfg(feature = "online-mode")]
373impl From<Proxy> for reqwest::Proxy {
374    fn from(proxy: Proxy) -> Self {
375        reqwest::Proxy::all(proxy.to_string())
376            .expect("azalea proxies should not fail to parse as reqwest proxies")
377    }
378}
379
380impl Connection<ClientboundHandshakePacket, ServerboundHandshakePacket> {
381    /// Create a new connection to the given address.
382    pub async fn new(address: &SocketAddr) -> Result<Self, ConnectionError> {
383        let stream = TcpStream::connect(address).await?;
384
385        // enable tcp_nodelay
386        stream.set_nodelay(true)?;
387
388        Self::new_from_stream(stream).await
389    }
390
391    /// Create a new connection to the given address and SOCKS5 proxy.
392    ///
393    /// If you're not using a proxy, use [`Self::new`] instead.
394    pub async fn new_with_proxy(
395        address: &SocketAddr,
396        proxy: Proxy,
397    ) -> Result<Self, ConnectionError> {
398        let proxy_stream = TcpStream::connect(proxy.addr).await?;
399        let mut stream = BufStream::new(proxy_stream);
400
401        let _ = socks5_impl::client::connect(&mut stream, address, proxy.auth)
402            .await
403            .map_err(io::Error::other)?;
404
405        Self::new_from_stream(stream.into_inner()).await
406    }
407
408    /// Create a new connection from an existing stream.
409    ///
410    /// Useful if you want to set custom options on the stream. Otherwise, just
411    /// use [`Self::new`].
412    pub async fn new_from_stream(stream: TcpStream) -> Result<Self, ConnectionError> {
413        let (read_stream, write_stream) = stream.into_split();
414
415        Ok(Connection {
416            reader: ReadConnection {
417                raw: RawReadConnection {
418                    read_stream,
419                    buffer: Cursor::new(Vec::new()),
420                    compression_threshold: None,
421                    dec_cipher: None,
422                },
423                _reading: PhantomData,
424            },
425            writer: WriteConnection {
426                raw: RawWriteConnection {
427                    write_stream,
428                    compression_threshold: None,
429                    enc_cipher: None,
430                },
431                _writing: PhantomData,
432            },
433        })
434    }
435
436    /// Change our state from handshake to login.
437    ///
438    /// This is the state that is used for logging in.
439    #[must_use]
440    pub fn login(self) -> Connection<ClientboundLoginPacket, ServerboundLoginPacket> {
441        Connection::from(self)
442    }
443
444    /// Change our state from handshake to status.
445    ///
446    /// This is the state that is used for pinging the server.
447    #[must_use]
448    pub fn status(self) -> Connection<ClientboundStatusPacket, ServerboundStatusPacket> {
449        Connection::from(self)
450    }
451}
452
453impl Connection<ClientboundLoginPacket, ServerboundLoginPacket> {
454    /// Set our compression threshold, i.e. the maximum size that a packet is
455    /// allowed to be without getting compressed.
456    ///
457    /// Setting it to 0 means every packet will be compressed. If you set it to
458    /// less than 0 then compression is disabled.
459    pub fn set_compression_threshold(&mut self, threshold: i32) {
460        // if you pass a threshold of less than 0, compression is disabled
461        if threshold >= 0 {
462            self.reader.raw.compression_threshold = Some(threshold as u32);
463            self.writer.raw.compression_threshold = Some(threshold as u32);
464        } else {
465            self.reader.raw.compression_threshold = None;
466            self.writer.raw.compression_threshold = None;
467        }
468    }
469
470    /// Set the encryption key that is used to encrypt and decrypt packets.
471    ///
472    /// It's the same for both reading and writing.
473    pub fn set_encryption_key(&mut self, key: [u8; 16]) {
474        let (enc_cipher, dec_cipher) = azalea_crypto::create_cipher(&key);
475        self.reader.raw.dec_cipher = Some(dec_cipher);
476        self.writer.raw.enc_cipher = Some(enc_cipher);
477    }
478
479    /// Change our state from login to configuration.
480    ///
481    /// This is the state where the server sends us the registries and the
482    /// resource pack.
483    #[must_use]
484    pub fn config(self) -> Connection<ClientboundConfigPacket, ServerboundConfigPacket> {
485        Connection::from(self)
486    }
487
488    /// Authenticate with Minecraft's servers, which is required to join
489    /// online-mode servers.
490    ///
491    /// This must happen when you get a `ClientboundLoginPacket::Hello` packet.
492    ///
493    /// # Examples
494    ///
495    /// ```rust,no_run
496    /// use azalea_auth::AuthResult;
497    /// use azalea_protocol::{
498    ///     connect::Connection,
499    ///     packets::login::{ClientboundLoginPacket, ServerboundKey},
500    /// };
501    /// use uuid::Uuid;
502    /// # use azalea_protocol::address::ServerAddr;
503    ///
504    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
505    /// let AuthResult {
506    ///     access_token,
507    ///     profile,
508    /// } = azalea_auth::auth("example@example.com", azalea_auth::AuthOpts::default())
509    ///     .await
510    ///     .expect("Couldn't authenticate");
511    /// #
512    /// # let address = ServerAddr::try_from("example@example.com").unwrap();
513    /// # let resolved_address = azalea_protocol::resolve::resolve_address(&address).await?;
514    ///
515    /// let mut conn = Connection::new(&resolved_address).await?;
516    ///
517    /// // transition to the login state, in a real program we would have done a handshake first
518    /// let mut conn = conn.login();
519    ///
520    /// match conn.read(Default::default()).await? {
521    ///     ClientboundLoginPacket::Hello(p) => {
522    ///         // tell Mojang we're joining the server & enable encryption
523    ///         let e = azalea_crypto::encrypt(&p.public_key, &p.challenge).unwrap();
524    ///         conn.authenticate(&access_token, &profile.id, e.secret_key, &p, None)
525    ///             .await?;
526    ///         conn.write(
527    ///             Default::default(),
528    ///             ServerboundKey {
529    ///                 key_bytes: e.encrypted_public_key,
530    ///                 encrypted_challenge: e.encrypted_challenge,
531    ///             },
532    ///         )
533    ///         .await?;
534    ///         conn.set_encryption_key(e.secret_key);
535    ///     }
536    ///     _ => {}
537    /// }
538    /// # Ok(())
539    /// # }
540    /// ```
541    #[cfg(feature = "online-mode")]
542    pub async fn authenticate(
543        &self,
544        access_token: &str,
545        uuid: &Uuid,
546        private_key: [u8; 16],
547        packet: &ClientboundHello,
548        sessionserver_proxy: Option<Proxy>,
549    ) -> Result<(), ClientSessionServerError> {
550        use azalea_auth::sessionserver::{self, SessionServerJoinOpts};
551
552        sessionserver::join(SessionServerJoinOpts {
553            access_token,
554            public_key: &packet.public_key,
555            private_key: &private_key,
556            uuid,
557            server_id: &packet.server_id,
558            proxy: sessionserver_proxy.map(Proxy::into),
559        })
560        .await
561    }
562}
563
564impl Connection<ServerboundHandshakePacket, ClientboundHandshakePacket> {
565    /// Change our state from handshake to login.
566    ///
567    /// This is the state that is used while negotiating encryption and
568    /// authenticating with Mojang.
569    #[must_use]
570    pub fn login(self) -> Connection<ServerboundLoginPacket, ClientboundLoginPacket> {
571        Connection::from(self)
572    }
573
574    /// Change our state from handshake to status.
575    ///
576    /// This is the state that is used for pinging the server.
577    #[must_use]
578    pub fn status(self) -> Connection<ServerboundStatusPacket, ClientboundStatusPacket> {
579        Connection::from(self)
580    }
581}
582
583impl Connection<ServerboundLoginPacket, ClientboundLoginPacket> {
584    /// Set our compression threshold, i.e. the maximum size that a packet is
585    /// allowed to be without getting compressed.
586    ///
587    /// If you set it to less than 0 then compression gets disabled.
588    pub fn set_compression_threshold(&mut self, threshold: i32) {
589        // if you pass a threshold of less than 0, compression is disabled
590        if threshold >= 0 {
591            self.reader.raw.compression_threshold = Some(threshold as u32);
592            self.writer.raw.compression_threshold = Some(threshold as u32);
593        } else {
594            self.reader.raw.compression_threshold = None;
595            self.writer.raw.compression_threshold = None;
596        }
597    }
598
599    /// Set the encryption key that is used to encrypt and decrypt packets.
600    ///
601    /// It's the same for both reading and writing.
602    pub fn set_encryption_key(&mut self, key: [u8; 16]) {
603        let (enc_cipher, dec_cipher) = azalea_crypto::create_cipher(&key);
604        self.reader.raw.dec_cipher = Some(dec_cipher);
605        self.writer.raw.enc_cipher = Some(enc_cipher);
606    }
607
608    /// Change our state from login to game.
609    ///
610    /// This is the state that's used when the client is actually in the game.
611    #[must_use]
612    pub fn game(self) -> Connection<ServerboundGamePacket, ClientboundGamePacket> {
613        Connection::from(self)
614    }
615
616    /// Verify connecting clients have authenticated with Minecraft's servers.
617    /// This must happen after the client sends a `ServerboundLoginPacket::Key`
618    /// packet.
619    #[cfg(feature = "online-mode")]
620    pub async fn authenticate(
621        &self,
622        username: &str,
623        public_key: &[u8],
624        private_key: &[u8; 16],
625        ip: Option<&str>,
626    ) -> Result<GameProfile, ServerSessionServerError> {
627        azalea_auth::sessionserver::serverside_auth(username, public_key, private_key, ip).await
628    }
629
630    /// Change our state back to configuration.
631    #[must_use]
632    pub fn config(self) -> Connection<ServerboundConfigPacket, ClientboundConfigPacket> {
633        Connection::from(self)
634    }
635}
636
637impl Connection<ServerboundConfigPacket, ClientboundConfigPacket> {
638    /// Change our state from configuration to game.
639    ///
640    /// This is the state that's used when the client is actually in the world.
641    #[must_use]
642    pub fn game(self) -> Connection<ServerboundGamePacket, ClientboundGamePacket> {
643        Connection::from(self)
644    }
645}
646
647impl Connection<ClientboundConfigPacket, ServerboundConfigPacket> {
648    /// Change our state from configuration to game.
649    ///
650    /// This is the state that's used when the client is actually in the world.
651    #[must_use]
652    pub fn game(self) -> Connection<ClientboundGamePacket, ServerboundGamePacket> {
653        Connection::from(self)
654    }
655}
656
657impl Connection<ClientboundGamePacket, ServerboundGamePacket> {
658    /// Change our state back to configuration.
659    #[must_use]
660    pub fn config(self) -> Connection<ClientboundConfigPacket, ServerboundConfigPacket> {
661        Connection::from(self)
662    }
663}
664impl Connection<ServerboundGamePacket, ClientboundGamePacket> {
665    /// Change our state back to configuration.
666    #[must_use]
667    pub fn config(self) -> Connection<ServerboundConfigPacket, ClientboundConfigPacket> {
668        Connection::from(self)
669    }
670}
671
672// rust doesn't let us implement From because allegedly it conflicts with
673// `core`'s "impl<T> From<T> for T" so we do this instead
674impl<R1, W1> Connection<R1, W1>
675where
676    R1: ProtocolPacket + Debug,
677    W1: ProtocolPacket + Debug,
678{
679    /// Creates a `Connection` of a type from a `Connection` of another type.
680    /// Useful for servers or custom packets.
681    #[must_use]
682    pub fn from<R2, W2>(connection: Connection<R1, W1>) -> Connection<R2, W2>
683    where
684        R2: ProtocolPacket + Debug,
685        W2: ProtocolPacket + Debug,
686    {
687        Connection {
688            reader: ReadConnection {
689                raw: connection.reader.raw,
690                _reading: PhantomData,
691            },
692            writer: WriteConnection {
693                raw: connection.writer.raw,
694                _writing: PhantomData,
695            },
696        }
697    }
698
699    /// Convert an existing `TcpStream` into a `Connection`. Useful for servers.
700    pub fn wrap(stream: TcpStream) -> Connection<R1, W1> {
701        let (read_stream, write_stream) = stream.into_split();
702
703        Connection {
704            reader: ReadConnection {
705                raw: RawReadConnection {
706                    read_stream,
707                    buffer: Cursor::new(Vec::new()),
708                    compression_threshold: None,
709                    dec_cipher: None,
710                },
711                _reading: PhantomData,
712            },
713            writer: WriteConnection {
714                raw: RawWriteConnection {
715                    write_stream,
716                    compression_threshold: None,
717                    enc_cipher: None,
718                },
719                _writing: PhantomData,
720            },
721        }
722    }
723
724    /// Convert from a `Connection` into a `TcpStream`. Useful for servers.
725    pub fn unwrap(self) -> Result<TcpStream, ReuniteError> {
726        self.reader
727            .raw
728            .read_stream
729            .reunite(self.writer.raw.write_stream)
730    }
731}