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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![allow(bad_style, dead_code)]

use std::io;
use std::mem;
use std::net::{TcpStream, TcpListener, UdpSocket, Ipv4Addr, Ipv6Addr};

use libc::{self, c_int, socklen_t, c_void, c_uint};

use {TcpBuilder, UdpBuilder};

#[cfg(feature = "nightly")] use std::time::Duration;

#[cfg(unix)] type Socket = c_int;
#[cfg(unix)] use std::os::unix::prelude::*;
#[cfg(windows)] type Socket = libc::SOCKET;
#[cfg(windows)] use std::os::windows::prelude::*;
#[cfg(windows)] use ws2_32::*;

#[cfg(target_os = "linux")] const IPV6_MULTICAST_LOOP: c_int = 19;
#[cfg(target_os = "macos")] const IPV6_MULTICAST_LOOP: c_int = 11;
#[cfg(target_os = "freebsd")] const IPV6_MULTICAST_LOOP: c_int = 11;
#[cfg(target_os = "dragonfly")] const IPV6_MULTICAST_LOOP: c_int = 11;
#[cfg(target_os = "windows")] const IPV6_MULTICAST_LOOP: c_int = 11;
#[cfg(target_os = "linux")] const IPV6_V6ONLY: c_int = 26;
#[cfg(target_os = "macos")] const IPV6_V6ONLY: c_int = 27;
#[cfg(target_os = "windows")] const IPV6_V6ONLY: c_int = 27;
#[cfg(target_os = "freebsd")] const IPV6_V6ONLY: c_int = 27;
#[cfg(target_os = "dragonfly")] const IPV6_V6ONLY: c_int = 27;

#[cfg(windows)] const SIO_KEEPALIVE_VALS: libc::DWORD = 0x98000004;
#[cfg(windows)]
#[repr(C)]
struct tcp_keepalive {
    onoff: libc::c_ulong,
    keepalivetime: libc::c_ulong,
    keepaliveinterval: libc::c_ulong,
}

#[cfg(not(windows))]
extern "system" {
    fn getsockopt(sockfd: Socket,
                  level: c_int,
                  optname: c_int,
                  optval: *mut c_void,
                  optlen: *mut socklen_t) -> c_int;
}

fn setopt<T: Copy>(sock: Socket, opt: c_int, val: c_int,
                   payload: T) -> io::Result<()> {
    unsafe {
        let payload = &payload as *const T as *const c_void;
        try!(::cvt(libc::setsockopt(sock, opt, val, payload,
                                    mem::size_of::<T>() as socklen_t)));
        Ok(())
    }
}

fn getopt<T: Copy>(sock: Socket, opt: c_int, val: c_int) -> io::Result<T> {
    unsafe {
        let mut slot: T = mem::zeroed();
        let mut len = mem::size_of::<T>() as socklen_t;
        try!(::cvt(getsockopt(sock, opt, val, &mut slot as *mut _ as *mut _,
                              &mut len)));
        assert_eq!(len as usize, mem::size_of::<T>());
        Ok(slot)
    }
}

/// Extension methods for the standard [`TcpStream` type][link] in `std::net`.
///
/// [link]: https://doc.rust-lang.org/std/net/struct.TcpStream.html
pub trait TcpStreamExt {
    /// Sets the value of the `TCP_NODELAY` option on this socket.
    ///
    /// If set, this option disables the Nagle algorithm. This means that
    /// segments are always sent as soon as possible, even if there is only a
    /// small amount of data. When not set, data is buffered until there is a
    /// sufficient amount to send out, thereby avoiding the frequent sending of
    /// small packets.
    fn set_nodelay(&self, nodelay: bool) -> io::Result<()>;

    /// Gets the value of the `TCP_NODELAY` option on this socket.
    ///
    /// For more information about this option, see [`set_nodelay`][link].
    ///
    /// [link]: #tymethod.set_nodelay
    fn nodelay(&self) -> io::Result<bool>;

