condure/
net.rs

1/*
2 * Copyright (C) 2022 Fanout, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use log::error;
18use mio::net::{TcpListener, TcpStream, UnixListener, UnixStream};
19use socket2::Socket;
20use std::fmt;
21use std::os::unix::io::{FromRawFd, IntoRawFd};
22use std::ptr;
23
24pub fn set_socket_opts(stream: &mut TcpStream) {
25    if let Err(e) = stream.set_nodelay(true) {
26        error!("set nodelay failed: {:?}", e);
27    }
28
29    // safety: we move the value out of stream and replace it at the end
30    let ret = unsafe {
31        let s = ptr::read(stream);
32        let socket = Socket::from_raw_fd(s.into_raw_fd());
33        let ret = socket.set_keepalive(true);
34        ptr::write(stream, TcpStream::from_raw_fd(socket.into_raw_fd()));
35
36        ret
37    };
38
39    if let Err(e) = ret {
40        error!("set keepalive failed: {:?}", e);
41    }
42}
43
44#[derive(Debug)]
45pub enum SocketAddr {
46    Ip(std::net::SocketAddr),
47    Unix(mio::net::SocketAddr),
48}
49
50impl fmt::Display for SocketAddr {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        match self {
53            Self::Ip(a) => write!(f, "{}", a),
54            Self::Unix(a) => write!(f, "{:?}", a),
55        }
56    }
57}
58
59#[derive(Debug)]
60pub enum NetListener {
61    Tcp(TcpListener),
62    Unix(UnixListener),
63}
64
65#[derive(Debug)]
66pub enum NetStream {
67    Tcp(TcpStream),
68    Unix(UnixStream),
69}