Skip to main content

panoramic_courier/
send.rs

1use std::{io, net::SocketAddr, time::Duration};
2
3use snafu::ResultExt as _;
4use tokio::{io::AsyncWriteExt as _, net::UdpSocket};
5
6use crate::{net, Address, Error, HostPort, TargetSnafu, UnsupportedSnafu};
7
8/// Writes `payload` to `address` as given: one connection, or one datagram.
9///
10/// A `tcp`, `unix` or `pipe` send connects, writes the whole payload and closes the connection. A `udp` or `unixgram`
11/// send sends the payload as one datagram.
12///
13/// `limit` bounds the call, but a name lookup it cuts short keeps running on its blocking thread until the resolver
14/// answers.
15///
16/// # Errors
17///
18/// Fails with [`Error::Unsupported`] for an `http` or `grpc` address, which takes requests and not raw bytes, and for
19/// a socket or pipe this OS does not have. Fails with [`Error::Target`] when the connection or the write fails,
20/// including a datagram sent short, and [`Error::TimedOut`] when `limit` passes.
21pub async fn send(address: &Address, payload: &[u8], limit: Duration) -> Result<(), Error> {
22    let unsupported = |reason| {
23        UnsupportedSnafu {
24            operation: "send",
25            address: address.clone(),
26            reason,
27        }
28        .fail()
29    };
30    let context = || TargetSnafu {
31        action: "send to",
32        target: address.to_string(),
33    };
34    net::within("send", address, limit, async {
35        match address {
36            Address::Tcp(host_port) => {
37                let mut stream = net::connect_tcp(host_port).await?;
38                stream.write_all(payload).await.with_context(|_| context())?;
39                stream.shutdown().await.with_context(|_| context())
40            }
41            Address::Udp(host_port) => {
42                let sent = send_udp(host_port, payload).await?;
43                check_whole(sent, payload).with_context(|_| context())
44            }
45            Address::Http(_) | Address::Grpc(_) => unsupported("send writes raw bytes; use http for requests"),
46            #[cfg(unix)]
47            Address::UnixStream(path) => {
48                let mut stream = tokio::net::UnixStream::connect(path)
49                    .await
50                    .with_context(|_| context())?;
51                stream.write_all(payload).await.with_context(|_| context())?;
52                stream.shutdown().await.with_context(|_| context())
53            }
54            #[cfg(unix)]
55            Address::UnixDatagram(path) => {
56                let socket = tokio::net::UnixDatagram::unbound().with_context(|_| context())?;
57                let sent = socket.send_to(payload, path).await.with_context(|_| context())?;
58                check_whole(sent, payload).with_context(|_| context())
59            }
60            #[cfg(not(unix))]
61            Address::UnixStream(_) | Address::UnixDatagram(_) => unsupported("this OS has no Unix sockets"),
62            #[cfg(windows)]
63            Address::NamedPipe(name) => {
64                let mut pipe = net::open_pipe(name).with_context(|_| context())?;
65                pipe.write_all(payload).await.with_context(|_| context())?;
66                pipe.flush().await.with_context(|_| context())
67            }
68            #[cfg(not(windows))]
69            Address::NamedPipe(_) => unsupported("named pipes exist only on Windows"),
70        }
71    })
72    .await
73}
74
75/// Sends one datagram to the first resolved address, from a socket of the same address family.
76async fn send_udp(host_port: &HostPort, payload: &[u8]) -> Result<usize, Error> {
77    let addr = net::resolve(host_port).await?[0];
78    let local: SocketAddr = match addr {
79        SocketAddr::V4(_) => ([0, 0, 0, 0], 0).into(),
80        SocketAddr::V6(_) => ([0u16; 8], 0).into(),
81    };
82    let context = || TargetSnafu {
83        action: "send to",
84        target: host_port.to_string(),
85    };
86    let socket = UdpSocket::bind(local).await.with_context(|_| context())?;
87    socket.send_to(payload, addr).await.with_context(|_| context())
88}
89
90fn check_whole(sent: usize, payload: &[u8]) -> io::Result<()> {
91    if sent == payload.len() {
92        Ok(())
93    } else {
94        Err(io::Error::new(
95            io::ErrorKind::WriteZero,
96            format!("sent {sent} of {} bytes in one datagram", payload.len()),
97        ))
98    }
99}