    /// Sets whether keepalive messages are enabled to be sent on this socket.
    ///
    /// On Unix, this option will set the `SO_KEEPALIVE` as well as the
    /// `TCP_KEEPALIVE` or `TCP_KEEPIDLE` option (depending on your platform).
    /// On Windows, this will set the `SIO_KEEPALIVE_VALS` option.
    ///
    /// If `None` is specified then keepalive messages are disabled, otherwise
    /// the number of milliseconds specified will be the time to remain idle
    /// before sending a TCP keepalive probe.
    ///
    /// Some platforms specify this value in seconds, so sub-second millisecond
    /// specifications may be omitted.
    fn set_keepalive_ms(&self, keepalive: Option<u32>) -> io::Result<()>;

    /// Returns whether keepalive messages are enabled on this socket, and if so
    /// the amount of milliseconds between them.
    ///
    /// For more information about this option, see [`set_keepalive_ms`][link].
    ///
    /// [link]: #tymethod.set_keepalive_ms
    fn keepalive_ms(&self) -> io::Result<Option<u32>>;

    /// Sets whether keepalive messages are enabled to be sent on this socket.
    ///
    /// On Unix, this option will set the `SO_KEEPALIVE` as well as the
    /// `TCP_KEEPALIVE` or `TCP_KEEPIDLE` option (depending on your platform).
    /// On Windows, this will set the `SIO_KEEPALIVE_VALS` option.
    ///
    /// If `None` is specified then keepalive messages are disabled, otherwise
    /// the duration specified will be the time to remain idle before sending a
    /// TCP keepalive probe.
    ///
    /// Some platforms specify this value in seconds, so sub-second
    /// specifications may be omitted.
    #[cfg(feature = "nightly")]
    fn set_keepalive(&self, keepalive: Option<Duration>) -> io::Result<()>;

    /// Returns whether keepalive messages are enabled on this socket, and if so
    /// the duration of time between them.
    ///
    /// For more information about this option, see [`set_keepalive`][link].
    ///
    /// [link]: #tymethod.set_keepalive
    #[cfg(feature = "nightly")]
    fn keepalive(&self) -> io::Result<Option<Duration>>;

    /// Sets the `SO_RCVTIMEO` option for this socket.
    ///
    /// This option specifies the timeout, in milliseconds, of how long calls to
    /// this socket's `read` function will wait before returning a timeout. A
    /// value of `None` means that no read timeout should be specified and
    /// otherwise `Some` indicates the number of milliseconds for the timeout.
    fn set_read_timeout_ms(&self, val: Option<u32>) -> io::Result<()>;

    /// Sets the `SO_RCVTIMEO` option for this socket.
    ///
    /// This option specifies the timeout of how long calls to this socket's
    /// `read` function will wait before returning a timeout. A value of `None`
    /// means that no read timeout should be specified and otherwise `Some`
    /// indicates the number of duration of the timeout.
    #[cfg(feature = "nightly")]
    fn set_read_timeout(&self, val: Option<Duration>) -> io::Result<()>;

    /// Gets the value of the `SO_RCVTIMEO` option for this socket.
    ///
    /// For more information about this option, see [`set_read_timeout_ms`][link].
    ///
    /// [link]: #tymethod.set_read_timeout_ms
    fn read_timeout_ms(&self) -> io::Result<Option<u32>>;

    /// Gets the value of the `SO_RCVTIMEO` option for this socket.
    ///
    /// For more information about this option, see [`set_read_timeout`][link].
    ///
    /// [link]: #tymethod.set_read_timeout
    #[cfg(feature = "nightly")]
    fn read_timeout(&self) -> io::Result<Option<Duration>>;

    /// Sets the `SO_SNDTIMEO` option for this socket.
    ///
    /// This option specifies the timeout, in milliseconds, of how long calls to
    /// this socket's `write` function will wait before returning a timeout. A
    /// value of `None` means that no read timeout should be specified and
    /// otherwise `Some` indicates the number of milliseconds for the timeout.
    fn set_write_timeout_ms(&self, val: Option<u32>) -> io::Result<()>;

