|
| 1 | +// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT |
| 2 | +// file at the top-level directory of this distribution and at |
| 3 | +// http://rust-lang.org/COPYRIGHT. |
| 4 | +// |
| 5 | +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 7 | +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 8 | +// option. This file may not be copied, modified, or distributed |
| 9 | +// except according to those terms. |
| 10 | + |
| 11 | +use prelude::v1::*; |
| 12 | + |
| 13 | +use ffi::CString; |
| 14 | +use io::{self, Error, ErrorKind}; |
| 15 | +use libc::{self, c_int, c_char, c_void, socklen_t}; |
| 16 | +use mem; |
| 17 | +use net::{IpAddr, SocketAddr, Shutdown}; |
| 18 | +use num::Int; |
| 19 | +use sys::c; |
| 20 | +use sys::net::{cvt, cvt_r, cvt_gai, Socket, init, wrlen_t}; |
| 21 | +use sys_common::{AsInner, FromInner, IntoInner}; |
| 22 | + |
| 23 | +//////////////////////////////////////////////////////////////////////////////// |
| 24 | +// sockaddr and misc bindings |
| 25 | +//////////////////////////////////////////////////////////////////////////////// |
| 26 | + |
| 27 | +fn hton<I: Int>(i: I) -> I { i.to_be() } |
| 28 | +fn ntoh<I: Int>(i: I) -> I { Int::from_be(i) } |
| 29 | + |
| 30 | +fn setsockopt<T>(sock: &Socket, opt: c_int, val: c_int, |
| 31 | + payload: T) -> io::Result<()> { |
| 32 | + unsafe { |
| 33 | + let payload = &payload as *const T as *const c_void; |
| 34 | + try!(cvt(libc::setsockopt(*sock.as_inner(), opt, val, payload, |
| 35 | + mem::size_of::<T>() as socklen_t))); |
| 36 | + Ok(()) |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +#[allow(dead_code)] |
| 41 | +fn getsockopt<T: Copy>(sock: &Socket, opt: c_int, |
| 42 | + val: c_int) -> io::Result<T> { |
| 43 | + unsafe { |
| 44 | + let mut slot: T = mem::zeroed(); |
| 45 | + let mut len = mem::size_of::<T>() as socklen_t; |
| 46 | + let ret = try!(cvt(c::getsockopt(*sock.as_inner(), opt, val, |
| 47 | + &mut slot as *mut _ as *mut _, |
| 48 | + &mut len))); |
| 49 | + assert_eq!(ret as usize, mem::size_of::<T>()); |
| 50 | + Ok(slot) |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +fn sockname<F>(f: F) -> io::Result<SocketAddr> |
| 55 | + where F: FnOnce(*mut libc::sockaddr, *mut socklen_t) -> c_int |
| 56 | +{ |
| 57 | + unsafe { |
| 58 | + let mut storage: libc::sockaddr_storage = mem::zeroed(); |
| 59 | + let mut len = mem::size_of_val(&storage) as socklen_t; |
| 60 | + try!(cvt(f(&mut storage as *mut _ as *mut _, &mut len))); |
| 61 | + sockaddr_to_addr(&storage, len as usize) |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +fn sockaddr_to_addr(storage: &libc::sockaddr_storage, |
| 66 | + len: usize) -> io::Result<SocketAddr> { |
| 67 | + match storage.ss_family as libc::c_int { |
| 68 | + libc::AF_INET => { |
| 69 | + assert!(len as usize >= mem::size_of::<libc::sockaddr_in>()); |
| 70 | + Ok(FromInner::from_inner(unsafe { |
| 71 | + *(storage as *const _ as *const libc::sockaddr_in) |
| 72 | + })) |
| 73 | + } |
| 74 | + libc::AF_INET6 => { |
| 75 | + assert!(len as usize >= mem::size_of::<libc::sockaddr_in6>()); |
| 76 | + Ok(FromInner::from_inner(unsafe { |
| 77 | + *(storage as *const _ as *const libc::sockaddr_in6) |
| 78 | + })) |
| 79 | + } |
| 80 | + _ => { |
| 81 | + Err(Error::new(ErrorKind::InvalidInput, "invalid argument", None)) |
| 82 | + } |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +//////////////////////////////////////////////////////////////////////////////// |
| 87 | +// get_host_addresses |
| 88 | +//////////////////////////////////////////////////////////////////////////////// |
| 89 | + |
| 90 | +extern "system" { |
| 91 | + fn getaddrinfo(node: *const c_char, service: *const c_char, |
| 92 | + hints: *const libc::addrinfo, |
| 93 | + res: *mut *mut libc::addrinfo) -> c_int; |
| 94 | + fn freeaddrinfo(res: *mut libc::addrinfo); |
| 95 | +} |
| 96 | + |
| 97 | +pub struct LookupHost { |
| 98 | + original: *mut libc::addrinfo, |
| 99 | + cur: *mut libc::addrinfo, |
| 100 | +} |
| 101 | + |
| 102 | +impl Iterator for LookupHost { |
| 103 | + type Item = io::Result<SocketAddr>; |
| 104 | + fn next(&mut self) -> Option<io::Result<SocketAddr>> { |
| 105 | + unsafe { |
| 106 | + if self.cur.is_null() { return None } |
| 107 | + let ret = sockaddr_to_addr(mem::transmute((*self.cur).ai_addr), |
| 108 | + (*self.cur).ai_addrlen as usize); |
| 109 | + self.cur = (*self.cur).ai_next as *mut libc::addrinfo; |
| 110 | + Some(ret) |
| 111 | + } |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +impl Drop for LookupHost { |
| 116 | + fn drop(&mut self) { |
| 117 | + unsafe { freeaddrinfo(self.original) } |
| 118 | + } |
| 119 | +} |
| 120 | + |
| 121 | +pub fn lookup_host(host: &str) -> io::Result<LookupHost> { |
| 122 | + init(); |
| 123 | + |
| 124 | + let c_host = CString::from_slice(host.as_bytes()); |
| 125 | + let mut res = 0 as *mut _; |
| 126 | + unsafe { |
| 127 | + try!(cvt_gai(getaddrinfo(c_host.as_ptr(), 0 as *const _, 0 as *const _, |
| 128 | + &mut res))); |
| 129 | + Ok(LookupHost { original: res, cur: res }) |
| 130 | + } |
| 131 | +} |
| 132 | + |
| 133 | +//////////////////////////////////////////////////////////////////////////////// |
| 134 | +// TCP streams |
| 135 | +//////////////////////////////////////////////////////////////////////////////// |
| 136 | + |
| 137 | +pub struct TcpStream { |
| 138 | + inner: Socket, |
| 139 | +} |
| 140 | + |
| 141 | +impl TcpStream { |
| 142 | + pub fn connect(addr: &SocketAddr) -> io::Result<TcpStream> { |
| 143 | + init(); |
| 144 | + |
| 145 | + let sock = try!(Socket::new(addr, libc::SOCK_STREAM)); |
| 146 | + |
| 147 | + let (addrp, len) = addr.into_inner(); |
| 148 | + try!(cvt_r(|| unsafe { libc::connect(*sock.as_inner(), addrp, len) })); |
| 149 | + Ok(TcpStream { inner: sock }) |
| 150 | + } |
| 151 | + |
| 152 | + pub fn socket(&self) -> &Socket { &self.inner } |
| 153 | + |
| 154 | + pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { |
| 155 | + setsockopt(&self.inner, libc::IPPROTO_TCP, libc::TCP_NODELAY, |
| 156 | + nodelay as c_int) |
| 157 | + } |
| 158 | + |
| 159 | + pub fn set_keepalive(&self, seconds: Option<u32>) -> io::Result<()> { |
| 160 | + let ret = setsockopt(&self.inner, libc::SOL_SOCKET, libc::SO_KEEPALIVE, |
| 161 | + seconds.is_some() as c_int); |
| 162 | + match seconds { |
| 163 | + Some(n) => ret.and_then(|()| self.set_tcp_keepalive(n)), |
| 164 | + None => ret, |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + #[cfg(any(target_os = "macos", target_os = "ios"))] |
| 169 | + fn set_tcp_keepalive(&self, seconds: u32) -> io::Result<()> { |
| 170 | + setsockopt(&self.inner, libc::IPPROTO_TCP, libc::TCP_KEEPALIVE, |
| 171 | + seconds as c_int) |
| 172 | + } |
| 173 | + #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] |
| 174 | + fn set_tcp_keepalive(&self, seconds: u32) -> io::Result<()> { |
| 175 | + setsockopt(&self.inner, libc::IPPROTO_TCP, libc::TCP_KEEPIDLE, |
| 176 | + seconds as c_int) |
| 177 | + } |
| 178 | + #[cfg(not(any(target_os = "macos", |
| 179 | + target_os = "ios", |
| 180 | + target_os = "freebsd", |
| 181 | + target_os = "dragonfly")))] |
| 182 | + fn set_tcp_keepalive(&self, _seconds: u32) -> io::Result<()> { |
| 183 | + Ok(()) |
| 184 | + } |
| 185 | + |
| 186 | + pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { |
| 187 | + self.inner.read(buf) |
| 188 | + } |
| 189 | + |
| 190 | + pub fn write(&self, buf: &[u8]) -> io::Result<usize> { |
| 191 | + let ret = try!(cvt(unsafe { |
| 192 | + libc::send(*self.inner.as_inner(), |
| 193 | + buf.as_ptr() as *const c_void, |
| 194 | + buf.len() as wrlen_t, |
| 195 | + 0) |
| 196 | + })); |
| 197 | + Ok(ret as usize) |
| 198 | + } |
| 199 | + |
| 200 | + pub fn peer_addr(&self) -> io::Result<SocketAddr> { |
| 201 | + sockname(|buf, len| unsafe { |
| 202 | + libc::getpeername(*self.inner.as_inner(), buf, len) |
| 203 | + }) |
| 204 | + } |
| 205 | + |
| 206 | + pub fn socket_addr(&self) -> io::Result<SocketAddr> { |
| 207 | + sockname(|buf, len| unsafe { |
| 208 | + libc::getsockname(*self.inner.as_inner(), buf, len) |
| 209 | + }) |
| 210 | + } |
| 211 | + |
| 212 | + pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { |
| 213 | + use libc::consts::os::bsd44::SHUT_RDWR; |
| 214 | + |
| 215 | + let how = match how { |
| 216 | + Shutdown::Write => libc::SHUT_WR, |
| 217 | + Shutdown::Read => libc::SHUT_RD, |
| 218 | + Shutdown::Both => SHUT_RDWR, |
| 219 | + }; |
| 220 | + try!(cvt(unsafe { libc::shutdown(*self.inner.as_inner(), how) })); |
| 221 | + Ok(()) |
| 222 | + } |
| 223 | + |
| 224 | + pub fn duplicate(&self) -> io::Result<TcpStream> { |
| 225 | + self.inner.duplicate().map(|s| TcpStream { inner: s }) |
| 226 | + } |
| 227 | +} |
| 228 | + |
| 229 | +//////////////////////////////////////////////////////////////////////////////// |
| 230 | +// TCP listeners |
| 231 | +//////////////////////////////////////////////////////////////////////////////// |
| 232 | + |
| 233 | +pub struct TcpListener { |
| 234 | + inner: Socket, |
| 235 | +} |
| 236 | + |
| 237 | +impl TcpListener { |
| 238 | + pub fn bind(addr: &SocketAddr) -> io::Result<TcpListener> { |
| 239 | + init(); |
| 240 | + |
| 241 | + let sock = try!(Socket::new(addr, libc::SOCK_STREAM)); |
| 242 | + |
| 243 | + // On platforms with Berkeley-derived sockets, this allows |
| 244 | + // to quickly rebind a socket, without needing to wait for |
| 245 | + // the OS to clean up the previous one. |
| 246 | + if !cfg!(windows) { |
| 247 | + try!(setsockopt(&sock, libc::SOL_SOCKET, libc::SO_REUSEADDR, |
| 248 | + 1 as c_int)); |
| 249 | + } |
| 250 | + |
| 251 | + // Bind our new socket |
| 252 | + let (addrp, len) = addr.into_inner(); |
| 253 | + try!(cvt(unsafe { libc::bind(*sock.as_inner(), addrp, len) })); |
| 254 | + |
| 255 | + // Start listening |
| 256 | + try!(cvt(unsafe { libc::listen(*sock.as_inner(), 128) })); |
| 257 | + Ok(TcpListener { inner: sock }) |
| 258 | + } |
| 259 | + |
| 260 | + pub fn socket(&self) -> &Socket { &self.inner } |
| 261 | + |
| 262 | + pub fn socket_addr(&self) -> io::Result<SocketAddr> { |
| 263 | + sockname(|buf, len| unsafe { |
| 264 | + libc::getsockname(*self.inner.as_inner(), buf, len) |
| 265 | + }) |
| 266 | + } |
| 267 | + |
| 268 | + pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { |
| 269 | + let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() }; |
| 270 | + let mut len = mem::size_of_val(&storage) as socklen_t; |
| 271 | + let sock = try!(self.inner.accept(&mut storage as *mut _ as *mut _, |
| 272 | + &mut len)); |
| 273 | + let addr = try!(sockaddr_to_addr(&storage, len as usize)); |
| 274 | + Ok((TcpStream { inner: sock, }, addr)) |
| 275 | + } |
| 276 | + |
| 277 | + pub fn duplicate(&self) -> io::Result<TcpListener> { |
| 278 | + self.inner.duplicate().map(|s| TcpListener { inner: s }) |
| 279 | + } |
| 280 | +} |
| 281 | + |
| 282 | +//////////////////////////////////////////////////////////////////////////////// |
| 283 | +// UDP |
| 284 | +//////////////////////////////////////////////////////////////////////////////// |
| 285 | + |
| 286 | +pub struct UdpSocket { |
| 287 | + inner: Socket, |
| 288 | +} |
| 289 | + |
| 290 | +impl UdpSocket { |
| 291 | + pub fn bind(addr: &SocketAddr) -> io::Result<UdpSocket> { |
| 292 | + init(); |
| 293 | + |
| 294 | + let sock = try!(Socket::new(addr, libc::SOCK_DGRAM)); |
| 295 | + let (addrp, len) = addr.into_inner(); |
| 296 | + try!(cvt(unsafe { libc::bind(*sock.as_inner(), addrp, len) })); |
| 297 | + Ok(UdpSocket { inner: sock }) |
| 298 | + } |
| 299 | + |
| 300 | + pub fn socket(&self) -> &Socket { &self.inner } |
| 301 | + |
| 302 | + pub fn socket_addr(&self) -> io::Result<SocketAddr> { |
| 303 | + sockname(|buf, len| unsafe { |
| 304 | + libc::getsockname(*self.inner.as_inner(), buf, len) |
| 305 | + }) |
| 306 | + } |
| 307 | + |
| 308 | + pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { |
| 309 | + let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() }; |
| 310 | + let mut addrlen = mem::size_of_val(&storage) as socklen_t; |
| 311 | + |
| 312 | + let n = try!(cvt(unsafe { |
| 313 | + libc::recvfrom(*self.inner.as_inner(), |
| 314 | + buf.as_mut_ptr() as *mut c_void, |
| 315 | + buf.len() as wrlen_t, 0, |
| 316 | + &mut storage as *mut _ as *mut _, &mut addrlen) |
| 317 | + })); |
| 318 | + Ok((n as usize, try!(sockaddr_to_addr(&storage, addrlen as usize)))) |
| 319 | + } |
| 320 | + |
| 321 | + pub fn send_to(&self, buf: &[u8], dst: &SocketAddr) -> io::Result<usize> { |
| 322 | + let (dstp, dstlen) = dst.into_inner(); |
| 323 | + let ret = try!(cvt(unsafe { |
| 324 | + libc::sendto(*self.inner.as_inner(), |
| 325 | + buf.as_ptr() as *const c_void, buf.len() as wrlen_t, |
| 326 | + 0, dstp, dstlen) |
| 327 | + })); |
| 328 | + Ok(ret as usize) |
| 329 | + } |
| 330 | + |
| 331 | + pub fn set_broadcast(&self, on: bool) -> io::Result<()> { |
| 332 | + setsockopt(&self.inner, libc::SOL_SOCKET, libc::SO_BROADCAST, |
| 333 | + on as c_int) |
| 334 | + } |
| 335 | + |
| 336 | + pub fn set_multicast_loop(&self, on: bool) -> io::Result<()> { |
| 337 | + setsockopt(&self.inner, libc::IPPROTO_IP, |
| 338 | + libc::IP_MULTICAST_LOOP, on as c_int) |
| 339 | + } |
| 340 | + |
| 341 | + pub fn join_multicast(&self, multi: &IpAddr) -> io::Result<()> { |
| 342 | + match *multi { |
| 343 | + IpAddr::V4(..) => { |
| 344 | + self.set_membership(multi, libc::IP_ADD_MEMBERSHIP) |
| 345 | + } |
| 346 | + IpAddr::V6(..) => { |
| 347 | + self.set_membership(multi, libc::IPV6_ADD_MEMBERSHIP) |
| 348 | + } |
| 349 | + } |
| 350 | + } |
| 351 | + pub fn leave_multicast(&self, multi: &IpAddr) -> io::Result<()> { |
| 352 | + match *multi { |
| 353 | + IpAddr::V4(..) => { |
| 354 | + self.set_membership(multi, libc::IP_DROP_MEMBERSHIP) |
| 355 | + } |
| 356 | + IpAddr::V6(..) => { |
| 357 | + self.set_membership(multi, libc::IPV6_DROP_MEMBERSHIP) |
| 358 | + } |
| 359 | + } |
| 360 | + } |
| 361 | + fn set_membership(&self, addr: &IpAddr, opt: c_int) -> io::Result<()> { |
| 362 | + match *addr { |
| 363 | + IpAddr::V4(ref addr) => { |
| 364 | + let mreq = libc::ip_mreq { |
| 365 | + imr_multiaddr: *addr.as_inner(), |
| 366 | + // interface == INADDR_ANY |
| 367 | + imr_interface: libc::in_addr { s_addr: 0x0 }, |
| 368 | + }; |
| 369 | + setsockopt(&self.inner, libc::IPPROTO_IP, opt, mreq) |
| 370 | + } |
| 371 | + IpAddr::V6(ref addr) => { |
| 372 | + let mreq = libc::ip6_mreq { |
| 373 | + ipv6mr_multiaddr: *addr.as_inner(), |
| 374 | + ipv6mr_interface: 0, |
| 375 | + }; |
| 376 | + setsockopt(&self.inner, libc::IPPROTO_IPV6, opt, mreq) |
| 377 | + } |
| 378 | + } |
| 379 | + } |
| 380 | + |
| 381 | + pub fn multicast_time_to_live(&self, ttl: i32) -> io::Result<()> { |
| 382 | + setsockopt(&self.inner, libc::IPPROTO_IP, libc::IP_MULTICAST_TTL, |
| 383 | + ttl as c_int) |
| 384 | + } |
| 385 | + |
| 386 | + pub fn time_to_live(&self, ttl: i32) -> io::Result<()> { |
| 387 | + setsockopt(&self.inner, libc::IPPROTO_IP, libc::IP_TTL, ttl as c_int) |
| 388 | + } |
| 389 | + |
| 390 | + pub fn duplicate(&self) -> io::Result<UdpSocket> { |
| 391 | + self.inner.duplicate().map(|s| UdpSocket { inner: s }) |
| 392 | + } |
| 393 | +} |
0 commit comments