summary refs log tree commit diff
path: root/src/libstd/rt/uv/addrinfo.rs
blob: 83a7e64b1397f6b944667d1029a1a9e282dd5b1a (plain)
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
// Copyright 2013 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.

use cast::transmute;
use cell::Cell;
use c_str::ToCStr;
use libc::{c_int, c_void};
use option::{Option, Some, None};
use ptr::null;
use rt::uv::uvll;
use rt::uv::uvll::UV_GETADDRINFO;
use rt::uv::{Loop, UvError, NativeHandle};
use rt::uv::status_to_maybe_uv_error;
use rt::uv::net::UvAddrInfo;

type GetAddrInfoCallback = ~fn(GetAddrInfoRequest, &UvAddrInfo, Option<UvError>);

pub struct GetAddrInfoRequest(*uvll::uv_getaddrinfo_t);

pub struct RequestData {
    getaddrinfo_cb: Option<GetAddrInfoCallback>,
}

impl GetAddrInfoRequest {
    pub fn new() -> GetAddrInfoRequest {
        let req = unsafe { uvll::malloc_req(UV_GETADDRINFO) };
        assert!(req.is_not_null());
        let mut req: GetAddrInfoRequest = NativeHandle::from_native_handle(req);
        req.install_req_data();
        return req;
    }

    pub fn getaddrinfo(&mut self, loop_: &Loop, node: Option<&str>,
                       service: Option<&str>, hints: Option<UvAddrInfo>,
                       cb: GetAddrInfoCallback) {

        assert!(node.is_some() || service.is_some());

        let (c_node, c_node_ptr) = match node {
            Some(n) => {
                let c_node = n.to_c_str();
                let c_node_ptr = c_node.with_ref(|r| r);
                (Some(c_node), c_node_ptr)
            }
            None => (None, null())
        };

        let (c_service, c_service_ptr) = match service {
            Some(s) => {
                let c_service = s.to_c_str();
                let c_service_ptr = c_service.with_ref(|r| r);
                (Some(c_service), c_service_ptr)
            }
            None => (None, null())
        };

        let cb = Cell::new(cb);
        let wrapper_cb: GetAddrInfoCallback = |req, addrinfo, err| {
            // Capture some heap values that need to stay alive for the
            // getaddrinfo call
            let _ = &c_node;
            let _ = &c_service;

            let cb = cb.take();
            cb(req, addrinfo, err)
        };

        // XXX: Implement hints
        assert!(hints.is_none());

        self.get_req_data().getaddrinfo_cb = Some(wrapper_cb);

        unsafe {
            assert!(0 == uvll::getaddrinfo(loop_.native_handle(),
                                           self.native_handle(),
                                           getaddrinfo_cb,
                                           c_node_ptr,
                                           c_service_ptr,
                                           null()));
        }

        extern "C" fn getaddrinfo_cb(req: *uvll::uv_getaddrinfo_t,
                                     status: c_int,
                                     res: *uvll::addrinfo) {
            let mut req: GetAddrInfoRequest = NativeHandle::from_native_handle(req);
            let err = status_to_maybe_uv_error(status);
            let addrinfo = UvAddrInfo(res);
            let data = req.get_req_data();
            (*data.getaddrinfo_cb.get_ref())(req, &addrinfo, err);
            unsafe {
                uvll::freeaddrinfo(res);
            }
        }
    }

    fn get_loop(&self) -> Loop {
        unsafe {
            Loop {
                handle: uvll::get_loop_from_fs_req(self.native_handle())
            }
        }
    }

    fn install_req_data(&mut self) {
        let req = self.native_handle() as *uvll::uv_getaddrinfo_t;
        let data = ~RequestData {
            getaddrinfo_cb: None
        };
        unsafe {
            let data = transmute::<~RequestData, *c_void>(data);
            uvll::set_data_for_req(req, data);
        }
    }

    fn get_req_data<'r>(&'r mut self) -> &'r mut RequestData {
        unsafe {
            let data = uvll::get_data_for_req(self.native_handle());
            let data = transmute::<&*c_void, &mut ~RequestData>(&data);
            return &mut **data;
        }
    }

    fn delete(self) {
        unsafe {
            let data = uvll::get_data_for_req(self.native_handle());
            let _data = transmute::<*c_void, ~RequestData>(data);
            uvll::set_data_for_req(self.native_handle(), null::<()>());
            uvll::free_req(self.native_handle());
        }
    }
}

impl NativeHandle<*uvll::uv_getaddrinfo_t> for GetAddrInfoRequest {
    fn from_native_handle(handle: *uvll::uv_getaddrinfo_t) -> GetAddrInfoRequest {
        GetAddrInfoRequest(handle)
    }
    fn native_handle(&self) -> *uvll::uv_getaddrinfo_t {
        match self { &GetAddrInfoRequest(ptr) => ptr }
    }
}

#[cfg(test)]
mod test {
    use option::{Some, None};
    use rt::uv::Loop;
    use rt::uv::net::accum_sockaddrs;
    use rt::io::net::ip::{SocketAddr, Ipv4Addr};
    use super::*;

    #[test]
    fn getaddrinfo_test() {
        let mut loop_ = Loop::new();
        let mut req = GetAddrInfoRequest::new();
        do req.getaddrinfo(&loop_, Some("localhost"), None, None) |_, addrinfo, _| {
            let sockaddrs = accum_sockaddrs(addrinfo);
            let mut found_local = false;
            let local_addr = &SocketAddr {
                ip: Ipv4Addr(127, 0, 0, 1),
                port: 0
            };
            for addr in sockaddrs.iter() {
                found_local = found_local || addr == local_addr;
            }
            assert!(found_local);
        }
        loop_.run();
        loop_.close();
        req.delete();
    }
}