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
// 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>.

//! Framed TCP protocol: reads & writes frames (corresponding to LNP messages)
//! from TCP stream

use amplify::Bipolar;
use core::convert::TryFrom;
use core::time::Duration;
use inet2_addr::InetSocketAddr;
use std::io::{Read, Write};
use std::net::SocketAddr;

use super::{Duplex, Error, RecvFrame, SendFrame};

/// Wraps TcpStream
///
/// We need this wrapper structure since we can't implement foreign traits, such
/// as Bipolar, for a foreign type.
#[derive(Debug)]
pub struct Connection {
    pub(self) stream: std::net::TcpStream,
    pub(self) remote_addr: InetSocketAddr,
}

impl Connection {
    pub fn with(
        stream: std::net::TcpStream,
        remote_addr: InetSocketAddr,
    ) -> Self {
        Self {
            stream,
            remote_addr,
        }
    }

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

    // TODO: (v0.2) Transform into bind method + special Listener object with
    //       accept method
    pub fn accept(inet_addr: InetSocketAddr) -> Result<Self, Error> {
        if let Ok(socket_addr) = SocketAddr::try_from(inet_addr) {
            let listener = std::net::TcpListener::bind(socket_addr)?;
            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(Self::with(stream, remote_addr.into()))
        } else {
            Err(Error::TorNotSupportedYet)
        }
    }
}

impl Duplex for Connection {
    #[inline]
    fn as_receiver(&mut self) -> &mut dyn RecvFrame {
        &mut self.stream
    }

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

    #[inline]
    fn split(self) -> (Box<dyn RecvFrame + Send>, Box<dyn SendFrame + Send>) {
        (
            Box::new(
                self.stream.try_clone().expect("Error cloning TCP socket"),
            ),
            Box::new(self.stream),
        )
    }
}

impl Bipolar for Connection {
    type Left = std::net::TcpStream;
    type Right = std::net::TcpStream;

    fn join(left: Self::Left, right: Self::Right) -> 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"
        );
        Self {
            stream: left,
            // TODO: (v1) Replace with remote address, wbich will require
            //       creation of TcpSocket wrapper type
            remote_addr: Default::default(),
        }
    }

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

impl RecvFrame for std::net::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 std::net::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())
    }
}

// TODO: (v1) Do Async... implementations for FTCP based on
//       tokio::net::TcpStream