1 //! Primitives for working with TCP
2 //!
3 //! The types provided in this module are non-blocking by default and are
4 //! designed to be portable across all supported Mio platforms. As long as the
5 //! [portability guidelines] are followed, the behavior should be identical no
6 //! matter the target platform.
7 //!
8 /// [portability guidelines]: ../struct.Poll.html#portability
9 
10 use std::fmt;
11 use std::io::{Read, Write};
12 use std::net::{self, SocketAddr, SocketAddrV4, SocketAddrV6, Ipv4Addr, Ipv6Addr};
13 use std::time::Duration;
14 
15 use net2::TcpBuilder;
16 use iovec::IoVec;
17 
18 use {io, sys, Ready, Poll, PollOpt, Token};
19 use event::Evented;
20 use poll::SelectorId;
21 
22 /*
23  *
24  * ===== TcpStream =====
25  *
26  */
27 
28 /// A non-blocking TCP stream between a local socket and a remote socket.
29 ///
30 /// The socket will be closed when the value is dropped.
31 ///
32 /// # Examples
33 ///
34 /// ```
35 /// # use std::net::TcpListener;
36 /// # use std::error::Error;
37 /// #
38 /// # fn try_main() -> Result<(), Box<Error>> {
39 /// #     let _listener = TcpListener::bind("127.0.0.1:34254")?;
40 /// use mio::{Events, Ready, Poll, PollOpt, Token};
41 /// use mio::net::TcpStream;
42 /// use std::time::Duration;
43 ///
44 /// let stream = TcpStream::connect(&"127.0.0.1:34254".parse()?)?;
45 ///
46 /// let poll = Poll::new()?;
47 /// let mut events = Events::with_capacity(128);
48 ///
49 /// // Register the socket with `Poll`
50 /// poll.register(&stream, Token(0), Ready::writable(),
51 ///               PollOpt::edge())?;
52 ///
53 /// poll.poll(&mut events, Some(Duration::from_millis(100)))?;
54 ///
55 /// // The socket might be ready at this point
56 /// #     Ok(())
57 /// # }
58 /// #
59 /// # fn main() {
60 /// #     try_main().unwrap();
61 /// # }
62 /// ```
63 pub struct TcpStream {
64     sys: sys::TcpStream,
65     selector_id: SelectorId,
66 }
67 
68 use std::net::Shutdown;
69 
70 // TODO: remove when fuchsia's set_nonblocking is fixed in libstd
71 #[cfg(target_os = "fuchsia")]
set_nonblocking(stream: &net::TcpStream) -> io::Result<()>72 fn set_nonblocking(stream: &net::TcpStream) -> io::Result<()> {
73     sys::set_nonblock(
74         ::std::os::unix::io::AsRawFd::as_raw_fd(stream))
75 }
76 #[cfg(not(target_os = "fuchsia"))]
set_nonblocking(stream: &net::TcpStream) -> io::Result<()>77 fn set_nonblocking(stream: &net::TcpStream) -> io::Result<()> {
78     stream.set_nonblocking(true)
79 }
80 
81 
82 impl TcpStream {
83     /// Create a new TCP stream and issue a non-blocking connect to the
84     /// specified address.
85     ///
86     /// This convenience method is available and uses the system's default
87     /// options when creating a socket which is then connected. If fine-grained
88     /// control over the creation of the socket is desired, you can use
89     /// `net2::TcpBuilder` to configure a socket and then pass its socket to
90     /// `TcpStream::connect_stream` to transfer ownership into mio and schedule
91     /// the connect operation.
connect(addr: &SocketAddr) -> io::Result<TcpStream>92     pub fn connect(addr: &SocketAddr) -> io::Result<TcpStream> {
93         let sock = match *addr {
94             SocketAddr::V4(..) => TcpBuilder::new_v4(),
95             SocketAddr::V6(..) => TcpBuilder::new_v6(),
96         }?;
97         // Required on Windows for a future `connect_overlapped` operation to be
98         // executed successfully.
99         if cfg!(windows) {
100             sock.bind(&inaddr_any(addr))?;
101         }
102         TcpStream::connect_stream(sock.to_tcp_stream()?, addr)
103     }
104 
105     /// Creates a new `TcpStream` from the pending socket inside the given
106     /// `std::net::TcpBuilder`, connecting it to the address specified.
107     ///
108     /// This constructor allows configuring the socket before it's actually
109     /// connected, and this function will transfer ownership to the returned
110     /// `TcpStream` if successful. An unconnected `TcpStream` can be created
111     /// with the `net2::TcpBuilder` type (and also configured via that route).
112     ///
113     /// The platform specific behavior of this function looks like:
114     ///
115     /// * On Unix, the socket is placed into nonblocking mode and then a
116     ///   `connect` call is issued.
117     ///
118     /// * On Windows, the address is stored internally and the connect operation
119     ///   is issued when the returned `TcpStream` is registered with an event
120     ///   loop. Note that on Windows you must `bind` a socket before it can be
121     ///   connected, so if a custom `TcpBuilder` is used it should be bound
122     ///   (perhaps to `INADDR_ANY`) before this method is called.
connect_stream(stream: net::TcpStream, addr: &SocketAddr) -> io::Result<TcpStream>123     pub fn connect_stream(stream: net::TcpStream,
124                           addr: &SocketAddr) -> io::Result<TcpStream> {
125         Ok(TcpStream {
126             sys: sys::TcpStream::connect(stream, addr)?,
127             selector_id: SelectorId::new(),
128         })
129     }
130 
131     /// Creates a new `TcpStream` from a standard `net::TcpStream`.
132     ///
133     /// This function is intended to be used to wrap a TCP stream from the
134     /// standard library in the mio equivalent. The conversion here will
135     /// automatically set `stream` to nonblocking and the returned object should
136     /// be ready to get associated with an event loop.
137     ///
138     /// Note that the TCP stream here will not have `connect` called on it, so
139     /// it should already be connected via some other means (be it manually, the
140     /// net2 crate, or the standard library).
from_stream(stream: net::TcpStream) -> io::Result<TcpStream>141     pub fn from_stream(stream: net::TcpStream) -> io::Result<TcpStream> {
142         set_nonblocking(&stream)?;
143 
144         Ok(TcpStream {
145             sys: sys::TcpStream::from_stream(stream),
146             selector_id: SelectorId::new(),
147         })
148     }
149 
150     /// Returns the socket address of the remote peer of this TCP connection.
peer_addr(&self) -> io::Result<SocketAddr>151     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
152         self.sys.peer_addr()
153     }
154 
155     /// Returns the socket address of the local half of this TCP connection.
local_addr(&self) -> io::Result<SocketAddr>156     pub fn local_addr(&self) -> io::Result<SocketAddr> {
157         self.sys.local_addr()
158     }
159 
160     /// Creates a new independently owned handle to the underlying socket.
161     ///
162     /// The returned `TcpStream` is a reference to the same stream that this
163     /// object references. Both handles will read and write the same stream of
164     /// data, and options set on one stream will be propagated to the other
165     /// stream.
try_clone(&self) -> io::Result<TcpStream>166     pub fn try_clone(&self) -> io::Result<TcpStream> {
167         self.sys.try_clone().map(|s| {
168             TcpStream {
169                 sys: s,
170                 selector_id: self.selector_id.clone(),
171             }
172         })
173     }
174 
175     /// Shuts down the read, write, or both halves of this connection.
176     ///
177     /// This function will cause all pending and future I/O on the specified
178     /// portions to return immediately with an appropriate value (see the
179     /// documentation of `Shutdown`).
shutdown(&self, how: Shutdown) -> io::Result<()>180     pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
181         self.sys.shutdown(how)
182     }
183 
184     /// Sets the value of the `TCP_NODELAY` option on this socket.
185     ///
186     /// If set, this option disables the Nagle algorithm. This means that
187     /// segments are always sent as soon as possible, even if there is only a
188     /// small amount of data. When not set, data is buffered until there is a
189     /// sufficient amount to send out, thereby avoiding the frequent sending of
190     /// small packets.
set_nodelay(&self, nodelay: bool) -> io::Result<()>191     pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
192         self.sys.set_nodelay(nodelay)
193     }
194 
195     /// Gets the value of the `TCP_NODELAY` option on this socket.
196     ///
197     /// For more information about this option, see [`set_nodelay`][link].
198     ///
199     /// [link]: #method.set_nodelay
nodelay(&self) -> io::Result<bool>200     pub fn nodelay(&self) -> io::Result<bool> {
201         self.sys.nodelay()
202     }
203 
204     /// Sets the value of the `SO_RCVBUF` option on this socket.
205     ///
206     /// Changes the size of the operating system's receive buffer associated
207     /// with the socket.
set_recv_buffer_size(&self, size: usize) -> io::Result<()>208     pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> {
209         self.sys.set_recv_buffer_size(size)
210     }
211 
212     /// Gets the value of the `SO_RCVBUF` option on this socket.
213     ///
214     /// For more information about this option, see
215     /// [`set_recv_buffer_size`][link].
216     ///
217     /// [link]: #method.set_recv_buffer_size
recv_buffer_size(&self) -> io::Result<usize>218     pub fn recv_buffer_size(&self) -> io::Result<usize> {
219         self.sys.recv_buffer_size()
220     }
221 
222     /// Sets the value of the `SO_SNDBUF` option on this socket.
223     ///
224     /// Changes the size of the operating system's send buffer associated with
225     /// the socket.
set_send_buffer_size(&self, size: usize) -> io::Result<()>226     pub fn set_send_buffer_size(&self, size: usize) -> io::Result<()> {
227         self.sys.set_send_buffer_size(size)
228     }
229 
230     /// Gets the value of the `SO_SNDBUF` option on this socket.
231     ///
232     /// For more information about this option, see
233     /// [`set_send_buffer_size`][link].
234     ///
235     /// [link]: #method.set_send_buffer_size
send_buffer_size(&self) -> io::Result<usize>236     pub fn send_buffer_size(&self) -> io::Result<usize> {
237         self.sys.send_buffer_size()
238     }
239 
240     /// Sets whether keepalive messages are enabled to be sent on this socket.
241     ///
242     /// On Unix, this option will set the `SO_KEEPALIVE` as well as the
243     /// `TCP_KEEPALIVE` or `TCP_KEEPIDLE` option (depending on your platform).
244     /// On Windows, this will set the `SIO_KEEPALIVE_VALS` option.
245     ///
246     /// If `None` is specified then keepalive messages are disabled, otherwise
247     /// the duration specified will be the time to remain idle before sending a
248     /// TCP keepalive probe.
249     ///
250     /// Some platforms specify this value in seconds, so sub-second
251     /// specifications may be omitted.
set_keepalive(&self, keepalive: Option<Duration>) -> io::Result<()>252     pub fn set_keepalive(&self, keepalive: Option<Duration>) -> io::Result<()> {
253         self.sys.set_keepalive(keepalive)
254     }
255 
256     /// Returns whether keepalive messages are enabled on this socket, and if so
257     /// the duration of time between them.
258     ///
259     /// For more information about this option, see [`set_keepalive`][link].
260     ///
261     /// [link]: #method.set_keepalive
keepalive(&self) -> io::Result<Option<Duration>>262     pub fn keepalive(&self) -> io::Result<Option<Duration>> {
263         self.sys.keepalive()
264     }
265 
266     /// Sets the value for the `IP_TTL` option on this socket.
267     ///
268     /// This value sets the time-to-live field that is used in every packet sent
269     /// from this socket.
set_ttl(&self, ttl: u32) -> io::Result<()>270     pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
271         self.sys.set_ttl(ttl)
272     }
273 
274     /// Gets the value of the `IP_TTL` option for this socket.
275     ///
276     /// For more information about this option, see [`set_ttl`][link].
277     ///
278     /// [link]: #method.set_ttl
ttl(&self) -> io::Result<u32>279     pub fn ttl(&self) -> io::Result<u32> {
280         self.sys.ttl()
281     }
282 
283     /// Sets the value for the `IPV6_V6ONLY` option on this socket.
284     ///
285     /// If this is set to `true` then the socket is restricted to sending and
286     /// receiving IPv6 packets only. In this case two IPv4 and IPv6 applications
287     /// can bind the same port at the same time.
288     ///
289     /// If this is set to `false` then the socket can be used to send and
290     /// receive packets from an IPv4-mapped IPv6 address.
set_only_v6(&self, only_v6: bool) -> io::Result<()>291     pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
292         self.sys.set_only_v6(only_v6)
293     }
294 
295     /// Gets the value of the `IPV6_V6ONLY` option for this socket.
296     ///
297     /// For more information about this option, see [`set_only_v6`][link].
298     ///
299     /// [link]: #method.set_only_v6
only_v6(&self) -> io::Result<bool>300     pub fn only_v6(&self) -> io::Result<bool> {
301         self.sys.only_v6()
302     }
303 
304     /// Sets the value for the `SO_LINGER` option on this socket.
set_linger(&self, dur: Option<Duration>) -> io::Result<()>305     pub fn set_linger(&self, dur: Option<Duration>) -> io::Result<()> {
306         self.sys.set_linger(dur)
307     }
308 
309     /// Gets the value of the `SO_LINGER` option on this socket.
310     ///
311     /// For more information about this option, see [`set_linger`][link].
312     ///
313     /// [link]: #method.set_linger
linger(&self) -> io::Result<Option<Duration>>314     pub fn linger(&self) -> io::Result<Option<Duration>> {
315         self.sys.linger()
316     }
317 
318     #[deprecated(since = "0.6.9", note = "use set_keepalive")]
319     #[cfg(feature = "with-deprecated")]
320     #[doc(hidden)]
set_keepalive_ms(&self, keepalive: Option<u32>) -> io::Result<()>321     pub fn set_keepalive_ms(&self, keepalive: Option<u32>) -> io::Result<()> {
322         self.set_keepalive(keepalive.map(|v| {
323             Duration::from_millis(u64::from(v))
324         }))
325     }
326 
327     #[deprecated(since = "0.6.9", note = "use keepalive")]
328     #[cfg(feature = "with-deprecated")]
329     #[doc(hidden)]
keepalive_ms(&self) -> io::Result<Option<u32>>330     pub fn keepalive_ms(&self) -> io::Result<Option<u32>> {
331         self.keepalive().map(|v| {
332             v.map(|v| {
333                 ::convert::millis(v) as u32
334             })
335         })
336     }
337 
338     /// Get the value of the `SO_ERROR` option on this socket.
339     ///
340     /// This will retrieve the stored error in the underlying socket, clearing
341     /// the field in the process. This can be useful for checking errors between
342     /// calls.
take_error(&self) -> io::Result<Option<io::Error>>343     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
344         self.sys.take_error()
345     }
346 
347     /// Receives data on the socket from the remote address to which it is
348     /// connected, without removing that data from the queue. On success,
349     /// returns the number of bytes peeked.
350     ///
351     /// Successive calls return the same data. This is accomplished by passing
352     /// `MSG_PEEK` as a flag to the underlying recv system call.
peek(&self, buf: &mut [u8]) -> io::Result<usize>353     pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
354         self.sys.peek(buf)
355     }
356 
357     /// Read in a list of buffers all at once.
358     ///
359     /// This operation will attempt to read bytes from this socket and place
360     /// them into the list of buffers provided. Note that each buffer is an
361     /// `IoVec` which can be created from a byte slice.
362     ///
363     /// The buffers provided will be filled in sequentially. A buffer will be
364     /// entirely filled up before the next is written to.
365     ///
366     /// The number of bytes read is returned, if successful, or an error is
367     /// returned otherwise. If no bytes are available to be read yet then
368     /// a "would block" error is returned. This operation does not block.
369     ///
370     /// On Unix this corresponds to the `readv` syscall.
read_bufs(&self, bufs: &mut [&mut IoVec]) -> io::Result<usize>371     pub fn read_bufs(&self, bufs: &mut [&mut IoVec]) -> io::Result<usize> {
372         self.sys.readv(bufs)
373     }
374 
375     /// Write a list of buffers all at once.
376     ///
377     /// This operation will attempt to write a list of byte buffers to this
378     /// socket. Note that each buffer is an `IoVec` which can be created from a
379     /// byte slice.
380     ///
381     /// The buffers provided will be written sequentially. A buffer will be
382     /// entirely written before the next is written.
383     ///
384     /// The number of bytes written is returned, if successful, or an error is
385     /// returned otherwise. If the socket is not currently writable then a
386     /// "would block" error is returned. This operation does not block.
387     ///
388     /// On Unix this corresponds to the `writev` syscall.
write_bufs(&self, bufs: &[&IoVec]) -> io::Result<usize>389     pub fn write_bufs(&self, bufs: &[&IoVec]) -> io::Result<usize> {
390         self.sys.writev(bufs)
391     }
392 }
393 
inaddr_any(other: &SocketAddr) -> SocketAddr394 fn inaddr_any(other: &SocketAddr) -> SocketAddr {
395     match *other {
396         SocketAddr::V4(..) => {
397             let any = Ipv4Addr::new(0, 0, 0, 0);
398             let addr = SocketAddrV4::new(any, 0);
399             SocketAddr::V4(addr)
400         }
401         SocketAddr::V6(..) => {
402             let any = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0);
403             let addr = SocketAddrV6::new(any, 0, 0, 0);
404             SocketAddr::V6(addr)
405         }
406     }
407 }
408 
409 impl Read for TcpStream {
read(&mut self, buf: &mut [u8]) -> io::Result<usize>410     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
411         (&self.sys).read(buf)
412     }
413 }
414 
415 impl<'a> Read for &'a TcpStream {
read(&mut self, buf: &mut [u8]) -> io::Result<usize>416     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
417         (&self.sys).read(buf)
418     }
419 }
420 
421 impl Write for TcpStream {
write(&mut self, buf: &[u8]) -> io::Result<usize>422     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
423         (&self.sys).write(buf)
424     }
425 
flush(&mut self) -> io::Result<()>426     fn flush(&mut self) -> io::Result<()> {
427         (&self.sys).flush()
428     }
429 }
430 
431 impl<'a> Write for &'a TcpStream {
write(&mut self, buf: &[u8]) -> io::Result<usize>432     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
433         (&self.sys).write(buf)
434     }
435 
flush(&mut self) -> io::Result<()>436     fn flush(&mut self) -> io::Result<()> {
437         (&self.sys).flush()
438     }
439 }
440 
441 impl Evented for TcpStream {
register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()>442     fn register(&self, poll: &Poll, token: Token,
443                 interest: Ready, opts: PollOpt) -> io::Result<()> {
444         self.selector_id.associate_selector(poll)?;
445         self.sys.register(poll, token, interest, opts)
446     }
447 
reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()>448     fn reregister(&self, poll: &Poll, token: Token,
449                   interest: Ready, opts: PollOpt) -> io::Result<()> {
450         self.sys.reregister(poll, token, interest, opts)
451     }
452 
deregister(&self, poll: &Poll) -> io::Result<()>453     fn deregister(&self, poll: &Poll) -> io::Result<()> {
454         self.sys.deregister(poll)
455     }
456 }
457 
458 impl fmt::Debug for TcpStream {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result459     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
460         fmt::Debug::fmt(&self.sys, f)
461     }
462 }
463 
464 /*
465  *
466  * ===== TcpListener =====
467  *
468  */
469 
470 /// A structure representing a socket server
471 ///
472 /// # Examples
473 ///
474 /// ```
475 /// # use std::error::Error;
476 /// # fn try_main() -> Result<(), Box<Error>> {
477 /// use mio::{Events, Ready, Poll, PollOpt, Token};
478 /// use mio::net::TcpListener;
479 /// use std::time::Duration;
480 ///
481 /// let listener = TcpListener::bind(&"127.0.0.1:34255".parse()?)?;
482 ///
483 /// let poll = Poll::new()?;
484 /// let mut events = Events::with_capacity(128);
485 ///
486 /// // Register the socket with `Poll`
487 /// poll.register(&listener, Token(0), Ready::readable(),
488 ///               PollOpt::edge())?;
489 ///
490 /// poll.poll(&mut events, Some(Duration::from_millis(100)))?;
491 ///
492 /// // There may be a socket ready to be accepted
493 /// #     Ok(())
494 /// # }
495 /// #
496 /// # fn main() {
497 /// #     try_main().unwrap();
498 /// # }
499 /// ```
500 pub struct TcpListener {
501     sys: sys::TcpListener,
502     selector_id: SelectorId,
503 }
504 
505 impl TcpListener {
506     /// Convenience method to bind a new TCP listener to the specified address
507     /// to receive new connections.
508     ///
509     /// This function will take the following steps:
510     ///
511     /// 1. Create a new TCP socket.
512     /// 2. Set the `SO_REUSEADDR` option on the socket.
513     /// 3. Bind the socket to the specified address.
514     /// 4. Call `listen` on the socket to prepare it to receive new connections.
515     ///
516     /// If fine-grained control over the binding and listening process for a
517     /// socket is desired then the `net2::TcpBuilder` methods can be used in
518     /// combination with the `TcpListener::from_listener` method to transfer
519     /// ownership into mio.
bind(addr: &SocketAddr) -> io::Result<TcpListener>520     pub fn bind(addr: &SocketAddr) -> io::Result<TcpListener> {
521         // Create the socket
522         let sock = match *addr {
523             SocketAddr::V4(..) => TcpBuilder::new_v4(),
524             SocketAddr::V6(..) => TcpBuilder::new_v6(),
525         }?;
526 
527         // Set SO_REUSEADDR, but only on Unix (mirrors what libstd does)
528         if cfg!(unix) {
529             sock.reuse_address(true)?;
530         }
531 
532         // Bind the socket
533         sock.bind(addr)?;
534 
535         // listen
536         let listener = sock.listen(1024)?;
537         Ok(TcpListener {
538             sys: sys::TcpListener::new(listener)?,
539             selector_id: SelectorId::new(),
540         })
541     }
542 
543     #[deprecated(since = "0.6.13", note = "use from_std instead")]
544     #[cfg(feature = "with-deprecated")]
545     #[doc(hidden)]
from_listener(listener: net::TcpListener, _: &SocketAddr) -> io::Result<TcpListener>546     pub fn from_listener(listener: net::TcpListener, _: &SocketAddr)
547                          -> io::Result<TcpListener> {
548         TcpListener::from_std(listener)
549     }
550 
551     /// Creates a new `TcpListener` from an instance of a
552     /// `std::net::TcpListener` type.
553     ///
554     /// This function will set the `listener` provided into nonblocking mode on
555     /// Unix, and otherwise the stream will just be wrapped up in an mio stream
556     /// ready to accept new connections and become associated with an event
557     /// loop.
558     ///
559     /// The address provided must be the address that the listener is bound to.
from_std(listener: net::TcpListener) -> io::Result<TcpListener>560     pub fn from_std(listener: net::TcpListener) -> io::Result<TcpListener> {
561         sys::TcpListener::new(listener).map(|s| {
562             TcpListener {
563                 sys: s,
564                 selector_id: SelectorId::new(),
565             }
566         })
567     }
568 
569     /// Accepts a new `TcpStream`.
570     ///
571     /// This may return an `Err(e)` where `e.kind()` is
572     /// `io::ErrorKind::WouldBlock`. This means a stream may be ready at a later
573     /// point and one should wait for a notification before calling `accept`
574     /// again.
575     ///
576     /// If an accepted stream is returned, the remote address of the peer is
577     /// returned along with it.
accept(&self) -> io::Result<(TcpStream, SocketAddr)>578     pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
579         let (s, a) = try!(self.accept_std());
580         Ok((TcpStream::from_stream(s)?, a))
581     }
582 
583     /// Accepts a new `std::net::TcpStream`.
584     ///
585     /// This method is the same as `accept`, except that it returns a TCP socket
586     /// *in blocking mode* which isn't bound to `mio`. This can be later then
587     /// converted to a `mio` type, if necessary.
accept_std(&self) -> io::Result<(net::TcpStream, SocketAddr)>588     pub fn accept_std(&self) -> io::Result<(net::TcpStream, SocketAddr)> {
589         self.sys.accept()
590     }
591 
592     /// Returns the local socket address of this listener.
local_addr(&self) -> io::Result<SocketAddr>593     pub fn local_addr(&self) -> io::Result<SocketAddr> {
594         self.sys.local_addr()
595     }
596 
597     /// Creates a new independently owned handle to the underlying socket.
598     ///
599     /// The returned `TcpListener` is a reference to the same socket that this
600     /// object references. Both handles can be used to accept incoming
601     /// connections and options set on one listener will affect the other.
try_clone(&self) -> io::Result<TcpListener>602     pub fn try_clone(&self) -> io::Result<TcpListener> {
603         self.sys.try_clone().map(|s| {
604             TcpListener {
605                 sys: s,
606                 selector_id: self.selector_id.clone(),
607             }
608         })
609     }
610 
611     /// Sets the value for the `IP_TTL` option on this socket.
612     ///
613     /// This value sets the time-to-live field that is used in every packet sent
614     /// from this socket.
set_ttl(&self, ttl: u32) -> io::Result<()>615     pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
616         self.sys.set_ttl(ttl)
617     }
618 
619     /// Gets the value of the `IP_TTL` option for this socket.
620     ///
621     /// For more information about this option, see [`set_ttl`][link].
622     ///
623     /// [link]: #method.set_ttl
ttl(&self) -> io::Result<u32>624     pub fn ttl(&self) -> io::Result<u32> {
625         self.sys.ttl()
626     }
627 
628     /// Sets the value for the `IPV6_V6ONLY` option on this socket.
629     ///
630     /// If this is set to `true` then the socket is restricted to sending and
631     /// receiving IPv6 packets only. In this case two IPv4 and IPv6 applications
632     /// can bind the same port at the same time.
633     ///
634     /// If this is set to `false` then the socket can be used to send and
635     /// receive packets from an IPv4-mapped IPv6 address.
set_only_v6(&self, only_v6: bool) -> io::Result<()>636     pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
637         self.sys.set_only_v6(only_v6)
638     }
639 
640     /// Gets the value of the `IPV6_V6ONLY` option for this socket.
641     ///
642     /// For more information about this option, see [`set_only_v6`][link].
643     ///
644     /// [link]: #method.set_only_v6
only_v6(&self) -> io::Result<bool>645     pub fn only_v6(&self) -> io::Result<bool> {
646         self.sys.only_v6()
647     }
648 
649     /// Get the value of the `SO_ERROR` option on this socket.
650     ///
651     /// This will retrieve the stored error in the underlying socket, clearing
652     /// the field in the process. This can be useful for checking errors between
653     /// calls.
take_error(&self) -> io::Result<Option<io::Error>>654     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
655         self.sys.take_error()
656     }
657 }
658 
659 impl Evented for TcpListener {
register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()>660     fn register(&self, poll: &Poll, token: Token,
661                 interest: Ready, opts: PollOpt) -> io::Result<()> {
662         self.selector_id.associate_selector(poll)?;
663         self.sys.register(poll, token, interest, opts)
664     }
665 
reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()>666     fn reregister(&self, poll: &Poll, token: Token,
667                   interest: Ready, opts: PollOpt) -> io::Result<()> {
668         self.sys.reregister(poll, token, interest, opts)
669     }
670 
deregister(&self, poll: &Poll) -> io::Result<()>671     fn deregister(&self, poll: &Poll) -> io::Result<()> {
672         self.sys.deregister(poll)
673     }
674 }
675 
676 impl fmt::Debug for TcpListener {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result677     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
678         fmt::Debug::fmt(&self.sys, f)
679     }
680 }
681 
682 /*
683  *
684  * ===== UNIX ext =====
685  *
686  */
687 
688 #[cfg(all(unix, not(target_os = "fuchsia")))]
689 use std::os::unix::io::{IntoRawFd, AsRawFd, FromRawFd, RawFd};
690 
691 #[cfg(all(unix, not(target_os = "fuchsia")))]
692 impl IntoRawFd for TcpStream {
into_raw_fd(self) -> RawFd693     fn into_raw_fd(self) -> RawFd {
694         self.sys.into_raw_fd()
695     }
696 }
697 
698 #[cfg(all(unix, not(target_os = "fuchsia")))]
699 impl AsRawFd for TcpStream {
as_raw_fd(&self) -> RawFd700     fn as_raw_fd(&self) -> RawFd {
701         self.sys.as_raw_fd()
702     }
703 }
704 
705 #[cfg(all(unix, not(target_os = "fuchsia")))]
706 impl FromRawFd for TcpStream {
from_raw_fd(fd: RawFd) -> TcpStream707     unsafe fn from_raw_fd(fd: RawFd) -> TcpStream {
708         TcpStream {
709             sys: FromRawFd::from_raw_fd(fd),
710             selector_id: SelectorId::new(),
711         }
712     }
713 }
714 
715 #[cfg(all(unix, not(target_os = "fuchsia")))]
716 impl IntoRawFd for TcpListener {
into_raw_fd(self) -> RawFd717     fn into_raw_fd(self) -> RawFd {
718         self.sys.into_raw_fd()
719     }
720 }
721 
722 #[cfg(all(unix, not(target_os = "fuchsia")))]
723 impl AsRawFd for TcpListener {
as_raw_fd(&self) -> RawFd724     fn as_raw_fd(&self) -> RawFd {
725         self.sys.as_raw_fd()
726     }
727 }
728 
729 #[cfg(all(unix, not(target_os = "fuchsia")))]
730 impl FromRawFd for TcpListener {
from_raw_fd(fd: RawFd) -> TcpListener731     unsafe fn from_raw_fd(fd: RawFd) -> TcpListener {
732         TcpListener {
733             sys: FromRawFd::from_raw_fd(fd),
734             selector_id: SelectorId::new(),
735         }
736     }
737 }
738