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
use std::{
    fs::File,
    io::{self, copy, Cursor, Error, ErrorKind},
    process::Command,
    time::Duration,
};

use hyper::{body::Bytes, client::HttpConnector, Body, Client, Method, Request, Response};
use hyper_tls::HttpsConnector;
use tokio::time::timeout;
use url::Url;

/// Creates a simple HTTP GET request with no header and no body.
pub fn create_get(url: &str, path: &str) -> io::Result<Request<Body>> {
    let uri = match join_uri(url, path) {
        Ok(u) => u,
        Err(e) => return Err(e),
    };

    let req = match Request::builder()
        .method(Method::GET)
        .uri(uri.as_str())
        .body(Body::empty())
    {
        Ok(r) => r,
        Err(e) => {
            return Err(Error::new(
                ErrorKind::Other,
                format!("failed to create request {}", e),
            ));
        }
    };

    Ok(req)
}

const JSON_CONTENT_TYPE: &str = "application/json";

/// Creates a simple HTTP POST request with JSON header and body.
pub fn create_json_post(url: &str, path: &str, d: &str) -> io::Result<Request<Body>> {
    let uri = join_uri(url, path)?;

    let req = match Request::builder()
        .method(Method::POST)
        .header("content-type", JSON_CONTENT_TYPE)
        .uri(uri.as_str())
        .body(Body::from(String::from(d)))
    {
        Ok(r) => r,
        Err(e) => {
            return Err(Error::new(
                ErrorKind::Other,
                format!("failed to create request {}", e),
            ));
        }
    };

    Ok(req)
}

/// Sends a HTTP request, reads response in "hyper::body::Bytes".
pub async fn read_bytes(
    req: Request<Body>,
    timeout_dur: Duration,
    is_https: bool,
    check_status_code: bool,
) -> io::Result<Bytes> {
    let resp = send_req(req, timeout_dur, is_https).await?;
    if !resp.status().is_success() {
        log::warn!(
            "unexpected HTTP response code {} (server error {})",
            resp.status(),
            resp.status().is_server_error()
        );
        if check_status_code {
            return Err(Error::new(
                ErrorKind::Other,
                format!(
                    "unexpected HTTP response code {} (server error {})",
                    resp.status(),
                    resp.status().is_server_error()
                ),
            ));
        }
    }

    // set timeouts for reads
    // https://github.com/hyperium/hyper/issues/1097
    let future_task = hyper::body::to_bytes(resp);
    let ret = timeout(timeout_dur, future_task).await;

    let bytes;
    match ret {
        Ok(result) => match result {
            Ok(b) => bytes = b,
            Err(e) => {
                return Err(Error::new(
                    ErrorKind::Other,
                    format!("failed to read response {}", e),
                ));
            }
        },
        Err(e) => {
            return Err(Error::new(
                ErrorKind::Other,
                format!("failed to read response {}", e),
            ));
        }
    }

    Ok(bytes)
}

/// Sends a HTTP(s) request and wait for its response.
async fn send_req(
    req: Request<Body>,
    timeout_dur: Duration,
    is_https: bool,
) -> io::Result<Response<Body>> {
    // ref. https://github.com/tokio-rs/tokio-tls/blob/master/examples/hyper-client.rs
    // ref. https://docs.rs/hyper/latest/hyper/client/struct.HttpConnector.html
    // ref. https://github.com/hyperium/hyper-tls/blob/master/examples/client.rs
    let mut connector = HttpConnector::new();
    // ref. https://github.com/hyperium/hyper/issues/1097
    connector.set_connect_timeout(Some(Duration::from_secs(5)));

    let task = {
        if !is_https {
            let cli = Client::builder().build(connector);
            cli.request(req)
        } else {
            // TODO: implement "curl --insecure"
            let https_connector = HttpsConnector::new_with_connector(connector);
            let cli = Client::builder().build(https_connector);
            cli.request(req)
        }
    };

    let res = timeout(timeout_dur, task).await?;
    match res {
        Ok(resp) => Ok(resp),
        Err(e) => {
            return Err(Error::new(
                ErrorKind::Other,
                format!("failed to fetch response {}", e),
            ))
        }
    }
}

