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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
use std::{
io,
io::{Read, Write},
sync::mpsc::{sync_channel, Receiver, SyncSender, TrySendError},
thread,
time::Duration,
};
use curl::easy::{Auth, Easy2};
use git_features::io::pipe;
use crate::client::http::curl::curl_is_spurious;
use crate::client::{
blocking_io::http::{self, curl::Error, redirect},
http::options::{FollowRedirects, ProxyAuthMethod},
};
#[derive(Default)]
struct Handler {
send_header: Option<pipe::Writer>,
send_data: Option<pipe::Writer>,
receive_body: Option<pipe::Reader>,
checked_status: bool,
last_status: usize,
follow: FollowRedirects,
}
impl Handler {
fn reset(&mut self) {
self.checked_status = false;
self.last_status = 0;
self.follow = FollowRedirects::default();
}
fn parse_status_inner(data: &[u8]) -> Result<usize, Box<dyn std::error::Error + Send + Sync>> {
let code = data
.split(|b| *b == b' ')
.nth(1)
.ok_or("Expected HTTP/<VERSION> STATUS")?;
let code = std::str::from_utf8(code)?;
code.parse().map_err(Into::into)
}
fn parse_status(data: &[u8], follow: FollowRedirects) -> Option<(usize, Box<dyn std::error::Error + Send + Sync>)> {
let valid_end = match follow {
FollowRedirects::Initial | FollowRedirects::All => 308,
FollowRedirects::None => 299,
};
match Self::parse_status_inner(data) {
Ok(status) if !(200..=valid_end).contains(&status) => {
Some((status, format!("Received HTTP status {}", status).into()))
}
Ok(_) => None,
Err(err) => Some((500, err)),
}
}
}
impl curl::easy::Handler for Handler {
fn write(&mut self, data: &[u8]) -> Result<usize, curl::easy::WriteError> {
drop(self.send_header.take()); match self.send_data.as_mut() {
Some(writer) => writer.write_all(data).map(|_| data.len()).or(Ok(0)),
None => Ok(0), }
}
fn read(&mut self, data: &mut [u8]) -> Result<usize, curl::easy::ReadError> {
match self.receive_body.as_mut() {
Some(reader) => reader.read(data).map_err(|_err| curl::easy::ReadError::Abort),
None => Ok(0), }
}
fn header(&mut self, data: &[u8]) -> bool {
if let Some(writer) = self.send_header.as_mut() {
if self.checked_status {
writer.write_all(data).ok();
} else {
self.checked_status = true;
self.last_status = 200;
if let Some((status, err)) = Handler::parse_status(data, self.follow) {
self.last_status = status;
writer
.channel
.send(Err(io::Error::new(
if status == 401 {
io::ErrorKind::PermissionDenied
} else if (500..600).contains(&status) {
io::ErrorKind::ConnectionAborted
} else {
io::ErrorKind::Other
},
err,
)))
.ok();
}
}
};
true
}
}
pub struct Request {
pub url: String,
pub base_url: String,
pub headers: curl::easy::List,
pub upload: bool,
pub config: http::Options,
}
pub struct Response {
pub headers: pipe::Reader,
pub body: pipe::Reader,
pub upload_body: pipe::Writer,
}
pub fn new() -> (
thread::JoinHandle<Result<(), Error>>,
SyncSender<Request>,
Receiver<Response>,
) {
let (req_send, req_recv) = sync_channel(0);
let (res_send, res_recv) = sync_channel(0);
let handle = std::thread::spawn(move || -> Result<(), Error> {
let mut handle = Easy2::new(Handler::default());
handle.pipewait(false)?;
handle.tcp_keepalive(true)?;
let mut follow = None;
let mut redirected_base_url = None::<String>;
for Request {
url,
base_url,
mut headers,
upload,
config:
http::Options {
extra_headers,
follow_redirects,
low_speed_limit_bytes_per_second,
low_speed_time_seconds,
connect_timeout,
proxy,
no_proxy,
proxy_auth_method,
user_agent,
proxy_authenticate,
verbose,
backend: _,
},
} in req_recv
{
let effective_url = redirect::swap_tails(redirected_base_url.as_deref(), &base_url, url.clone());
handle.url(&effective_url)?;
handle.post(upload)?;
for header in extra_headers {
headers.append(&header)?;
}
headers.append("Expect:")?;
handle.verbose(verbose)?;
let mut proxy_auth_action = None;
if let Some(proxy) = proxy {
handle.proxy(&proxy)?;
let proxy_type = if proxy.starts_with("socks5h") {
curl::easy::ProxyType::Socks5Hostname
} else if proxy.starts_with("socks5") {
curl::easy::ProxyType::Socks5
} else if proxy.starts_with("socks4a") {
curl::easy::ProxyType::Socks4a
} else if proxy.starts_with("socks") {
curl::easy::ProxyType::Socks4
} else {
curl::easy::ProxyType::Http
};
handle.proxy_type(proxy_type)?;
if let Some((obtain_creds_action, authenticate)) = proxy_authenticate {
let creds = authenticate.lock().expect("no panics in other threads")(obtain_creds_action)?
.expect("action to fetch credentials");
handle.proxy_username(&creds.identity.username)?;
handle.proxy_password(&creds.identity.password)?;
proxy_auth_action = Some((creds.next, authenticate));
}
}
if let Some(no_proxy) = no_proxy {
handle.noproxy(&no_proxy)?;
}
if let Some(user_agent) = user_agent {
handle.useragent(&user_agent)?;
}
handle.http_headers(headers)?;
handle.transfer_encoding(false)?;
if let Some(timeout) = connect_timeout {
handle.connect_timeout(timeout)?;
}
{
let mut auth = Auth::new();
match proxy_auth_method {
ProxyAuthMethod::AnyAuth => auth
.basic(true)
.digest(true)
.digest_ie(true)
.gssnegotiate(true)
.ntlm(true)
.aws_sigv4(true),
ProxyAuthMethod::Basic => auth.basic(true),
ProxyAuthMethod::Digest => auth.digest(true),
ProxyAuthMethod::Negotiate => auth.digest_ie(true),
ProxyAuthMethod::Ntlm => auth.ntlm(true),
};
handle.proxy_auth(&auth)?;
}
handle.tcp_keepalive(true)?;
if low_speed_time_seconds > 0 && low_speed_limit_bytes_per_second > 0 {
handle.low_speed_limit(low_speed_limit_bytes_per_second)?;
handle.low_speed_time(Duration::from_secs(low_speed_time_seconds))?;
}
let (receive_data, receive_headers, send_body) = {
let handler = handle.get_mut();
let (send, receive_data) = pipe::unidirectional(1);
handler.send_data = Some(send);
let (send, receive_headers) = pipe::unidirectional(1);
handler.send_header = Some(send);
let (send_body, receive_body) = pipe::unidirectional(None);
handler.receive_body = Some(receive_body);
(receive_data, receive_headers, send_body)
};
let follow = follow.get_or_insert(follow_redirects);
handle.get_mut().follow = *follow;
handle.follow_location(matches!(*follow, FollowRedirects::Initial | FollowRedirects::All))?;
if *follow == FollowRedirects::Initial {
*follow = FollowRedirects::None;
}
if res_send
.send(Response {
headers: receive_headers,
body: receive_data,
upload_body: send_body,
})
.is_err()
{
break;
}
if let Err(err) = handle.perform() {
let handler = handle.get_mut();
handler.reset();
if let Some((action, authenticate)) = proxy_auth_action {
authenticate.lock().expect("no panics in other threads")(action.erase()).ok();
}
let err = Err(io::Error::new(
curl_is_spurious(&err)
.then(|| std::io::ErrorKind::ConnectionReset)
.unwrap_or(std::io::ErrorKind::Other),
err,
));
handler.receive_body.take();
match (handler.send_header.take(), handler.send_data.take()) {
(Some(header), mut data) => {
if let Err(TrySendError::Disconnected(err)) | Err(TrySendError::Full(err)) =
header.channel.try_send(err)
{
if let Some(body) = data.take() {
body.channel.try_send(err).ok();
}
}
}
(None, Some(body)) => {
body.channel.try_send(err).ok();
}
(None, None) => {}
};
} else {
let handler = handle.get_mut();
if let Some((action, authenticate)) = proxy_auth_action {
authenticate.lock().expect("no panics in other threads")(if handler.last_status == 200 {
action.store()
} else {
action.erase()
})?;
}
handler.reset();
handler.receive_body.take();
handler.send_header.take();
handler.send_data.take();
let actual_url = handle
.effective_url()?
.expect("effective url is present and valid UTF-8");
if actual_url != effective_url {
redirected_base_url = redirect::base_url(actual_url, &base_url, url)?.into();
}
}
}
Ok(())
});
(handle, req_send, res_recv)
}
impl From<Error> for http::Error {
fn from(err: Error) -> Self {
http::Error::Detail {
description: err.to_string(),
}
}
}
impl From<curl::Error> for http::Error {
fn from(err: curl::Error) -> Self {
http::Error::Detail {
description: err.to_string(),
}
}
}