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
// LNP/BP Core Library implementing LNPBP specifications & standards
// Written in 2020 by
//     Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the MIT License
// along with this software.
// If not, see <https://opensource.org/licenses/MIT>.

//! Types generic over specific implementations

use std::convert::TryFrom;
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::time::Duration;

use amplify::Bipolar;
use inet2_addr::InetSocketAddr;

use crate::transport::{Error, RecvFrame, SendFrame};
use crate::DuplexConnection;

/// A market trait for concrete stream implementations which can be used as a
/// generic parameter in a [`Connection`] object.
pub trait Stream: RecvFrame + SendFrame + From<TcpStream> {}

/// Connection with a stream that can be cloned if split into receiver and
/// sender. Connection combines such stream for a specific destination address.
///
/// This connection type is used by FTCP and Brontide protocols.
#[derive(Debug)]
pub struct Connection<S: Stream> {
    pub(self) stream: S,
    pub(self) remote_addr: InetSocketAddr,
}

impl<S: Stream> Connection<S> {
    pub fn with(stream: TcpStream, remote_addr: InetSocketAddr) -> Self {
        Self {
            stream: S::from(stream),
            remote_addr,
        }
    }
}

impl<S: Stream + DuplexConnection> DuplexConnection for Connection<S> {
    #[inline]
    fn as_receiver(&mut self) -> &mut dyn RecvFrame {
        self.stream.as_receiver()
    }

    #[inline]
    fn as_sender(&mut self) -> &mut dyn SendFrame { self.stream.as_sender() }

    #[inline]
    fn split(self) -> (Box<dyn RecvFrame + Send>, Box<dyn SendFrame + Send>) {
        self.stream.split()
    }
}

impl<S: Stream + Bipolar<Left = S, Right = S>> Bipolar for Connection<S> {
    type Left = S;
    type Right = S;

    fn join(left: S, right: S) -> Self {
        Connection {
            stream: S::join(left, right),
            // TODO: (v1) Replace with remote address
            remote_addr: Default::default(),
        }
    }

    fn split(self) -> (Self::Left, Self::Right) { self.stream.split() }
}

/// Extensions trait for simplifying [`TcpStream`] API in working with
/// [`InetSocketAddr`] sockets
pub trait TcpInetStream: Sized {
    fn connect_inet_socket(inet_addr: InetSocketAddr) -> Result<Self, Error>;

    fn accept_inet_socket(
        listener: &TcpListener,
    ) -> Result<(Self, SocketAddr), Error>;

    fn join(left: Self, right: Self) -> Self;

    fn split(self) -> (Self, Self);
}

impl TcpInetStream for TcpStream {
    fn connect_inet_socket(inet_addr: InetSocketAddr) -> Result<Self, Error> {
        if let Ok(socket_addr) = SocketAddr::try_from(inet_addr) {
            let stream = TcpStream::connect(socket_addr)?;
            // NB: This is how we handle ping-pong cycles
            stream.set_read_timeout(Some(Duration::from_secs(30)))?;
            Ok(stream)
        } else {
            Err(Error::TorNotSupportedYet)
        }
    }

    fn accept_inet_socket(
        listener: &TcpListener,
    ) -> Result<(Self, SocketAddr), Error> {
        let (stream, remote_addr) = listener.accept()?;
        // NB: This is how we handle ping-pong cycles
        stream.set_read_timeout(Some(Duration::from_secs(30)))?;
        Ok((stream, remote_addr))
    }

    fn join(left: Self, right: Self) -> Self {
        #[cfg(not(target_os = "windows"))]
        use std::os::unix::io::AsRawFd;
        #[cfg(target_os = "windows")]
        use std::os::windows::io::AsRawSocket;

        #[cfg(not(target_os = "windows"))]
        assert_eq!(
            left.as_raw_fd(),
            right.as_raw_fd(),
            "Two independent TCP sockets can't be joined"
        );
        #[cfg(target_os = "windows")]
        assert_eq!(
            left.as_raw_socket(),
            right.as_raw_socket(),
            "Two independent TCP sockets can't be joined"
        );

        left
    }

    fn split(self) -> (Self, Self) {
        (self.try_clone().expect("TcpStream cloning failed"), self)
    }
}

impl RecvFrame for TcpStream {
    fn recv_frame(&mut self) -> Result<Vec<u8>, Error> {
        let mut len_buf = [0u8; 2];
        self.read_exact(&mut len_buf)?;
        let len = u16::from_be_bytes(len_buf) as usize;
        let mut buf: Vec<u8> = vec![
            0u8;
            len + super::FRAME_PREFIX_SIZE
                + super::FRAME_SUFFIX_SIZE
        ];
        buf[0..2].copy_from_slice(&len_buf);
        self.read_exact(&mut buf[2..])?;
        Ok(buf)
    }

    fn recv_raw(&mut self, len: usize) -> Result<Vec<u8>, Error> {
        let mut buf: Vec<u8> = vec![0u8; len];
        self.read_exact(&mut buf)?;
        Ok(buf)
    }
}

impl SendFrame for TcpStream {
    fn send_frame(&mut self, data: &[u8]) -> Result<usize, Error> {
        let len = data.len();
        if len > super::MAX_FRAME_SIZE {
            return Err(Error::OversizedFrame(len));
        }
        self.write_all(data)?;
        Ok(len)
    }

    fn send_raw(&mut self, data: &[u8]) -> Result<usize, Error> {
        self.write_all(data)?;
        Ok(data.len())
    }
}