]> git.proxmox.com Git - rustc.git/blob - src/libstd/sys/common/net.rs
Imported Upstream version 1.9.0+dfsg1
[rustc.git] / src / libstd / sys / common / net.rs
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 cmp;
14 use ffi::CString;
15 use fmt;
16 use io::{self, Error, ErrorKind};
17 use libc::{c_int, c_void};
18 use mem;
19 use net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr};
20 use ptr;
21 use sys::net::{cvt, cvt_r, cvt_gai, Socket, init, wrlen_t};
22 use sys::net::netc as c;
23 use sys_common::{AsInner, FromInner, IntoInner};
24 use time::Duration;
25
26 #[cfg(any(target_os = "dragonfly", target_os = "freebsd",
27 target_os = "ios", target_os = "macos",
28 target_os = "openbsd", target_os = "netbsd"))]
29 use sys::net::netc::IPV6_JOIN_GROUP as IPV6_ADD_MEMBERSHIP;
30 #[cfg(not(any(target_os = "dragonfly", target_os = "freebsd",
31 target_os = "ios", target_os = "macos",
32 target_os = "openbsd", target_os = "netbsd")))]
33 use sys::net::netc::IPV6_ADD_MEMBERSHIP;
34 #[cfg(any(target_os = "dragonfly", target_os = "freebsd",
35 target_os = "ios", target_os = "macos",
36 target_os = "openbsd", target_os = "netbsd"))]
37 use sys::net::netc::IPV6_LEAVE_GROUP as IPV6_DROP_MEMBERSHIP;
38 #[cfg(not(any(target_os = "dragonfly", target_os = "freebsd",
39 target_os = "ios", target_os = "macos",
40 target_os = "openbsd", target_os = "netbsd")))]
41 use sys::net::netc::IPV6_DROP_MEMBERSHIP;
42
43 ////////////////////////////////////////////////////////////////////////////////
44 // sockaddr and misc bindings
45 ////////////////////////////////////////////////////////////////////////////////
46
47 pub fn setsockopt<T>(sock: &Socket, opt: c_int, val: c_int,
48 payload: T) -> io::Result<()> {
49 unsafe {
50 let payload = &payload as *const T as *const c_void;
51 cvt(c::setsockopt(*sock.as_inner(), opt, val, payload,
52 mem::size_of::<T>() as c::socklen_t))?;
53 Ok(())
54 }
55 }
56
57 pub fn getsockopt<T: Copy>(sock: &Socket, opt: c_int,
58 val: c_int) -> io::Result<T> {
59 unsafe {
60 let mut slot: T = mem::zeroed();
61 let mut len = mem::size_of::<T>() as c::socklen_t;
62 cvt(c::getsockopt(*sock.as_inner(), opt, val,
63 &mut slot as *mut _ as *mut _,
64 &mut len))?;
65 assert_eq!(len as usize, mem::size_of::<T>());
66 Ok(slot)
67 }
68 }
69
70 fn sockname<F>(f: F) -> io::Result<SocketAddr>
71 where F: FnOnce(*mut c::sockaddr, *mut c::socklen_t) -> c_int
72 {
73 unsafe {
74 let mut storage: c::sockaddr_storage = mem::zeroed();
75 let mut len = mem::size_of_val(&storage) as c::socklen_t;
76 cvt(f(&mut storage as *mut _ as *mut _, &mut len))?;
77 sockaddr_to_addr(&storage, len as usize)
78 }
79 }
80
81 fn sockaddr_to_addr(storage: &c::sockaddr_storage,
82 len: usize) -> io::Result<SocketAddr> {
83 match storage.ss_family as c_int {
84 c::AF_INET => {
85 assert!(len as usize >= mem::size_of::<c::sockaddr_in>());
86 Ok(SocketAddr::V4(FromInner::from_inner(unsafe {
87 *(storage as *const _ as *const c::sockaddr_in)
88 })))
89 }
90 c::AF_INET6 => {
91 assert!(len as usize >= mem::size_of::<c::sockaddr_in6>());
92 Ok(SocketAddr::V6(FromInner::from_inner(unsafe {
93 *(storage as *const _ as *const c::sockaddr_in6)
94 })))
95 }
96 _ => {
97 Err(Error::new(ErrorKind::InvalidInput, "invalid argument"))
98 }
99 }
100 }
101
102 #[cfg(target_os = "android")]
103 fn to_ipv6mr_interface(value: u32) -> c_int {
104 value as c_int
105 }
106
107 #[cfg(not(target_os = "android"))]
108 fn to_ipv6mr_interface(value: u32) -> ::libc::c_uint {
109 value as ::libc::c_uint
110 }
111
112 ////////////////////////////////////////////////////////////////////////////////
113 // get_host_addresses
114 ////////////////////////////////////////////////////////////////////////////////
115
116 pub struct LookupHost {
117 original: *mut c::addrinfo,
118 cur: *mut c::addrinfo,
119 }
120
121 impl Iterator for LookupHost {
122 type Item = io::Result<SocketAddr>;
123 fn next(&mut self) -> Option<io::Result<SocketAddr>> {
124 unsafe {
125 if self.cur.is_null() { return None }
126 let ret = sockaddr_to_addr(mem::transmute((*self.cur).ai_addr),
127 (*self.cur).ai_addrlen as usize);
128 self.cur = (*self.cur).ai_next as *mut c::addrinfo;
129 Some(ret)
130 }
131 }
132 }
133
134 unsafe impl Sync for LookupHost {}
135 unsafe impl Send for LookupHost {}
136
137 impl Drop for LookupHost {
138 fn drop(&mut self) {
139 unsafe { c::freeaddrinfo(self.original) }
140 }
141 }
142
143 pub fn lookup_host(host: &str) -> io::Result<LookupHost> {
144 init();
145
146 let c_host = CString::new(host)?;
147 let mut res = ptr::null_mut();
148 unsafe {
149 cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), ptr::null(),
150 &mut res))?;
151 Ok(LookupHost { original: res, cur: res })
152 }
153 }
154
155 ////////////////////////////////////////////////////////////////////////////////
156 // TCP streams
157 ////////////////////////////////////////////////////////////////////////////////
158
159 pub struct TcpStream {
160 inner: Socket,
161 }
162
163 impl TcpStream {
164 pub fn connect(addr: &SocketAddr) -> io::Result<TcpStream> {
165 init();
166
167 let sock = Socket::new(addr, c::SOCK_STREAM)?;
168
169 let (addrp, len) = addr.into_inner();
170 cvt_r(|| unsafe { c::connect(*sock.as_inner(), addrp, len) })?;
171 Ok(TcpStream { inner: sock })
172 }
173
174 pub fn socket(&self) -> &Socket { &self.inner }
175
176 pub fn into_socket(self) -> Socket { self.inner }
177
178 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
179 self.inner.set_timeout(dur, c::SO_RCVTIMEO)
180 }
181
182 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
183 self.inner.set_timeout(dur, c::SO_SNDTIMEO)
184 }
185
186 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
187 self.inner.timeout(c::SO_RCVTIMEO)
188 }
189
190 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
191 self.inner.timeout(c::SO_SNDTIMEO)
192 }
193
194 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
195 self.inner.read(buf)
196 }
197
198 pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
199 self.inner.read_to_end(buf)
200 }
201
202 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
203 let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
204 let ret = cvt(unsafe {
205 c::send(*self.inner.as_inner(),
206 buf.as_ptr() as *const c_void,
207 len,
208 0)
209 })?;
210 Ok(ret as usize)
211 }
212
213 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
214 sockname(|buf, len| unsafe {
215 c::getpeername(*self.inner.as_inner(), buf, len)
216 })
217 }
218
219 pub fn socket_addr(&self) -> io::Result<SocketAddr> {
220 sockname(|buf, len| unsafe {
221 c::getsockname(*self.inner.as_inner(), buf, len)
222 })
223 }
224
225 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
226 self.inner.shutdown(how)
227 }
228
229 pub fn duplicate(&self) -> io::Result<TcpStream> {
230 self.inner.duplicate().map(|s| TcpStream { inner: s })
231 }
232
233 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
234 self.inner.set_nodelay(nodelay)
235 }
236
237 pub fn nodelay(&self) -> io::Result<bool> {
238 self.inner.nodelay()
239 }
240
241 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
242 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL, ttl as c_int)
243 }
244
245 pub fn ttl(&self) -> io::Result<u32> {
246 let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL)?;
247 Ok(raw as u32)
248 }
249
250 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
251 self.inner.take_error()
252 }
253
254 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
255 self.inner.set_nonblocking(nonblocking)
256 }
257 }
258
259 impl FromInner<Socket> for TcpStream {
260 fn from_inner(socket: Socket) -> TcpStream {
261 TcpStream { inner: socket }
262 }
263 }
264
265 impl fmt::Debug for TcpStream {
266 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
267 let mut res = f.debug_struct("TcpStream");
268
269 if let Ok(addr) = self.socket_addr() {
270 res.field("addr", &addr);
271 }
272
273 if let Ok(peer) = self.peer_addr() {
274 res.field("peer", &peer);
275 }
276
277 let name = if cfg!(windows) {"socket"} else {"fd"};
278 res.field(name, &self.inner.as_inner())
279 .finish()
280 }
281 }
282
283 ////////////////////////////////////////////////////////////////////////////////
284 // TCP listeners
285 ////////////////////////////////////////////////////////////////////////////////
286
287 pub struct TcpListener {
288 inner: Socket,
289 }
290
291 impl TcpListener {
292 pub fn bind(addr: &SocketAddr) -> io::Result<TcpListener> {
293 init();
294
295 let sock = Socket::new(addr, c::SOCK_STREAM)?;
296
297 // On platforms with Berkeley-derived sockets, this allows
298 // to quickly rebind a socket, without needing to wait for
299 // the OS to clean up the previous one.
300 if !cfg!(windows) {
301 setsockopt(&sock, c::SOL_SOCKET, c::SO_REUSEADDR,
302 1 as c_int)?;
303 }
304
305 // Bind our new socket
306 let (addrp, len) = addr.into_inner();
307 cvt(unsafe { c::bind(*sock.as_inner(), addrp, len) })?;
308
309 // Start listening
310 cvt(unsafe { c::listen(*sock.as_inner(), 128) })?;
311 Ok(TcpListener { inner: sock })
312 }
313
314 pub fn socket(&self) -> &Socket { &self.inner }
315
316 pub fn into_socket(self) -> Socket { self.inner }
317
318 pub fn socket_addr(&self) -> io::Result<SocketAddr> {
319 sockname(|buf, len| unsafe {
320 c::getsockname(*self.inner.as_inner(), buf, len)
321 })
322 }
323
324 pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
325 let mut storage: c::sockaddr_storage = unsafe { mem::zeroed() };
326 let mut len = mem::size_of_val(&storage) as c::socklen_t;
327 let sock = self.inner.accept(&mut storage as *mut _ as *mut _,
328 &mut len)?;
329 let addr = sockaddr_to_addr(&storage, len as usize)?;
330 Ok((TcpStream { inner: sock, }, addr))
331 }
332
333 pub fn duplicate(&self) -> io::Result<TcpListener> {
334 self.inner.duplicate().map(|s| TcpListener { inner: s })
335 }
336
337 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
338 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL, ttl as c_int)
339 }
340
341 pub fn ttl(&self) -> io::Result<u32> {
342 let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL)?;
343 Ok(raw as u32)
344 }
345
346 pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
347 setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY, only_v6 as c_int)
348 }
349
350 pub fn only_v6(&self) -> io::Result<bool> {
351 let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY)?;
352 Ok(raw != 0)
353 }
354
355 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
356 self.inner.take_error()
357 }
358
359 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
360 self.inner.set_nonblocking(nonblocking)
361 }
362 }
363
364 impl FromInner<Socket> for TcpListener {
365 fn from_inner(socket: Socket) -> TcpListener {
366 TcpListener { inner: socket }
367 }
368 }
369
370 impl fmt::Debug for TcpListener {
371 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
372 let mut res = f.debug_struct("TcpListener");
373
374 if let Ok(addr) = self.socket_addr() {
375 res.field("addr", &addr);
376 }
377
378 let name = if cfg!(windows) {"socket"} else {"fd"};
379 res.field(name, &self.inner.as_inner())
380 .finish()
381 }
382 }
383
384 ////////////////////////////////////////////////////////////////////////////////
385 // UDP
386 ////////////////////////////////////////////////////////////////////////////////
387
388 pub struct UdpSocket {
389 inner: Socket,
390 }
391
392 impl UdpSocket {
393 pub fn bind(addr: &SocketAddr) -> io::Result<UdpSocket> {
394 init();
395
396 let sock = Socket::new(addr, c::SOCK_DGRAM)?;
397 let (addrp, len) = addr.into_inner();
398 cvt(unsafe { c::bind(*sock.as_inner(), addrp, len) })?;
399 Ok(UdpSocket { inner: sock })
400 }
401
402 pub fn socket(&self) -> &Socket { &self.inner }
403
404 pub fn into_socket(self) -> Socket { self.inner }
405
406 pub fn socket_addr(&self) -> io::Result<SocketAddr> {
407 sockname(|buf, len| unsafe {
408 c::getsockname(*self.inner.as_inner(), buf, len)
409 })
410 }
411
412 pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
413 let mut storage: c::sockaddr_storage = unsafe { mem::zeroed() };
414 let mut addrlen = mem::size_of_val(&storage) as c::socklen_t;
415 let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
416
417 let n = cvt(unsafe {
418 c::recvfrom(*self.inner.as_inner(),
419 buf.as_mut_ptr() as *mut c_void,
420 len, 0,
421 &mut storage as *mut _ as *mut _, &mut addrlen)
422 })?;
423 Ok((n as usize, sockaddr_to_addr(&storage, addrlen as usize)?))
424 }
425
426 pub fn send_to(&self, buf: &[u8], dst: &SocketAddr) -> io::Result<usize> {
427 let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
428 let (dstp, dstlen) = dst.into_inner();
429 let ret = cvt(unsafe {
430 c::sendto(*self.inner.as_inner(),
431 buf.as_ptr() as *const c_void, len,
432 0, dstp, dstlen)
433 })?;
434 Ok(ret as usize)
435 }
436
437 pub fn duplicate(&self) -> io::Result<UdpSocket> {
438 self.inner.duplicate().map(|s| UdpSocket { inner: s })
439 }
440
441 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
442 self.inner.set_timeout(dur, c::SO_RCVTIMEO)
443 }
444
445 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
446 self.inner.set_timeout(dur, c::SO_SNDTIMEO)
447 }
448
449 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
450 self.inner.timeout(c::SO_RCVTIMEO)
451 }
452
453 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
454 self.inner.timeout(c::SO_SNDTIMEO)
455 }
456
457 pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
458 setsockopt(&self.inner, c::SOL_SOCKET, c::SO_BROADCAST, broadcast as c_int)
459 }
460
461 pub fn broadcast(&self) -> io::Result<bool> {
462 let raw: c_int = getsockopt(&self.inner, c::SOL_SOCKET, c::SO_BROADCAST)?;
463 Ok(raw != 0)
464 }
465
466 pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
467 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_LOOP, multicast_loop_v4 as c_int)
468 }
469
470 pub fn multicast_loop_v4(&self) -> io::Result<bool> {
471 let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_LOOP)?;
472 Ok(raw != 0)
473 }
474
475 pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
476 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_TTL, multicast_ttl_v4 as c_int)
477 }
478
479 pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
480 let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_TTL)?;
481 Ok(raw as u32)
482 }
483
484 pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
485 setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_MULTICAST_LOOP, multicast_loop_v6 as c_int)
486 }
487
488 pub fn multicast_loop_v6(&self) -> io::Result<bool> {
489 let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_MULTICAST_LOOP)?;
490 Ok(raw != 0)
491 }
492
493 pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr)
494 -> io::Result<()> {
495 let mreq = c::ip_mreq {
496 imr_multiaddr: *multiaddr.as_inner(),
497 imr_interface: *interface.as_inner(),
498 };
499 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_ADD_MEMBERSHIP, mreq)
500 }
501
502 pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32)
503 -> io::Result<()> {
504 let mreq = c::ipv6_mreq {
505 ipv6mr_multiaddr: *multiaddr.as_inner(),
506 ipv6mr_interface: to_ipv6mr_interface(interface),
507 };
508 setsockopt(&self.inner, c::IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, mreq)
509 }
510
511 pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr)
512 -> io::Result<()> {
513 let mreq = c::ip_mreq {
514 imr_multiaddr: *multiaddr.as_inner(),
515 imr_interface: *interface.as_inner(),
516 };
517 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_DROP_MEMBERSHIP, mreq)
518 }
519
520 pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32)
521 -> io::Result<()> {
522 let mreq = c::ipv6_mreq {
523 ipv6mr_multiaddr: *multiaddr.as_inner(),
524 ipv6mr_interface: to_ipv6mr_interface(interface),
525 };
526 setsockopt(&self.inner, c::IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, mreq)
527 }
528
529 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
530 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL, ttl as c_int)
531 }
532
533 pub fn ttl(&self) -> io::Result<u32> {
534 let raw: c_int = getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL)?;
535 Ok(raw as u32)
536 }
537
538 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
539 self.inner.take_error()
540 }
541
542 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
543 self.inner.set_nonblocking(nonblocking)
544 }
545
546 pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
547 self.inner.read(buf)
548 }
549
550 pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
551 let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
552 let ret = cvt(unsafe {
553 c::send(*self.inner.as_inner(),
554 buf.as_ptr() as *const c_void,
555 len,
556 0)
557 })?;
558 Ok(ret as usize)
559 }
560
561 pub fn connect(&self, addr: &SocketAddr) -> io::Result<()> {
562 let (addrp, len) = addr.into_inner();
563 cvt_r(|| unsafe { c::connect(*self.inner.as_inner(), addrp, len) }).map(|_| ())
564 }
565 }
566
567 impl FromInner<Socket> for UdpSocket {
568 fn from_inner(socket: Socket) -> UdpSocket {
569 UdpSocket { inner: socket }
570 }
571 }
572
573 impl fmt::Debug for UdpSocket {
574 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
575 let mut res = f.debug_struct("UdpSocket");
576
577 if let Ok(addr) = self.socket_addr() {
578 res.field("addr", &addr);
579 }
580
581 let name = if cfg!(windows) {"socket"} else {"fd"};
582 res.field(name, &self.inner.as_inner())
583 .finish()
584 }
585 }