    /// Sets the `SO_SNDTIMEO` option for this socket.
    ///
    /// This option specifies the timeout of how long calls to this socket's
    /// `write` function will wait before returning a timeout. A value of `None`
    /// means that no read timeout should be specified and otherwise `Some`
    /// indicates the duration of the timeout.
    #[cfg(feature = "nightly")]
    fn set_write_timeout(&self, val: Option<Duration>) -> io::Result<()>;

    /// Gets the value of the `SO_SNDTIMEO` option for this socket.
    ///
    /// For more information about this option, see [`set_write_timeout_ms`][link].
    ///
    /// [link]: #tymethod.set_write_timeout_ms
    fn write_timeout_ms(&self) -> io::Result<Option<u32>>;

    /// Gets the value of the `SO_SNDTIMEO` option for this socket.
    ///
    /// For more information about this option, see [`set_write_timeout`][link].
    ///
    /// [link]: #tymethod.set_write_timeout
    #[cfg(feature = "nightly")]
    fn write_timeout(&self) -> io::Result<Option<Duration>>;

    /// Sets the value for the `IP_TTL` option on this socket.
    ///
    /// This value sets the time-to-live field that is used in every packet sent
    /// from this socket.
    fn set_ttl(&self, ttl: u32) -> io::Result<()>;

    /// Gets the value of the `IP_TTL` option for this socket.
    ///
    /// For more information about this option, see [`set_ttl`][link].
    ///
    /// [link]: #tymethod.set_ttl
    fn ttl(&self) -> io::Result<u32>;

    /// Sets the value for the `IPV6_V6ONLY` option on this socket.
    ///
    /// If this is set to `true` then the socket is restricted to sending and
    /// receiving IPv6 packets only. In this case two IPv4 and IPv6 applications
    /// can bind the same port at the same time.
    ///
    /// If this is set to `false` then the socket can be used to send and
    /// receive packets from an IPv4-mapped IPv6 address.
    fn set_only_v6(&self, only_v6: bool) -> io::Result<()>;

    /// Gets the value of the `IPV6_V6ONLY` option for this socket.
    ///
    /// For more information about this option, see [`set_only_v6`][link].
    ///
    /// [link]: #tymethod.set_only_v6
    fn only_v6(&self) -> io::Result<bool>;
}

/// Extension methods for the standard [`TcpListener` type][link] in `std::net`.
///
/// [link]: https://doc.rust-lang.org/std/net/struct.TcpListener.html
pub trait TcpListenerExt {
    /// Sets the value for the `IP_TTL` option on this socket.
    ///
    /// This is the same as [`TcpStreamExt::set_ttl`][other].
    ///
    /// [other]: trait.TcpStreamExt.html#tymethod.set_ttl
    fn set_ttl(&self, ttl: u32) -> io::Result<()>;

    /// Gets the value of the `IP_TTL` option for this socket.
    ///
    /// For more information about this option, see
    /// [`TcpStreamExt::set_ttl`][link].
    ///
    /// [link]: trait.TcpStreamExt.html#tymethod.set_ttl
    fn ttl(&self) -> io::Result<u32>;

    /// Sets the value for the `IPV6_V6ONLY` option on this socket.
    ///
    /// For more information about this option, see
    /// [`TcpStreamExt::set_only_v6`][link].
    ///
    /// [link]: trait.TcpStreamExt.html#tymethod.set_only_v6
    fn set_only_v6(&self, only_v6: bool) -> io::Result<()>;

    /// Gets the value of the `IPV6_V6ONLY` option for this socket.
    ///
    /// For more information about this option, see
    /// [`TcpStreamExt::set_only_v6`][link].
    ///
    /// [link]: trait.TcpStreamExt.html#tymethod.set_only_v6
    fn only_v6(&self) -> io::Result<bool>;
}

/// Extension methods for the standard [`UdpSocket` type][link] in `std::net`.
///
/// [link]: https://doc.rust-lang.org/std/net/struct.UdpSocket.html
pub trait UdpSocketExt {
    /// Sets the value of the `SO_BROADCAST` option for this socket.
    ///
    /// When enabled, this socket is allowed to send packets to a broadcast
    /// address.
    fn set_broadcast(&self, broadcast: bool) -> io::Result<()>;

