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
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
use std::ffi::CString;
use std::marker::PhantomData;
use std::mem;
use std::net::{
    IpAddr,
    Ipv4Addr,
    Ipv6Addr,
    SocketAddr,
};
use std::os::raw::{
    c_char,
    c_int,
    c_uchar,
    c_void,
};
use std::ptr;
use std::sync::Arc;

use c_ares_sys;
use c_types;

use a::{
    AResults,
    query_a_callback,
};
use aaaa::{
    AAAAResults,
    query_aaaa_callback,
};
use cname::{
    CNameResults,
    query_cname_callback,
};
use error::{
    Error,
    Result,
};
use flags::Flags;
use host::{
    HostResults,
    get_host_callback,
};
use mx::{
    MXResults,
    query_mx_callback,
};
use nameinfo::{
    NameInfoResult,
    get_name_info_callback,
};
use naptr::{
    NAPTRResults,
    query_naptr_callback,
};
use ni_flags::NIFlags;
use ns::{
    NSResults,
    query_ns_callback,
};
use ptr::{
    PTRResults,
    query_ptr_callback,
};
use query::query_callback;
use soa::{
    SOAResult,
    query_soa_callback,
};
use srv::{
    SRVResults,
    query_srv_callback,
};
use txt::{
    TXTResults,
    query_txt_callback,
};
use types::{
    AddressFamily,
    DnsClass,
    QueryType,
    Socket,
};
use utils::{
  ipv4_as_in_addr,
  ipv6_as_in6_addr,
  socket_addrv4_as_sockaddr_in,
  socket_addrv6_as_sockaddr_in6,
};

/// Used to configure the behaviour of the name resolver.
#[derive(Default)]
pub struct Options {
    ares_options: c_ares_sys::ares_options,
    optmask: c_int,
    domains: Vec<CString>,
    lookups: Option<CString>,
    socket_state_callback: Option<Arc<FnMut(Socket, bool, bool) + Send + 'static>>,
}

impl Options {
    /// Returns a fresh `Options`, on which no values are set.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set flags controlling the behaviour of the resolver.  The available
    /// flags are documented [here](flags/index.html).
    pub fn set_flags(&mut self, flags: Flags) -> &mut Self {
        self.ares_options.flags = flags.bits();
        self.optmask |= c_ares_sys::ARES_OPT_FLAGS;
        self
    }

    /// Set the number of milliseconds each name server is given to respond to
    /// a query on the first try.  (After the first try, the timeout algorithm
    /// becomes more complicated, but scales linearly with the value of
    /// timeout).  The default is 5000ms.
    pub fn set_timeout(&mut self, ms: u32) -> &mut Self {
        self.ares_options.timeout = ms as c_int;
        self.optmask |= c_ares_sys::ARES_OPT_TIMEOUTMS;
        self
    }

    /// Set the number of tries the resolver will try contacting each name
    /// server before giving up.  The default is four tries.
    pub fn set_tries(&mut self, tries: u32) -> &mut Self {
        self.ares_options.tries = tries as c_int;
        self.optmask |= c_ares_sys::ARES_OPT_TRIES;
        self
    }

    /// Set the number of dots which must be present in a domain name for it to
    /// be queried for "as is" prior to querying for it with the default domain
    /// extensions appended.  The default value is 1 unless set otherwise by
    /// resolv.conf or the RES_OPTIONS environment variable.
    pub fn set_ndots(&mut self, ndots: u32) -> &mut Self {
        self.ares_options.ndots = ndots as c_int;
        self.optmask |= c_ares_sys::ARES_OPT_NDOTS;
        self
    }

    /// Set the UDP port to use for queries.  The default value is 53, the
    /// standard name service port.
    pub fn set_udp_port(&mut self, udp_port: u16) -> &mut Self {
        self.ares_options.udp_port = udp_port;
        self.optmask |= c_ares_sys::ARES_OPT_UDP_PORT;
        self
    }

    /// Set the TCP port to use for queries.  The default value is 53, the
    /// standard name service port.
    pub fn set_tcp_port(&mut self, tcp_port: u16) -> &mut Self {
        self.ares_options.tcp_port = tcp_port;
        self.optmask |= c_ares_sys::ARES_OPT_TCP_PORT;
        self
    }

