summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorFerris Tseng <ferris@navapbc.com>2020-05-16 17:32:06 -0400
committerFerris Tseng <ferris@navapbc.com>2020-05-16 17:32:06 -0400
commitba53395d88f9820fcd26b05192845d2eca365217 (patch)
tree4784806fca250cd4789d99dde4830ea6b6f6faa9
parenta872cc2922ad94c10e57784bd5d7c7cd81b84878 (diff)
downloadrust-ipfs-api-ba53395d88f9820fcd26b05192845d2eca365217.tar.gz
rust-ipfs-api-ba53395d88f9820fcd26b05192845d2eca365217.tar.xz
better handling of multiaddrs
-rw-r--r--ipfs-api/src/client/from_uri.rs126
-rw-r--r--ipfs-api/src/client/internal.rs11
2 files changed, 113 insertions, 24 deletions
diff --git a/ipfs-api/src/client/from_uri.rs b/ipfs-api/src/client/from_uri.rs
index 6762e84..71a7385 100644
--- a/ipfs-api/src/client/from_uri.rs
+++ b/ipfs-api/src/client/from_uri.rs
@@ -6,10 +6,11 @@
// copied, modified, or distributed except according to those terms.
//
use http::uri::{Builder, InvalidUri, PathAndQuery, Scheme, Uri};
-use parity_multiaddr::{Multiaddr, Protocol};
+use parity_multiaddr::{self as multiaddr, Multiaddr, Protocol};
use std::{
fs,
- net::{IpAddr, SocketAddr, SocketAddrV4, SocketAddrV6},
+ net::{SocketAddr, SocketAddrV4, SocketAddrV6},
+ str::FromStr,
};
const VERSION_PATH_V0: &'static str = "/api/v0";
@@ -40,11 +41,9 @@ pub trait TryFromUri: Sized {
/// Creates a new client from a host name and port.
///
- fn from_host_and_port(host: &str, port: u16) -> Result<Self, http::Error> {
+ 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::HTTP)
- .authority(&authority[..]);
+ let builder = Builder::new().scheme(scheme).authority(&authority[..]);
build_base_path(builder).map(Self::build_with_base_uri)
}
@@ -76,28 +75,58 @@ pub trait TryFromUri: Sized {
}
}
- /// Creates a new client connected to the endpoint specified in ~/.ipfs/api.
+ /// Creates a new client from a multiaddr.
///
- fn from_multiaddr(multiaddr: Multiaddr) -> Option<Self> {
- let mut addr: Option<IpAddr> = None;
+ 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::Ip4(v4addr) => addr = Some(v4addr.into()),
- Protocol::Ip6(v6addr) => addr = Some(v6addr.into()),
Protocol::Tcp(tcpport) => port = Some(tcpport),
- _ => {
- return None;
- }
+ Protocol::Http => scheme = Some(Scheme::HTTP),
+ Protocol::Https => scheme = Some(Scheme::HTTPS),
+ _ => (),
}
}
- if let (Some(addr), Some(port)) = (addr, port) {
- Some(Self::from_socket(Scheme::HTTP, SocketAddr::new(addr, port)).unwrap())
- } else {
- None
+ 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.
@@ -107,7 +136,64 @@ pub trait TryFromUri: Sized {
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| parity_multiaddr::from_url(&multiaddr_str).ok())
- .and_then(Self::from_multiaddr)
+ .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"
+ );
}
diff --git a/ipfs-api/src/client/internal.rs b/ipfs-api/src/client/internal.rs
index 5667ab2..fcc4ddb 100644
--- a/ipfs-api/src/client/internal.rs
+++ b/ipfs-api/src/client/internal.rs
@@ -79,7 +79,7 @@ impl Default for IpfsClient {
///
fn default() -> IpfsClient {
Self::from_ipfs_config()
- .unwrap_or_else(|| Self::from_host_and_port("localhost", 5001).unwrap())
+ .unwrap_or_else(|| Self::from_host_and_port(Scheme::HTTP, "localhost", 5001).unwrap())
}
}
@@ -88,7 +88,7 @@ impl IpfsClient {
///
#[deprecated(
since = "0.7.2",
- note = "Please use [`client::TryFromUri::from_host_and_port`]"
+ note = "Please use [`client::TryFromUri::from_host_and_port`]. Removing in next major version."
)]
pub fn new(host: &str, port: u16) -> Result<IpfsClient, InvalidUri> {
let uri = format!("http://{}:{}", host, port);
@@ -97,14 +97,17 @@ impl IpfsClient {
Self::from_str(&uri[..])
}
- #[deprecated(since = "0.7.2", note = "Please use [`client::TryFromUri::from_uri`]")]
+ #[deprecated(
+ since = "0.7.2",
+ note = "Please use [`client::TryFromUri::from_uri`]. Removing in next major version."
+ )]
pub fn new_from_uri(uri: &str) -> Result<IpfsClient, InvalidUri> {
Self::from_str(uri)
}
#[deprecated(
since = "0.7.2",
- note = "Please use [`client::TryFromUri::from_socket`]"
+ note = "Please use [`client::TryFromUri::from_socket`]. Removing in next major version."
)]
pub fn from(socket_addr: SocketAddr) -> IpfsClient {
Self::from_socket(Scheme::HTTP, socket_addr).unwrap()