    /// Gets the value of the `SO_BROADCAST` option for this socket.
    ///
    /// For more information about this option, see
    /// [`set_broadcast`][link].
    ///
    /// [link]: #tymethod.set_broadcast
    fn broadcast(&self) -> io::Result<bool>;

    /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
    ///
    /// If enabled, multicast packets will be looped back to the local socket.
    /// Note that this may not have any affect on IPv6 sockets.
    fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()>;

    /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
    ///
    /// For more information about this option, see
    /// [`set_multicast_loop_v4`][link].
    ///
    /// [link]: #tymethod.set_multicast_loop_v4
    fn multicast_loop_v4(&self) -> io::Result<bool>;

    /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
    ///
    /// Indicates the time-to-live value of outgoing multicast packets for
    /// this socket. The default value is 1 which means that multicast packets
    /// don't leave the local network unless explicitly requested.
    ///
    /// Note that this may not have any affect on IPv6 sockets.
    fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()>;

    /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
    ///
    /// For more information about this option, see
    /// [`set_multicast_ttl_v4`][link].
    ///
    /// [link]: #tymethod.set_multicast_ttl_v4
    fn multicast_ttl_v4(&self) -> io::Result<u32>;

    /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
    ///
    /// Controls whether this socket sees the multicast packets it sends itself.
    /// Note that this may not have any affect on IPv4 sockets.
    fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()>;

    /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
    ///
    /// For more information about this option, see
    /// [`set_multicast_loop_v6`][link].
    ///
    /// [link]: #tymethod.set_multicast_loop_v6
    fn multicast_loop_v6(&self) -> io::Result<bool>;

    /// Sets the value for the `IP_TTL` option on this socket.
    ///
    /// This is the same as [`TcpStreamExt::set_ttl`][other].
    ///
    /// [other]: trait.TcpStreamExt.html#tymethod.set_ttl
    fn set_ttl(&self, ttl: u32) -> io::Result<()>;

    /// Gets the value of the `IP_TTL` option for this socket.
    ///
    /// For more information about this option, see
    /// [`TcpStreamExt::set_ttl`][link].
    ///
    /// [link]: trait.TcpStreamExt.html#tymethod.set_ttl
    fn ttl(&self) -> io::Result<u32>;

    /// Sets the value for the `IPV6_V6ONLY` option on this socket.
    ///
    /// For more information about this option, see
    /// [`TcpStreamExt::set_only_v6`][link].
    ///
    /// [link]: trait.TcpStreamExt.html#tymethod.set_only_v6
    fn set_only_v6(&self, only_v6: bool) -> io::Result<()>;

    /// Gets the value of the `IPV6_V6ONLY` option for this socket.
    ///
    /// For more information about this option, see
    /// [`TcpStreamExt::set_only_v6`][link].
    ///
    /// [link]: trait.TcpStreamExt.html#tymethod.set_only_v6
    fn only_v6(&self) -> io::Result<bool>;

    /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
    ///
    /// This function specifies a new multicast group for this socket to join.
    /// The address must be a valid multicast address, and `interface` is the
    /// address of the local interface with which the system should join the
    /// multicast group. If it's equal to `INADDR_ANY` then an appropriate
    /// interface is chosen by the system.
    fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr)
                         -> io::Result<()>;

    /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
    ///
    /// This function specifies a new multicast group for this socket to join.
    /// The address must be a valid multicast address, and `interface` is the
    /// index of the interface to join/leave (or 0 to indicate any interface).
    fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32)
                         -> io::Result<()>;

    /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
    ///
    /// For more information about this option, see
    /// [`join_multicast_v4`][link].
    ///
    /// [link]: #tymethod.join_multicast_v4
    fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr)
                          -> io::Result<()>;

    /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
    ///
    /// For more information about this option, see
    /// [`join_multicast_v6`][link].
    ///
    /// [link]: #tymethod.join_multicast_v6
    fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32)
                          -> io::Result<()>;
}

