about summary refs log tree commit diff
path: root/library/std/src/sys/net/connection/xous/tcpstream.rs
blob: e8aea8b706a58a0ccf871a07c9901e39ab44e84e (plain)
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
use core::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};

use super::*;
use crate::fmt;
use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut};
use crate::net::{IpAddr, Ipv4Addr, Shutdown, SocketAddr, SocketAddrV4, SocketAddrV6};
use crate::os::xous::services;
use crate::sync::Arc;
use crate::time::Duration;

macro_rules! unimpl {
    () => {
        return Err(io::const_error!(
            io::ErrorKind::Unsupported,
            "this function is not yet implemented",
        ));
    };
}

enum ReadOrPeek {
    Read,
    Peek,
}

#[derive(Clone)]
pub struct TcpStream {
    fd: u16,
    local_port: u16,
    remote_port: u16,
    peer_addr: SocketAddr,
    // milliseconds
    read_timeout: Arc<AtomicU32>,
    // milliseconds
    write_timeout: Arc<AtomicU32>,
    handle_count: Arc<AtomicUsize>,
    nonblocking: Arc<AtomicBool>,
}

fn sockaddr_to_buf(duration: Duration, addr: &SocketAddr, buf: &mut [u8]) {
    // Construct the request.
    let port_bytes = addr.port().to_le_bytes();
    buf[0] = port_bytes[0];
    buf[1] = port_bytes[1];
    for (dest, src) in buf[2..].iter_mut().zip((duration.as_millis() as u64).to_le_bytes()) {
        *dest = src;
    }
    match addr.ip() {
        IpAddr::V4(addr) => {
            buf[10] = 4;
            for (dest, src) in buf[11..].iter_mut().zip(addr.octets()) {
                *dest = src;
            }
        }
        IpAddr::V6(addr) => {
            buf[10] = 6;
            for (dest, src) in buf[11..].iter_mut().zip(addr.octets()) {
                *dest = src;
            }
        }
    }
}

impl TcpStream {
    pub(crate) fn from_listener(
        fd: u16,
        local_port: u16,
        remote_port: u16,
        peer_addr: SocketAddr,
    ) -> TcpStream {
        TcpStream {
            fd,
            local_port,
            remote_port,
            peer_addr,
            read_timeout: Arc::new(AtomicU32::new(0)),
            write_timeout: Arc::new(AtomicU32::new(0)),
            handle_count: Arc::new(AtomicUsize::new(1)),
            nonblocking: Arc::new(AtomicBool::new(false)),
        }
    }

    pub fn connect(socketaddr: io::Result<&SocketAddr>) -> io::Result<TcpStream> {
        Self::connect_timeout(socketaddr?, Duration::ZERO)
    }

    pub fn connect_timeout(addr: &SocketAddr, duration: Duration) -> io::Result<TcpStream> {
        let mut connect_request = ConnectRequest { raw: [0u8; 4096] };

        // Construct the request.
        sockaddr_to_buf(duration, &addr, &mut connect_request.raw);

        let Ok((_, valid)) = crate::os::xous::ffi::lend_mut(
            services::net_server(),
            services::NetLendMut::StdTcpConnect.into(),
            &mut connect_request.raw,
            0,
            4096,
        ) else {
            return Err(io::const_error!(io::ErrorKind::InvalidInput, "invalid response"));
        };

        // The first four bytes should be zero upon success, and will be nonzero
        // for an error.
        let response = connect_request.raw;
        if response[0] != 0 || valid == 0 {
            // errcode is a u8 but stuck in a u16 where the upper byte is invalid. Mask & decode accordingly.
            let errcode = response[0];
            if errcode == NetError::SocketInUse as u8 {
                return Err(io::const_error!(io::ErrorKind::ResourceBusy, "socket in use"));
            } else if errcode == NetError::Unaddressable as u8 {
                return Err(io::const_error!(io::ErrorKind::AddrNotAvailable, "invalid address"));
            } else {
                return Err(io::const_error!(
                    io::ErrorKind::InvalidInput,
                    "unable to connect or internal error",
                ));
            }
        }
        let fd = u16::from_le_bytes([response[2], response[3]]);
        let local_port = u16::from_le_bytes([response[4], response[5]]);
        let remote_port = u16::from_le_bytes([response[6], response[7]]);
        // println!(
        //     "Connected with local port of {}, remote port of {}, file handle of {}",
        //     local_port, remote_port, fd
        // );
        Ok(TcpStream {
            fd,
            local_port,
            remote_port,
            peer_addr: *addr,
            read_timeout: Arc::new(AtomicU32::new(0)),
            write_timeout: Arc::new(AtomicU32::new(0)),
            handle_count: Arc::new(AtomicUsize::new(1)),
            nonblocking: Arc::new(AtomicBool::new(false)),
        })
    }

    pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
        if let Some(to) = timeout {
            if to.is_zero() {
                return Err(io::Error::ZERO_TIMEOUT);
            }
        }
        self.read_timeout.store(
            timeout.map(|t| t.as_millis().min(u32::MAX as u128) as u32).unwrap_or_default(),
            Ordering::Relaxed,
        );
        Ok(())
    }

    pub fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
        if let Some(to) = timeout {
            if to.is_zero() {
                return Err(io::Error::ZERO_TIMEOUT);
            }
        }
        self.write_timeout.store(
            timeout.map(|t| t.as_millis().min(u32::MAX as u128) as u32).unwrap_or_default(),
            Ordering::Relaxed,
        );
        Ok(())
    }

    pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
        match self.read_timeout.load(Ordering::Relaxed) {
            0 => Ok(None),
            t => Ok(Some(Duration::from_millis(t as u64))),
        }
    }

    pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
        match self.write_timeout.load(Ordering::Relaxed) {
            0 => Ok(None),
            t => Ok(Some(Duration::from_millis(t as u64))),
        }
    }

    fn read_or_peek(&self, buf: &mut [u8], op: ReadOrPeek) -> io::Result<usize> {
        let mut receive_request = ReceiveData { raw: [0u8; 4096] };
        let data_to_read = buf.len().min(receive_request.raw.len());

        let opcode = match op {
            ReadOrPeek::Read => {
                services::NetLendMut::StdTcpRx(self.fd, self.nonblocking.load(Ordering::Relaxed))
            }
            ReadOrPeek::Peek => {
                services::NetLendMut::StdTcpPeek(self.fd, self.nonblocking.load(Ordering::Relaxed))
            }
        };

        let Ok((offset, length)) = crate::os::xous::ffi::lend_mut(
            services::net_server(),
            opcode.into(),
            &mut receive_request.raw,
            // Reuse the `offset` as the read timeout
            self.read_timeout.load(Ordering::Relaxed) as usize,
            data_to_read,
        ) else {
            return Err(io::const_error!(
                io::ErrorKind::InvalidInput,
                "library failure: wrong message type or messaging error",
            ));
        };

        if offset != 0 {
            for (dest, src) in buf.iter_mut().zip(receive_request.raw[..length].iter()) {
                *dest = *src;
            }
            Ok(length)
        } else {
            let result = receive_request.raw;
            if result[0] != 0 {
                if result[1] == 8 {
                    // timed out
                    return Err(io::const_error!(io::ErrorKind::TimedOut, "timeout"));
                }
                if result[1] == 9 {
                    // would block
                    return Err(io::const_error!(io::ErrorKind::WouldBlock, "would block"));
                }
            }
            Err(io::const_error!(io::ErrorKind::Other, "recv_slice failure"))
        }
    }

    pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
        self.read_or_peek(buf, ReadOrPeek::Peek)
    }

    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
        self.read_or_peek(buf, ReadOrPeek::Read)
    }

    pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
        crate::io::default_read_vectored(|b| self.read(b), bufs)
    }

    pub fn read_buf(&self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
        crate::io::default_read_buf(|buf| self.read(buf), cursor)
    }

    pub fn is_read_vectored(&self) -> bool {
        false
    }

    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
        let mut send_request = SendData { raw: [0u8; 4096] };
        for (dest, src) in send_request.raw.iter_mut().zip(buf) {
            *dest = *src;
        }
        let buf_len = send_request.raw.len().min(buf.len());

        let (_offset, _valid) = crate::os::xous::ffi::lend_mut(
            services::net_server(),
            services::NetLendMut::StdTcpTx(self.fd).into(),
            &mut send_request.raw,
            // Reuse the offset as the timeout
            self.write_timeout.load(Ordering::Relaxed) as usize,
            buf_len,
        )
        .or(Err(io::const_error!(io::ErrorKind::InvalidInput, "internal error")))?;

        if send_request.raw[0] != 0 {
            if send_request.raw[4] == 8 {
                // timed out
                return Err(io::const_error!(
                    io::ErrorKind::BrokenPipe,
                    "timeout or connection closed",
                ));
            } else if send_request.raw[4] == 9 {
                // would block
                return Err(io::const_error!(io::ErrorKind::WouldBlock, "would block"));
            } else {
                return Err(io::const_error!(io::ErrorKind::InvalidInput, "error when sending"));
            }
        }
        Ok(u32::from_le_bytes([
            send_request.raw[4],
            send_request.raw[5],
            send_request.raw[6],
            send_request.raw[7],
        ]) as usize)
    }

    pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
        crate::io::default_write_vectored(|b| self.write(b), bufs)
    }

    pub fn is_write_vectored(&self) -> bool {
        false
    }

    pub fn peer_addr(&self) -> io::Result<SocketAddr> {
        Ok(self.peer_addr)
    }

    pub fn socket_addr(&self) -> io::Result<SocketAddr> {
        let mut get_addr = GetAddress { raw: [0u8; 4096] };

        let Ok((_offset, _valid)) = crate::os::xous::ffi::lend_mut(
            services::net_server(),
            services::NetLendMut::StdGetAddress(self.fd).into(),
            &mut get_addr.raw,
            0,
            0,
        ) else {
            return Err(io::const_error!(io::ErrorKind::InvalidInput, "internal error"));
        };
        let mut i = get_addr.raw.iter();
        match *i.next().unwrap() {
            4 => Ok(SocketAddr::V4(SocketAddrV4::new(
                Ipv4Addr::new(
                    *i.next().unwrap(),
                    *i.next().unwrap(),
                    *i.next().unwrap(),
                    *i.next().unwrap(),
                ),
                self.local_port,
            ))),
            6 => {
                let mut new_addr = [0u8; 16];
                for (src, octet) in i.zip(new_addr.iter_mut()) {
                    *octet = *src;
                }
                Ok(SocketAddr::V6(SocketAddrV6::new(new_addr.into(), self.local_port, 0, 0)))
            }
            _ => Err(io::const_error!(io::ErrorKind::InvalidInput, "internal error")),
        }
    }

    pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
        crate::os::xous::ffi::blocking_scalar(
            services::net_server(),
            services::NetBlockingScalar::StdTcpStreamShutdown(self.fd, how).into(),
        )
        .or(Err(io::const_error!(io::ErrorKind::InvalidInput, "unexpected return value")))
        .map(|_| ())
    }

    pub fn duplicate(&self) -> io::Result<TcpStream> {
        self.handle_count.fetch_add(1, Ordering::Relaxed);
        Ok(self.clone())
    }

    pub fn set_linger(&self, _: Option<Duration>) -> io::Result<()> {
        unimpl!();
    }

    pub fn linger(&self) -> io::Result<Option<Duration>> {
        unimpl!();
    }

    pub fn set_nodelay(&self, enabled: bool) -> io::Result<()> {
        crate::os::xous::ffi::blocking_scalar(
            services::net_server(),
            services::NetBlockingScalar::StdSetNodelay(self.fd, enabled).into(),
        )
        .or(Err(io::const_error!(io::ErrorKind::InvalidInput, "unexpected return value")))
        .map(|_| ())
    }

    pub fn nodelay(&self) -> io::Result<bool> {
        Ok(crate::os::xous::ffi::blocking_scalar(
            services::net_server(),
            services::NetBlockingScalar::StdGetNodelay(self.fd).into(),
        )
        .or(Err(io::const_error!(io::ErrorKind::InvalidInput, "unexpected return value")))
        .map(|res| res[0] != 0)?)
    }

    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
        if ttl > 255 {
            return Err(io::const_error!(io::ErrorKind::InvalidInput, "TTL must be less than 256"));
        }
        crate::os::xous::ffi::blocking_scalar(
            services::net_server(),
            services::NetBlockingScalar::StdSetTtlTcp(self.fd, ttl).into(),
        )
        .or(Err(io::const_error!(io::ErrorKind::InvalidInput, "unexpected return value")))
        .map(|_| ())
    }

    pub fn ttl(&self) -> io::Result<u32> {
        Ok(crate::os::xous::ffi::blocking_scalar(
            services::net_server(),
            services::NetBlockingScalar::StdGetTtlTcp(self.fd).into(),
        )
        .or(Err(io::const_error!(io::ErrorKind::InvalidInput, "unexpected return value")))
        .map(|res| res[0] as _)?)
    }

    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
        // this call doesn't have a meaning on our platform, but we can at least not panic if it's used.
        Ok(None)
    }

    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
        self.nonblocking.store(nonblocking, Ordering::Relaxed);
        Ok(())
    }
}

impl fmt::Debug for TcpStream {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "TCP connection to {:?} port {} to local port {}",
            self.peer_addr, self.remote_port, self.local_port
        )
    }
}

impl Drop for TcpStream {
    fn drop(&mut self) {
        if self.handle_count.fetch_sub(1, Ordering::Relaxed) == 1 {
            // only drop if we're the last clone
            crate::os::xous::ffi::blocking_scalar(
                services::net_server(),
                services::NetBlockingScalar::StdTcpClose(self.fd).into(),
            )
            .unwrap();
        }
    }
}