summaryrefslogtreecommitdiffstats
path: root/ipfs-api/src/client/from_uri.rs
blob: 71a73853d1003a6f2a70303aa6795cc764e8f8f3 (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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
// Copyright 2020 rust-ipfs-api Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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 http::uri::{Builder, InvalidUri, PathAndQuery, Scheme, Uri};
use parity_multiaddr::{self as multiaddr, Multiaddr, Protocol};
use std::{
    fs,
    net::{SocketAddr, SocketAddrV4, SocketAddrV6},
    str::FromStr,
};

const VERSION_PATH_V0: &'static str = "/api/v0";

/// Builds the base url path for the Ipfs api.
///
fn build_base_path(builder: Builder) -> Result<Uri, http::Error> {
    builder.path_and_query(VERSION_PATH_V0).build()
}

pub trait TryFromUri: Sized {
    /// Builds a new client from a base URI to the IPFS API.
    ///
    fn build_with_base_uri(uri: Uri) -> Self;

    /// Creates a new client from a str.
    ///
    /// Note: This constructor will overwrite the path/query part of the URI.
    ///
    fn from_str(uri: &str) -> Result<Self, InvalidUri> {
        let uri: Uri = uri.parse()?;
        let mut parts = uri.into_parts();

        parts.path_and_query = Some(PathAndQuery::from_static(VERSION_PATH_V0));

        Ok(Self::build_with_base_uri(Uri::from_parts(parts).unwrap()))
    }

    /// Creates a new client from a host name and port.
    ///
    fn from_host_and_port(scheme: Scheme, host: &str, port: u16) -> Result<Self, http::Error> {
        let authority = format!("{}:{}", host, port);
        let builder = Builder::new().scheme(scheme).authority(&authority[..]);

        build_base_path(builder).map(Self::build_with_base_uri)
    }

    /// Creates a new client from an IPV4 address and port number.
    ///
    fn from_ipv4(scheme: Scheme, addr: SocketAddrV4) -> Result<Self, http::Error> {
        let authority = format!("{}", addr);
        let builder = Builder::new().scheme(scheme).authority(&authority[..]);

        build_base_path(builder).map(Self::build_with_base_uri)
    }

    /// Creates a new client from an IPV6 addr and port number.
    ///
    fn from_ipv6(scheme: Scheme, addr: SocketAddrV6) -> Result<Self, http::Error> {
        let authority = format!("{}", addr);
        let builder = Builder::new().scheme(scheme).authority(&authority[..]);

        build_base_path(builder).map(Self::build_with_base_uri)
    }

    /// Creates a new client from an IP address and port number.
    ///
    fn from_socket(scheme: Scheme, socket_addr: SocketAddr) -> Result<Self, http::Error> {
        match socket_addr {
            SocketAddr::V4(addr) => Self::from_ipv4(scheme, addr),
            SocketAddr::V6(addr) => Self::from_ipv6(scheme, addr),
        }
    }

    /// Creates a new client from a multiaddr.
    ///
    fn from_multiaddr(multiaddr: Multiaddr) -> Result<Self, multiaddr::Error> {
        let mut scheme: Option<Scheme> = None;
        let mut port: Option<u16> = None;

        for addr_component in multiaddr.iter() {
            match addr_component {
                Protocol::Tcp(tcpport) => port = Some(tcpport),
                Protocol::Http => scheme = Some(Scheme::HTTP),
                Protocol::Https => scheme = Some(Scheme::HTTPS),
                _ => (),
            }
        }

        let scheme = scheme.unwrap_or(Scheme::HTTP);

        if let Some(port) = port {
            for addr_component in multiaddr.iter() {
                match addr_component {
                    Protocol::Tcp(_) | Protocol::Http | Protocol::Https => (),
                    Protocol::Ip4(v4addr) => {
                        return Ok(Self::from_ipv4(scheme, SocketAddrV4::new(v4addr, port)).unwrap())
                    }
                    Protocol::Ip6(v6addr) => {
                        return Ok(
                            Self::from_ipv6(scheme, SocketAddrV6::new(v6addr, port, 0, 0)).unwrap(),
                        )
                    }
                    Protocol::Dns4(ref v4host) => {
                        return Ok(Self::from_host_and_port(scheme, v4host, port).unwrap())
                    }
                    Protocol::Dns6(ref v6host) => {
                        return Ok(Self::from_host_and_port(scheme, v6host, port).unwrap())
                    }
                    _ => {
                        return Err(multiaddr::Error::InvalidMultiaddr);
                    }
                }
            }
        }

        Err(multiaddr::Error::InvalidMultiaddr)
    }

    /// Creates a new client from a multiaddr.
    ///
    fn from_multiaddr_str(multiaddr: &str) -> Result<Self, multiaddr::Error> {
        parity_multiaddr::from_url(multiaddr)
            .map_err(|e| multiaddr::Error::ParsingError(Box::new(e)))
            .or_else(|_| Multiaddr::from_str(multiaddr))
            .and_then(Self::from_multiaddr)
    }

    /// Creates a new client connected to the endpoint specified in ~/.ipfs/api.
    ///
    #[inline]
    fn from_ipfs_config() -> Option<Self> {
        dirs::home_dir()
            .map(|home_dir| home_dir.join(".ipfs").join("api"))
            .and_then(|multiaddr_path| fs::read_to_string(&multiaddr_path).ok())
            .and_then(|multiaddr_str| Self::from_multiaddr_str(&multiaddr_str).ok())
    }
}

#[cfg(test)]
mod tests {
    use crate::client::TryFromUri;
    use http::uri::{Scheme, Uri};

    #[derive(Debug)]
    struct StringWrapper(String);

    impl TryFromUri for StringWrapper {
        fn build_with_base_uri(uri: Uri) -> Self {
            StringWrapper(uri.to_string())
        }
    }

    macro_rules! test_from_value_fn_ok {
        ([$method: path]: $($f: ident ($($args: expr),+) => $output: expr),+) => {
            $(
                #[test]
                fn $f() {
                    let result: Result<StringWrapper, _> = $method($($args),+);

                    assert!(
                        result.is_ok(),
                        format!("should be ok but failed with error: {:?}", result.unwrap_err())
                    );

                    let StringWrapper(result) = result.unwrap();

                    assert!(
                        result == $output,
                        format!("got: ({}) expected: ({})", result, $output)
                    );
                }
            )+
        };
    }

    test_from_value_fn_ok!(
        [TryFromUri::from_str]:
        test_from_str_0_ok ("http://localhost:5001") => "http://localhost:5001/api/v0",
        test_from_str_1_ok ("https://ipfs.io:9001") => "https://ipfs.io:9001/api/v0"
    );

    test_from_value_fn_ok!(
        [TryFromUri::from_host_and_port]:
        test_from_host_and_port_0_ok (Scheme::HTTP, "localhost", 5001) => "http://localhost:5001/api/v0",
        test_from_host_and_port_1_ok (Scheme::HTTP, "ipfs.io", 9001) => "http://ipfs.io:9001/api/v0"
    );

    test_from_value_fn_ok!(
        [TryFromUri::from_multiaddr_str]:
        test_from_multiaddr_str_0_ok ("http://localhost:5001/") => "http://localhost:5001/api/v0",
        test_from_multiaddr_str_1_ok ("https://ipfs.io:9001/") => "https://ipfs.io:9001/api/v0",
        test_from_multiaddr_str_2_ok ("/ip4/127.0.0.1/tcp/5001/http") => "http://127.0.0.1:5001/api/v0",
        test_from_multiaddr_str_3_ok ("/ip6/0:0:0:0:0:0:0:0/tcp/5001/http") => "http://[::]:5001/api/v0"
    );
}