trait AsSock {
    fn as_sock(&self) -> Socket;
}

#[cfg(unix)]
impl<T: AsRawFd> AsSock for T {
    fn as_sock(&self) -> Socket { self.as_raw_fd() }
}
#[cfg(windows)]
impl<T: AsRawSocket> AsSock for T {
    fn as_sock(&self) -> Socket { self.as_raw_socket() }
}

cfg_if! {
    if #[cfg(any(target_os = "macos", target_os = "ios"))] {
        const KEEPALIVE_OPTION: libc::c_int = libc::TCP_KEEPALIVE;
    } else if #[cfg(unix)] {
        const KEEPALIVE_OPTION: libc::c_int = libc::TCP_KEEPIDLE;
    } else {
    }
}

impl TcpStreamExt for TcpStream {
    fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
        setopt(self.as_sock(), libc::IPPROTO_TCP, libc::TCP_NODELAY,
               nodelay as c_int)
    }
    fn nodelay(&self) -> io::Result<bool> {
        getopt(self.as_sock(), libc::IPPROTO_TCP, libc::TCP_NODELAY)
            .map(int2bool)
    }

    #[cfg(feature = "nightly")]
    fn set_keepalive(&self, keepalive: Option<Duration>) -> io::Result<()> {
        self.set_keepalive_ms(keepalive.map(dur2ms))
    }

    #[cfg(feature = "nightly")]
    fn keepalive(&self) -> io::Result<Option<Duration>> {
        self.keepalive_ms().map(|o| o.map(ms2dur))
    }

    #[cfg(unix)]
    fn set_keepalive_ms(&self, keepalive: Option<u32>) -> io::Result<()> {
        try!(setopt(self.as_sock(), libc::SOL_SOCKET, libc::SO_KEEPALIVE,
                    keepalive.is_some() as c_int));
        if let Some(dur) = keepalive {
            try!(setopt(self.as_sock(), libc::IPPROTO_TCP, KEEPALIVE_OPTION,
                        dur as c_int));
        }
        Ok(())
    }

    #[cfg(unix)]
    fn keepalive_ms(&self) -> io::Result<Option<u32>> {
        let keepalive = try!(getopt::<c_int>(self.as_sock(), libc::SOL_SOCKET,
                                             libc::SO_KEEPALIVE));
        if keepalive == 0 {
            return Ok(None)
        }
        let secs = try!(getopt::<c_int>(self.as_sock(), libc::IPPROTO_TCP,
                                        KEEPALIVE_OPTION));
        Ok(Some(secs as u32))
    }

    #[cfg(windows)]
    fn set_keepalive_ms(&self, keepalive: Option<u32>) -> io::Result<()> {
        let ms = keepalive.unwrap_or(libc::INFINITE);
        let ka = tcp_keepalive {
            onoff: keepalive.is_some() as libc::c_ulong,
            keepalivetime: ms as libc::c_ulong,
            keepaliveinterval: ms as libc::c_ulong,
        };
        unsafe {
            ::cvt_win(WSAIoctl(self.as_sock(),
                               SIO_KEEPALIVE_VALS,
                               &ka as *const _ as *mut _,
                               mem::size_of_val(&ka) as libc::DWORD,
                               0 as *mut _,
                               0,
                               0 as *mut _,
                               0 as *mut _,
                               None)).map(|_| ())
        }
    }

    #[cfg(windows)]
    fn keepalive_ms(&self) -> io::Result<Option<u32>> {
        let mut ka = tcp_keepalive {
            onoff: 0,
            keepalivetime: 0,
            keepaliveinterval: 0,
        };
        unsafe {
            try!(::cvt_win(WSAIoctl(self.as_sock(),
                                    SIO_KEEPALIVE_VALS,
                                    0 as *mut _,
                                    0,
                                    &mut ka as *mut _ as *mut _,
                                    mem::size_of_val(&ka) as libc::DWORD,
                                    0 as *mut _,
                                    0 as *mut _,
                                    None)));
        }
        Ok({
            if ka.onoff == 0 {
                None
            } else {
                timeout2ms(ka.keepaliveinterval as libc::DWORD)
            }
        })
    }

    fn set_read_timeout_ms(&self, dur: Option<u32>) -> io::Result<()> {
        setopt(self.as_sock(), libc::SOL_SOCKET, libc::SO_RCVTIMEO,
               ms2timeout(dur))
    }

    fn read_timeout_ms(&self) -> io::Result<Option<u32>> {
        getopt(self.as_sock(), libc::SOL_SOCKET, libc::SO_RCVTIMEO)
            .map(timeout2ms)
    }

    fn set_write_timeout_ms(&self, dur: Option<u32>) -> io::Result<()> {
        setopt(self.as_sock(), libc::SOL_SOCKET, libc::SO_SNDTIMEO,
               ms2timeout(dur))
    }

    fn write_timeout_ms(&self) -> io::Result<Option<u32>> {
        getopt(self.as_sock(), libc::SOL_SOCKET, libc::SO_SNDTIMEO)
            .map(timeout2ms)
    }

    #[cfg(feature = "nightly")]
    fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
        self.set_read_timeout_ms(dur.map(dur2ms))
    }

    #[cfg(feature = "nightly")]
    fn read_timeout(&self) -> io::Result<Option<Duration>> {
        self.read_timeout_ms().map(|o| o.map(ms2dur))
    }

    #[cfg(feature = "nightly")]
    fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
        self.set_write_timeout_ms(dur.map(dur2ms))
    }

    #[cfg(feature = "nightly")]
    fn write_timeout(&self) -> io::Result<Option<Duration>> {
        self.write_timeout_ms().map(|o| o.map(ms2dur))
    }

    fn set_ttl(&self, ttl: u32) -> io::Result<()> {
        setopt(self.as_sock(), libc::IPPROTO_IP, libc::IP_TTL, ttl as c_int)
    }

    fn ttl(&self) -> io::Result<u32> {
        getopt::<c_int>(self.as_sock(), libc::IPPROTO_IP, libc::IP_TTL)
            .map(|b| b as u32)
    }

    fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
        setopt(self.as_sock(), libc::IPPROTO_IPV6, IPV6_V6ONLY, only_v6 as c_int)
    }

    fn only_v6(&self) -> io::Result<bool> {
        getopt(self.as_sock(), libc::IPPROTO_IPV6, IPV6_V6ONLY).map(int2bool)
    }
}