    /// Set the domains to search, instead of the domains specified in
    /// resolv.conf or the domain derived from the kernel hostname variable.
    pub fn set_domains(&mut self, domains: &[&str]) -> &mut Self {
        self.domains = domains
            .iter()
            .map(|&s| CString::new(s).unwrap())
            .collect();
        self.optmask |= c_ares_sys::ARES_OPT_DOMAINS;
        self
    }

    /// Set the lookups to perform for host queries. `lookups` should be set to
    /// a string of the characters "b" or "f", where "b" indicates a DNS lookup
    /// and "f" indicates a lookup in the hosts file.
    pub fn set_lookups(&mut self, lookups: &str) -> &mut Self {
        let c_lookups = CString::new(lookups).unwrap();
        self.lookups = Some(c_lookups);
        self.optmask |= c_ares_sys::ARES_OPT_LOOKUPS;
        self
    }

    /// Set the callback function to be invoked when a socket changes state.
    ///
    /// `callback(socket, read, write)` will be called when a socket changes
    /// state:
    ///
    /// -  `read` is set to true if the socket should listen for read events
    /// -  `write` is set to true if the socket should listen for write events.
    pub fn set_socket_state_callback<F>(&mut self, callback: F) -> &mut Self
        where F: FnMut(Socket, bool, bool) + Send + 'static {
        let boxed_callback = Arc::new(callback);
        self.ares_options.sock_state_cb = Some(socket_state_callback::<F>);
        self.ares_options.sock_state_cb_data =
            &*boxed_callback as *const _ as *mut c_void;
        self.socket_state_callback = Some(boxed_callback);
        self.optmask |= c_ares_sys::ARES_OPT_SOCK_STATE_CB;
        self
    }

    /// Set the socket send buffer size.
    pub fn set_sock_send_buffer_size(&mut self, size: u32) -> &mut Self {
        self.ares_options.socket_send_buffer_size = size as c_int;
        self.optmask |= c_ares_sys::ARES_OPT_SOCK_SNDBUF;
        self
    }

    /// Set the socket receive buffer size.
    pub fn set_sock_receive_buffer_size(&mut self, size: u32) -> &mut Self {
        self.ares_options.socket_receive_buffer_size = size as c_int;
        self.optmask |= c_ares_sys::ARES_OPT_SOCK_RCVBUF;
        self
    }

    /// Configure round robin selection of nameservers.
    pub fn set_rotate(&mut self) -> &mut Self {
        self.optmask |= c_ares_sys::ARES_OPT_ROTATE;
        self
    }

    /// Prevent round robin selection of nameservers.
    pub fn set_no_rotate(&mut self) -> &mut Self {
        self.optmask |= c_ares_sys::ARES_OPT_NOROTATE;
        self
    }

    /// Set the EDNS packet size.
    pub fn set_ednspsz(&mut self, size: u32) -> &mut Self {
        self.ares_options.ednspsz = size as c_int;
        self.optmask |= c_ares_sys::ARES_OPT_EDNSPSZ;
        self
    }
}

/// A channel for name service lookups.
pub struct Channel {
    ares_channel: c_ares_sys::ares_channel,
    phantom: PhantomData<c_ares_sys::ares_channeldata>,

    // For ownership only.
    _socket_state_callback: Option<Arc<FnMut(Socket, bool, bool) + Send + 'static>>,
}

