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 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
|
// Copyright 2021-2022 Ian Jackson and contributors to Hippotat
// SPDX-License-Identifier: GPL-3.0-or-later WITH LicenseRef-Hippotat-OpenSSL-Exception
// There is NO WARRANTY.
#![allow(clippy::style)]
#![allow(clippy::unit_arg)]
#![allow(clippy::useless_format)]
#![allow(clippy::while_let_loop)]
use hippotat::prelude::*;
use hippotat_macros::into_crlfs;
#[derive(clap::Parser,Debug)]
pub struct Opts {
#[clap(flatten)]
log: LogOpts,
#[clap(flatten)]
config: config::CommonOpts,
/// Print config item(s), do not actually run
///
/// Argument is (comma-separated) list of config keys;
/// values will be printed tab-separated.
/// The key `pretty` dumps the whole config in a pretty debug format.
///
/// One line is output for each association.
/// Additional pseudo-config-keys are recognised:
/// `client`: our client virtual IP address;
/// `server`: server's logical name in the config;
/// `link`: the link name including the `[ ]`.
#[clap(long)]
print_config: Option<String>,
}
type OutstandingRequest<'r> = Pin<Box<
dyn Future<Output=Option<Box<[u8]>>> + Send + 'r
>>;
struct ClientContext<'c> {
ic: &'c InstanceConfig,
hclient: &'c reqwest::Client,
reporter: &'c parking_lot::Mutex<Reporter<'c>>,
}
#[derive(Debug)]
struct TxQueued {
expires: Instant,
data: Box<[u8]>,
}
#[throws(AE)]
fn submit_request<'r, 'c:'r>(
c: &'c ClientContext,
req_num: &mut ReqNum,
reqs: &mut Vec<OutstandingRequest<'r>>,
upbound: FramesData,
) {
let show_timeout = c.ic.http_timeout
.saturating_add(Duration::from_nanos(999_999_999))
.as_secs();
let time_t = time_t_now();
let time_t = format!("{:x}", time_t);
let hmac = token_hmac(c.ic.secret.0.as_bytes(), time_t.as_bytes());
//dbg!(DumpHex(&hmac));
let mut token = time_t;
write!(token, " ").unwrap();
BASE64_CONFIG.encode_string(hmac, &mut token);
let req_num = { *req_num += 1; *req_num };
let prefix1 = format!(into_crlfs!(
r#"--b
Content-Type: text/plain; charset="utf-8"
Content-Disposition: form-data; name="m"
{}
{}
{}
{}
{}
{}
{}"#),
&c.ic.link.client,
token,
c.ic.target_requests_outstanding,
show_timeout,
c.ic.mtu,
c.ic.max_batch_down,
c.ic.max_batch_up,
);
let prefix2 = format!(into_crlfs!(
r#"
--b
Content-Type: application/octet-stream
Content-Disposition: form-data; name="d"
"#),
);
let suffix = format!(into_crlfs!(
r#"
--b--
"#),
);
macro_rules! content { {
$out:ty,
$iter:ident,
$into:ident,
} => {
itertools::chain![
IntoIterator::into_iter([
prefix1.$into(),
prefix2.$into(),
]).take(
if upbound.is_empty() { 1 } else { 2 }
),
Itertools::intersperse(
upbound.$iter().map(|u| { let out: $out = u.$into(); out }),
SLIP_END_SLICE.$into()
),
[ suffix.$into() ],
]
}}
let body_len: usize = content!(
&[u8],
iter,
as_ref,
).map(|b| b.len()).sum();
trace!("{} #{}: req; tx body_len={} frames={}",
&c.ic, req_num, body_len, upbound.len());
let body = http_body_util::StreamBody::new(
futures::stream::iter(
content!(
Bytes,
into_iter,
into,
).map(|by| Ok::<_, Void>(http_body::Frame::data(by)))
)
);
let req = {
let url = c.ic.url.clone();
let mut req = reqwest::Request::new(reqwest::Method::POST, url);
let h = req.headers_mut();
let ctype = r#"multipart/form-data; boundary="b""#;
let ctype = reqwest::header::HeaderValue::from_static(ctype);
h.insert("Content-Type", ctype);
*req.body_mut() = Some(reqwest::Body::wrap(body));
req
};
let resp = c.hclient.execute(req);
let fut = Box::pin(async move {
let r = async { tokio::time::timeout( c.ic.effective_http_timeout, async {
let resp = resp.await.context("make request")?;
let status = resp.status();
let max_body = c.ic.max_batch_down.sat() + MAX_OVERHEAD;
let body = futures::stream::unfold(resp, |mut resp| async {
resp.chunk().await.transpose().map(|r| (r, resp))
});
pin!(body);
let resp = read_limited_bytes(
max_body, default(), default(), body.as_mut(),
).await
.context("fetching response body")?;
if ! status.is_success() {
throw!(anyhow!("HTTP error status={} body={:?}",
&status, String::from_utf8_lossy(&resp)));
}
Ok::<_,AE>(resp)
}).await? }.await;
let r = c.reporter.lock().filter(Some(req_num), r);
if let Some(r) = &r {
trace!("{} #{}: rok; rx bytes={}", &c.ic, req_num, r.len());
} else {
tokio::time::sleep(c.ic.http_retry).await;
}
r
});
reqs.push(fut);
}
async fn run_client(
ic: InstanceConfig,
hclient: reqwest::Client,
) -> Result<Void, AE>
{
debug!("{}: config: {:?}", &ic, &ic);
let reporter = parking_lot::Mutex::new(Reporter::new(&ic));
let c = ClientContext {
reporter: &reporter,
hclient: &hclient,
ic: &ic,
};
let mut ipif = Ipif::start(&ic.ipif, Some(ic.to_string()))?;
let mut req_num: ReqNum = 0;
let mut tx_queue: VecDeque<TxQueued> = default();
let mut upbound = Frames::default();
let mut reqs: Vec<OutstandingRequest>
= Vec::with_capacity(ic.max_requests_outstanding.sat());
let mut rx_queue: FrameQueueBuf = default();
let trouble = async {
loop {
let rx_queue_space =
if rx_queue.remaining() < ic.max_batch_down.sat() {
Ok(())
} else {
Err(())
};
select! {
biased;
y = ipif.rx.write_all_buf(&mut rx_queue),
if ! rx_queue.is_empty() =>
{
let () = y.context("write rx data to ipif")?;
},
() = async {
let expires = tx_queue.front().unwrap().expires;
tokio::time::sleep_until(expires).await
},
if ! tx_queue.is_empty() =>
{
let _ = tx_queue.pop_front();
},
data = Ipif::next_frame(&mut ipif.tx),
if tx_queue.is_empty() =>
{
let data = data?;
//eprintln!("data={:?}", DumpHex(&data));
match slip::process1(Slip2Mime, ic.mtu, &data, |header| {
let saddr = ip_packet_addr::<false>(header)?;
if saddr != ic.link.client.0 { throw!(PE::Src(saddr)) }
Ok(())
}) {
Ok((data, ())) => tx_queue.push_back(TxQueued {
data,
expires: Instant::now() + ic.max_queue_time
}),
Err(PE::Empty) => { },
Err(e@ PE::Src(_)) => debug!("{}: tx discarding: {}", &ic, e),
Err(e) => error!("{}: tx discarding: {}", &ic, e),
};
},
_ = async { },
if ! upbound.tried_full() &&
! tx_queue.is_empty() =>
{
while let Some(TxQueued { data, expires }) = tx_queue.pop_front() {
match upbound.add(ic.max_batch_up, data.into()/*todo:504*/) {
Err(data) => {
tx_queue.push_front(TxQueued { data: data.into(), expires });
break;
}
Ok(()) => { },
}
}
},
_ = async { },
if rx_queue_space.is_ok() &&
(reqs.len() < ic.target_requests_outstanding.sat() ||
(reqs.len() < ic.max_requests_outstanding.sat() &&
! upbound.is_empty()))
=>
{
submit_request(&c, &mut req_num, &mut reqs,
mem::take(&mut upbound).into())?;
},
(got, goti, _) = async { future::select_all(&mut reqs).await },
if ! reqs.is_empty() =>
{
// This future was Ready and has returned the value,
// which is in `got`. We don't want the completed future.
let _: Pin<Box<dyn Future<Output = _>>> = reqs.swap_remove(goti);
if let Some(got) = got {
//eprintln!("got={:?}", DumpHex(&got));
match slip::processn(SlipNoConv,ic.mtu, &got, |header| {
let addr = ip_packet_addr::<true>(header)?;
if addr != ic.link.client.0 { throw!(PE::Dst(addr)) }
Ok(())
},
|(o,())| future::ready(Ok({ rx_queue.push_esc(o); })),
|e| Ok::<_,SlipFramesError<Void>>( {
error!("{} #{}: rx discarding: {}", &ic, req_num, e);
})).await
{
Ok(()) => reporter.lock().success(),
Err(SlipFramesError::ErrorOnlyBad) => {
reqs.push(Box::pin(async {
tokio::time::sleep(ic.http_retry).await;
None
}));
},
Err(SlipFramesError::Other(v)) => unreachable!("{}", v),
}
}
},
_ = tokio::time::sleep(c.ic.effective_http_timeout),
if rx_queue_space.is_err() =>
{
reporter.lock().filter(None, Err::<Void,_>(
anyhow!("rx queue full, blocked")
));
},
}
}
}.await;
ipif.quitting(Some(&ic)).await;
trouble
}
#[tokio::main]
async fn main() {
let opts = <Opts as clap::Parser>::parse();
let (ics,) = config::startup(
"hippotat", LinkEnd::Client,
&opts.config, &opts.log, |_, ics|
{
PrintConfigOpt(&opts.print_config)
.implement(ics, )?;
Ok(())
}, |_, ics| async move {
Ok((ics,))
}).await;
let hclient = reqwest::Client::builder()
.http1_title_case_headers()
.build().expect("build reqwest Client");
info!("starting");
let () = future::select_all(
ics.into_iter().map(|ic| Box::pin(async {
let assocname = ic.to_string();
info!("{} starting", &assocname);
let hclient = hclient.clone();
let join = task::spawn(async {
run_client(ic, hclient).await.void_unwrap_err()
});
match join.await {
Ok(e) => {
error!("{} failed: {}", &assocname, e);
},
Err(je) => {
error!("{} panicked!", &assocname);
panic::resume_unwind(je.into_panic());
},
}
}))
).await.0;
error!("quitting because one of your client connections crashed");
process::exit(16);
}
#[test]
fn verify_cli() {
hippotat::utils::verify_cli::<Opts>();
}
|