#[cfg(unix)]
fn ms2timeout(dur: Option<u32>) -> libc::timeval {
    // TODO: be more rigorous
    match dur {
        Some(d) => libc::timeval {
            tv_sec: (d / 1000) as libc::time_t,
            tv_usec: (d % 1000) as libc::suseconds_t,
        },
        None => libc::timeval { tv_sec: 0, tv_usec: 0 },
    }
}

#[cfg(unix)]
fn timeout2ms(dur: libc::timeval) -> Option<u32> {
    if dur.tv_sec == 0 && dur.tv_usec == 0 {
        None
    } else {
        Some(dur.tv_sec as u32 * 1000 + dur.tv_usec as u32 / 1000)
    }
}

#[cfg(windows)]
fn ms2timeout(dur: Option<u32>) -> libc::DWORD {
    dur.unwrap_or(0)
}

#[cfg(windows)]
fn timeout2ms(dur: libc::DWORD) -> Option<u32> {
    if dur == 0 {
        None
    } else {
        Some(dur)
    }
}

#[cfg(feature = "nightly")]
fn ms2dur(ms: u32) -> Duration {
    Duration::new((ms as u64) / 1000, (ms as u32) % 1000 * 1_000_000)
}

#[cfg(feature = "nightly")]
fn dur2ms(dur: Duration) -> u32 {
    (dur.as_secs() as u32 * 1000) + (dur.subsec_nanos() / 1_000_000)
}

fn int2bool(n: c_int) -> bool {
    if n == 0 {false} else {true}
}