impl Channel {
    /// Create a new channel for name service lookups.
    pub fn new(mut options: Options) -> Result<Channel> {
        // Initialize the library.
        let lib_rc = unsafe {
            c_ares_sys::ares_library_init(c_ares_sys::ARES_LIB_INIT_ALL)
        };
        if lib_rc != c_ares_sys::ARES_SUCCESS {
            return Err(Error::from(lib_rc))
        }

        // We deferred setting up domains in the options - do it now.
        let domains: Vec<_> = options.domains
            .iter()
            .map(|s| s.as_ptr())
            .collect();
        options.ares_options.domains =
            domains.as_ptr() as *mut *mut c_char;
        options.ares_options.ndomains = domains.len() as c_int;

        // Likewise for lookups.
        for c_lookup in &options.lookups {
            options.ares_options.lookups =
                c_lookup.as_ptr() as *mut c_char;
        }

        // Initialize the channel.
        let mut ares_channel = ptr::null_mut();
        let channel_rc = unsafe {
            c_ares_sys::ares_init_options(
                &mut ares_channel,
                &mut options.ares_options,
                options.optmask)
        };
        if channel_rc != c_ares_sys::ARES_SUCCESS {
            unsafe { c_ares_sys::ares_library_cleanup(); }
            return Err(Error::from(channel_rc))
        }

        let channel = Channel {
            ares_channel: ares_channel,
            phantom: PhantomData,
            _socket_state_callback: options.socket_state_callback,
        };
        Ok(channel)
    }

    /// Duplicate a channel.
    pub fn try_clone(&self) -> Result<Channel> {
        let mut ares_channel = ptr::null_mut();
        let rc = unsafe {
            c_ares_sys::ares_dup(&mut ares_channel, self.ares_channel)
        };
        if rc != c_ares_sys::ARES_SUCCESS {
            return Err(Error::from(rc))
        }

        let callback = self._socket_state_callback.as_ref().cloned();
        let channel = Channel {
            ares_channel: ares_channel,
            phantom: PhantomData,
            _socket_state_callback: callback,
        };
        Ok(channel)
    }

    /// Handle input, output, and timeout events associated with the specified
    /// file descriptors (sockets).
    ///
    /// Providing a value for `read_fd` indicates that the identified socket
    /// is readable; likewise providing a value for `write_fd` indicates that
    /// the identified socket is writable.  Use `SOCKET_BAD` for "no action".
    pub fn process_fd(&mut self, read_fd: Socket, write_fd: Socket) {
        unsafe {
            c_ares_sys::ares_process_fd(self.ares_channel, read_fd, write_fd);
        }
    }

    /// Handle input and output events associated with the specified file
    /// descriptors (sockets).  Also handles timeouts associated with the
    /// `Channel`.
    pub fn process(
        &mut self,
        read_fds: &mut c_types::fd_set,
        write_fds: &mut c_types::fd_set) {
        unsafe {
            c_ares_sys::ares_process(self.ares_channel, read_fds, write_fds);
        }
    }

    /// Retrieve the set of socket descriptors which the calling application
    /// should wait on for reading and / or writing.
    pub fn get_sock(&self) -> GetSock {
        let mut socks = [0; c_ares_sys::ARES_GETSOCK_MAXNUM];
        let bitmask = unsafe {
            c_ares_sys::ares_getsock(
                self.ares_channel,
                socks.as_mut_ptr(),
                c_ares_sys::ARES_GETSOCK_MAXNUM as c_int)
        };
        GetSock::new(socks, bitmask as u32)
    }

    /// Retrieve the set of socket descriptors which the calling application
    /// should wait on for reading and / or writing.
    pub fn fds(
        &self,
        read_fds: &mut c_types::fd_set,
        write_fds: &mut c_types::fd_set) -> u32 {
        unsafe {
            c_ares_sys::ares_fds(self.ares_channel, read_fds, write_fds) as u32
        }
    }

    /// Set the list of servers to contact, instead of the servers specified
    /// in resolv.conf or the local named.
    ///
    /// String format is `host[:port]`.  IPv6 addresses with ports require
    /// square brackets eg `[2001:4860:4860::8888]:53`.
    pub fn set_servers(
        &mut self,
        servers: &[&str]) -> Result<&mut Self> {
        let servers_csv = servers.join(",");
        let c_servers = CString::new(servers_csv).unwrap();
        let ares_rc = unsafe {
            c_ares_sys::ares_set_servers_ports_csv(
                self.ares_channel,
                c_servers.as_ptr())
        };
        if ares_rc == c_ares_sys::ARES_SUCCESS {
            Ok(self)
        } else {
            Err(Error::from(ares_rc))
        }
    }

    /// Set the local IPv4 address from which to make queries.
    pub fn set_local_ipv4(&mut self, ipv4: &Ipv4Addr) -> &mut Self {
        unsafe {
            c_ares_sys::ares_set_local_ip4(
                self.ares_channel,
                u32::from(*ipv4));
        }
        self
    }

