Skip to content

Commit

Permalink
Handle http client errors
Browse files Browse the repository at this point in the history
  • Loading branch information
SudoDios committed Sep 1, 2024
1 parent 4d53d28 commit 8cedf3d
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 42 deletions.
43 changes: 23 additions & 20 deletions src/http/http_client.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::fs::File;
use std::io::Error;
use std::io::{Error, ErrorKind};
use std::pin::Pin;
use std::task::{Context, Poll};
use serde_json::Value;
Expand Down Expand Up @@ -55,28 +55,28 @@ impl AsyncWrite for ClientStream {

impl HttpClient {

pub async fn open(url : &str) -> Self {
let pared_url = Self::parse_url(url);
let tcp_stream = TcpStream::connect(format!("{}:{}",pared_url.1,pared_url.2)).await.unwrap();
pub async fn open(url : &str) -> std::io::Result<Self> {
let pared_url = Self::parse_url(url)?;
let tcp_stream = TcpStream::connect(format!("{}:{}",pared_url.1,pared_url.2)).await?;
let stream = if pared_url.2 == 443 {
let tls_stream = setup_tls_connector(pared_url.1.clone(),tcp_stream).await;
ClientStream::Tls(tls_stream)
} else {
ClientStream::Tcp(tcp_stream)
};
HttpClient {
Ok(HttpClient {
host : pared_url.1,
path : pared_url.3,
stream
}
})
}

pub async fn send_request_json(&mut self,packet : &[u8]) -> Option<Value> {
self.stream.write_all(packet).await.unwrap();
pub async fn send_request_json(&mut self,packet : &[u8]) -> std::io::Result<Option<Value>> {
self.stream.write_all(packet).await?;
let mut read_data = Vec::new();
loop {
let mut response = vec![0; 128];
let read = self.stream.read(&mut response).await.unwrap();
let read = self.stream.read(&mut response).await?;
read_data.extend(response);
if read < 128 { //EOF
break;
Expand All @@ -88,12 +88,12 @@ impl HttpClient {
let mut split_body = response.splitn(2,"\r\n\r\n");
let resp_body = split_body.nth(1).unwrap_or("");
if let Ok(parsed_json_body) = serde_json::from_str::<Value>(resp_body) {
Some(parsed_json_body)
Ok(Some(parsed_json_body))
} else {
None
Ok(None)
}
} else {
None
Ok(None)
}
}

Expand Down Expand Up @@ -142,15 +142,18 @@ impl HttpClient {
}
}

fn parse_url(url: &str) -> (String,String,i32,String) {
let (scheme, rest) = url.split_once("://").unwrap();
let (host, path) = if rest.contains('/') {
rest.split_once('/').unwrap()
fn parse_url(url: &str) -> std::io::Result<(String,String,i32,String)> {
if let Some((scheme, rest)) = url.split_once("://") {
let (host, path) = if rest.contains('/') {
rest.split_once('/').unwrap()
} else {
(rest,"")
};
let port = if scheme == "https" { 443 } else { 80 };
Ok((scheme.to_string(),host.to_string(),port,path.to_string()))
} else {
(rest,"")
};
let port = if scheme == "https" { 443 } else { 80 };
(scheme.to_string(),host.to_string(),port,path.to_string())
Err(Error::new(ErrorKind::Other,"Error parsing input url"))
}
}

}
44 changes: 24 additions & 20 deletions src/ip/ip_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,33 +122,37 @@ impl IPInfo {
}

async fn get_isp_info_from_api(ip : &str) -> Option<String> {
let config = SERVER_CONFIG.get().unwrap();
let config = SERVER_CONFIG.get()?;
let ip_info_token = config.ipinfo_api_key.clone();
if ip_info_token.is_empty() {
return None
}
let mut client = HttpClient::open("https://ipinfo.io").await;
let request = format!(
"GET /{}/json?token={} HTTP/1.1\r\n\
if let Ok(mut client) = HttpClient::open("https://ipinfo.io").await {
let request = format!(
"GET /{}/json?token={} HTTP/1.1\r\n\
Host: ipinfo.io\r\n\r\n",
ip,
ip_info_token
);
if let Some(res_body) = client.send_request_json(request.as_bytes()).await {
let isp = if let Some(org) = res_body.get("org") {
Some(org.as_str().unwrap())
} else {
let asn_name = &res_body["asn"]["name"];
if !asn_name.is_null() {
Some(asn_name.as_str().unwrap())
ip,
ip_info_token
);
if let Ok(Some(res_body)) = client.send_request_json(request.as_bytes()).await {
let isp = if let Some(org) = res_body.get("org") {
Some(org.as_str()?)
} else {
None
}
};
isp.as_ref()?;
let output = format!("{} - {}, {}",ip,isp.unwrap(),res_body.get("country").unwrap().as_str().unwrap());
Some(output)
let asn_name = &res_body["asn"]["name"];
if !asn_name.is_null() {
Some(asn_name.as_str()?)
} else {
None
}
};
isp.as_ref()?;
let output = format!("{} - {}, {}",ip,isp?,res_body.get("country")?.as_str()?);
Some(output)
} else {
None
}
} else {
warn!("Http client error.");
None
}
}
Expand Down
8 changes: 6 additions & 2 deletions src/ip/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use log::error;
use tokio::runtime::Runtime;
use crate::http::http_client::HttpClient;

Expand All @@ -7,7 +8,10 @@ pub mod mmdb;
pub fn update_ipdb(url : &str,file_name : &str) {
let runtime = Runtime::new().unwrap();
runtime.block_on(async {
let mut client = HttpClient::open(url).await;
client.download_file(file_name).await;
if let Ok(mut client) = HttpClient::open(url).await {
client.download_file(file_name).await;
} else {
error!("Http client error.")
}
});
}

0 comments on commit 8cedf3d

Please sign in to comment.