impl UdpSocketExt for UdpSocket {
    fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
        setopt(self.as_sock(), libc::SOL_SOCKET, libc::SO_BROADCAST,
               broadcast as c_int)
    }
    fn broadcast(&self) -> io::Result<bool> {
        getopt(self.as_sock(), libc::SOL_SOCKET, libc::SO_BROADCAST)
            .map(int2bool)
    }
    fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
        setopt(self.as_sock(), libc::IPPROTO_IP, libc::IP_MULTICAST_LOOP,
               multicast_loop_v4 as c_int)
    }
    fn multicast_loop_v4(&self) -> io::Result<bool> {
        getopt(self.as_sock(), libc::IPPROTO_IP, libc::IP_MULTICAST_LOOP)
            .map(int2bool)
    }
    fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
        setopt(self.as_sock(), libc::IPPROTO_IP, libc::IP_MULTICAST_TTL,
               multicast_ttl_v4 as c_int)
    }
    fn multicast_ttl_v4(&self) -> io::Result<u32> {
        getopt::<c_int>(self.as_sock(), libc::IPPROTO_IP, libc::IP_MULTICAST_TTL)
            .map(|b| b as u32)
    }
    fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
        setopt(self.as_sock(), libc::IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
               multicast_loop_v6 as c_int)
    }
    fn multicast_loop_v6(&self) -> io::Result<bool> {
        getopt(self.as_sock(), libc::IPPROTO_IPV6, IPV6_MULTICAST_LOOP)
            .map(int2bool)
    }

    fn set_ttl(&self, ttl: u32) -> io::Result<()> {
        setopt(self.as_sock(), libc::IPPROTO_IP, libc::IP_TTL, ttl as c_int)
    }

    fn ttl(&self) -> io::Result<u32> {
        getopt::<c_int>(self.as_sock(), libc::IPPROTO_IP, libc::IP_TTL)
            .map(|b| b as u32)
    }

    fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
        setopt(self.as_sock(), libc::IPPROTO_IPV6, IPV6_V6ONLY, only_v6 as c_int)
    }

    fn only_v6(&self) -> io::Result<bool> {
        getopt(self.as_sock(), libc::IPPROTO_IPV6, IPV6_V6ONLY).map(int2bool)
    }

    fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr)
                         -> io::Result<()> {
        let mreq = libc::ip_mreq {
            imr_multiaddr: ip2in_addr(multiaddr),
            imr_interface: ip2in_addr(interface),
        };
        setopt(self.as_sock(), libc::IPPROTO_IP, libc::IP_ADD_MEMBERSHIP, mreq)
    }

    fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32)
                         -> io::Result<()> {
        let mreq = libc::ip6_mreq {
            ipv6mr_multiaddr: ip2in6_addr(multiaddr),
            ipv6mr_interface: interface as c_uint,
        };
        setopt(self.as_sock(), libc::IPPROTO_IPV6, libc::IPV6_ADD_MEMBERSHIP,
               mreq)
    }

    fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr)
                          -> io::Result<()> {
        let mreq = libc::ip_mreq {
            imr_multiaddr: ip2in_addr(multiaddr),
            imr_interface: ip2in_addr(interface),
        };
        setopt(self.as_sock(), libc::IPPROTO_IP, libc::IP_DROP_MEMBERSHIP, mreq)
    }

    fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32)
                          -> io::Result<()> {
        let mreq = libc::ip6_mreq {
            ipv6mr_multiaddr: ip2in6_addr(multiaddr),
            ipv6mr_interface: interface as c_uint,
        };
        setopt(self.as_sock(), libc::IPPROTO_IPV6, libc::IPV6_DROP_MEMBERSHIP,
               mreq)
    }
}

fn ip2in_addr(ip: &Ipv4Addr) -> libc::in_addr {
    let oct = ip.octets();
    libc::in_addr {
        s_addr: ::hton(((oct[0] as u32) << 24) |
                       ((oct[1] as u32) << 16) |
                       ((oct[2] as u32) <<  8) |
                       ((oct[3] as u32) <<  0)),
    }
}