    /// Set the local IPv6 address from which to make queries.
    pub fn set_local_ipv6(&mut self, ipv6: &Ipv6Addr) -> &mut Self {
        let in6_addr = ipv6_as_in6_addr(ipv6);
        unsafe {
            c_ares_sys::ares_set_local_ip6(
                self.ares_channel,
                &in6_addr as *const _ as *const c_uchar);
        }
        self
    }

    /// Set the local device from which to make queries.
    pub fn set_local_device(&mut self, device: &str) -> &mut Self {
        let c_dev = CString::new(device).unwrap();
        unsafe {
            c_ares_sys::ares_set_local_dev(self.ares_channel, c_dev.as_ptr());
        }
        self
    }

    /// Initiate a single-question DNS query for the A records associated with
    /// `name`.
    ///
    /// On completion, `handler` is called with the result.
    pub fn query_a<F>(&mut self, name: &str, handler: F)
        where F: FnOnce(Result<AResults>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_query(
                self.ares_channel,
                c_name.as_ptr(),
                DnsClass::IN as c_int,
                QueryType::A as c_int,
                Some(query_a_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a series of single-question DNS queries for the A records
    /// associated with `name`.
    ///
    /// On completion, `handler` is called with the result.
    pub fn search_a<F>(&mut self, name: &str, handler: F)
        where F: FnOnce(Result<AResults>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_search(
                self.ares_channel,
                c_name.as_ptr(),
                DnsClass::IN as c_int,
                QueryType::A as c_int,
                Some(query_a_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a single-question DNS query for the AAAA records associated
    /// with `name`.
    ///
    /// On completion, `handler` is called with the result.
    pub fn query_aaaa<F>(&mut self, name: &str, handler: F)
        where F: FnOnce(Result<AAAAResults>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_query(
                self.ares_channel,
                c_name.as_ptr(),
                DnsClass::IN as c_int,
                QueryType::AAAA as c_int,
                Some(query_aaaa_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a series of single-question DNS queries for the AAAA records
    /// associated with `name`.
    ///
    /// On completion, `handler` is called with the result.
    pub fn search_aaaa<F>(&mut self, name: &str, handler: F)
        where F: FnOnce(Result<AAAAResults>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_search(
                self.ares_channel,
                c_name.as_ptr(),
                DnsClass::IN as c_int,
                QueryType::AAAA as c_int,
                Some(query_aaaa_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a single-question DNS query for the CNAME records associated
    /// with `name`.
    ///
    /// On completion, `handler` is called with the result.
    pub fn query_cname<F>(&mut self, name: &str, handler: F)
        where F: FnOnce(Result<CNameResults>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_query(
                self.ares_channel,
                c_name.as_ptr(),
                DnsClass::IN as c_int,
                QueryType::CNAME as c_int,
                Some(query_cname_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a series of single-question DNS queries for the CNAME records
    /// associated with `name`.
    ///
    /// On completion, `handler` is called with the result.
    pub fn search_cname<F>(&mut self, name: &str, handler: F)
        where F: FnOnce(Result<CNameResults>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_search(
                self.ares_channel,
                c_name.as_ptr(),
                DnsClass::IN as c_int,
                QueryType::CNAME as c_int,
                Some(query_cname_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a single-question DNS query for the MX records associated
    /// with `name`.
    ///
    /// On completion, `handler` is called with the result.
    pub fn query_mx<F>(&mut self, name: &str, handler: F)
        where F: FnOnce(Result<MXResults>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_query(
                self.ares_channel,
                c_name.as_ptr(),
                DnsClass::IN as c_int,
                QueryType::MX as c_int,
                Some(query_mx_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a series of single-question DNS queries for the MX records
    /// associated with `name`.
    ///
    /// On completion, `handler` is called with the result.
    pub fn search_mx<F>(&mut self, name: &str, handler: F)
        where F: FnOnce(Result<MXResults>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_search(
                self.ares_channel,
                c_name.as_ptr(),
                DnsClass::IN as c_int,
                QueryType::MX as c_int,
                Some(query_mx_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a single-question DNS query for the NAPTR records associated
    /// with `name`.
    ///
    /// On completion, `handler` is called with the result.
    pub fn query_naptr<F>(&mut self, name: &str, handler: F)
        where F: FnOnce(Result<NAPTRResults>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_query(
                self.ares_channel,
                c_name.as_ptr(),
                DnsClass::IN as c_int,
                QueryType::NAPTR as c_int,
                Some(query_naptr_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a series of single-question DNS queries for the NAPTR records
    /// associated with `name`.
    ///
    /// On completion, `handler` is called with the result.
    pub fn search_naptr<F>(&mut self, name: &str, handler: F)
        where F: FnOnce(Result<NAPTRResults>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_search(
                self.ares_channel,
                c_name.as_ptr(),
                DnsClass::IN as c_int,
                QueryType::NAPTR as c_int,
                Some(query_naptr_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a single-question DNS query for the NS records associated
    /// with `name`.
    ///
    /// On completion, `handler` is called with the result.
    pub fn query_ns<F>(&mut self, name: &str, handler: F)
        where F: FnOnce(Result<NSResults>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_query(
                self.ares_channel,
                c_name.as_ptr(),
                DnsClass::IN as c_int,
                QueryType::NS as c_int,
                Some(query_ns_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a series of single-question DNS queries for the NS records
    /// associated with `name`.
    ///
    /// On completion, `handler` is called with the result.
    pub fn search_ns<F>(&mut self, name: &str, handler: F)
        where F: FnOnce(Result<NSResults>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_search(
                self.ares_channel,
                c_name.as_ptr(),
                DnsClass::IN as c_int,
                QueryType::NS as c_int,
                Some(query_ns_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a single-question DNS query for the PTR records associated
    /// with `name`.
    ///
    /// On completion, `handler` is called with the result.
    pub fn query_ptr<F>(&mut self, name: &str, handler: F)
        where F: FnOnce(Result<PTRResults>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_query(
                self.ares_channel,
                c_name.as_ptr(),
                DnsClass::IN as c_int,
                QueryType::PTR as c_int,
                Some(query_ptr_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a series of single-question DNS queries for the PTR records
    /// associated with `name`.
    ///
    /// On completion, `handler` is called with the result.
    pub fn search_ptr<F>(&mut self, name: &str, handler: F)
        where F: FnOnce(Result<PTRResults>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_search(
                self.ares_channel,
                c_name.as_ptr(),
                DnsClass::IN as c_int,
                QueryType::PTR as c_int,
                Some(query_ptr_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a single-question DNS query for the SOA records associated
    /// with `name`.
    ///
    /// On completion, `handler` is called with the result.
    pub fn query_soa<F>(&mut self, name: &str, handler: F)
        where F: FnOnce(Result<SOAResult>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_query(
                self.ares_channel,
                c_name.as_ptr(),
                DnsClass::IN as c_int,
                QueryType::SOA as c_int,
                Some(query_soa_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a series of single-question DNS queries for the SOA records
    /// associated with `name`.
    ///
    /// On completion, `handler` is called with the result.
    pub fn search_soa<F>(&mut self, name: &str, handler: F)
        where F: FnOnce(Result<SOAResult>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_search(
                self.ares_channel,
                c_name.as_ptr(),
                DnsClass::IN as c_int,
                QueryType::SOA as c_int,
                Some(query_soa_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a single-question DNS query for the SRV records associated
    /// with `name`.
    ///
    /// On completion, `handler` is called with the result.
    pub fn query_srv<F>(&mut self, name: &str, handler: F)
        where F: FnOnce(Result<SRVResults>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_query(
                self.ares_channel,
                c_name.as_ptr(),
                DnsClass::IN as c_int,
                QueryType::SRV as c_int,
                Some(query_srv_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a series of single-question DNS queries for the SRV records
    /// associated with `name`.
    ///
    /// On completion, `handler` is called with the result.
    pub fn search_srv<F>(&mut self, name: &str, handler: F)
        where F: FnOnce(Result<SRVResults>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_search(
                self.ares_channel,
                c_name.as_ptr(),
                DnsClass::IN as c_int,
                QueryType::SRV as c_int,
                Some(query_srv_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a single-question DNS query for the TXT records associated
    /// with `name`.
    ///
    /// On completion, `handler` is called with the result.
    pub fn query_txt<F>(&mut self, name: &str, handler: F)
        where F: FnOnce(Result<TXTResults>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_query(
                self.ares_channel,
                c_name.as_ptr(),
                DnsClass::IN as c_int,
                QueryType::TXT as c_int,
                Some(query_txt_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a series of single-question DNS queries for the TXT records
    /// associated with `name`.
    ///
    /// On completion, `handler` is called with the result.
    pub fn search_txt<F>(&mut self, name: &str, handler: F)
        where F: FnOnce(Result<TXTResults>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_search(
                self.ares_channel,
                c_name.as_ptr(),
                DnsClass::IN as c_int,
                QueryType::TXT as c_int,
                Some(query_txt_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Perform a host query by address.
    ///
    /// On completion, `handler` is called with the result.
    pub fn get_host_by_address<F>(
        &mut self,
        address: &IpAddr,
        handler: F) where F: FnOnce(Result<HostResults>) + Send + 'static {
        let in_addr: c_types::in_addr;
        let in6_addr: c_types::in6_addr;
        let c_addr = match *address {
            IpAddr::V4(ref v4) => {
                in_addr = ipv4_as_in_addr(v4);
                &in_addr as *const _ as *const c_void
            },
            IpAddr::V6(ref v6) => {
                in6_addr = ipv6_as_in6_addr(v6);
                &in6_addr as *const _ as *const c_void
            },
        };
        let (family, length) = match *address {
            IpAddr::V4(_) => {
                (AddressFamily::INET, mem::size_of::<c_types::in_addr>())
            },
            IpAddr::V6(_) => {
                (AddressFamily::INET6, mem::size_of::<c_types::in6_addr>())
            },
        };
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_gethostbyaddr(
                self.ares_channel,
                c_addr,
                length as c_int,
                family as c_int,
                Some(get_host_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Perform a host query by name.
    ///
    /// On completion, `handler` is called with the result.
    pub fn get_host_by_name<F>(
        &mut self,
        name: &str,
        family: AddressFamily,
        handler: F) where F: FnOnce(Result<HostResults>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_gethostbyname(
                self.ares_channel,
                c_name.as_ptr(),
                family as c_int,
                Some(get_host_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Address-to-nodename translation in protocol-independent manner.
    ///
    /// The valid values for `flags` are documented
    /// [here](ni_flags/index.html).
    ///
    /// On completion, `handler` is called with the result.
    pub fn get_name_info<F>(
        &mut self,
        address: &SocketAddr,
        flags: NIFlags,
        handler: F)
        where F: FnOnce(Result<NameInfoResult>) + Send + 'static {
        let sockaddr_in: c_types::sockaddr_in;
        let sockaddr_in6: c_types::sockaddr_in6;
        let c_addr = match *address {
            SocketAddr::V4(ref v4) => {
                sockaddr_in = socket_addrv4_as_sockaddr_in(v4);
                &sockaddr_in as *const _ as *const c_types::sockaddr
            },
            SocketAddr::V6(ref v6) => {
                sockaddr_in6 = socket_addrv6_as_sockaddr_in6(v6);
                &sockaddr_in6 as *const _ as *const c_types::sockaddr
            },
        };
        let length = match *address {
            SocketAddr::V4(_) => mem::size_of::<c_types::sockaddr_in>(),
            SocketAddr::V6(_) => mem::size_of::<c_types::sockaddr_in6>(),
        };
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_getnameinfo(
                self.ares_channel,
                c_addr,
                length as c_ares_sys::ares_socklen_t,
                flags.bits(),
                Some(get_name_info_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a single-question DNS query for `name`.  The class and type of
    /// the query are per the provided parameters, taking values as defined in
    /// `arpa/nameser.h`.
    ///
    /// On completion, `handler` is called with the result.
    ///
    /// This method is provided so that users can query DNS types for which
    /// `c-ares` does not provide a parser.  This is expected to be a last
    /// resort; if a suitable `query_xxx()` is available, that should be
    /// preferred.
    pub fn query<F>(
        &mut self,
        name: &str,
        dns_class: u16,
        query_type: u16,
        handler: F)
        where F: FnOnce(Result<&[u8]>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_query(
                self.ares_channel,
                c_name.as_ptr(),
                dns_class as c_int,
                query_type as c_int,
                Some(query_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Initiate a series of single-question DNS queries for `name`.  The class
    /// and type of the query are per the provided parameters, taking values as
    /// defined in `arpa/nameser.h`.
    ///
    /// On completion, `handler` is called with the result.
    ///
    /// This method is provided so that users can query DNS types for which
    /// `c-ares` does not provide a parser.  This is expected to be a last
    /// resort; if a suitable `search_xxx()` is available, that should be
    /// preferred.
    pub fn search<F>(
        &mut self,
        name: &str,
        dns_class: u16,
        query_type: u16,
        handler: F)
        where F: FnOnce(Result<&[u8]>) + Send + 'static {
        let c_name = CString::new(name).unwrap();
        let c_arg = Box::into_raw(Box::new(handler));
        unsafe {
            c_ares_sys::ares_search(
                self.ares_channel,
                c_name.as_ptr(),
                dns_class as c_int,
                query_type as c_int,
                Some(query_callback::<F>),
                c_arg as *mut c_void);
        }
    }

    /// Cancel all requests made on this `Channel`.
    ///
    /// Callbacks will be invoked for each pending query, passing a result
    /// `Err(Error::ECANCELLED)`.
    pub fn cancel(&mut self) {
        unsafe { c_ares_sys::ares_cancel(self.ares_channel); }
    }
}

impl Drop for Channel {
    fn drop(&mut self) {
        unsafe {
            c_ares_sys::ares_destroy(self.ares_channel);
            c_ares_sys::ares_library_cleanup();
        }
    }
}

unsafe impl Send for Channel { }
unsafe impl Sync for Channel { }
unsafe impl Send for Options { }
unsafe impl Sync for Options { }

pub unsafe extern "C" fn socket_state_callback<F>(
    data: *mut c_void,
    socket_fd: c_ares_sys::ares_socket_t,
    readable: c_int,
    writable: c_int)
    where F: FnMut(Socket, bool, bool) + Send + 'static {
    let handler = data as *mut F;
    (*handler)(socket_fd, readable != 0, writable != 0);
}

/// Information about the set of sockets that `c-ares` is interested in, as
/// returned by `get_sock()`.
#[derive(Clone, Copy, Debug)]
pub struct GetSock {
    socks: [c_ares_sys::ares_socket_t; c_ares_sys::ARES_GETSOCK_MAXNUM],
    bitmask: u32,
}

impl GetSock {
    fn new(
        socks: [c_ares_sys::ares_socket_t; c_ares_sys::ARES_GETSOCK_MAXNUM],
        bitmask: u32) -> GetSock {
        GetSock {
            socks: socks,
            bitmask: bitmask,
        }
    }

    /// Returns an iterator over the sockets that `c-ares` is interested in.
    pub fn iter(&self) -> GetSockIter {
        GetSockIter {
            next: 0,
            getsock: self,
        }
    }
}

/// Iterator for sockets of interest to `c-ares`.
///
/// Iterator items are `(socket, readable, writable)`.
#[derive(Clone, Copy, Debug)]
pub struct GetSockIter<'a> {
    next: usize,
    getsock: &'a GetSock,
}

impl<'a> Iterator for GetSockIter<'a> {
    type Item = (Socket, bool, bool);
    fn next(&mut self) -> Option<Self::Item> {
        let index = self.next;
        self.next += 1;
        if index >= c_ares_sys::ARES_GETSOCK_MAXNUM {
            None
        } else {
            let bit = 1 << index;
            let readable = (self.getsock.bitmask & bit) != 0;
            let bit = bit << c_ares_sys::ARES_GETSOCK_MAXNUM;
            let writable = (self.getsock.bitmask & bit) != 0;
            if readable || writable {
                let fd = self.getsock.socks[index];
                Some((fd, readable, writable))
            } else {
                None
            }
        }
    }
}

impl<'a> IntoIterator for &'a GetSock {
    type Item = (Socket, bool, bool);
    type IntoIter = GetSockIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}