#[test]
fn test_read_bytes_timeout() {
    let _ = env_logger::builder()
        .filter_level(log::LevelFilter::Info)
        .is_test(true)
        .try_init();

    macro_rules! ab {
        ($e:expr) => {
            tokio_test::block_on($e)
        };
    }

    let ret = join_uri("http://localhost:12", "invalid");
    assert!(ret.is_ok());
    let u = ret.unwrap();
    let u = u.to_string();

    let ret = Request::builder()
        .method(hyper::Method::POST)
        .uri(u)
        .body(Body::empty());
    assert!(ret.is_ok());
    let req = ret.unwrap();
    let ret = ab!(read_bytes(req, Duration::from_secs(1), false, true));
    assert!(!ret.is_ok());
}

pub fn join_uri(url: &str, path: &str) -> io::Result<Url> {
    let mut uri = match Url::parse(url) {
        Ok(u) => u,
        Err(e) => {
            return Err(Error::new(
                ErrorKind::Other,
                format!("failed to parse client URL {}", e),
            ))
        }
    };

    if !path.is_empty() {
        match uri.join(path) {
            Ok(u) => uri = u,
            Err(e) => {
                return Err(Error::new(
                    ErrorKind::Other,
                    format!("failed to join parsed URL {}", e),
                ));
            }
        }
    }

    Ok(uri)
}

#[test]
fn test_join_uri() {
    let ret = Url::parse("http://localhost:9850/ext/X/sendMultiple");
    let expected = ret.unwrap();

    let ret = join_uri("http://localhost:9850/", "/ext/X/sendMultiple");
    assert!(ret.is_ok());
    let t = ret.unwrap();
    assert_eq!(t, expected);

    let ret = join_uri("http://localhost:9850", "/ext/X/sendMultiple");
    assert!(ret.is_ok());
    let t = ret.unwrap();
    assert_eq!(t, expected);

    let ret = join_uri("http://localhost:9850", "ext/X/sendMultiple");
    assert!(ret.is_ok());
    let t = ret.unwrap();
    assert_eq!(t, expected);
}

/// Downloads a file to the "file_path".
pub async fn download_file(ep: &str, file_path: &str) -> io::Result<()> {
    log::info!("downloading the file via {}", ep);
    let resp = reqwest::get(ep)
        .await
        .map_err(|e| Error::new(ErrorKind::Other, format!("failed reqwest::get {}", e)))?;

    let mut content = Cursor::new(
        resp.bytes()
            .await
            .map_err(|e| Error::new(ErrorKind::Other, format!("failed bytes {}", e)))?,
    );

    let mut f = File::create(file_path)?;
    copy(&mut content, &mut f)?;

    Ok(())
}

/// TODO: implement this with native Rust
pub async fn get_non_tls(url: &str, url_path: &str) -> io::Result<Vec<u8>> {
    let joined = join_uri(url, url_path)?;
    log::debug!("non-TLS HTTP get for {:?}", joined);

    let output = {
        if url.starts_with("https") {
            log::info!("sending via curl --insecure");
            let mut cmd = Command::new("curl");
            cmd.arg("--insecure");
            cmd.arg(joined.as_str());
            let output = cmd.output()?;
            output.stdout
        } else {
            let req = create_get(url, url_path)?;
            let buf = match read_bytes(
                req,
                Duration::from_secs(15),
                url.starts_with("https"),
                false,
            )
            .await
            {
                Ok(b) => b,
                Err(e) => return Err(e),
            };
            buf.to_vec()
        }
    };
    Ok(output)
}

/// TODO: implement this with native Rust
pub async fn post_non_tls(url: &str, url_path: &str, data: &str) -> io::Result<Vec<u8>> {
    let joined = join_uri(url, url_path)?;
    log::debug!("non-TLS HTTP post {}-byte data to {:?}", data.len(), joined);

    let output = {
        if url.starts_with("https") {
            log::info!("sending via curl --insecure");
            let mut cmd = Command::new("curl");
            cmd.arg("--insecure");
            cmd.arg("-X POST");
            cmd.arg("--header 'content-type:application/json;'");
            cmd.arg(format!("--data '{}'", data));
            cmd.arg(joined.as_str());
            let output = cmd.output()?;
            output.stdout
        } else {
            let req = create_json_post(url, url_path, data)?;
            let buf = match read_bytes(req, Duration::from_secs(15), false, false).await {
                Ok(b) => b,
                Err(e) => return Err(e),
            };
            buf.to_vec()
        }
    };
    Ok(output)
}