fn ip2in6_addr(ip: &Ipv6Addr) -> libc::in6_addr {
    let seg = ip.segments();
    libc::in6_addr {
        s6_addr: [
            ::hton(seg[0]),
            ::hton(seg[1]),
            ::hton(seg[2]),
            ::hton(seg[3]),
            ::hton(seg[4]),
            ::hton(seg[5]),
            ::hton(seg[6]),
            ::hton(seg[7]),
        ],
    }
}

impl TcpListenerExt for TcpListener {
    fn set_ttl(&self, ttl: u32) -> io::Result<()> {
        setopt(self.as_sock(), libc::IPPROTO_IP, libc::IP_TTL, ttl as c_int)
    }

    fn ttl(&self) -> io::Result<u32> {
        getopt::<c_int>(self.as_sock(), libc::IPPROTO_IP, libc::IP_TTL)
            .map(|b| b as u32)
    }

    fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
        setopt(self.as_sock(), libc::IPPROTO_IPV6, IPV6_V6ONLY, only_v6 as c_int)
    }

    fn only_v6(&self) -> io::Result<bool> {
        getopt(self.as_sock(), libc::IPPROTO_IPV6, IPV6_V6ONLY).map(int2bool)
    }
}

impl TcpBuilder {
    /// Sets the value for the `IP_TTL` option on this socket.
    ///
    /// This is the same as [`TcpStreamExt::set_ttl`][other].
    ///
    /// [other]: trait.TcpStreamExt.html#tymethod.set_ttl
    pub fn ttl(&self, ttl: u32) -> io::Result<&Self> {
        setopt(self.as_sock(), libc::IPPROTO_IP, libc::IP_TTL, ttl as c_int)
            .map(|()| self)
    }

    /// Sets the value for the `IPV6_V6ONLY` option on this socket.
    ///
    /// This is the same as [`TcpStreamExt::set_only_v6`][other].
    ///
    /// [other]: trait.TcpStreamExt.html#tymethod.set_only_v6
    pub fn only_v6(&self, only_v6: bool) -> io::Result<&Self> {
        setopt(self.as_sock(), libc::IPPROTO_IPV6, IPV6_V6ONLY, only_v6 as c_int)
            .map(|()| self)
    }

    /// Set value for the `SO_REUSEADDR` option on this socket.
    ///
    /// This indicates that futher calls to `bind` may allow reuse of local
    /// addresses. For IPv4 sockets this means that a socket may bind even when
    /// there's a socket already listening on this port.
    pub fn reuse_address(&self, reuse: bool) -> io::Result<&Self> {
        setopt(self.as_sock(), libc::SOL_SOCKET, libc::SO_REUSEADDR,
               reuse as c_int).map(|()| self)
    }
}

impl UdpBuilder {
    /// Sets the value for the `IP_TTL` option on this socket.
    ///
    /// This is the same as [`TcpStreamExt::set_ttl`][other].
    ///
    /// [other]: trait.TcpStreamExt.html#tymethod.set_ttl
    pub fn ttl(&self, ttl: u32) -> io::Result<&Self> {
        setopt(self.as_sock(), libc::IPPROTO_IP, libc::IP_TTL, ttl as c_int)
            .map(|()| self)
    }

    /// Sets the value for the `IPV6_V6ONLY` option on this socket.
    ///
    /// This is the same as [`TcpStream::only_v6`][other].
    ///
    /// [other]: struct.TcpBuilder.html#method.only_v6
    pub fn only_v6(&self, only_v6: bool) -> io::Result<&Self> {
        setopt(self.as_sock(), libc::IPPROTO_IPV6, IPV6_V6ONLY, only_v6 as c_int)
            .map(|()| self)
    }

    /// Set value for the `SO_REUSEADDR` option on this socket.
    ///
    /// This is the same as [`TcpBuilder::reuse_address`][other].
    ///
    /// [other]: struct.TcpBuilder.html#method.reuse_address
    pub fn reuse_address(&self, reuse: bool) -> io::Result<&Self> {
        setopt(self.as_sock(), libc::SOL_SOCKET, libc::SO_REUSEADDR,
               reuse as c_int).map(|()| self)
    }
}