Files
@ 3b6c40dc10e1
Branch filter:
Location: CSY/reowolf/src/runtime2/stdlib/internet.rs
3b6c40dc10e1
9.6 KiB
application/rls-services+xml
Initial TCP component implementation
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 | use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::mem::size_of;
use std::io::{Error as IoError, ErrorKind as IoErrorKind};
use libc::{
c_int,
sockaddr_in, sockaddr_in6, in_addr, in6_addr,
socket, bind, listen, accept, connect, close,
};
use mio::{event, Interest, Registry, Token};
#[derive(Debug)]
pub enum SocketError {
Opening,
Modifying,
Binding,
Listening,
Connecting,
Accepted,
Accepting,
}
enum SocketState {
Opened,
Listening,
}
/// TCP connection
pub struct SocketTcpClient {
socket_handle: libc::c_int,
is_blocking: bool,
}
impl SocketTcpClient {
pub fn new(ip: IpAddr, port: u16) -> Result<Self, SocketError> {
const BLOCKING: bool = false;
let socket_handle = create_and_connect_socket(
libc::SOCK_STREAM, libc::IPPROTO_TCP, ip, port
)?;
if !set_socket_blocking(socket_handle, BLOCKING) {
unsafe{ libc::close(socket_handle); }
return Err(SocketError::Modifying);
}
return Ok(SocketTcpClient{
socket_handle,
is_blocking: BLOCKING,
})
}
pub fn send(&self, message: &[u8]) -> Result<usize, IoError> {
let result = unsafe{
let message_pointer = message.as_ptr().cast();
libc::send(self.socket_handle, message_pointer, message.len() as libc::size_t, 0)
};
if result < 0 {
return Err(IoError::last_os_error());
}
return Ok(result as usize);
}
/// Receives data from the TCP socket. Returns the number of bytes received.
/// More bytes may be present even thought `used < buffer.len()`.
pub fn receive(&self, buffer: &mut [u8]) -> Result<usize, IoError> {
let result = unsafe {
let message_pointer = buffer.as_mut_ptr().cast();
libc::recv(self.socket_handle, message_pointer, buffer.len(), 0)
};
if result < 0 {
return Err(IoError::last_os_error());
}
return Ok(result as usize);
}
}
impl Drop for SocketTcpClient {
fn drop(&mut self) {
debug_assert!(self.socket_handle >= 0);
unsafe{ close(self.socket_handle) };
}
}
/// Raw socket receiver. Essentially a listener that accepts a single connection
struct SocketRawRx {
listen_handle: c_int,
accepted_handle: c_int,
}
impl SocketRawRx {
pub fn new(ip: Option<Ipv4Addr>, port: u16) -> Result<Self, SocketError> {
let ip = ip.unwrap_or(Ipv4Addr::UNSPECIFIED); // unspecified is the same as INADDR_ANY
let address = unsafe{ in_addr{
s_addr: std::mem::transmute(ip.octets()),
}};
let socket_address = sockaddr_in{
sin_family: libc::AF_INET as libc::sa_family_t,
sin_port: htons(port),
sin_addr: address,
sin_zero: [0; 8],
};
unsafe {
let socket_handle = create_and_bind_socket(libc::SOCK_RAW, 0, IpAddr::V4(ip), port)?;
let result = listen(socket_handle, 3);
if result < 0 { return Err(SocketError::Listening); }
return Ok(SocketRawRx{
listen_handle: socket_handle,
accepted_handle: -1,
});
}
}
// pub fn try_accept(&mut self, timeout_ms: u32) -> Result<(), SocketError> {
// if self.accepted_handle >= 0 {
// // Already accepted a connection
// return Err(SocketError::Accepted);
// }
//
// let mut socket_address = sockaddr_in{
// sin_family: 0,
// sin_port: 0,
// sin_addr: in_addr{ s_addr: 0 },
// sin_zero: [0; 8]
// };
// let mut size = size_of::<sockaddr_in>() as u32;
// unsafe {
// let result = accept(self.listen_handle, &mut socket_address as *mut _, &mut size as *mut _);
// if result < 0 {
// return Err(SocketError::Accepting);
// }
// }
//
// return Ok(());
// }
}
impl Drop for SocketRawRx {
fn drop(&mut self) {
if self.accepted_handle >= 0 {
unsafe {
close(self.accepted_handle);
}
}
if self.listen_handle >= 0 {
unsafe {
close(self.listen_handle);
}
}
}
}
// The following is essentially stolen from `mio`'s io_source.rs file.
#[cfg(unix)]
trait AsRawFileDescriptor {
fn as_raw_file_descriptor(&self) -> c_int;
}
impl AsRawFileDescriptor for SocketTcpClient {
fn as_raw_file_descriptor(&self) -> c_int {
return self.socket_handle;
}
}
/// Performs the `socket` and `bind` calls.
fn create_and_bind_socket(socket_type: libc::c_int, protocol: libc::c_int, ip: IpAddr, port: u16) -> Result<libc::c_int, SocketError> {
let family = socket_family_from_ip(ip);
unsafe {
let socket_handle = socket(family, socket_type, protocol);
if socket_handle < 0 {
return Err(SocketError::Opening);
}
let result = match ip {
IpAddr::V4(ip) => {
let (socket_address, address_size) = create_sockaddr_in_v4(ip, port);
let socket_pointer = &socket_address as *const sockaddr_in;
bind(socket_handle, socket_pointer.cast(), address_size)
},
IpAddr::V6(ip) => {
let (socket_address, address_size) = create_sockaddr_in_v6(ip, port);
let socket_pointer= &socket_address as *const sockaddr_in6;
bind(socket_handle, socket_pointer.cast(), address_size)
}
};
if result < 0 {
close(socket_handle);
return Err(SocketError::Binding);
}
return Ok(socket_handle);
}
}
/// Performs the `socket` and `connect` calls
fn create_and_connect_socket(socket_type: libc::c_int, protocol: libc::c_int, ip: IpAddr, port: u16) -> Result<libc::c_int, SocketError> {
let family = socket_family_from_ip(ip);
unsafe {
let socket_handle = socket(family, socket_type, protocol);
if socket_handle < 0 {
return Err(SocketError::Opening);
}
let result = match ip {
IpAddr::V4(ip) => {
let (socket_address, address_size) = create_sockaddr_in_v4(ip, port);
let socket_pointer = &socket_address as *const sockaddr_in;
connect(socket_handle, socket_pointer.cast(), address_size)
},
IpAddr::V6(ip) => {
let (socket_address, address_size) = create_sockaddr_in_v6(ip, port);
let socket_pointer= &socket_address as *const sockaddr_in6;
connect(socket_handle, socket_pointer.cast(), address_size)
}
};
if result < 0 {
close(socket_handle);
return Err(SocketError::Connecting);
}
return Ok(socket_handle);
}
}
#[inline]
fn create_sockaddr_in_v4(ip: Ipv4Addr, port: u16) -> (sockaddr_in, libc::socklen_t) {
let address = unsafe{
in_addr{
s_addr: std::mem::transmute(ip.octets())
}
};
let socket_address = sockaddr_in{
sin_family: libc::AF_INET as libc::sa_family_t,
sin_port: htons(port),
sin_addr: address,
sin_zero: [0; 8]
};
let address_size = size_of::<sockaddr_in>();
return (socket_address, address_size as _);
}
#[inline]
fn create_sockaddr_in_v6(ip: Ipv6Addr, port: u16) -> (sockaddr_in6, libc::socklen_t) {
// flow label is advised to be, according to RFC6437 a (somewhat
// secure) random number taken from a uniform distribution
let flow_info = rand::random();
let address = unsafe{
in6_addr{
s6_addr: ip.octets()
}
};
let socket_address = sockaddr_in6{
sin6_family: libc::AF_INET6 as libc::sa_family_t,
sin6_port: htons(port),
sin6_flowinfo: flow_info,
sin6_addr: address,
sin6_scope_id: 0, // incorrect in case of loopback address
};
let address_size = size_of::<sockaddr_in6>();
return (socket_address, address_size as _);
}
#[inline]
fn set_socket_blocking(handle: libc::c_int, blocking: bool) -> bool {
if handle < 0 {
return false;
}
unsafe{
let mut flags = libc::fcntl(handle, libc::F_GETFL, 0);
if flags < 0 {
return false;
}
if blocking {
flags &= !libc::O_NONBLOCK;
} else {
flags |= libc::O_NONBLOCK;
}
let result = libc::fcntl(handle, libc::F_SETFL, flags);
if result < 0 {
return false;
}
}
return true;
}
#[inline]
fn socket_family_from_ip(ip: IpAddr) -> libc::c_int {
return match ip {
IpAddr::V4(_) => libc::AF_INET,
IpAddr::V6(_) => libc::AF_INET6,
};
}
#[inline]
fn htons(port: u16) -> u16 {
return port.to_be();
}
mod tests {
use std::net::*;
use super::*;
// #[test] @nocommit Remove this
// fn test_inet_thingo() {
// const SIZE: usize = 1024;
//
// let s = SocketTcpClient::new(IpAddr::V4(Ipv4Addr::new(142, 250, 179, 163)), 80).expect("connect");
// s.send(b"GET / HTTP/1.1\r\n\r\n").expect("sending");
// let mut total = Vec::<u8>::new();
// let mut buffer = [0; SIZE];
// let mut received = SIZE;
//
// while received > 0 {
// received = s.receive(&mut buffer).expect("receiving");
// println!("DEBUG: Received {} bytes", received);
// total.extend_from_slice(&buffer[..received]);
// }
// let as_str = String::from_utf8_lossy(total.as_slice());
// println!("Yay! Got {} bytes:\n{}", as_str.len(), as_str);
// }
}
|