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
use std::io::{ErrorKind, Read, Write};
use std::net::ToSocketAddrs;

use super::sleep;

pub struct TcpStream {
    std_stream: std::net::TcpStream,
}

impl TcpStream {
    /// Wraps `std_stream` so we can perform async operations on it.
    ///
    /// # Errors
    /// Returns any
    /// [`Err(std::io::Error)`](https://doc.rust-lang.org/stable/std/io/struct.Error.html)
    /// returned by
    /// [`std::net::TcpStream::set_nonblocking`](https://doc.rust-lang.org/stable/std/net/struct.TcpStream.html#method.set_nonblocking).
    pub fn new(std_stream: std::net::TcpStream) -> Result<Self, std::io::Error> {
        std_stream.set_nonblocking(true)?;
        safina_timer::start_timer_thread();
        Ok(Self { std_stream })
    }

    /// Opens a TCP connection to `addr`.
    ///
    /// Uses
    /// [`safina_executor::schedule_blocking`](https://docs.rs/safina-executor/latest/safina_executor/fn.schedule_blocking.html)
    /// to perform the blocking connect call.
    /// Panics if the caller is not running on an
    /// [`Executor`](https://docs.rs/safina-executor/latest/safina_executor/struct.Executor.html).
    ///
    /// # Errors
    /// Returns any
    /// [`Err(std::io::Error)`](https://doc.rust-lang.org/stable/std/io/struct.Error.html)
    /// returned by
    /// [`std::net::TcpStream::connect`](https://doc.rust-lang.org/stable/std/net/struct.TcpListener.html#method.connect).
    pub async fn connect<A: ToSocketAddrs + Send + 'static>(
        addr: A,
    ) -> Result<Self, std::io::Error> {
        safina_executor::schedule_blocking(move || {
            TcpStream::new(std::net::TcpStream::connect(addr)?)
        })
        .await
    }

    #[must_use]
    pub fn inner(&self) -> &std::net::TcpStream {
        &self.std_stream
    }

    pub fn inner_mut(&mut self) -> &mut std::net::TcpStream {
        &mut self.std_stream
    }

    #[must_use]
    pub fn into_inner(self) -> std::net::TcpStream {
        self.std_stream
    }

    /// Reads some bytes from the socket and places them in `buf`.
    /// Returns the number of bytes read.
    ///
    /// This is an async version of
    /// [`std::io::Read::read`](https://doc.rust-lang.org/stable/std/io/trait.Read.html#tymethod.read).
    ///
    /// # Errors
    /// Returns any
    /// [`Err(std::io::Error)`](https://doc.rust-lang.org/stable/std/io/struct.Error.html)
    /// returned by
    /// [`std::net::TcpStream::read`](https://doc.rust-lang.org/stable/std/net/struct.TcpListener.html#method.read).
    pub async fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
        loop {
            match self.std_stream.read(buf) {
                Ok(num_read) => return Ok(num_read),
                Err(e) if e.kind() == ErrorKind::WouldBlock || e.kind() == ErrorKind::TimedOut => {
                    sleep().await;
                }
                Err(e) => return Err(e),
            }
        }
    }

    /// Reads all bytes until the socket is shutdown for reading.
    /// Appends the bytes to `buf`.
    ///
    /// This is an async version of
    /// [`std::io::Read::read_to_end`](https://doc.rust-lang.org/stable/std/io/trait.Read.html#method.read_to_end).
    ///
    /// # Errors
    /// Returns any
    /// [`Err(std::io::Error)`](https://doc.rust-lang.org/stable/std/io/struct.Error.html)
    /// returned by
    /// [`std::net::TcpStream::read`](https://doc.rust-lang.org/stable/std/net/struct.TcpListener.html#method.read).
    pub async fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, std::io::Error> {
        let mut chunk = [0_u8; 128 * 1024];
        let mut total_read = 0_usize;
        loop {
            match self.std_stream.read(&mut chunk) {
                Ok(0) => return Ok(total_read),
                Ok(num_read) => {
                    buf.extend_from_slice(&chunk[..num_read]);
                    total_read += num_read;
                }
                Err(e) if e.kind() == ErrorKind::WouldBlock || e.kind() == ErrorKind::TimedOut => {
                    sleep().await;
                }
                Err(e) if e.kind() == ErrorKind::Interrupted => {}
                Err(e) => return Err(e),
            }
        }
    }

    /// Reads all bytes until the socket is shutdown for reading.
    /// Interprets the bytes as a single UTF-8 string and appends it to `buf`.
    ///
    /// This is an async version of
    /// [`std::io::Read::read_to_string`](https://doc.rust-lang.org/stable/std/io/trait.Read.html#method.read_to_string).
    ///
    /// # Errors
    /// Returns any
    /// [`Err(std::io::Error)`](https://doc.rust-lang.org/stable/std/io/struct.Error.html)
    /// returned by
    /// [`std::net::TcpStream::read`](https://doc.rust-lang.org/stable/std/net/struct.TcpListener.html#method.read).
    ///
    /// Returns `ErrorKind::InvalidData` if the bytes are not valid UTF-8.
    pub async fn read_to_string(&mut self, buf: &mut String) -> Result<usize, std::io::Error> {
        let mut bytes = Vec::new();
        self.read_to_end(&mut bytes).await?;
        let num_read = bytes.len();
        let mut result = String::from_utf8(bytes)
            .map_err(|e| std::io::Error::new(ErrorKind::InvalidData, format!("{}", e)))?;
        core::mem::swap(buf, &mut result);
        Ok(num_read)
    }

    /// Reads the exact number of bytes required to fill `buf`.
    ///
    /// This is an async version of
    /// [`std::io::Read::read_exact`](https://doc.rust-lang.org/stable/std/io/trait.Read.html#method.read_exact).
    ///
    /// # Errors
    /// Returns any
    /// [`Err(std::io::Error)`](https://doc.rust-lang.org/stable/std/io/struct.Error.html)
    /// returned by
    /// [`std::net::TcpStream::read`](https://doc.rust-lang.org/stable/std/net/struct.TcpListener.html#method.read).
    pub async fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), std::io::Error> {
        let mut dest = buf;
        while !dest.is_empty() {
            match self.std_stream.read(dest) {
                Ok(0) => return Err(std::io::Error::new(ErrorKind::UnexpectedEof, "eof")),
                Ok(num_read) => {
                    dest = &mut dest[num_read..];
                }
                Err(e) if e.kind() == ErrorKind::WouldBlock || e.kind() == ErrorKind::TimedOut => {
                    sleep().await;
                }
                Err(e) if e.kind() == ErrorKind::Interrupted => {}
                Err(e) => return Err(e),
            }
        }
        Ok(())
    }

    /// Reads bytes into `bufs`, filling each buffer in order.
    /// The final buffer written to may be partially filled.
    ///
    /// Returns the total number of bytes read.
    ///
    /// This is an async version of
    /// [`std::net::TcpStream::read_vectored`](https://doc.rust-lang.org/stable/std/net/struct.TcpListener.html#method.read_vectored).
    ///
    /// # Errors
    /// Returns any
    /// [`Err(std::io::Error)`](https://doc.rust-lang.org/stable/std/io/struct.Error.html)
    /// returned by
    /// [`std::net::TcpStream::read_vectored`](https://doc.rust-lang.org/stable/std/net/struct.TcpListener.html#method.read_vectored).
    pub async fn read_vectored(
        &mut self,
        bufs: &mut [std::io::IoSliceMut<'_>],
    ) -> Result<usize, std::io::Error> {
        loop {
            match self.std_stream.read_vectored(bufs) {
                Ok(num_read) => return Ok(num_read),
                Err(e) if e.kind() == ErrorKind::WouldBlock || e.kind() == ErrorKind::TimedOut => {
                    sleep().await;
                }
                Err(e) => return Err(e),
            }
        }
    }

    /// Waits to receive some data on the socket, then copies it into `buf`.
    ///
    /// Returns the number of bytes copied.
    ///
    /// Repeated calls return the same data.
    /// Call [`read`](#method.read) to remove data from the socket.
    ///
    /// This is an async version of
    /// [`std::net::TcpStream::peek`](https://doc.rust-lang.org/stable/std/net/struct.TcpStream.html#method.peek).
    ///
    /// # Errors
    /// Returns any
    /// [`Err(std::io::Error)`](https://doc.rust-lang.org/stable/std/io/struct.Error.html)
    /// returned by
    /// [`std::net::TcpStream::peek`](https://doc.rust-lang.org/stable/std/net/struct.TcpStream.html#method.peek).
    pub async fn peek(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
        loop {
            match self.std_stream.peek(buf) {
                Ok(num_read) => return Ok(num_read),
                Err(e) if e.kind() == ErrorKind::WouldBlock || e.kind() == ErrorKind::TimedOut => {
                    sleep().await;
                }
                Err(e) => return Err(e),
            }
        }
    }

    /// Writes the bytes in `buf` to the socket.
    /// Returns the number of bytes written.
    ///
    /// # Errors
    /// Returns any
    /// [`Err(std::io::Error)`](https://doc.rust-lang.org/stable/std/io/struct.Error.html)
    /// returned by
    /// [`std::net::TcpStream::write`](https://doc.rust-lang.org/stable/std/net/struct.TcpStream.html#method.write).
    pub async fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> {
        loop {
            match self.std_stream.write(buf) {
                Ok(num) => return Ok(num),
                Err(e)
                    if e.kind() == ErrorKind::WouldBlock
                        || e.kind() == ErrorKind::TimedOut
                        || (
                            // http://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/
                            // Os { code: 41, kind: Other, message: "Protocol wrong type for socket" }
                            e.kind() == ErrorKind::Other && e.raw_os_error() == Some(41)
                        ) =>
                {
                    sleep().await;
                }
                Err(e) => return Err(e),
            }
        }
    }

    /// Sends all buffered data that was previously written on this socket and
    /// waits for receipt confirmation by the remote machine.
    ///
    /// # Errors
    /// Returns [`std::io::Error`](https://doc.rust-lang.org/stable/std/io/struct.Error.html)
    /// if the connection failed
    /// or the remote machine did not respond within a timeout period.
    pub async fn flush(&mut self) -> Result<(), std::io::Error> {
        loop {
            match self.std_stream.flush() {
                Ok(()) => return Ok(()),
                Err(e)
                    if e.kind() == ErrorKind::WouldBlock
                        || e.kind() == ErrorKind::TimedOut
                        || (e.kind() == ErrorKind::Other && e.raw_os_error() == Some(41)) =>
                {
                    sleep().await;
                }
                Err(e) => return Err(e),
            }
        }
    }

    /// Writes all bytes in `buf` to the socket.
    ///
    /// # Errors
    /// Returns any
    /// [`Err(std::io::Error)`](https://doc.rust-lang.org/stable/std/io/struct.Error.html)
    /// returned by
    /// [`std::net::TcpStream::write`](https://doc.rust-lang.org/stable/std/net/struct.TcpStream.html#method.write).
    pub async fn write_all(&mut self, mut buf: &[u8]) -> Result<(), std::io::Error> {
        while !buf.is_empty() {
            match self.std_stream.write(buf) {
                Ok(0) => {}
                Ok(num_written) => {
                    buf = &buf[num_written..];
                }
                Err(e)
                    if e.kind() == ErrorKind::WouldBlock
                        || e.kind() == ErrorKind::TimedOut
                        || (e.kind() == ErrorKind::Other && e.raw_os_error() == Some(41)) =>
                {
                    sleep().await;
                }
                Err(e) => return Err(e),
            }
        }
        Ok(())
    }

    /// Writes data from a slice of buffers.
    ///
    /// Takes data from each buffer in order.  May partially read the last buffer read.
    ///
    /// Returns the number of bytes written.
    ///
    /// # Errors
    /// Returns any
    /// [`Err(std::io::Error)`](https://doc.rust-lang.org/stable/std/io/struct.Error.html)
    /// returned by
    /// [`std::net::TcpStream::write_vectored`](https://doc.rust-lang.org/stable/std/net/struct.TcpListener.html#method.write_vectored).
    pub async fn write_vectored(
        &mut self,
        bufs: &[std::io::IoSlice<'_>],
    ) -> Result<usize, std::io::Error> {
        loop {
            match self.std_stream.write_vectored(bufs) {
                Ok(num) => return Ok(num),
                Err(e)
                    if e.kind() == ErrorKind::WouldBlock
                        || e.kind() == ErrorKind::TimedOut
                        || (e.kind() == ErrorKind::Other && e.raw_os_error() == Some(41)) =>
                {
                    sleep().await;
                }
                Err(e) => return Err(e),
            }
        }
    }
}