| 1 |
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 2 |
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 3 |
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 4 |
// option. This file may not be copied, modified, or distributed |
| 5 |
// except according to those terms. |
| 6 |
|
| 7 |
use std::{ |
| 8 |
io::{Error, Read, Result, Write}, |
| 9 |
num::TryFromIntError, |
| 10 |
os::fd::{AsRawFd, FromRawFd as _, OwnedFd}, |
| 11 |
sync::atomic::Ordering, |
| 12 |
}; |
| 13 |
|
| 14 |
use libc::{fsync, read, socket, write, SOCK_RAW}; |
| 15 |
|
| 16 |
use crate::unlikely_err; |
| 17 |
|
| 18 |
#[cfg(any(target_os = "linux", target_os = "android"))] |
| 19 |
type AtomicRouteSocketSeq = std::sync::atomic::AtomicU32; |
| 20 |
#[cfg(any(target_os = "linux", target_os = "android"))] |
| 21 |
type RouteSocketSeq = u32; |
| 22 |
|
| 23 |
#[cfg(not(any(target_os = "linux", target_os = "android")))] |
| 24 |
type AtomicRouteSocketSeq = std::sync::atomic::AtomicI32; |
| 25 |
#[cfg(not(any(target_os = "linux", target_os = "android")))] |
| 26 |
type RouteSocketSeq = i32; |
| 27 |
|
| 28 |
static SEQ: AtomicRouteSocketSeq = AtomicRouteSocketSeq::new(0); |
| 29 |
|
| 30 |
pub struct RouteSocket(OwnedFd); |
| 31 |
|
| 32 |
impl RouteSocket { |
| 33 |
pub fn new(domain: libc::c_int, protocol: libc::c_int) -> Result<Self> { |
| 34 |
let fd = unsafe { socket(domain, SOCK_RAW, protocol) }; |
| 35 |
if fd == -1 { |
| 36 |
return Err(Error::last_os_error()); |
| 37 |
} |
| 38 |
Ok(Self(unsafe { OwnedFd::from_raw_fd(fd) })) |
| 39 |
} |
| 40 |
|
| 41 |
pub fn new_seq() -> RouteSocketSeq { |
| 42 |
SEQ.fetch_add(1, Ordering::Relaxed) |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
impl AsRawFd for RouteSocket { |
| 47 |
fn as_raw_fd(&self) -> i32 { |
| 48 |
self.0.as_raw_fd() |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
fn check_result(res: isize) -> Result<usize> { |
| 53 |
if res == -1 { |
| 54 |
Err(Error::last_os_error()) |
| 55 |
} else { |
| 56 |
Ok(res |
| 57 |
.try_into() |
| 58 |
.map_err(|e: TryFromIntError| unlikely_err(e.to_string()))?) |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
impl Write for RouteSocket { |
| 63 |
fn write(&mut self, buf: &[u8]) -> Result<usize> { |
| 64 |
let res = unsafe { write(self.as_raw_fd(), buf.as_ptr().cast(), buf.len()) }; |
| 65 |
check_result(res) |
| 66 |
} |
| 67 |
|
| 68 |
fn flush(&mut self) -> Result<()> { |
| 69 |
let res = unsafe { fsync(self.as_raw_fd()) }; |
| 70 |
check_result(res as isize).and(Ok(())) |
| 71 |
} |
| 72 |
} |
| 73 |
|
| 74 |
impl Read for RouteSocket { |
| 75 |
fn read(&mut self, buf: &mut [u8]) -> Result<usize> { |
| 76 |
// If we've written a well-formed message into the kernel via `write`, we should be able to |
| 77 |
// read a well-formed message back out, and not block. |
| 78 |
let res = unsafe { read(self.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len()) }; |
| 79 |
check_result(res) |
| 80 |
} |
| 81 |
} |